How would one have dynamic "secondary" keys? For example, how we have it in Jira. We have a project name, for example "Test" with the shortcut "TEST". All associated tickets in this project are given a ID "TEST-1234", "TEST-1235", and so on.
How would one model this in Postgres?
In my mind, I worked out a table project
with name VARCHAR(xx)
and short VARCHAR(8)
. The ticket table would somehow look like this:
CREATE TABLE ticket
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
identifier INTEGER ???,
FOREIGN KEY (project_id) REFERENCES project(id),
)
How would you construct an identifier
that is incrementing for every new ticket that is referencing the same project_id
?
2
Answers
Per-project serials are subject to race conditions. The best solution depends on the complete situation.
One way: every session that wants to write a new a
ticket
row has to lock the parent tableproject
first, to get (limited) exclusive write access for just the given project. This way you eliminate race conditions without blocking the wholeticket
table.Like:
The subquery always returns a row due to the aggregate function. So this even works for the first row per project, starting with 1.
You could do this with a relative counter like so
1) create a counter table like this one :
2) create a function to increase the counter and give a new value :
3) use it in queries like :