I installed postgresql - docker[postgres:9.6.24] and manually saved some rows on the table, lets say, I added 10 rows.
When I used sqlalchemy to insert new rows on the table, I got this error
sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "bird_pkey" DETAIL: Key (bird_id)=(1) already exists.
Code -
session = self.Session()
bird_data = Bird(name='Parrot', population=50)
session.add(vehicle)
session.commit()
Table -
class Bird(Base):
__tablename__ = 'bird'
bird_id = Column(Integer, primary_key=True)
name = Column(String)
population = Column(Integer)
But, there are 10 records already saved in the Bird
table. I don't why the primary key is showing the unique constrain error as it is usually calculate the primary key value automatically for the new records.
How to solve this
I tried this answer, but I got the syntax error
create sequence bird_seq increment 1 start 11;
SELECT nextval('bird_seq');
select setval('bird_seq', (select max(bird_id) from bird)+1);
but this is also not worked, I got the same error, but this time the bird_id
is assigned to 2
sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "bird_pkey" DETAIL: Key (bird_id)=(2) already exists.
How to solve this?
The primary_key for this table is not properly assigned, Now I am wondering that, this issue will cause error for all other tables when inserting new records? If so, How to solve this issue for all tables in the database
Thanks