Inserting data as foreign key constraint in grails - grails

Continuing to the post of reading-from-XML-and-storing-the-values-in-database-using-grails
am facing an another problem in it. As the employee id is related to other tables as foreign key how am suppose to insert the data into the database without conflict what i want to add in grails code to avoid the below displayed error.
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:Cannot
add or update a child rowL a foreign key constraint fails.. ( CONSTRAINT 'EMPLOYEE_ID_HEADER'
FOREIGN KEY ('EMPLOYEE_ID') REFERENCES 'employee_header'('employee_id'))
here employee_id is a column and employee_header is a separate table that contains employee_id as a foreign key.

Finally I got the answer, when you are inserting the values in database the related foreign key tables will get affects initially. So to handle this situation we have to insert the foreign key related table at first then the table we need to add exactly.
For the reference, at first I had given the code like this
sql.executeInsert("insert into order_item (order_id,product_id,
order_item_seq_id) values (${order_id},${product_id},${order_item_seq_id})")
sql.executeInsert("insert into product(product_id) values(${product_id})")
This first inserts the order_item table then the foreignkey constraint table product, so the data did not inserted. So the correct code is
sql.executeInsert("insert into order_header(order_id) values(${order_id})")
sql.executeInsert("insert into product(product_id) values(${product_id})")
sql.executeInsert("insert into order_item (order_id,product_id,
order_item_seq_id) values (${order_id},${product_id},${order_item_seq_id})")
Now this inserts the data successfully without errors.

Related

duplicate key value violates unique constraint. But there is no records in that table with the same details

I have a table with email as unique constraint. But when I try to insert the values. It showing unique constraint error, even there is no data in the table. If I try delete query it returns 0 results. I'm using PostgreSQL 12

Unable to find column names in a FK constraint

I have created two tables in Snowflake.
create or replace TRANSIENT TABLE TESTPARENT (
COL1 NUMBER(38,0) NOT NULL,
COL2 VARCHAR(16777216) NOT NULL,
COL3 VARCHAR(16777216) NOT NULL,
constraint UNIQ_COL3 unique (COL3)
);
create or replace TRANSIENT TABLE TESTCHILD3 (
COL_A NUMBER(38,0) NOT NULL,
COL_B NUMBER(38,0) NOT NULL,
ABCDEF VARCHAR(16777216) NOT NULL,
constraint FKEY_1 foreign key (COL_A, COL_B) references TEST_DB.PUBLIC.TESTPARENT1(COL1,COL2),
constraint FKEY_2 foreign key (ABCDEF) references TEST_DB.PUBLIC.TESTPARENT(COL3)
);
Now I want to execute a query and see the names of columns that are involved in FKEY_2 FOREIGN KEY
in Table TESTCHILD3, but it seems like there are no DB Table/View that keeps this information. I can find out the column names for UNIQUE KEY & PRIMARY KEY but there is nothing for FOREIGN KEYS.
EDIT
I have already tried INFORMATION_SCHEMA.TABLE_CONSTRAINTS, along with INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS and all the other system tables. No luck. Only DESC TABLE is giving me some info related to CONSTRAINTS and COLUMNS but that also has FOREIGN KEY CONSTRAINTS information missing.
SHOW IMPORTED KEYS IN TABLE <fk_table_name>;
Updated answer:
I was checking on something unrelated and noticed a very efficient way to list all primary and foreign keys:
show exported keys in account; -- Foreign keys
show primary keys in account;
When you limit the call to a table, it appears you have to request the foreign keys that point to the parent table:
show exported keys in table "DB_NAME"."SCHEMA_NAME"."PARENT_TABLE";
You can check the documentation for how to limit the show command to a specific database or schema, but this returns rich information in a table very quickly.
maybe you can try to query this view: INFORMATION_SCHEMA.TABLE_CONSTRAINTS
Note: TABLE_CONSTRAINTS only displays objects for which the current role for the session has been granted access privileges.
For more see: https://docs.snowflake.net/manuals/sql-reference/info-schema/table_constraints.html

Fluent Migrate Candidate Key

