How to add the index_elements to the on_conflict_do_update() method

853 views
Skip to first unread message

Chaozy Z

unread,
Dec 7, 2021, 5:21:49 PM12/7/21
to sqlalchemy
Hi there, I just started to learn SQLAlchemy. 0

I have a `on_conflict_do_update` command as follows:

```

insert_stmt = insert(MessageSymbol).values(message_id=12345, symbol_id=1)

do_update_stmt = insert_stmt.on_conflict_do_update( index_elements=['message_id'], set_=dict( symbol_id=123 ) )

```

and my MessageSymbol is defined as follow:

```

class MessageSymbol(Base):

 __tablename__ = "message_symbol" 


message_id = Column(BigInteger, primary_key=True, nullable=False) 


symbol_id = Column(BigInteger, nullable=False)

```

When the command is executed it throws the error:

```

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.InvalidColumnReference) there is no unique or exclusion constraint matching the ON CONFLICT specification

[SQL: INSERT INTO message_symbol (message_id, symbol_id) VALUES (%(message_id)s, %(symbol_id)s) ON CONFLICT (message_id) DO UPDATE SET symbol_id = %(param_1)s]
[parameters: {'message_id': 12345, 'symbol_id': 1, 'param_1': 123}]

```

Since I have defined the `message_id` as the primary key I assume it should be a unique constraint. I am wondering what else is being missing? 

Chaozy

Chaozy Z

unread,
Dec 7, 2021, 5:27:33 PM12/7/21
to sqlalchemy
I also tried to add unique=True to the column message_id but still fail with the same error

Simon King

unread,
Dec 8, 2021, 4:45:04 AM12/8/21
to sqlal...@googlegroups.com
Does the table definition in postgres match your SQLAlchemy
definition? Adding "unique=True" to the SQLAlchemy table definition
will not automatically add an index to an existing table in the
database.

If you connect to the database using "psql" and run "\d
message_symbol", does it show the primary key and/or unique index?

Simon
> --
> SQLAlchemy -
> The Python SQL Toolkit and Object Relational Mapper
>
> http://www.sqlalchemy.org/
>
> 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.
> To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/734ae718-fde8-4b54-9de9-b2d81698a0dfn%40googlegroups.com.

Chaozy Z

unread,
Dec 8, 2021, 10:06:43 AM12/8/21
to sqlalchemy
Many thanks your suggestion!  I checked the properties of the table and it turns that the primary key is actually the composite of both the message_id and the symbol_id. Problem solved by simply adding the symbol_id into the index_elements. Thank you again for your time and assistance!

Chaozy

Reply all
Reply to author
Forward
0 new messages