Closed mxfactorial closed 3 years ago
workaround
timescale requires a default timestamp on the column targeted by the triggered function
the triggered function then overwrites the default timestamp
#!/bin/bash
docker run \
--rm \
-d \
--name timescaledb \
-p 5433:5432 \
-e POSTGRES_PASSWORD=password \
timescale/timescaledb:latest-pg13
sleep 2 # wait for postgres availability
docker exec timescaledb psql -U postgres -d postgres -c "CREATE DATABASE accounting;"
sql1="CREATE TABLE transaction (
id SERIAL,
author character varying(255) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id, created_at)
);
CREATE TABLE transaction_item (
id SERIAL,
transaction_id integer NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id, created_at)
);
select create_hypertable('transaction_item', 'created_at');
CREATE OR REPLACE FUNCTION copy_transaction_created_at()
RETURNS trigger AS
\$\$
BEGIN
NEW.created_at = (SELECT created_at FROM transaction WHERE id = NEW.transaction_id);
RETURN NEW;
END;
\$\$
LANGUAGE plpgsql;
CREATE TRIGGER copy_transaction_created_at
BEFORE INSERT ON transaction_item
FOR EACH ROW
EXECUTE PROCEDURE copy_transaction_created_at();
insert into transaction (author) values ('GroceryStore');"
sql2="insert into transaction_item (transaction_id) values (1);"
docker exec timescaledb psql -U postgres -d accounting -c "${sql1}"
sleep 1
docker exec timescaledb psql -U postgres -d accounting -c "${sql2}"
docker exec timescaledb psql -U postgres -d accounting -c "select * from transaction;"
docker exec timescaledb psql -U postgres -d accounting -c "select * from transaction_item;"
docker stop timescaledb >/dev/null
Relevant system information:
postgres --version
): 13.3\dx
inpsql
): 2.4Describe the bug hypertable constraint blocks trigger from copying values before insert
To Reproduce Steps to reproduce the behavior:
start.sh
-- select create_hypertable('transaction_item', 'created_at');
linechmod +x start.sh && ./start.sh
*note:
created_at
value copies with zero errors whenselect create_hypertable()
statement remains commentedExpected behavior trigger copies
transaction.created_at
value totransaction_item.created_at
beforetransaction_item
insertActual behavior hypertable not-null constraint violates before trigger copies value
Screenshots If applicable, add screenshots to help explain your problem.
Additional context Add any other context about the problem here.