"SQLSTATE[23000]: Integrity constraint violation" with valid constraint - mysql

I'm using Symfony 2 with Doctrine.
I have 4 classes: Country, District, County and Local. District has a foreign key of Country; County has a foreign of District; Local has a foreign key of District.
The problem is that when inserting a County (using data fixtures), I get the error
SQLSTATE[23000]: Integrity constraint violation:
I dumped the SQL to create the tables and constraints and got this:
CREATE TABLE Country (id INT AUTO_INCREMENT NOT NULL,
name VARCHAR(255) NOT NULL,
insertedAt DATETIME NOT NULL,
flag LONGTEXT DEFAULT NULL COMMENT '(DC2Type:object)',
PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE County (id INT AUTO_INCREMENT NOT NULL,
name VARCHAR(255) NOT NULL,
insertedAt DATETIME NOT NULL,
insertedBy INT NOT NULL,
idDistrict INT NOT NULL,
INDEX IDX_5F4EFA13438082DC (insertedBy),
INDEX IDX_5F4EFA1362627EDC (idDistrict),
PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE District (id INT AUTO_INCREMENT NOT NULL,
name VARCHAR(255) NOT NULL,
insertedAt DATETIME NOT NULL,
insertedBy INT NOT NULL,
idCountry INT NOT NULL,
INDEX IDX_C8B736D1438082DC (insertedBy),
INDEX IDX_C8B736D143CAA294 (idCountry),
PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE LOCAL (id INT AUTO_INCREMENT NOT NULL,
name VARCHAR(255) NOT NULL,
insertedAt DATETIME NOT NULL,
insertedBy INT NOT NULL,
idCounty INT NOT NULL,
INDEX IDX_4A17A7EC438082DC (insertedBy),
INDEX IDX_4A17A7EC3BF357BF (idCounty),
PRIMARY KEY(id)) ENGINE = InnoDB;
ALTER TABLE County ADD CONSTRAINT FK_5F4EFA13438082DC
FOREIGN KEY (insertedBy) REFERENCES Account(id);
ALTER TABLE County ADD CONSTRAINT FK_5F4EFA1362627EDC
FOREIGN KEY (idDistrict) REFERENCES District(id);
ALTER TABLE District ADD CONSTRAINT FK_C8B736D1438082DC
FOREIGN KEY (insertedBy) REFERENCES Account(id);
ALTER TABLE District ADD CONSTRAINT FK_C8B736D143CAA294
FOREIGN KEY (idCountry) REFERENCES Country(id);
ALTER TABLE LOCAL ADD CONSTRAINT FK_4A17A7EC438082DC
FOREIGN KEY (insertedBy) REFERENCES Account(id);
ALTER TABLE LOCAL ADD CONSTRAINT FK_4A17A7EC3BF357BF
FOREIGN KEY (idCounty) REFERENCES County(id);
The problem is not in the DataFixture itself because I tried to insert a County using PhpMyAdmin and got the same error.
All tables are created in InnoDB engine and I can successfully create a Country and a District. The error occurs only with the County entity.
Thanks

Your fixture file is probably attempting to insert a row for County for which there is no corresponding row matching the accountId or the districtId.
ALTER TABLE County ADD CONSTRAINT FK_5F4EFA13438082DC
FOREIGN KEY (insertedBy) REFERENCES Account(id);
This key forces you to ensure that the accountid you enter into the County table has a matching id in the account table.
ALTER TABLE County ADD CONSTRAINT FK_5F4EFA1362627EDC
FOREIGN KEY (idDistrict) REFERENCES District(id);
Same as accountId, except no matching id in the district table.
So double check your fixtures file and ensure that that district and account rows are inserted (and committed) before you insert a county row.

Actually there is a bug in MySQL server 5.6.33-79.0
Percona Server (GPL), Release 79.0, Revision 2084bdb
in Linux (x86_64)

Unistalled MAMP Pro and installed apache, mysql and php one by one. Same project worked under this new environment

Related

Converting MySQL code to PostgreSQL using foreign keys

I am trying to create tables with a primary key and foreign key in Postgresql. Originally was created in MySQL but I do not know how to convert can someone assist.
I converted the first table but the instructor table is giving me problems
CREATE TABLE instructor_detail (
id SERIAL PRIMARY KEY,
youtube_channel VARCHAR(128) NULL,
hobby VARCHAR(45) NULL
);
DROP TABLE IF EXISTS instructor;
`CREATE TABLE instructor (
id SERIAL PRIMARY KEY,
first_name VARCHAR(45) NULL,
last_name VARCHAR(45) NULL,
email VARCHAR(45) NULL,
instructor_detail_id INT NULL,
CREATE INDEX fk_detail_idx ON instructor (instructor_detail_id), CONSTRAINT fk_detail FOREIGN KEY (instructor_detail_id) REFERENCES instructor_detail (id) ON DELETE NO ACTION ON UPDATE NO ACTION
);`
ERROR: syntax error at or near "CREATE"
LINE 7: CREATE INDEX fk_detail_idx ON instructor (instructor_detai...
The foreign key constraint will work in PostgreSQL, no change is required.
The KEY clause is a MySQL extension to create an index within CREATE TABLE, which PostgreSQL does not support.
You'll have to convert the KEY clause to a separate CREATE INDEX statement in PostgresSQL.

MySQL - Error Code 1215, cannot add foreign key constraint

i got these two succesfull queries:
create table Donors (
donor_id int not null auto_increment primary key,
gender varchar(1) not null,
date_of_birth date not null,
first_name varchar(20) not null,
middle_name varchar(20),
last_name varchar(30) not null,
home_phone tinyint(10),
work_phone tinyint(10),
cell_mobile_phone tinyint(10),
medical_condition text,
other_details text );
and
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id) );
but when i try this one:
create table Medical_Conditions (
condition_code int not null,
condition_name varchar(50) not null,
condition_description text,
other_details text,
primary key(condition_code),
foreign key(condition_code) references Donors_Medical_Condition(condition_code) );
i get "Error Code: 1215, cannot add foreign key constraint"
i dont know what am i doing wrong.
In MySql, a foreign key reference needs to reference to an index (including primary key), where the first part of the index matches the foreign key field. If you create an an index on condition_code or change the primary key st that condition_code is first you should be able to create the index.
To define a foreign key, the referenced parent field must have an index defined on it.
As per documentation on foreign key constraints:
REFERENCES tbl_name (index_col_name,...)
Define an INDEX on condition_code in parent table Donors_Medical_Condition and it should be working.
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
KEY ( condition_code ), -- <---- this is newly added index key
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id) );
But it seems you defined your tables order and references wrongly.
You should have defined foreign key in Donors_Medical_Condition table but not in Donors_Medical_Conditions table. The latter seems to be a parent.
Modify your script accordingly.
They should be written as:
-- create parent table first ( general practice )
create table Medical_Conditions (
condition_code int not null,
condition_name varchar(50) not null,
condition_description text,
other_details text,
primary key(condition_code)
);
-- child table of Medical_Conditions
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id),
foreign key(condition_code)
references Donors_Medical_Condition(condition_code)
);
Refer to:
MySQL Using FOREIGN KEY Constraints
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION
A workaround for those who need a quick how-to:
FYI: My issue was NOT caused by the inconsistency of the columns’ data types/sizes, collation or InnoDB storage engine.
How to:
Download a MySQL workbench and use it’s GUI to add foreign key. That’s it!
Why:
The error DOES have something to do with indexes. I learned this from the DML script automatically generated by the MySQL workbench. Which also helped me to rule out all those inconsistency possibilities.It applies to one of the conditions to which the foreign key definition subject. That is: “MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan.” Here is the official statement: http://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html
I did not get the idea of adding an index ON the foreign key column(in the child table), only paid attention to the referenced TO column(in the parent table).
Here is the auto-generated script(PHONE.PERSON_ID did not have index originally):
ALTER TABLE `netctoss`.`phone`
ADD INDEX `personfk_idx` (`PERSON_ID` ASC);
ALTER TABLE `netctoss`.`phone`
ADD CONSTRAINT `personfk`
FOREIGN KEY (`PERSON_ID`)
REFERENCES `netctoss`.`person` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
I think you've got your tables a bit backwards. I'm assuming that Donors_Medical_Condtion links donors and medical conditions, so you want a foreign key for donors and conditions on that table.
UPDATED
Ok, you're also creating your tables in the wrong order. Here's the entire script:
create table Donors (
donor_id int not null auto_increment primary key,
gender varchar(1) not null,
date_of_birth date not null,
first_name varchar(20) not null,
middle_name varchar(20),
last_name varchar(30) not null,
home_phone tinyint(10),
work_phone tinyint(10),
cell_mobile_phone tinyint(10),
medical_condition text,
other_details text );
create table Medical_Conditions (
condition_code int not null,
condition_name varchar(50) not null,
condition_description text,
other_details text,
primary key(condition_code) );
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id),
foreign key(condition_code) references Medical_Conditions(condition_code) );
I got the same issue and as per given answers, I verified all datatype and reference but every time I recreate my tables I get this error. After spending couple of hours I came to know below command which gave me inside of error-
SHOW ENGINE INNODB STATUS;
LATEST FOREIGN KEY ERROR
------------------------
2015-05-16 00:55:24 12af3b000 Error in foreign key constraint of table letmecall/lmc_service_result_ext:
there is no index in referenced table which would contain
the columns as the first columns, or the data types in the
referenced table do not match the ones in table. Constraint:
,
CONSTRAINT "fk_SERVICE_RESULT_EXT_LMC_SERVICE_RESULT1" FOREIGN KEY ("FK_SERVICE_RESULT") REFERENCES "LMC_SERVICE_RESULT" ("SERVICE_RESULT") ON DELETE NO ACTION ON UPDATE NO ACTION
I removed all relation using mysql workbench but still I see same error. After spending few more minutes, I execute below statement to see all constraint available in DB-
select * from information_schema.table_constraints where
constraint_schema = 'XXXXX'
I was wondering that I have removed all relationship using mysql workbench but still that constraint was there. And the reason was that because this constraint was already created in db.
Since it was my test DB So I dropped DB and when I recreate all table along with this table then it worked. So solution was that this constraint must be deleted from DB before creating new tables.
Check that both fields are the same size and if the referenced field is unsigned then the referencing field should also be unsigned.

