Search code examples
pythonpostgresqlsqlalchemy

SQLAlchemy - is BigInteger Identity column possible in ORM?


I want to create BigInteger Identity column in SQLAlchemy ORM. Documentation does not have any example of either ORM Identity or BigInteger Identity.

  1. Is this possible at all? I don't see any parameter for Identity type that would allow specifying inner integer type
  2. How to do this? Do I have to create custom type and pass it inside Mapping[] brackets?

Solution

  • This seems to work:

    import sqlalchemy as sa    
    from sqlalchemy.orm import mapped_column, Mapped, DeclarativeBase    
        
          
    class Base(DeclarativeBase):    
        pass    
        
          
    class Test(Base):    
        __tablename__ = 't75312537'    
        
        id: Mapped[int] = mapped_column(    
            sa.BigInteger, sa.Identity(), primary_key=True    
        )    
        
        
    engine = sa.create_engine('postgresql+psycopg2:///test', echo=True)    
    Base.metadata.drop_all(engine, checkfirst=True)    
    Base.metadata.create_all(engine)
    

    Output:

    CREATE TABLE t75312537 (
        id BIGINT GENERATED BY DEFAULT AS IDENTITY, 
        PRIMARY KEY (id)
    )
    

    See the docs at Identity Columns (GENERATED {ALWAYS | BY DEFAULT} AS IDENTITY).