0

I am currently developing an API for invoices. And I want to create an Invoice table with invoiceNumber field that would be auto incrementing but as a string. Something like this:

  1. INV00001
  2. INV00002
  3. INV00003

Is it possible to do it somehow using SQLAlchemy?

I tried to use the Sequence function from SQLAlchemy, but I know it is designed only for integers.

1 Answer 1

0

Using the SQL in this answer from Gordon Linoff, we can define a column with a default that combines an integer sequence and a string prefix like this:

import sqlalchemy as sa

engine = sa.create_engine('postgresql+psycopg2:///test', echo=True)

tbl = sa.Table(
    't77185472',
    sa.MetaData(),
    sa.Column(
        'strseq',
        sa.String,
        server_default=sa.text(
            """('INV' || lpad(nextval('test_seq')::text, 6, '0'))"""
        ),
    ),
)

The column definition depends on the existence of the sequence test_seq. We can optionally add a pair of listeners to drop and create this sequence when the table is dropped or created to keep them in sync.

@sa.event.listens_for(tbl, 'after_drop')
def receive_after_drop(target, connection, **kw):
    """Drop the sequence if `tbl` is dropped."""
    connection.execute(sa.text("""DROP SEQUENCE IF EXISTS test_seq"""))


@sa.event.listens_for(tbl, 'before_create')
def receive_before_create(target, connection, **kw):
    """Create the sequence before `tbl` is created."""
    connection.execute(sa.text("""CREATE SEQUENCE test_seq"""))
Sign up to request clarification or add additional context in comments.

1 Comment

You could perhaps achieve a similar result using an identity column and a computed column to apply the string manipulation, but identity just uses a sequence in the background anyway so it doesn't seem very efficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.