Unusual 1452 error with Doctrine - mysql

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.

Related

Not sure why this syntax error is happening

Hi I'm not very familiar with MySQL as I have only started using it today and I keep getting this syntax error and am not really sure what the problem is. I have attached a screenshot of the code and also pasted it below with the error in bold.
I'm sorry if this is a silly error that is easily fixed I'm just not sure how to fix it and would be very appreciative of any help.
CREATE TABLE copy (
`code` INT NOT NULL,
isbn CHAR(17) NOT NULL,
duration TINYINT NOT NULL,
CONSTRAINT pkcopy PRIMARY KEY (isbn, `code`),
CONSTRAINT fkcopy FOREIGN KEY (isbn) REFERENCES book (isbn));
CREATE TABLE student (
`no` INT NOT NULL,
`name` VARCHAR(30) NOT NULL,
school CHAR(3) NOT NULL,
embargo BIT NOT NULL,
CONSTRAINT pkstudent PRIMARY KEY (`no`));
CREATE TABLE loan (
`code` INT NOT NULL,
`no` INT NOT NULL,
taken DATE NOT NULL,
due DATE NOT NULL,
`return` DATE NULL,
CONSTRAINT pkloan PRIMARY KEY (taken, `code`, `no`),
CONSTRAINT fkloan FOREIGN KEY (`code`, `no`) REFERENCES copy, student **(**`code`, `no`));
Create the tables first, then use the ALTER TABLE statement to add the foreign keys one by one. You won't be able to call two different tables on the foreign key, so you'll have to use an ID that maps to both. Here is an example to add the foreign keys after the table has been created:
Add a new table named vendors and change the products table to include the vendor id field:
USE dbdemo;
CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
To add a foreign key to the products table, you use the following statement:
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;

Error code 1215: cannot add foreign key constraint MySQL

I'm having a problem creating a database in MySQL.
The error code:'Error code 1215: cannot add foreign key constraint' pops up when i try to implement my changes. I've paid attention to all the necessary things but i can't find the solution.
This error only happened after i added some tables after having made an initial database(which did work), so hopefully i'm not dealing with this problem throughout the whole project.
Here's a snippet of the code in which the error occurs, the foreign key that's not working correctly is 'tournament_id' referencing to 'id' in tournament:
CREATE DATABASE allin;
USE allin;
CREATE TABLE employee (
phone_number char(12) NOT NULL,
birth_date date NOT NULL,
tournament_id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(phone_number),
FOREIGN KEY(tournament_id) REFERENCES tournament(id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Second table:
CREATE TABLE tournament (
id int NOT NULL AUTO_INCREMENT,
date date NOT NULL,
time time NOT NULL,
cost decimal(5,2) NOT NULL,
min_players int NOT NULL,
min_age int NOT NULL,
max_age int NOT NULL,
location_id int NULL,
winner_id int NULL,
type varchar(40) NULL,
PRIMARY KEY(id),
FOREIGN KEY(winner_id) REFERENCES player(id) ON DELETE SET NULL ON UPDATE CASCADE,
FOREIGN KEY(location_id) REFERENCES event_location(id) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The issue is here:
FOREIGN KEY(tournament_id) REFERENCES tournament(id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
the above query is of CREATE TABLE employee. In this query, you are creating a FOREIGN KEY that refers to tournament(id), but as of now there is no tournament table exist in the specified database as the tournament table create query is reside below in the sequence.
I layman terms we can say, you are trying to refer a table column that
do not exist.
So to resolve this, run all you parent table creation query first, and than child table.
tournament_id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(phone_number)
Hey, I don't think you could set another primary key while an "auto increment" already exist

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 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;

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

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