Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

python - How to execute DDL statement in a different schema?

I'd like to execute a DDL statement (for example: create table test(id int, str varchar)) in different DB schemas.

In order to execute this DDL i was going to use the following code:

from sqlalchemy import DDL, text, create_engine

engine = create_engine(...)

ddl_cmd = "create table test(id int, str varchar)"

DDL(ddl_cmd).execute(bind=engine)

How can I specify in which DB schema to execute this DDL statement, not changing the DDL command itself?

I don't understand why such a basic parameter like schema is missing in the DDL().execute() method. I guess I'm missing some important concept, but I couldn't figure it out.


UPD: I've found the "schema_translate_map" execution option, but it didn't work for me - the table will be still created in the default schema.

Here are my attempts:

conn = engine.connect().execution_options(schema_translate_map={None: "my_schema"})

then i tried different variants:

# variant 1
conn.execute(ddl_cmd)
# variant 2
conn.execution_options(schema_translate_map={None: "my_schema"}).execute()
# variant 3
DDL(ddl_cmd).compile(bind=conn).execute()
# variant 4
DDL(ddl_cmd).compile(bind=conn).execution_options(schema_translate_map={None: "my_schema"})

but every time the table will be created in the default schema. :(


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...