/* Add rows for sensors */
INSERT INTO sensors (ident, name, auth_key)
    SELECT
        sensor,
        IFNULL(
            (SELECT c.value FROM sensor_config c WHERE c.sensor = sensor),
            sensor
        ) as "name",
        hex(randomblob(32)) as "auth_key"
    FROM sensor_values
    GROUP BY sensor;

/* We need to add FK key and the only way is to create new table */
/* So we rename old table, create a new one and migrate the data there */
ALTER TABLE sensor_values RENAME TO sensor_values_old;

CREATE TABLE IF NOT EXISTS sensor_values (
	timestamp INTEGER NOT NULL,
	sensor_id INTEGER NOT NULL,
	value REAL NOT NULL,
    FOREIGN KEY (sensor_id) REFERENCES sensors(id)
);

INSERT INTO sensor_values (timestamp, sensor_id, value)
    SELECT timestamp, (SELECT s.id FROM sensors s WHERE s.ident = sensor), value
    FROM sensor_values_old;

DROP TABLE sensor_values_old;

/* this column was temporary */
ALTER TABLE sensors DROP COLUMN ident;