MySQL error for 2 tables cannot add foreign key constraint

I am trying to create 2 tables in the same database. however it still cannot create foreign key.
create table countryadrc
(
adrc char(3) not null,
county varchar(30) not null,
primary key (adrc),
unique (adrc, county)
);
it is the other table which observe the error
create table localities
(
county varchar(30) not null,
locality tinyint not null,
primary key (county),
foreign key (county) references countryadrc (county)
);
Your schema seems to be a little strange but you can technically make it work if you swap columns in UNIQUE constraint in countryadrc table.
Using FOREIGN KEY Constraints
... In the referencing table, there must be an index where the foreign key
columns are listed as the first columns in the same order ...
create table countryadrc
(
adrc char(3) not null,
county varchar(30) not null,
primary key (adrc),
unique (county, adrc) -- county should be the leftmost column in the index
);
Here is SQLFiddle demo

mysql error 150: cannot create table

I am stuck with this error no 150 problem in mysql and I know there have been questions
which discuss this problem but I still can't find where I am wrong. Here is the database I am trying to create:
create table business (
ident varchar(40) NOT NULL,
name varchar(50) NOT NULL,
rating INT UNSIGNED NOT NULL,
PRIMARY KEY(ident)
) ENGINE=InnoDB;
create table deals (
business_id varchar(40) NOT NULL,
deals_id varchar(20) NOT NULL,
deals_title varchar(50) NOT NULL,
PRIMARY KEY (business_id, deals_id),
FOREIGN KEY (business_id) REFERENCES business(ident) ON DELETE CASCADE
) ENGINE=InnoDB;
create table d_options (
business_id varchar(40) NOT NULL,
dealid varchar(20) NOT NULL,
option_title varchar(40) NOT NULL,
PRIMARY KEY(business_id, dealid, option_title),
FOREIGN KEY(business_id) REFERENCES business(ident) ON DELETE CASCADE,
FOREIGN KEY(dealid) REFERENCES deals(deals_id)
) ENGINE=InnoDB;
I get error: ERROR 1005 (HY000): Can't create table 'test.d_options' (errno: 150)
I know for foreign key constraints to be satisfied there should be a index in the parent table as per mysql documentation, but I think that there is by default indexing
on primary key.
The result of innodb status is:
120530 0:47:48 Error in foreign key constraint of table test/d_options:
FOREIGN KEY(dealid) REFERENCES deals(deals_id)
) ENGINE=InnoDB:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Any help is appriciated.
You have a compound primary key on (business_id, deal_id) and they are indexed as a pair, but to satisfy the FK, you need another index on deal_id alone:
create table deals (
business_id varchar(40) NOT NULL,
deals_id varchar(20) NOT NULL,
deals_title varchar(50) NOT NULL,
PRIMARY KEY (business_id, deals_id),
FOREIGN KEY (business_id) REFERENCES business(ident) ON DELETE CASCADE,
/* Add an index on deals_id, separate from the compound PK */
INDEX idx_deals_id (deals_id)
) ENGINE=InnoDB;

