Created
January 7, 2017 21:07
-
-
Save iuridiniz/2f0e0a0642fa6b891df1bf0857dd59e9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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), nullable=True, default=None, server_default='NULL') | |
email = Column(types.String(255), unique=True, nullable=False) | |
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 | |
# you can use User.__table__.c too, it is a alias to columns | |
result = dict([(c.name, any([c.primary_key, c.unique])) for c in User.__table__.columns]) | |
print(result) | |
# also if you want to check only some columns: | |
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]))) | |
engine = create_engine('mysql:///test?unix_socket=/tmp/mysql/socket', echo=True) | |
####################################################### | |
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) | |
engine = create_engine('mysql:///test?unix_socket=/tmp/mysql/socket', echo=True) | |
session = scoped_session(sessionmaker(bind=engine)) | |
Base.metadata.drop_all(engine) | |
Base.metadata.create_all(engine) | |
from alembic.migration import MigrationContext | |
from alembic.operations import Operations | |
ctx = MigrationContext.configure(engine) | |
op = Operations(ctx) | |
with op.batch_alter_table("user") as batch_op: | |
batch_op.add_column(Column('foo', types.Integer)) | |
batch_op.add_column(Column('bar', types.Integer)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment