LoginSignup
3
1

More than 3 years have passed since last update.

sqlacodegenを使って既存のMySQLサーバからSQLAlchemyのテーブル定義を生成する

Last updated at Posted at 2020-10-27

まっさらなAmazonLinux2でやるときの手順です

実行環境

OS: AmazonLinux2 (Linux version 4.14.193-149.317.amzn2.x86_64)
python: Python 2.7.18

やること

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
pip install sqlacodegen pymysql
sqlacodegen mysql+pymysql://user:password@sqlhost/dbname

オプション:
--outfile: 標準出力ではなく、ファイルに書き出す
--tables: テーブルを指定
これで標準出力に全テーブルのSQLAlchemy定義が出力されます

公式サイトにはoursqlというのを使うと書いてありますが、この環境では下記エラーが出るためpymysqlを使います
https://pypi.org/project/sqlacodegen/

Traceback (most recent call last):
  File "/home/ec2-user/.local/bin/sqlacodegen", line 8, in <module>
    sys.exit(main())
  File "/home/ec2-user/.local/lib/python2.7/site-packages/sqlacodegen/main.py", line 44, in main
    engine = create_engine(args.url)
  File "/home/ec2-user/.local/lib/python2.7/site-packages/sqlalchemy/engine/__init__.py", line 500, in create_engine
    return strategy.create(*args, **kwargs)
  File "/home/ec2-user/.local/lib/python2.7/site-packages/sqlalchemy/engine/strategies.py", line 61, in create
    entrypoint = u._get_entrypoint()
  File "/home/ec2-user/.local/lib/python2.7/site-packages/sqlalchemy/engine/url.py", line 172, in _get_entrypoint
    cls = registry.load(name)
  File "/home/ec2-user/.local/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 254, in load
    loader = self.auto_fn(name)
  File "/home/ec2-user/.local/lib/python2.7/site-packages/sqlalchemy/dialects/__init__.py", line 32, in _auto_fn
    dialect, driver = name.split(".")
ValueError: too many values to unpack
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1