3

I want to generate unique invoice number per team. I want to have it generated automatically by postgresql database.

I looked at the documentation for creating sequences in postgresql docs. However, I could not find out how I would specify that, the numbers should be unique on team_id level in the table.

Not sure if this is even possible.

Currently, I am creating the next number through code like this team.invoices.maximum(:invoice_number).to_i +

To deal with concurrency, I have created unique index on the invoices table (team_id, invoice_number). This will prevent duplicate numbers being created on team level.

But, I wanted this to be generated from postgresql itself.

adil hussain
  • 800
  • 4
  • 10
  • Refer this : https://stackoverflow.com/a/6632280/7998591 or https://stackoverflow.com/a/11496945/7998591 – Kaushik Nayak Apr 30 '18 at 16:21
  • Are the invoice numbers per team have no gaps ? Would you like the database to create the invoice number? did you have a look on Default attribute? finally, did you try PostgreSQl domain type. – Adam Apr 30 '18 at 16:54
  • @kaushikNayak, using an 'OWNED BY' attribute while creating a Sequence won't assign unique sequences for each team which is my current requirement. – adil hussain May 01 '18 at 03:52

1 Answers1

0

I couldnot find a direct solution from postgresql. However, I found out this gem called sequenced which helped me create scoped sequences supporting concurrent transactions.

adil hussain
  • 800
  • 4
  • 10