Search code examples
pythonsqlalchemyintrospection

SQLAlchemy introspection


What I am trying to do is to get from SqlAlchemy entity definition all it's Column()'s, determine their types and constraints, to be able to pre-validate, convert data and display custom forms to user.

How can I introspect it?

Example:

class Person(Base):
    '''
        Represents Person
    '''
    __tablename__ = 'person'

    # Columns
    id = Column(String(8), primary_key=True, default=uid_gen)
    title = Column(String(512), nullable=False)
    birth_date = Column(DateTime, nullable=False)

I want to get this id, title, birth date, determine their restrictions (such as title is string and max length is 512 or birth_date is datetime etc)

Thank you


Solution

  • If you are using sqlalchemy 0.8, then you should check out the new feature New Class Inspection System. Sample code extract from the documentation:

    class User(Base):
        __tablename__ = 'user'
    
        id = Column(Integer, primary_key=True)
        name = Column(String)
        name_syn = synonym(name)
        addresses = relationship(Address)
    
    # universal entry point is inspect()
    >>> b = inspect(User)
    
    # column collection
    >>> b.columns
    [<id column>, <name column>]
    

    Otherwise, see Accessing Tables and Columns part of the documentation. Again, code extract from the docu:

    employees = Table(...)
    # or if using declarative
    #employees = Employee.__table__
    
    # or just
    employees.c.employee_id
    
    # via string
    employees.c['employee_id']
    
    # iterate through all columns
    for c in employees.c:
        print c
    
    # access a column's name, type, nullable, primary key, foreign key
    employees.c.employee_id.name
    employees.c.employee_id.type
    employees.c.employee_id.nullable
    employees.c.employee_id.primary_key
    employees.c.employee_dept.foreign_keys