SQLAlchemy Determine If Unique Constraint Exists

北城余情 提交于 2020-07-22 04:08:42

问题


I have a SQLAlchemy model on which I want to run validation. Part of the validation is to ensure a UniqueConstraint exists on a (few) column(s). I know what the columns are. Is there a good way to do this with SQLAlchemy? The underlying database I am using is MySQL.


回答1:


You could use SQLalchemy reflection API.

In order to get the unique constraints, issue a get_unique_constraints.

Primary keys are unique, so you must issue a get_pk_constraint too.

table created with:

CREATE TABLE user (
    id INTEGER NOT NULL, 
    name VARCHAR(255), 
    email VARCHAR(255), 
    login VARCHAR(255), 
    PRIMARY KEY (id), 
    UNIQUE (email), 
    UNIQUE (login)
)

example:

from sqlalchemy import create_engine
from sqlalchemy.engine.reflection import Inspector

# engine = create_engine(...)

insp = Inspector.from_engine(engine)

print "PK: %r" % insp.get_pk_constraint("user")
print "UNIQUE: %r" % insp.get_unique_constraints("user")

output:

PK: {'name': None, 'constrained_columns': [u'login']}
UNIQUE: [{'column_names': [u'email'], 'name': None}, {'column_names': [u'login'], 'name': None}]

You can verify the unique constraints by:

pk = insp.get_pk_constraint("user")['constrained_columns']
unique = map(lambda x: x['column_names'], insp.get_unique_constraints("user"))

for column in ['name', 'id', 'email', 'login']:
    print "Column %r has an unique constraint: %s" %(column, [column] in [pk]+unique)

output:

Column 'name' has an unique constraint: False
Column 'id' has an unique constraint: True
Column 'email' has an unique constraint: True
Column 'login' has an unique constraint: True

Update 01

The code above only check constraint for columns of an already created table, if you want to inspect the columns before the creation is more simple:

from sqlalchemy import create_engine, Column, types
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session

Base = declarative_base()

class User(Base):
    __tablename__ = "user"
    id = Column(types.Integer, primary_key=True)
    name = Column(types.String(255))
    email = Column(types.String(255), unique=True)
    login = Column(types.String(255), unique=True)

# do not create any table
#engine = create_engine('sqlite:///:memory:', echo=True)
#session = scoped_session(sessionmaker(bind=engine))
#Base.metadata.create_all(engine)

# check if column is (any) a primary_key or has unique constraint
# Note1: You can use User.__table__.c too, it is a alias to columns
# Note2: If you don't want to use __table__, you could use the reflection API like:
#        >>> from sqlalchemy.inspection import inspect
#        >>> columns = inspect(User).columns
result = dict([(c.name, any([c.primary_key, c.unique])) for c in User.__table__.columns])

print(result)

output:

{'email': True, 'login': True, 'id': True, 'name': False}

If you want to check only some columns, you could only do:

for column_name in ['name', 'id', 'email', 'login']:
    c = User.__table__.columns.get(column_name)
    print("Column %r has an unique constraint: %s" %(column_name, any([c.primary_key, c.unique])))

output:

Column 'name' has an unique constraint: False
Column 'id' has an unique constraint: True
Column 'email' has an unique constraint: True
Column 'login' has an unique constraint: True


来源:https://stackoverflow.com/questions/33878830/sqlalchemy-determine-if-unique-constraint-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!