I do insert operations into the database (Postgres) and then immediately take the last serial id. If 10 people do the same thing, can they break the sequence of my database operations?
INSERT INTO table VALUES (DEFAULT,...);
SELECT currval(pg_get_serial_sequence('table','column')) as inserted_id;
I'm afraid that may happen situation like:
INSERT INTO table VALUES (DEFAULT,...);
Meanwhile, another user was doing insertions and I end up getting the wrong id;
SELECT currval(pg_get_serial_sequence('table','column')) as inserted_id;
pg_get_serial_sequence(table_name, column_name)
gets the name of the sequence that a serial
, smallserial
or bigserial
column uses.
From the PostgreSQL documentation currval
will:
Return the value most recently obtained by nextval for this sequence in the current session. (An error is reported if nextval has never been called for this sequence in this session.) Because this is returning a session-local value, it gives a predictable answer whether or not other sessions have executed nextval since the current session did.
Based on the above, noting the emphases, the answer to your question "If 10 people do the same thing, can they break the sequence of my database operations?" is no.
It's an easy one to test too. Take two instances of of pgAdmin or whatever client you prefer.
On client 1:
CREATE TABLE foo (id BIGSERIAL PRIMARY KEY, some_column TEXT);
INSERT INTO foo(some_column) VALUES('a');
On client 2:
INSERT INTO foo(some_column) VALUES('b');
On client 1:
SELECT CURRVAL(PG_GET_SERIAL_SEQUENCE('foo','id')) AS inserted_id; -- it will return 1
On client 2:
SELECT CURRVAL(PG_GET_SERIAL_SEQUENCE('foo','id')) AS inserted_id; -- it will return 2