I am currently writing a function in the plpgsql language to create partitions which will hold sensor data for each month (one partition for one month and sensor). I am stuck with this error:
ERROR: missing FROM-clause entry for table »curr_sensor« SQL state: 42P01 Context: SQL-Query »CREATE TABLE sensor_1_201609 (CHECK (timestamp >= date(curr_sensor.timestamp) AND timestamp < (date(curr_sensor.timestamp) + interval '1 month'))) INHERITS (sensor_fake_data)« PL/pgSQL-Function create_partition_per_sensor_and_month() Line 20 at EXECUTE
The function looks as follows:
CREATE OR REPLACE FUNCTION create_partition_per_sensor_and_month() RETURNS text as
$BODY$
-- declare variables
DECLARE
loop_count integer := 0;
curr_sensor sensor_fake_data%rowtype;
curr_partition_limit timestamp;
partition_table_name text;
partition_index_timestamp_name text;
partition_index_id_name text;
-- begin with the for loop...loop over every sensor and partition based on sensor and the timestamp
BEGIN --replace mumber with variable
FOR curr_sensor IN SELECT * FROM sensor_fake_data WHERE sensor_id = 1 ORDER BY timestamp ASC
LOOP
IF (loop_count = 0 OR curr_sensor.timestamp > curr_partition_limit) THEN
curr_partition_limit := curr_sensor.timestamp + interval '1 month';
partition_table_name := 'sensor_' || cast(curr_sensor.sensor_id as text) || '_' || to_char(date(curr_sensor.timestamp), 'YYYYMM');
partition_index_timestamp_name := 'index_timestamp_' || cast(curr_sensor.sensor_id as text) || date(curr_sensor.timestamp);
partition_index_id_name := 'index_id_' || cast(curr_sensor.sensor_id as text) || date(curr_sensor.timestamp);
EXECUTE 'CREATE TABLE ' || partition_table_name || ' (CHECK (timestamp >= date(curr_sensor.timestamp) ' ||
'AND timestamp < (date(curr_sensor.timestamp) + interval ' || '''1 month''' || '))) ' ||
'INHERITS (sensor_fake_data)';
-- add index to the new table
EXECUTE format('CREATE INDEX %I ON %I (timestamp)', partition_index_timestamp_name, partition_table_name);
EXECUTE format('CREATE INDEX %I ON %I (sensor_id)', partition_index_id_name, partition_table_name);
EXECUTE format('INSERT INTO %I VALUES(curr_sensor.*)', partition_table_name);
ELSE
EXECUTE format('INSERT INTO %I VALUES(curr_sensor.*)', partition_table_name);
END IF;
loop_count := loop_count + 1;
END LOOP;
END;
$BODY$
I dont understand why there is missing a FROM-Clause. In general I don't understand the Error since I am just trying to create a table (at line 20) and to set some check constraints?