sql >> Databasteknik >  >> RDS >> Mysql

SQLAlchemy Bestäm om unik begränsning finns

Du kan använda SQLalchemy reflection API .

För att få de unika begränsningarna, utfärda en get_unique_constraints .

Primära nycklar är unika, så du måste utfärda en get_pk_constraint också.

tabell skapad med:

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

exempel:

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

utdata:

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

Du kan verifiera de unika begränsningarna genom att:

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)

utdata:

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

Uppdatering 01

Koden ovan kontrollerar bara begränsningar för kolumner i en redan skapad tabell, om du vill inspektera kolumnerna innan skapandet är enklare:

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)

utdata:

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

Om du bara vill markera några kolumner kan du bara göra:

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

utdata:

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



  1. Ska jag inaktivera MySQL strikt läge?

  2. MySQL:Varför använda VARCHAR(20) istället för VARCHAR(255)?

  3. django.core.exceptions.ImproperlyConfigured:Fel vid laddning av MySQLdb-modul:Ingen modul med namnet MySQLdb

  4. FEL 1118 (42000) Radstorleken är för stor