Let's imagine that we're building GitHub and we have two tables: repos
and issues
. Every GitHub repo has a collection of issues, and so the issues
table has a foreign key of repo_id
.
Now, when you're browsing a GitHub repo's issues, you don't want to be exposed to the internal id
. Instead, you want something like a number
, which increments from 1..n
for only that repository. You want your first issue in your new repo to be numbered 1
, not whatever the next id
for an issue on GitHub is.
Of course, you need a way to increment, and you want to make sure that the number
is unique when scoped to the repo. And so you especially want to avoid then any race condition where the same number can be generated twice.
What's the most straightforward way of handling this? A trigger? Something else entirely?
I am using PostgreSQL but would prefer approaches that are vanilla SQL where possible, e.g. triggers. If there's a simpler Postgres approach, then that would also be useful.
Any code that demonstrate your approach would be extraordinarily useful. Thanks!