kazukgw
2/23/2016 - 2:28 PM

mysql の create_table を mssql のものに変換するやつ

mysql の create_table を mssql のものに変換するやつ

#!/usr/bin/env python

# sqlalchemy
# https://github.com/zzzeek/sqlalchemy

# sqlalchemy engine
# http://docs.sqlalchemy.org/en/rel_1_0/core/engines.html

# reflection
# http://docs.sqlalchemy.org/en/latest/core/reflection.html

# printing raw sql from create
# http://stackoverflow.com/questions/2128717/sqlalchemy-printing-raw-sql-from-create

# apt-get install unixodbc unixodbc-dev
# pip install mysql-python pyodbc
# pip install sqlalchemy

from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.schema import CreateTable
from sqlalchemy.dialects.mysql.base import TINYINT
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.dialects.mysql import VARCHAR

# mysql
# mysql_engine = create_engine('mysql://user:password@host:port/database')
meta = MetaData(bind=mysql_engine)
enquete_table = Table('enquetes',
                      meta,
                      autoload=True,
                      autoload_with=mysql_engine)

# mssql
mssql_engine = create_engine('mssql+pyodbc://user:password@host/database')
table = CreateTable(enquete_table)

# https://github.com/zzzeek/sqlalchemy/blob/master/lib/sqlalchemy/dialects/mssql/base.py#L738
@compiles(VARCHAR, 'mssql')
def compile_VARCHAR(element, compiler, **kw):
    return compiler.visit_NVARCHAR(element, **kw)

print table.compile(mssql_engine)