I am using rails 7 and postgres 14.5 and active record now seems out of sync with postgres.
I saved a user and I got ActiveRecord::RecordNotUnique (PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "users_pkey" DETAIL: Key (id)=(3) already exists. ):
From PostgreSQL: Unique violation: 7 ERROR: duplicate key value violates unique constraint "users_pkey", I ran SELECT setval(pg_get_serial_sequence('users', 'id'), coalesce(max(id)+1, 1), false) FROM users; which seemed to fix that initial issue and allowed me to save the user.
Then I destroyed the user and tried to save the user again and now I'm getting ActiveRecord::RecordNotUnique (PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_users_on_email" DETAIL: Key (email)=(test#test.com) already exists. ):
This is telling me that my active record is out of sync with my postgres.
Any ideas on how I can fix this out of sync issue or at least fix the index issue now?
Related
How to correct the following errors when a load my production database into the developement?
ยดยดยด
ERROR: relation "ar_internal_metadata" already exists
ERROR: relation "envelopes" already exists
ERROR: relation "envelopes_id_seq" already exists
ERROR: relation "registers" already exists
ERROR: relation "registers_id_seq" already exists
ERROR: relation "schema_migrations" already exists
ERROR: relation "signers" already exists
ERROR: relation "signers_id_seq" already exists
ERROR: relation "tenants" already exists
ERROR: relation "tenants_id_seq" already exists
ERROR: duplicate key value violates unique constraint "ar_internal_metadata_pkey"
DETAIL: Key (key)=(environment) already exists.
CONTEXT: COPY ar_internal_metadata, line 1
ERROR: duplicate key value violates unique constraint "schema_migrations_pkey"
DETAIL: Key (version)=(20170523182814) already exists.
CONTEXT: COPY schema_migrations, line 1
ERROR: multiple primary keys for table "ar_internal_metadata" are not allowed
ERROR: multiple primary keys for table "envelopes" are not allowed
ERROR: multiple primary keys for table "registers" are not allowed
ERROR: multiple primary keys for table "schema_migrations" are not allowed
ERROR: multiple primary keys for table "signers" are not allowed
ERROR: multiple primary keys for table "tenants" are not allowed
ERROR: relation "index_envelopes_on_creator_id" already exists
ERROR: relation "index_registers_on_creator_id" already exists
ERROR: relation "index_registers_on_envelope_id" already exists
ERROR: relation "index_signers_on_creator_id" already exists
ERROR: relation "index_signers_on_envelope_id" already exists
ERROR: constraint "fk_rails_60f86fe8da" for relation "registers" already exists
Could you give more details please?
My guess is that you did:
$ rails db:drop
Then
# rails db:create
$ rails db:migrate
Then you got that error
Could you confirm by editing your original message. Thx
In Rails 4.2 with Postgresql I got this error when trying to save a new ActiveRecord object
PG::UniqueViolation: ERROR: Duplicate Key Value Violates Unique Constraint 'My_table_name_pkey'
It looks like it's trying to insert the record into the table with a primary key that already exists. How do I sort this out?
It turns out that somtimes the counter PG uses to generate primary keys can get messed up (I don't know how) and it justs needs to be reset to be the maximum value for the primary key in the table.
I found this answer in Jasith Fernando's blog
For me this was happening in the development database so I went into a console for that db like this:
rails db development
Then the name of the variable that needs resetting is the name of the table appended with _id_seq so the command to reset it to the maximum primary key value is this
SELECT setval('my_table_id_seq', (SELECT MAX(id) FROM my_table));
I understand that rails is supposed to disable referential integrity when generating the fixtures. So after a quick Google search, i figured out that the solution to the error following error is to make my postgres user a super user. The error:
WARNING: Rails was not able to disable referential integrity.:00, ETA: 00:00:00
This is most likely caused due to missing permissions.
Rails needs superuser privileges to disable referential integrity.
ActiveRecord::InvalidForeignKey: ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: insert or update on table "responses" violates foreign key constraint "fk_rails_2ec3339f90"
DETAIL: Key (assessment_id)=(1) is not present in table "assessments".
: INSERT INTO "joe"."responses" ("assessment_id", "user_id", "question_id", "choice_id", "created_at", "updated_at") VALUES (1, 1, 1, 1, '2017-05-08', '2017-05-08')
I thought it would be an easy fix, but my postgres user is already a superuser. I did SHOW is_superuser; and the response was on. I even disabled all of the triggers manually from the command line with the same user using alter table responses disable trigger all;. When I list the postgres users using \du, the attributes show up as Superuser, Create role, Create DB.
I am very confident that my user is a superuser. There must be something else going on here. I am using the apartment gem for multi-tenancy. Help is appreciated. If you need any more code, let me know.
The user specified in config/database.yml - say rails_deploy_user needs to have superuser privileges defined, not the generic postgres user.
psql database_environment
\du; # find psql defined users and roles
ALTER ROLE rails_deploy_user WITH SUPERUSER;
This has been asked several times before (here and here, and more).
Every time I push my rails app to Heroku (for at least the last few months, I'd say), I have to reset my keys using the familiar
ActiveRecord::Base.connection.tables.each { |t| ActiveRecord::Base.connection.reset_pk_sequence!(t) }
incantation. Otherwise I get postgresql failures like this when I try to create new records:
PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "users_clients_pkey" DETAIL: Key (id)=(401) already exists. : INSERT INTO "users_clients" ("user_id", "client_id") VALUES (20, 46) RETURNING "id"
(This is an example; it happens on various tables, depending on what the first action is that's done on the app after a push.)
Once I do the reset-keys incantation, it's fine until my next push to heroku... even when my push does not include any migrations.
I'm a little baffled as to why this is happening and what can be done to prevent it.
No, there's no datatable manipulation code in my deployment tasks.
Its happening because the primary key(id) value already exists. Why? Because the primary key sequence in postgres is messed up. without looking at the database or knowing the schema, it difficult to suggest a solution but if your database can affort a downtime of 10-15mins. you can try
If there is just one table which is problem. you can Export all data into new set of table with new names without ID column.
drop existing tables and rename the newly created table to old tables's name.
enable writes to our app again.
But if entire DB is in a mess, then it need something more elaborate but I can't tell without looking the schema.
I'm using symfony 1.4 and doctrine. I've spent the last couple days playing with my schema, and I've gotten it to load up / build / behave properly but only on my local machine. When I copy the files to an account on Dreamhost, change the configuration to allow a connection to that database (and nothing else) I get the following error trying to delete something which should cascade (and does when I delete it on my local machine):
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent
row: a foreign key constraint fails (`ezshirtdb`.`item_options`, CONSTRAINT
`item_options_item_id_items_id` FOREIGN KEY (`item_id`) REFERENCES `items` (`id`))
This is my schema: http://pastie.org/1097068
These are my fixtures: http://pastie.org/1097072
The tables in the dreamhost DB are all InnoDB, the database itself seems to be MYISAM. Is that an issue? In this case, I can't delete Item #1, which has ItemOptions associated onto it, or any of the categories (which have items associated).
I'm totally lost, and could use a couple pointers. Thanks y'all.
I got errors like this a while back, and it was due to the foreign key being a different integer size after being generated.
Take a look at the database, and ensure that both the Items.ID field, and the ItemOptions.item_id field are the same type.
Delete the database and create it again. MyISAM or InnoDB, is irrelevant.