support explicit SERIAL on postgresql

Issue #3438 new
Michael Bayer
repo owner created an issue

No description provided.

Official response

  • Michael Bayer reporter

    here is a recipe to get this right now:

    from sqlalchemy import Column, Integer, String, create_engine, Sequence
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker
    
    from sqlalchemy.ext.compiler import compiles
    
    
    class SERIAL(Integer):
        pass
    
    
    @compiles(SERIAL, "postgresql")
    def _serial(element, compiler, **kw):
        return "SERIAL"
    
    
    engine = create_engine('postgres://scott:tiger@localhost/test', echo=True)
    Base = declarative_base()
    
    
    class Entity(Base):
        __tablename__ = 'person'
    
        id = Column(SERIAL, primary_key=True)
        id2 = Column(SERIAL, primary_key=True)
        label = Column(String(64))
    
    
    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)
    Session = sessionmaker(bind=engine)
    session = Session()
    
    session.add(Entity(label="One label"))
    session.flush()
    

Comments (4)

  1. Michael Bayer reporter

    here is a recipe to get this right now:

    from sqlalchemy import Column, Integer, String, create_engine, Sequence
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker
    
    from sqlalchemy.ext.compiler import compiles
    
    
    class SERIAL(Integer):
        pass
    
    
    @compiles(SERIAL, "postgresql")
    def _serial(element, compiler, **kw):
        return "SERIAL"
    
    
    engine = create_engine('postgres://scott:tiger@localhost/test', echo=True)
    Base = declarative_base()
    
    
    class Entity(Base):
        __tablename__ = 'person'
    
        id = Column(SERIAL, primary_key=True)
        id2 = Column(SERIAL, primary_key=True)
        label = Column(String(64))
    
    
    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)
    Session = sessionmaker(bind=engine)
    session = Session()
    
    session.add(Entity(label="One label"))
    session.flush()
    
  2. Log in to comment