SQLAlchemy – is BigInteger Identity column possible in ORM?

Question:

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?
Asked By: qalis

||

Answers:

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)
)
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.