Bulk insert creating duplicate primary-keys

15 views
Skip to first unread message

Colton Allen

unread,
Jun 12, 2019, 3:36:50 PM6/12/19
to sqlalchemy
I'm using Postgres and I am getting a duplicate primary key error when attempting to insert from a query.  My primary key is a UUID type.

statement = insert(my_table).from_select(['a', 'b'], select([sometable.c.a, sometable.c.b])
session
.execute(statement)
session
.commit()


Error: "DETAIL:  Key (id)=(f6bdf0e7-f2af-4f29-8122-5320e1ab428e) already exists."

This query runs successfully when the select on finds one row.  If there are more it fails.  Is there a way to instruct the query to generate a UUID for each row found?

Colton Allen

unread,
Jun 12, 2019, 3:38:42 PM6/12/19
to sqlalchemy
Also, I should mention the ID is not explicitly mentioned in the select query.  I am relying on the column's "default" argument to supply the UUID.

Also also, I made a typo.  It should read "when the select only finds one row".

Mike Bayer

unread,
Jun 12, 2019, 3:57:21 PM6/12/19
to sqlal...@googlegroups.com
what's the default on the column?  seems like that's the problem here.    if this is an in-SQLAlchemy default, that won't work, you need to generate the uuids on the database side if you are using a SELECT.   The functions are available through an extension on PG, there's background here: https://dba.stackexchange.com/a/122624/81161 on setting it all up.

if you dont want to set the DEFAULT on the column, you can run it in the SELECT using:

SELECT([func.uuid_generate_v1(), sometable.c.a, sometable.c.b])
--
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.
To post to this group, send email to sqlal...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages