Is there a simple (ie. non-hacky) and race-condition free way to create a partitioned sequence in PostgreSQL. Example:
Using a normal sequence in Issue:
| Project_ID | Issue |
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
| 2 | 4 |
Using a partitioned sequence in Issue:
| Project_ID | Issue |
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 2 | 2 |
You can use the ALTER TABLE… ADD PARTITION statement to add a partition to a table with a DEFAULT rule as long as there are no conflicting values between existing rows in the table and the values of the partition to be added.
Use the ALTER TABLE… SPLIT PARTITION command to divide a single partition into two partitions, maintaining the partitioning of the original table in the newly created partitions, and redistributing the partition's contents between the new partitions. The command syntax comes in two forms.
Table partitioning is one of the best-liked features out of the more recent PostgreSQL developments. However, there is no support for automatic partition creation yet.
I do not believe there is a simple way that is as easy as regular sequences, because:
nextval('myseq')
; but it cannot refer to other columns to inform the function which stream the value should come from.You can make something that works, but you probably won't think it simple. Addressing the above problems in turn:
multiseq (partition_id, next_val)
.Write a multinextval(seq_table, partition_id)
function that does something like the following:
seq_table
.partition_id
, with an incremented value. (Or insert a new row with value 2 if there is no existing one.)Create an insert trigger on your projects table that uses a call to multinextval('projects_table', NEW.Project_ID)
for insertions.
I have not used this entire plan myself, but I have tried something similar to each step individually. Examples of the multinextval
function and the trigger can be provided if you want to attempt this...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With