Last active
March 29, 2022 22:15
-
-
Save ktmud/d908deed863d13de4c0564781348cfa7 to your computer and use it in GitHub Desktop.
Understand how SQLAlchemy insert().from_select(..) works
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sqlalchemy as sa | |
from sqlalchemy.ext.declarative import declarative_base | |
Base = declarative_base() | |
class Model(Base): | |
__tablename__ = "model" | |
id = sa.Column("id", primary_key=True) | |
bbb = sa.Column("bbb") | |
ccc = sa.Column("ccc") | |
t = sa.table("ttt", sa.Column("aaa"), sa.Column("bbb")) | |
query = sa.select( | |
[ | |
Model, | |
(Model.ccc.is_(None) | Model.ccc == "").label("ddd_is_empty"), | |
Model.bbb.is_(True).label("bbb_is_true"), | |
] | |
) | |
print(query) | |
print(query.columns) | |
# The first parameter of `from_select(...)` can only be a list of column names. | |
# If you want to select complex expressions, you must define their aliases | |
# in the SELECT query. | |
print(t.insert().from_select(["bbb"], query)) | |
# Output -======= | |
# SELECT model.id, model.bbb, model.ccc, (model.ccc IS NULL OR model.ccc) = :param_1 AS ddd_is_empty, model.bbb IS true AS bbb_is_true | |
# FROM model | |
# ['id', 'bbb', 'ccc', 'ddd_is_empty', 'bbb_is_true'] | |
# INSERT INTO ttt (bbb) SELECT model.id, model.bbb, model.ccc, (model.ccc IS NULL OR model.ccc) = :param_1 AS ddd_is_empty, model.bbb IS true AS bbb_is_true | |
# FROM model |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment