synonym equivalent for core?

12 views
Skip to first unread message

Michael Merickel

unread,
Dec 22, 2020, 3:16:23 AM12/22/20
to sqlalchemy
Is there a way to make the following insert statement work by changing something in the Event object's definition? Note I've simplified the example, the reasons for using the core constructs in the first place are to use postgres ON CONFLICT directives with it otherwise yes I could simply use the ORM where the synonyms would work fine.

class Event(Base):
    id = Column(BigInteger, primary_key=True)
    start_date = Column(DateTime)
    start_time = synonym('start_date')

dbsession.execute(insert(Event.__table__).values(start_time=datetime.utcnow()).returning(Event.id)).scalar()

Error raised, presumably because a core insert construct doesn't support column aliases defined at the mapper level?

sqlalchemy.exc.CompileError: Unconsumed column names: start_time

Thanks!

- Michael

Michael Merickel

unread,
Dec 22, 2020, 3:26:20 AM12/22/20
to sqlalchemy
Well it looks like if I use column objects in a dict then it works out. For example:

...insert({Event.start_time: datetime.utcnow()})

Mike Bayer

unread,
Dec 22, 2020, 8:10:44 AM12/22/20
to noreply-spamdigest via sqlalchemy
hey Michael -

What looks to be happening there is you're making an INSERT against the Table object for Event, the columns in this Table object are:  "id", "start_date".    The Table has no information about "start_time" as that is an ORM construct only.   so your first example is equivalent towards:

table = Table("event", meta, Column("id", BigInteger), Column("start_date", DateTime))

stmt = table.insert().values(start_time=utcnow())

see the problem?


your second example which provides the actual "Event.start_time" attribute as a key allows SQLAlchemy to resolve that attribute into the Column it refers towards which is the Event.__table__.c.start_date column object.

Ideally if the insert() were against the Event ORM entity directly, the ORM would be smart enough to figure this out as in SQLAlchemy 1.4 we have ORM-enabled Core constructs, but currently insert() is the one that is not implemented right now.  so maybe someday!
--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
 
 
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.

Reply all
Reply to author
Forward
0 new messages