Unusual 1452 error with Doctrine

I'm currently breaking my head on a 1452 error (using Symfony2 with doctrine).
Here is the case:
I have 3 tables, Location, Concert and CD, and as expected a Concert take place at a Location, and a CD is related to a Concert, that's including some foreign keys.
Here is the SQL queries generated by doctrine to create the database:
CREATE TABLE CD (id INT AUTO_INCREMENT NOT NULL, concert INT NOT NULL, number INT NOT NULL, INDEX IDX_EB3C8BB0D57C02D2 (concert), PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE Concert (id INT AUTO_INCREMENT NOT NULL, location INT NOT NULL, date DATETIME NOT NULL, name VARCHAR(255) DEFAULT NULL, INDEX IDX_1AC13B4E5E9E89CB (location), PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE Location (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(40) NOT NULL, city VARCHAR(40) NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB;
ALTER TABLE CD ADD CONSTRAINT FK_EB3C8BB0D57C02D2 FOREIGN KEY (concert) REFERENCES Concert(id) ON UPDATE CASCADE ON DELETE CASCADE;
ALTER TABLE Concert ADD CONSTRAINT FK_1AC13B4E5E9E89CB FOREIGN KEY (location) REFERENCES Location(id) ON UPDATE CASCADE ON DELETE CASCADE;
The fact is, there is no problem to insert Location, and a connected Concert, to satisfy the CD's foreign key:
INSERT INTO Location (id, name, city) VALUES (NULL, 'Church', 'Berlin');
INSERT INTO Concert (id, location, date, name) VALUES (NULL, '1', '2012-06-20 19:30:00', NULL);
But then if I try to insert a CD:
INSERT INTO CD (id ,concert ,number) VALUES (NULL , '1', '1');
I got the famous error:
Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`festival`.`cd`, CONSTRAINT `FK_EB3C8BB0D57C02D2` FOREIGN KEY (`concert`) REFERENCES `Concert` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
So I've tried some hacks:
Escape the creation of the table Location and the related key:
CREATE TABLE CD (id INT AUTO_INCREMENT NOT NULL, concert INT NOT NULL, number INT NOT NULL, INDEX IDX_EB3C8BB0D57C02D2 (concert), PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE Concert (id INT AUTO_INCREMENT NOT NULL, location INT NOT NULL, date DATETIME NOT NULL, name VARCHAR(255) DEFAULT NULL, INDEX IDX_1AC13B4E5E9E89CB (location), PRIMARY KEY(id)) ENGINE = InnoDB;
ALTER TABLE CD ADD CONSTRAINT FK_EB3C8BB0D57C02D2 FOREIGN KEY (concert) REFERENCES Concert(id) ON UPDATE CASCADE ON DELETE CASCADE;
That's working well.
Delete the table Location after creation (and the related key):
CREATE TABLE CD (id INT AUTO_INCREMENT NOT NULL, concert INT NOT NULL, number INT NOT NULL, INDEX IDX_EB3C8BB0D57C02D2 (concert), PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE Concert (id INT AUTO_INCREMENT NOT NULL, location INT NOT NULL, date DATETIME NOT NULL, name VARCHAR(255) DEFAULT NULL, INDEX IDX_1AC13B4E5E9E89CB (location), PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE Location (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(40) NOT NULL, city VARCHAR(40) NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB;
ALTER TABLE CD ADD CONSTRAINT FK_EB3C8BB0D57C02D2 FOREIGN KEY (concert) REFERENCES Concert(id) ON UPDATE CASCADE ON DELETE CASCADE;
ALTER TABLE Concert ADD CONSTRAINT FK_1AC13B4E5E9E89CB FOREIGN KEY (location) REFERENCES Location(id) ON UPDATE CASCADE ON DELETE CASCADE;
ALTER TABLE Concert DROP FOREIGN KEY FK_1AC13B4E5E9E89CB;
ALTER TABLE Concert DROP INDEX IDX_1AC13B4E5E9E89CB;
DROP TABLE Location;
Same error.
Escape foreign key controlling
SET FOREIGN_KEY_CHECKS = 0;
Same error.
The two last tries, make me think of some index issue on the link Concert-Location ?
You understand, I am a bit lost.
Does anyone have already faced something similar ?
Thank a lot for knowledge,
Tom.
So,
According to MySQL documentation, MySQL server since 5.5.9 on OSX, fails on insertion with foreign keys. This bug seems to come with case sensitivity.
There is many ways to fix it (this list is non-exhaustive, and some options may not be effective):
Use only lowercase tables names.
Try to set lower_case_table_names to O or 1 (but on OS X it's not always possible cause of system's case sensitivity).
Downgrade to MySQL server 5.5.8 (I've not tested upgrading).
Thanks to this thread.