I have two tables One named "Root" which has columns Id,RootNumber, in which Id is primary Key.
Now when I tried to create another table with RootNumber as the foreign key I get below error
InnerException {"There are no primary or candidate keys in the
referenced table 'dbo.Root' that match the referencing column list in
the foreign key ("FK_CNTR_Root", \r\nCould not create constraint or
index. See previous errors."} System.Exception
{System.Data.SqlClient.SqlException}
this.CreateTableWithId32("CNTR", "Id", s => s
.WithColumn("CNTRNumber").AsString(10).NotNullable()
.WithColumn("CNTRName").AsString(10).NotNullable()
.WithColumn("RootNum").AsInt32().NotNullable()
.ForeignKey("FK_CNTR_Root", "Root", "RootNumber")
The error is very clear. You can make only the PrimaryKey column to be referenced as ForeignKey in another table. So Either make Id as a foreign key in other table or Change RootNumber to PrimaryKey of Root table.
Refer to this basic Foreign Key definition.

Sequelize : how to join on foreign keys

I'm using Sequelize and Node.js, and I need to join 2 tables on 2 foreign keys,
tableA.hasOne(tableB, { foreignKey: 'fk_tableB' });
tableB.belongsTo(tableA, {foreignKey: 'fk_tableB' });
(by the way, I don't understand the functionality of "targetKey")
but I can only obtain a join on tableA.primaryKey = tableB.fk_tableB.
How can I replace the tableA.primaryKey by tableA.fk_tableA?
I also tried to define twice tableA : in 2 different structures (one with the real primary key and the other with fk_tableA as primary key), but it's also not working (because I need the real tableA mode in another place).
Has someone an idea? Is it a bug from Sequelize?
How can I replace the tableA.primaryKey by tableA.fk_tableA?
There is no tableA.fk_tableA. But if there were, we would expect you to have named it that because column tableA.fk_tableA is a FK to a key column in tableA. Because that's the convention for naming a column fk_tableA. Similarly we would expect a belongTo like yours that adds a column that is a FK to the tableA PK to call it fk_tableA, not fk_tableB. Just like your hasOne gives tableA a column fk_tableB to the tableB PK. (If you want a FK to be to some other column than the PK then you say so via targetKey.)
If you so named FKs after their target table, you seem to want tableA.fk_tableB = tableB.fk_tableA. The way you have named them now, you seem to want tableA.fk_tableB = tableB.fk_tableB.
I need to join 2 tables on 2 foreign keys
It is extremely unlikely that you need the join above. Declaring a column to be a FK says that a value of the source/referencing column is always a value of the target/referenced column. Here targets are PKs. Such a join on a FK to one table and a FK to another table will only return rows that share the same PK value, even though the PKs are from different tables.

TEntity Remove method fails on many to many relationship that was created using database first

I am using Entity Framework 6.1.3 and a database first approach.
It is a small database with a many to many relationship between Tags and BoxedItems, a table named ItemsTags holds the relationship.
I get an exception when using the scaffolded code to delete a BoxedItem:
db.BoxedItems.Remove(boxedItem);
db.SaveChanges();
SqlException: The DELETE statement conflicted with the REFERENCE
constraint "FK_ItemsTags_Items". The conflict occurred in database
"TimeBox", table "dbo.ItemsTags", column 'IdItem'.
The relationship table code is bellow. The PK for BoxedItem needs to be a Guid and for Tags is a INT IDENTITY (1, 1).
CREATE TABLE [dbo].[ItemsTags] (
[IdItem] UNIQUEIDENTIFIER NOT NULL,
[IdTag] INT NOT NULL,
CONSTRAINT [PK_ItemsTags] PRIMARY KEY CLUSTERED ([IdItem] ASC, [IdTag] ASC),
CONSTRAINT [FK_ItemsTags_Tags] FOREIGN KEY ([IdTag]) REFERENCES [dbo].[Tags] ([Id]),
CONSTRAINT [FK_ItemsTags_Items] FOREIGN KEY ([IdItem]) REFERENCES [dbo].[BoxedItems] ([Id])
);
Would the EF auto generated code work out of the box if my BoxedItem PK was INT IDENTITY (1, 1)? EF seems to like it more for auto generated code.
Is there a smarter way to delete the BoxedItem, other than a custom SQL instruction?

Resources