Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint #15

Closed
nataly-obr opened this issue May 2, 2020 · 0 comments

Comments

@nataly-obr
Copy link

Description
session.commit() method produces IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint.

To Reproduce

class Currency(Base):
    __tablename__ = 'currency'

    currency_code = db.Column('currency_code', db.String(3), primary_key=True)
    currency_name = db.Column('currency_name', db.String(140))

Session = sessionmaker(bind=self.engine)
session = Session()
currency_list = [Currency(currency_code = 'USD'), Currency(currency_code = 'EUR')]
currency_list = list(map(lambda x: session.merge(x), currency_list))
session.bulk_save_objects(currency_list, update_changed_only=False)
session.commit() 

Additional information

  1. If I modify this code by adding session.commit() after session.merge(), everything works fine:
...
currency_list = list(map(lambda x: session.merge(x), currency_list))
session.commit() 
session.bulk_save_objects(currency_list, update_changed_only=False)
session.commit() 
  1. The table 'currency' is empty, so the currency_code that I'm trying to add doesn't exist in the database.
  2. Also no problem with adding this currency_code via
connection = psycopg2.connect(...) 
... 
statement = "INSERT INTO {0} ({1}) VALUES ({2}); ".format(table, columns, values) 
crsr.execute(statement)  
connection.commit()

Error

sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "currency_pkey"
DETAIL:  Key (currency_code)=(EUR) already exists.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant