deleteAll doesn't work with foreign keys to other rows in same table - activejdbc

I have a Model class that has an attribute referencing another instance of the same Model class. Its basically a tree structure in one Model.
When I try to exectute MyModel.deleteAll() it fails because a foreign key constraint fails.
Is there someway to easily suspend this constraint for the deleteAll query?
The only workaround I've found, since I'm using mysql, is to issue a TRUNCATE statement, which mysql accepts straight away.
Thanks in advance,
Evan
Exception details:
org.javalite.activejdbc.DBException: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (visibledb_testing.accountabilities, CONSTRAINT accountabilities_prototype_id FOREIGN KEY (prototype_id) REFERENCES accountabilities (id)), query: DELETE FROM accountabilities

The Model#deleteAll() simply generates SQL DELETE FROM YOURTABLE.
If you can run this on MySQL console, it will work from the model. If you are getting constraint violation, maybe you want to:
Base.exec("TRUNCATE " + MyModel.getTableName());
Alternatively, you can try http://javalite.io/delete_cascade#method-deletecascade. BE CAREFUL- this is a powerful but dangerous method, only use after reading all docs.

Related

Inserting new record and skip if foreign key conflict in sql server 2008 R2

I have the problem similar to this one SQL Server foreign key conflict in a multi values statement? However, in sql server 2008.
While I am reading data from csv file, there is some id already not exist in parent and thus return this error:
INSERT statement conflicted with the FOREIGN KEY constraint
May I know if there is a way similar to MySQL insert ignore. Such that I can simply skip the problematic data.
I accept that if there is no method other than creating a stored procedure with a new temp table (insert into a table without foreign key first, and then re-insert with where foreign_id exists in (select id from parent)).
As I really cannot find any in documentation, asking for ensuring I didn't miss anything.
One general solution which comes to mind would be to temporarily turn off the foreign key constraints, and do the insert. Then, afterwards, you may run a cleanup script/query to remove or rectify child records which are pointing to parents which do not exist. Once your data is in good shape, then turn on the foreign key constraints again.
Read How can foreign key constraints be temporarily disabled using T-SQL? to learn how to disable/enable a foreign key constraint for a single table:
ALTER TABLE MyTable NOCHECK CONSTRAINT MyConstraint -- disable
ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT MyConstraint -- enable

Adding foreign key fails unless data is first removed and reinserted after

I have an odd issue with foreign keys. I am trying to perform the following query:
ALTER TABLE [GroupMember] FOREIGN KEY ([Group]) REFERENCES [Group]([GUID])
Which gives me the following error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__GroupMember__Group__0D25C822". The conflict occurred in database "x", table "dbo.Group", column 'GUID'.
I then verified the existing things, which I have confirmed are all ok:
Referenced table (dbo.Group) has a defined PRIMARY KEY on [GUID] column
Referencing table (dbo.GroupMember) has no [Group]-values which do not exist in [GUID]-column of dbo.Group-table
No similarly referencing foreign keys exist already
From here on, I experimented. Taking some rows in and out, wiping the table, truncating the table. What I can conclude so far:
If I wipe the referencing table using DELETE FROM [GroupMember]; then try to apply the FK constraint, I receive the same error message
If I truncate the referencing table using TRUNCATE TABLE [GroupMember];, I can apply the FK constraint without errors. Additionally, I am able to reinsert the exact same data after applying the FK constraint, without problems.
From this I can conclude that the data itself is not the problem. Can anyone make sense of this? Why am I able to apply the constraint after truncating the table, but not after deleting all records?
If you are using Microsoft SSMS check whether unchecking "Prevent saving changes that require table re-creation" solves the problem. You'll find this in Options > Designers > Table and Database Designers.
I have had similar issues that have been resolved by this. Let me know if it works or not.
Good luck.

MS SQL Server - What is the value of WITH CHECK in a foreign key constraint?

When I have SQL Server Management Studio generate a table creation script for me, the foreign key constraints are a bit different than how I would write them.
Here is one:
ALTER TABLE [dbo].[GeoBytesCountries]
WITH CHECK
ADD CONSTRAINT [FK_GeoBytesCountries_MapReferenceId]
FOREIGN KEY ([MapReferenceId])
REFERENCES [dbo].[GeoBytesMapReferences] ([MapReferenceId])
GO
ALTER TABLE [dbo].[GeoBytesCountries]
CHECK CONSTRAINT [FK_GeoBytesCountries_MapReferenceId]
GO
I would write this foreign key constraint without "WITH CHECK" and the 2nd "CHECK CONSTRAINT" statement and expect to get the same functionality.
Can someone explain to me the value of the using "WITH CHECK" and a separate "CHECK CONSTRAINT" statement when you are writing a foreign key constraint for a table?
Or is the code below completely / functionally equivalent to the code above?
ALTER TABLE [dbo].[GeoBytesCountries]
ADD CONSTRAINT [FK_GeoBytesCountries_MapReferenceId]
FOREIGN KEY ([MapReferenceId])
REFERENCES [dbo].[GeoBytesMapReferences] ([MapReferenceId])
GO
The way I see it, the two step approach allows you to at least keep more "bad" data from getting in assuming the with check part fails. That is, your constraint will exist and apply to DML from that point forward, but you may have to do some cleanup on your existing data to make it a trusted constraint.

H2 database Unsuccessful schema statement when add index and foreign key constraint

H2 does not appear to support the index/FK syntax generated by hibernate for the MySQL5 dialects when using ;MODE=MYSQL and hibernate with a dialect of org.hibernate.dialect.MySQL5Dialect.
My goal here is to have one set of SQL scripts and use hibernate for the ORM parts. Everything works fine in MySQL 5.5 but when I try to use H2 for things like unit tests and starting up a demo version of my app I get hundreds of failures from hibernate generated alter table statements as shown below. Unfortunately, I have not been able to find a way to get hibernate to change the way the statements are generated but that might be an option as well. I tried using org.hibernate.dialect.H2Dialect but that produces more severe errors so I don't think that will work.
alter table SAM_PUBLISHEDSECUREDIP_T
add index FK1EDEA25B9482C945 (ASSESSMENTID),
add constraint FK1EDEA25B9482C945 foreign key (ASSESSMENTID)
references SAM_PUBLISHEDASSESSMENT_T (ID)
Results in an error like this in H2:
org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "ALTER
TABLE SAM_PUBLISHEDSECUREDIP_T ADD INDEX FK1EDEA25B9482C945
(ASSESSMENTID),[*] ADD CONSTRAINT FK1EDEA25B9482C945 FOREIGN KEY
(ASSESSMENTID) REFERENCES SAM_PUBLISHEDASSESSMENT_T (ID) "; SQL
statement: alter table SAM_PUBLISHEDSECUREDIP_T add index
FK1EDEA25B9482C945 (ASSESSMENTID), add constraint FK1EDEA25B9482C945
foreign key (ASSESSMENTID) references SAM_PUBLISHEDASSESSMENT_T (ID)
[42000-172]
NOTE: I am open to writing and providing a patch for H2 but I could use some tips on where to look in that codebase.
H2 is not 100% compatible with MySQL, even when using the MySQL mode. It seems some of your SQL statements are not supported by H2.
Creating an index is not done using alter table (does MySQL really use this strange syntax? Every DBMS I know uses CREATE INDEX to create an index).
You have to split this up in two statements:
CREATE INDEX fk_assessment_id_index
on SAM_PUBLISHEDSECUREDIP_T (ASSESSMENTID);
alter table SAM_PUBLISHEDSECUREDIP_T
add constraint FK1EDEA25B9482C945 foreign key (ASSESSMENTID)
references SAM_PUBLISHEDASSESSMENT_T (ID);
Those two statements should also work in MySQL if I'm not mistaken.

Problem with an SQL statement

I'm having a problem with an SQL statement.
I want to activate a "ON UPDATE CASCADE" behavior for a foreign key in a table with this statement :
ALTER TABLE "DB"."RECORD" ADD CONSTRAINT "RECORD_PT_OUTIL_FK1" FOREIGN KEY ("CDE_PO")
REFERENCES "DB"."PT_OUTIL" ("CDE_PO") ON UPDATE CASCADE ENABLE;
But when i run the statement in Oracle Developer, i just get this error message : "ORA-00905 : missing keyword"
I can't find what could be this missing keyword, i tried several changes but always the same error occurs.
I reuse a code generated by Oracle Developer it self and just modify it with what i want.
This is the generated code :
ALTER TABLE "DB"."RECORD" ADD CONSTRAINT "RECORD_PT_OUTIL_FK1" FOREIGN KEY ("CDE_PO")
REFERENCES "DB"."PT_OUTIL" ("CDE_PO") ON DELETE CASCADE DISABLE;
See, i just change the end of it.
So what's the matter here ? Am i missing something ? (please don't bash if it's something obvious :) )
Thx !
Oracle does not support the ON UPDATE clause for foreign keys.
See the description of the REFERENCES clause in the manual:
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/clauses002.htm#CJAIHHGC
Try by removing the DISABLE/ ENABLE at the end of your command
As per the ADD CONSTRAINT reference, there doesnt seem to be any "Enable / Disable" as part of the command.
I think it is something that your Oracle Developer is adding at the end (it being part of Oracle Syntax) and it might be causing the problem!!