SQLAlchemy printing raw SQL from create()

后端 未结 6 2020
别跟我提以往
别跟我提以往 2020-11-30 00:05

I am giving Pylons a try with SQLAlchemy, and I love it, there is just one thing, is it possible to print out the raw SQL CREATE TABLE data generated from

6条回答
  •  北海茫月
    2020-11-30 00:30

    It turns out this is straight-forward:

    from sqlalchemy.dialects import postgresql
    from sqlalchemy.schema import CreateTable
    from sqlalchemy import Table, Column, String, MetaData
    
    metadata = MetaData()
    
    users = Table('users', metadata,
                  Column('username', String)
    )
    
    statement = CreateTable(users)
    
    print(statement.compile(dialect=postgresql.dialect()))
    

    Outputs this:

    CREATE TABLE users (
        username VARCHAR
    )
    

    Going further, it can even support bound parameters in prepared statements.

    Reference

    How do I render SQL expressions as strings, possibly with bound parameters inlined?

    ...

    or without an Engine:

    from sqlalchemy.dialects import postgresql
    print(statement.compile(dialect=postgresql.dialect()))
    

    SOURCE: http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html#faq-sql-expression-string

    Example: Using SQL Alchemy to generate a user rename script

    #!/usr/bin/env python
    import csv
    from sqlalchemy.dialects import postgresql
    from sqlalchemy import bindparam, Table, Column, String, MetaData
    
    metadata = MetaData()
    
    users = Table('users', metadata,
                  Column('username', String)
    )
    
    renames = []
    
    with open('users.csv') as csvfile:
        for row in csv.DictReader(csvfile):
            renames.append({
                'from': row['sAMAccountName'],
                'to': row['mail']
            })
    
    for rename in renames:
        stmt = (users.update()
                .where(users.c.username == rename['from'])
                .values(username=rename['to']))
        print(str(stmt.compile(dialect=postgresql.dialect(),
                               compile_kwargs={"literal_binds": True})) + ';')
    

    When processing this users.csv:

    sAMAccountName,mail
    bmcboatface,boaty.mcboatface@example.com
    ndhyani,naina.dhyani@contoso.com
    

    Gives output like this:

    UPDATE users SET username='boaty.mcboatface@example.com' WHERE users.username = 'bmcboatface';
    UPDATE users SET username='naina.dhyani@contoso.com' WHERE users.username = 'ndhyani';users.username = 'ndhyani';
    

    Why a research vessel has an email address is yet to be determined. I have been in touch with Example Inc's IT team and have had no response.

提交回复
热议问题