What does the HsqlException "integrity constraint violation: foreign key no parent" mean? - hsqldb

I am getting this error in my HSQLDB :
Caused by: org.hsqldb.HsqlException: integrity constraint violation:
foreign key no parent; FK9GHQNBKBDJIGL1LN1V9DVN06O table: REVINFO
I initially thought it means that I was adding a null value to the column, however the key references a column (EDITORID) that is NULLABLE, so null values can be inserted.
I assume it is trying to add a value that does not yet exist in the referencing table, which I guess would make sense. However the exception does not tell me what actual value i am trying to insert.

updated: You were trying to insert a row with a value in the referencing column but there is no row with matching value in the referenced column. I checked the source code and although the actual value is added to the list of items to report, it is omitted when the error string is constructed. Therefore you need to rely on your code to report the value when you catch the SQLException until version 2.4.2 of HSQLDB enhances the reporting.

Related

The INSERT statement conflicted with the FOREIGN KEY constraint__ [duplicate]

I am getting the following error. Could you please help me?
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Sup_Item_Sup_Item_Cat". The conflict occurred in database "dev_bo", table "dbo.Sup_Item_Cat". The statement has been terminated.
Code:
insert into sup_item (supplier_id, sup_item_id, name, sup_item_cat_id,
status_code, last_modified_user_id, last_modified_timestamp, client_id)
values (10162425, 10, 'jaiso', '123123',
'a', '12', '2010-12-12', '1062425')
The last column client_id is causing the error. I tried to put the value which already exists in the dbo.Sup_Item_Cat into the column, corresponding to the sup_item.. but no joy :-(
In your table dbo.Sup_Item_Cat, it has a foreign key reference to another table. The way a FK works is it cannot have a value in that column that is not also in the primary key column of the referenced table.
If you have SQL Server Management Studio, open it up and sp_help 'dbo.Sup_Item_Cat'. See which column that FK is on, and which column of which table it references. You're inserting some bad data.
Let me know if you need anything explained better!
I had this issue myself, regarding the error message that is received trying to populate a foreign key field. I ended up on this page in hopes of finding the answer. The checked answer on this page is indeed the correct one, unfortunately I feel that the answer is a bit incomplete for people not as familiar with SQL. I am fairly apt at writing code but SQL queries are new to me as well as building database tables.
Despite the checked answer being correct:
Mike M wrote-
"The way a FK works is it cannot have a value in that column that is
not also in the primary key column of the referenced table."
What is missing from this answer is simply;
You must build the table containing the Primary Key first.
Another way to say it is;
You must Insert Data into the parent table, containing the Primary
Key, before attempting to insert data into the child table containing
the Foreign Key.
In short, many of the tutorials seem to be glazing over this fact so that if you were to try on your own and didn't realize there was an order of operations, then you would get this error. Naturally after adding the primary key data, your foreign key data in the child table must conform to the primary key field in the parent table, otherwise, you will still get this error.
If anyone read down this far. I hope this helped make the checked answer more clear. I know there are some of you who may feel that this sort of thing is pretty straight-forward and that opening a book would have answered this question before it was posted, but the truth is that not everyone learns in the same way.
You are trying to insert a record with a value in the foreign key column that doesn't exist in the foreign table.
For example: If you have Books and Authors tables where Books has a foreign key constraint on the Authors table and you try to insert a book record for which there is no author record.
You'll need to post your statement for more clarification. But...
That error means that the table you are inserting data into has a foreign key relationship with another table. Before data can be inserted, the value in the foreign key field must exist in the other table first.
The problem is not with client_id from what I can see. It looks more like the problem is with the 4th column, sup_item_cat_id
I would run
sp_helpconstraint sup_item
and pay attention to the constraint_keys column returned for the foreign key FK_Sup_Item_Sup_Item_Cat to confirm which column is the actual problem, but I am pretty sure it is not the one you are trying to fix. Besides '123123' looks suspect as well.
Something I found was that all the fields have to match EXACTLY.
For example, sending 'cat dog' is not the same as sending 'catdog'.
What I did to troubleshoot this was to script out the FK code from the table I was inserting data into, take note of the "Foreign Key" that had the constraints (in my case there were 2) and make sure those 2 fields values matched EXACTLY as they were in the table that was throwing the FK Constraint error.
Once I fixed the 2 fields giving my problems, life was good!
If you need a better explanation, let me know.
I ran into this problem when my insert value fields contained tabs and spaces that were not obvious to the naked eye. I had created my value list in Excel, copied, and pasted it to SQL, and run queries to find non-matches on my FK fields.
The match queries did not detect there were tabs and spaces in my FK field, but the INSERT did recognize them and it continued to generate the error.
I tested again by copying the content of the FK field in one record and pasting it into the insert query. When that record also failed, I looked closer at the data and finally detected the tabs/spaces.
Once I cleaned removed tabs/spaces, my issue was resolved. Hope this helps someone!
Double check the fields in the relationship the foreign key is defined for. SQL Server Management Studio may not have had the fields you wanted selected when you defined the relationship. This has burned me in the past.
run sp_helpconstraint
pay ATTENTION to the constraint_keys column returned for the foreign key
I had the same problem when I used code-first migrations to build my database for an MVC 5 application. I eventually found the seed method in my configuration.cs file to be causing the issue. My seed method was creating a table entry for the table containing the foreign key before creating the entry with the matching primary key.
Parent table data missing causes the problem.
In your problem non availability of data in "dbo.Sup_Item_Cat" causes the problem
I also got the same error in my SQL Code, This solution works for me,
Check the data in Primary Table May be you are entering a column value which is not present in the primary key column.
The problem was reproducible and intermittent for me using mybatis.
I'm sure I had correct DB configuration (PK, FK, auto increment etc)
I'm sure I had correct order of insertions (parent records first), in debug I could see parent record inserted with respective PK and just after that next statement failed with inserting child record with correct FK inside.
The problem was fixed by for reseeding identity with
DBCC CHECKIDENT ('schema.customer', RESEED, 0);
DBCC CHECKIDENT ('schema.account', RESEED, 0);
Exactly the same code that failed before started to work.
I would like somebody to explain me what was causing the issue.
In my case, I was inserting the values into the child table in the wrong order:
For the table with 2 columns: column1 and column2, I got this error when I mistakenly entered:
INSERT INTO Table VALUES('column2_value', 'column1_value');
The error was resolved when I used the below format:-
INSERT INTO Table (column2, column1) VALUES('column2_value', 'column1_value');
If your FK column table should contain that FK value as a primary key Value then data will be inserted.

Postgres ON CONFLICT ON CONSTRAINT triggering errors in the error log

I have a sql statement with ON CONFLICT ON CONSTRAINT in it to allow upserting. This seems to be working well except that my error logs have a bunch of errors related to this query.
I am confused by the error logging because we expect to run into this constraint and then just do the update - is there something broken here or is this just chatty logging?
RDS Postgres, version 12.7.
2021-12-18 16:00:32 UTC:172.31.1.154(33952):{username}#{database}:[28367]:ERROR: duplicate key value violates unique constraint "segments_sequence_number_event_id"
2021-12-18 16:00:32 UTC:172.31.1.154(33952):{username}#{database}:[28367]:DETAIL: Key (sequence_number, event_id)=(2, d5c70xxxx63478) already exists.
2021-12-18 16:00:32 UTC:172.31.1.154(33952):{username}#{database}:[28367]:STATEMENT: INSERT INTO segments (id,created_at,updated_at,event_id,sequence_number,start_time,end_time,bitrate,width,height) VALUES ('8e6d5xxxxbdae3','2021-12-18T16:00:32.596Z','2021-12-18T16:00:32.596Z','d5c70xxxx63478',2,1639843218000,1639843221000,2097152,1920,1080) ON CONFLICT ON CONSTRAINT sequence_number_event_id_unique DO UPDATE SET updated_at='2021-12-18T16:00:32.596Z',start_time=1639843218000,end_time=1639843221000,bitrate=2097152,width=1920,height=1080 RETURNING id,sequence_number,url,start_time,end_time,duration,bitrate,width,height,size,event_id,created_at,updated_at
Your ON CONFLICT clause uses ON CONSTRAINT sequence_number_event_id_unique
But the unique violation is raised by different constraint: unique constraint "segments_sequence_number_event_id"
To catch any and all conflicts, you can use ON CONFLICT DO NOTHING.
ON CONFLICT ... DO UPDATE can only catch a single "conflict target" (a single constraint, index, or index expressions).
Related:
How to use RETURNING with ON CONFLICT in PostgreSQL?
Aside: You don't have to pass values twice. You can just reuse values from excluded rows with:
...
SET (updated_at,start_time,end_time,bitrate,width,height)
= (EXCLUDED.updated_at,EXCLUDED.start_time,EXCLUDED.end_time,EXCLUDED.bitrate,EXCLUDED.width,EXCLUDED.height)
...
See:
How to UPSERT multiple rows with individual values in one statement?
Corner-case difference: Values from the EXCLUDED row include changes from possible triggers ON INSERT (which is typically desirable).

Error: The INSERT statement conflicted with the FOREIGN KEY constraint

A business user requested that I change a dropdown list to a textbox for creating records. The dropdown list is what was created by default for relating to tables in my database. As requested I made the change and replaced the dropdown list with an #Html.EditorFor element. I now get this error message when I try to create records. Is there a possible solution that can fix this error? There aren't any syntax errors that stop me from compiling my code. This error occurs at runtime.
This means that your forward thinking database designer placed a constraint in your database to stop people entering invalid values. Your application allows the user to enter invalid values, but luckily your database is stopping it.
A foreign key is how you ensure that a table only gets it's 'lookup' values from a valid list.
If you remove the constraint you will risk putting garbage into your database that is a great effort to fix.
If you start putting invalid values in this table it means things like inner joins stop working and data starts going missing in reports.
Need a bit more information such as tables being inserted and the foreign keys on it. Likely the text entered doesn't match that of the drop down. You would likely have to remove the foreign key. However if the design was that a numeric value was being inserted and not just a text one, The users now have a text area... where's the numeric value (I'm assuming some design here which is why I asked for tables and keys)? I'd likely do the following:
Change the table structure so that the value being inserted is character based (if not already)
Remove key constraint
Update the existing records so the text of the lookup value is replacing the numeric values (assuming numeric design of foreign key.
Drop original lookup table.
Alter design so code uses distinct on the column in the remaining table for it's list of values.
The alternative is that you'd have to insert the new text value first into the lookup table, then get it's new key value then do the insert statement. I suppose this could be handled with triggers and a before update statement but the question; but unless there's a reason to keep them separate, the above numbered list seems simpler in the long run
Previously with the dropdown, you were allowing the user to chose from the predefined values, i.e. values that were present in your lookup table to which you have put a foreign key constraint. But now as user can enter any value(which might not be present in the foreign table) thus resulting in this error.
To remove this error you can drop the constraint
ALTER TABLE <TABLE_NAME> DROP CONSTRAINT <FOREIGN_KEY_NAME>
or check the value(against the foreign key table) entered by user before inserting it.
UPDATE
If you have removed the foreign key constraint, then you'll have to insert any new(you'll have to check if data is new or old) data in the lookup table, assign it an ID and then insert this new ID in the main table to create the link between the two. NOTE: You can maintain the foreign key constraint in this case.

JDBC constraint exception details

I'm using JDBC to persist data to SQL Server and want to insert a new row into table that has a primary key, several foreign keys, and several uniqueness constraints on various columns. I am wondering how to handle constraint violations so that I can identify which fields need to be corrected (in order to report something meaningful to the user).
e.g:
table test: id (PRIMARY), fk_id (FOREIGN KEY), field1 (UNIQUE), field2 (UNIQUE)
Inserting a duplicate value in field1 OR field2 gives:
ErrorCode: 2627
SQLState: 23000
Violation of UNIQUE KEY constraint '<UNIQUE CONSTRAINT NAME>'. Cannot insert duplicate key in object 'dbo.test'. The duplicate key value is (<VALUE>).
However, this isn't enough to determine which field caused the exception (so I can tell the user, correct field1 or field2), short of parsing the error message and using the constraint name (which doesn't feel right and seems like a brittle solution).
The other way I can think of is to not rely on exceptions and instead query for any existing rows with the same value (manually checking for uniqueness before insertion). However, this requires potentially many queries in a serializable transaction (reducing concurrency). Worse, the transaction can deadlock and rollback if timing unfortunately conflicts with another transaction.
Is there a better way to achieve what I'm trying to do without having to parse (locale specific) exception messages?
What is the 'best practice' way?

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

I am getting the following error. Could you please help me?
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Sup_Item_Sup_Item_Cat". The conflict occurred in database "dev_bo", table "dbo.Sup_Item_Cat". The statement has been terminated.
Code:
insert into sup_item (supplier_id, sup_item_id, name, sup_item_cat_id,
status_code, last_modified_user_id, last_modified_timestamp, client_id)
values (10162425, 10, 'jaiso', '123123',
'a', '12', '2010-12-12', '1062425')
The last column client_id is causing the error. I tried to put the value which already exists in the dbo.Sup_Item_Cat into the column, corresponding to the sup_item.. but no joy :-(
In your table dbo.Sup_Item_Cat, it has a foreign key reference to another table. The way a FK works is it cannot have a value in that column that is not also in the primary key column of the referenced table.
If you have SQL Server Management Studio, open it up and sp_help 'dbo.Sup_Item_Cat'. See which column that FK is on, and which column of which table it references. You're inserting some bad data.
Let me know if you need anything explained better!
I had this issue myself, regarding the error message that is received trying to populate a foreign key field. I ended up on this page in hopes of finding the answer. The checked answer on this page is indeed the correct one, unfortunately I feel that the answer is a bit incomplete for people not as familiar with SQL. I am fairly apt at writing code but SQL queries are new to me as well as building database tables.
Despite the checked answer being correct:
Mike M wrote-
"The way a FK works is it cannot have a value in that column that is
not also in the primary key column of the referenced table."
What is missing from this answer is simply;
You must build the table containing the Primary Key first.
Another way to say it is;
You must Insert Data into the parent table, containing the Primary
Key, before attempting to insert data into the child table containing
the Foreign Key.
In short, many of the tutorials seem to be glazing over this fact so that if you were to try on your own and didn't realize there was an order of operations, then you would get this error. Naturally after adding the primary key data, your foreign key data in the child table must conform to the primary key field in the parent table, otherwise, you will still get this error.
If anyone read down this far. I hope this helped make the checked answer more clear. I know there are some of you who may feel that this sort of thing is pretty straight-forward and that opening a book would have answered this question before it was posted, but the truth is that not everyone learns in the same way.
You are trying to insert a record with a value in the foreign key column that doesn't exist in the foreign table.
For example: If you have Books and Authors tables where Books has a foreign key constraint on the Authors table and you try to insert a book record for which there is no author record.
You'll need to post your statement for more clarification. But...
That error means that the table you are inserting data into has a foreign key relationship with another table. Before data can be inserted, the value in the foreign key field must exist in the other table first.
The problem is not with client_id from what I can see. It looks more like the problem is with the 4th column, sup_item_cat_id
I would run
sp_helpconstraint sup_item
and pay attention to the constraint_keys column returned for the foreign key FK_Sup_Item_Sup_Item_Cat to confirm which column is the actual problem, but I am pretty sure it is not the one you are trying to fix. Besides '123123' looks suspect as well.
Something I found was that all the fields have to match EXACTLY.
For example, sending 'cat dog' is not the same as sending 'catdog'.
What I did to troubleshoot this was to script out the FK code from the table I was inserting data into, take note of the "Foreign Key" that had the constraints (in my case there were 2) and make sure those 2 fields values matched EXACTLY as they were in the table that was throwing the FK Constraint error.
Once I fixed the 2 fields giving my problems, life was good!
If you need a better explanation, let me know.
I ran into this problem when my insert value fields contained tabs and spaces that were not obvious to the naked eye. I had created my value list in Excel, copied, and pasted it to SQL, and run queries to find non-matches on my FK fields.
The match queries did not detect there were tabs and spaces in my FK field, but the INSERT did recognize them and it continued to generate the error.
I tested again by copying the content of the FK field in one record and pasting it into the insert query. When that record also failed, I looked closer at the data and finally detected the tabs/spaces.
Once I cleaned removed tabs/spaces, my issue was resolved. Hope this helps someone!
Double check the fields in the relationship the foreign key is defined for. SQL Server Management Studio may not have had the fields you wanted selected when you defined the relationship. This has burned me in the past.
run sp_helpconstraint
pay ATTENTION to the constraint_keys column returned for the foreign key
I had the same problem when I used code-first migrations to build my database for an MVC 5 application. I eventually found the seed method in my configuration.cs file to be causing the issue. My seed method was creating a table entry for the table containing the foreign key before creating the entry with the matching primary key.
Parent table data missing causes the problem.
In your problem non availability of data in "dbo.Sup_Item_Cat" causes the problem
I also got the same error in my SQL Code, This solution works for me,
Check the data in Primary Table May be you are entering a column value which is not present in the primary key column.
The problem was reproducible and intermittent for me using mybatis.
I'm sure I had correct DB configuration (PK, FK, auto increment etc)
I'm sure I had correct order of insertions (parent records first), in debug I could see parent record inserted with respective PK and just after that next statement failed with inserting child record with correct FK inside.
The problem was fixed by for reseeding identity with
DBCC CHECKIDENT ('schema.customer', RESEED, 0);
DBCC CHECKIDENT ('schema.account', RESEED, 0);
Exactly the same code that failed before started to work.
I would like somebody to explain me what was causing the issue.
In my case, I was inserting the values into the child table in the wrong order:
For the table with 2 columns: column1 and column2, I got this error when I mistakenly entered:
INSERT INTO Table VALUES('column2_value', 'column1_value');
The error was resolved when I used the below format:-
INSERT INTO Table (column2, column1) VALUES('column2_value', 'column1_value');
If your FK column table should contain that FK value as a primary key Value then data will be inserted.