Skip to content

Instantly share code, notes, and snippets.

@ktmud
Last active March 29, 2022 22:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ktmud/d908deed863d13de4c0564781348cfa7 to your computer and use it in GitHub Desktop.
Save ktmud/d908deed863d13de4c0564781348cfa7 to your computer and use it in GitHub Desktop.
Understand how SQLAlchemy insert().from_select(..) works
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