PostgreSQL - Partition tables and returning ID
By Vilem Otte
postgresql
Outline
Whenever working with any SQL database, once the dataset database runs on gets bigger, some more optimization techniques have to be used. One of such techniques is partitioning. A partitioned table externally should behave the same as non-partitioned one, but internally it will work on usually smaller tables which only store data with some specific criteria (typically split on either id or year).
For our example, in standard Postgresql scenarios we have a table like:
CREATE TABLE foo
(
id SERIAL,
data TEXT
);
It is typical to perform queries to insert new record, while obtaining an ID of newly inserted record, typically with a query like:
INSERT INTO foo(data) VALUES("Test") RETURNING id;
Running such query will return a row with id of newly added record. As long as we run on standard tables, this will work perfectly. The problem starts happening with partitioning.
Partitioning
Typically a partitioned table will hold the data satisfying some conditions in place of the parent table. Let's continue the above example by creating 2 partitions of the foo table by id. Like:
CREATE TABLE foo_1
(
CHECK (id BETWEEN 1 AND 99)
) INHERITS (foo);
CREATE TABLE foo_2
(
CHECK (id BETWEEN 100 AND 199)
) INHERITS (foo);
This creates 2 partition tables for the foo table - with some constraints for id column. The next thing that has to be specified is how records are inserted into the partition - which is done using a trigger and function.
CREATE OR REPLACE FUNCTION foo_insert()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
IF (NEW.id >= 1 AND NEW.id <= 99) THEN
INSERT INTO foo_1 VALUES (NEW.*);
ELSEIF (NEW.id >= 100 AND NEW.id <= 199) THEN
INSERT INTO foo_2 VALUES (NEW.*);
ELSE
RAISE EXCEPTION 'Out of range!';
ENDIF
RETURN NULL;
END;
$function$
And let's link the trigger to the foo table with:
CREATE TRIGGER foo_tr_insert BEFORE INSERT ON foo FOR EACH ROW EXECUTE PROCEDURE foo_insert();
Which executes foo_insert for each inserted row before insertion happens into foo table. And by returning null in the foo_insert - we will not continue executing any queries or triggers for current row (i.e. the row is not going to be inserted into the foo table, only to its partition.
Now the problem is - running a query like:
INSERT INTO foo(data) VALUES("Test") RETURNING id;
Is not going to return row with id anymore, as no such value can be returned from foo table due to how trigger and function are defined.
Solution
There is a solution to this problem, although it ends up with insertions being a bit less efficient, requiring a double write, followed by deletion. In short - we want to insert record into partitioned table, and also insert it into the parent table. This will ensure that id is returned for the new record, but we also have to remove newly inserted record into parent table, to ensure there are no duplicates (same record in parent and partition means that there is a duplicate!).
For this purpose we have to update trigger function that is executed before insertion to:
CREATE OR REPLACE FUNCTION foo_insert()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
IF (NEW.id >= 1 AND NEW.id <= 99) THEN
INSERT INTO foo_1 VALUES (NEW.*);
ELSEIF (NEW.id >= 100 AND NEW.id <= 199) THEN
INSERT INTO foo_2 VALUES (NEW.*);
ELSE
RAISE EXCEPTION 'Out of range!';
ENDIF
RETURN NEW;
END;
$function$
By returning a new record here, the same insertion will happen in the parent table.
To ensure deletion after the record has been added to main table (and id obtained for the RETURNING part of the query), a new function has to be defined:
CREATE OR REPLACE FUNCTION foo_after_insert()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
DECLARE
result foo%ROWTYPE;
BEGIN
DELETE
FROM ONLY foo
WHERE id = NEW.id
RETURNING id
INTO result;
RETURN result;
END;
$function$
And link this to the foo table through a trigger like:
CREATE TRIGGER foo_tr_after_insert AFTER INSERT ON foo FOR EACH ROW EXECUTE PROCEDURE foo_after_insert();
This solution incurs additional overhead and halves the efficiency of the insertion queries, it still has less impact than RULE paradigms (which have advantage only in large bulk scenarios). This can be considered a trade-off for consistency and maintainability.