Skip to content

Instantly share code, notes, and snippets.

@tehasdf
Created September 21, 2016 16:50
Show Gist options
  • Save tehasdf/7e58a06f18b78b2a6a5f0c88aafe7f14 to your computer and use it in GitHub Desktop.
Save tehasdf/7e58a06f18b78b2a6a5f0c88aafe7f14 to your computer and use it in GitHub Desktop.
asdf=# create table foo(id int, version int);
CREATE TABLE
Time: 2.335 ms
asdf=# create function version_err() returns trigger as $$
begin
raise exception 'wrong version';
end;
$$ language plpgsql;
CREATE FUNCTION
Time: 5.548 ms
asdf=# create trigger version_check_trigger
before update on foo
for each row
when (NEW.version != OLD.version + 1)
execute procedure version_err();
CREATE TRIGGER
Time: 7.160 ms
asdf=# insert into foo(id, version) values (1, 1);
INSERT 0 1
Time: 2.993 ms
asdf=# insert into foo(id, version) values (2, 1);
INSERT 0 1
Time: 0.396 ms
asdf=# update foo set version=2 where id=1;
UPDATE 1
Time: 3.465 ms
asdf=# update foo set version=2 where id=1;
ERROR: wrong version
Time: 0.695 ms
asdf=# update foo set version=2 where id=1;
ERROR: wrong version
Time: 0.550 ms
asdf=# update foo set version=3 where id=2;
ERROR: wrong version
Time: 0.533 ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment