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));
Related
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?
I have existing rails app that have some tables with some data. I did the CRUD operation directly from postgresql client before using activeadmin.
I don't know whether I missed the documentation or this is a bug: activeadmin cannot detect my existing autoincrement id for table.
If I refresh the submitted form until the auto increment id surpass the existing id in my table, it works.
First think which I could think of would be that you have passed the id parameter in permit params.
Please check that and if is present then remove it.
Secondly,as mentioned in the post that there are already data in the database so there is a problem with the sequences generated, since they can be only used once.
The solution is to set the sequence for your song_artists.id column to the highest value in the table with a query like this:
SELECT setval('song_artist_id_seq', (SELECT max(id) FROM song_artists));
I am assuming that your sequence name "song_artist_id_seq", table name "song_artist", and column name "id".
To get the sequence name run the below mentioned command:
SELECT pg_get_serial_sequence('tablename', 'columname');
For Resetting the postgres sequences from rails console:
ActiveRecord::Base.connection.tables.each do |t|
ActiveRecord::Base.connection.reset_pk_sequence!(t)
end
Another solution would be to override the save() method in your song_artist class to manually set the song_artist id for new records but is not advisable.
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.
I'm doing maintenance work on a Rails site that I inherited; it's driven by an Oracle database, and I've got access to both development and production installations of the site (each with its own Oracle DB). I'm running into an Oracle error when trying to insert data on the production site, but not the dev site:
ActiveRecord::StatementInvalid (OCIError: ORA-00001: unique constraint (DATABASE_NAME.PK_REGISTRATION_OWNERSHIP) violated: INSERT INTO registration_ownerships (updated_at, company_ownership_id, created_by, updated_by, registration_id, created_at) VALUES ('2006-05-04 16:30:47', 3, NULL, NULL, 2920, '2006-05-04 16:30:47')):
/usr/local/lib/ruby/gems/1.8/gems/activerecord-oracle-adapter-1.0.0.9250/lib/active_record/connection_adapters/oracle_adapter.rb:221:in `execute'
app/controllers/vendors_controller.rb:94:in `create'
As far as I can tell (I'm using Navicat as an Oracle client), the DB schema for the dev site is identical to that of the live site. I'm not an Oracle expert; can anyone shed light on why I'd be getting the error in one installation and not the other?
Incidentally, both dev and production registration_ownerships tables are populated with lots of data, including duplicate entries for country_ownership_id (driven by index PK_REGISTRATION_OWNERSHIP). Please let me know if you need more information to troubleshoot. I'm sorry I haven't given more already, but I just wasn't sure which details would be helpful.
UPDATE: I've tried dropping the constraint on the production server but it had no effect; I didn't want to drop the index as well because I'm not sure what the consequences might be and I don't want to make production less stable than it already is.
Curiously, I tried executing by hand the SQL that was throwing an error, and Oracle accepted the insert statement (though I had to wrap the dates in to_date() calls with string literals to get around an "ORA-01861: literal does not match format string" error). What might be going on here?
Based on the name of the constraint, PK_REGISTRATION_OWNERSHIP, you have a primary key violation. If these databases aren't maintaining this data in lockstep, something/someone has already inserted a record into the registration_ownerships table in your production database with company_ownership_id=2 & registration_id=2920. (I'm guessing at the specifics based on the names)
If this particular set of values needs to exist in the production database,
1) check that what's already there isn't what you're trying to insert. if it is, you're done.
2) If you need to insert your sample data as-is, you need to modify the existing data & re-insert it (and all the dependent/refering records), then you can insert your values.
If you query the table and find no matching rows, then one of the following may be the cause:
The session is trying to insert the row twice.
Another session has inserted the row, but hasn't committed yet.
Also, check that the state of the unique constraint is the same between dev and prod. Perhaps the one on dev is marked as not validated - check that the index exists on dev and is a unique index (note: in Oracle it is possible to have a unique constraint validated by a non-unique index).
Take a hard look at the underlying unique index for the constraint. The reason dropping the constraint doesn't change anything is because the index remains, and it's a unique index. What does the following tell you about the indexes in both environments? Are both indexes valid? Are both defined the same? Are they both actually unique?
SELECT ai.table_name, ai.index_name, ai.uniqueness, aic.column_name, ai.status
FROM all_constraints ac JOIN all_indexes ai ON (ac.index_name = ai.index_name)
JOIN all_ind_columns aic ON (ai.index_name = aic.index_name)
WHERE ac.owner = 'YOUR_USER'
AND ac.constraint_name = 'PK_REGISTRATION_OWNERSHIP'
ORDER BY ai.index_name, column_position;
As it happens, there was a spare copy of the "registrations" model lying around the directory; even though it had a different name ("registrations_2349871.rb" or something like that) Rails was running all model functionality (saving, validating, etc) twice, hence the key constraint violation! I've never seen behavior like this before. Deleting the rogue file solved the problem.