SQLalchemy keyword argument equivalent of `Column('id', Integer, Identity())`

Question:

Attempt: Column(name='id', type_=Integer, default=Identity())

I’m looking at https://docs.sqlalchemy.org/en/14/core/defaults.html#sqlalchemy.schema.Identity and https://docs.sqlalchemy.org/en/14/core/metadata.html#sqlalchemy.schema.Column.init but I can’t see what the equivalent would be, I tried default=Identity() but got a:

sqlalchemy.exc.ArgumentError: ColumnDefault may not be a server-side default type.

Am I meant to use https://docs.sqlalchemy.org/en/14/core/defaults.html#sqlalchemy.schema.DefaultClause or sqlalchemy.schema.DefaultGenerator? – Or is it not meant to be a default=/equivalent at all?

Asked By: A T

||

Answers:

If you want to pass Indentity() as a keyword argument, use server_default:

import sqlalchemy as sa

engine = sa.create_engine('postgresql+psycopg2:///test', echo=True, future=True)
t = sa.Table(
    't', sa.MetaData(), sa.Column('id', sa.Integer, server_default=sa.Identity(), primary_key=True)
)
t.create(engine)

Output

2022-12-18 21:27:32,265 INFO sqlalchemy.engine.Engine BEGIN (implicit)
INFO:sqlalchemy.engine.Engine:BEGIN (implicit)
2022-12-18 21:27:32,266 INFO sqlalchemy.engine.Engine 
CREATE TABLE t (
    id INTEGER GENERATED BY DEFAULT AS IDENTITY
    PRIMARY KEY (id)
)

...

Source code on GitHub

Answered By: snakecharmerb
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.