如何在SQLAlchemy中打印架构/表定义

时间:2019-07-03 08:43:24

标签: python sqlalchemy schema

如何使用sqlalchemy打印所有表的架构?

这是我使用sqlite3的方式:我运行SQL来打印出数据库中所有表的模式:

import sqlite3
conn = sqlite3.connect("example.db")
cur = conn.cursor()

rs = cur.execute(
    """
    SELECT name, sql FROM sqlite_master
    WHERE type='table'
    ORDER BY name;
    """)

for name, schema, *args in rs:
    print(name)
    print(schema)
    print()

具有如下所示的输出:

albums
CREATE TABLE "albums"
(
    [AlbumId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    [Title] NVARCHAR(160)  NOT NULL,
    [ArtistId] INTEGER  NOT NULL,
    FOREIGN KEY ([ArtistId]) REFERENCES "artists" ([ArtistId]) 
        ON DELETE NO ACTION ON UPDATE NO ACTION
)

artists
CREATE TABLE "artists"
(
    [ArtistId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    [Name] NVARCHAR(120)
)

有没有一种方法可以通过纯sqlalchemy api调用来做到这一点呢?

metadata = sqlalchemy.MetaData()
metadata.reflect(engine)
insp = sqlalchemy.inspect(engine)

for table_name in metadata.tables:
    print(table_name)
    for column in insp.get_columns(table_name):
        for name,value in column.items():
            print('  ', end='')
            if value:
                field = name if value in [True, 'auto'] else value 
                print(field, end=' ')
        print()

输出:

albums
  AlbumId   INTEGER       autoincrement   primary_key 
  Title   NVARCHAR(160)       autoincrement   
  ArtistId   INTEGER       autoincrement   

artists
  ArtistId   INTEGER       autoincrement   primary_key 
  Name   NVARCHAR(120)   nullable     autoincrement   

1 个答案:

答案 0 :(得分:1)

This bit in the SQLAlchemy docs可能会有所帮助:他们建议这样做:

def dump(sql, *multiparams, **params):
    print(sql.compile(dialect=engine.dialect))
engine = create_engine('postgresql://', strategy='mock', executor=dump)
metadata.create_all(engine, checkfirst=False)