MySQL foreign key restrictions are not being saved - mysql

I'm using MySQL version 5.5.25 and trying to create a foreign key from id_parent to id on the same table.
CREATE TABLE `acl_roles` (
`id` int(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(60) NOT NULL,
`id_parent` int(20) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_acl_roles` (`id_parent`),
CONSTRAINT `FK_acl_roles` FOREIGN KEY (`id_parent`) REFERENCES `acl_roles` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
When I do
ALTER TABLE `acl_roles` ADD CONSTRAINT `FK_acl_roles` FOREIGN KEY (`id_parent`) REFERENCES `acl_roles` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT ;
For some reason the latter executes without error yet when I execute SHOW CREATE TABLE acl_roles I get the exact same schema and the restrictions are not applied no matter how many times I run the query.

ON DELETE RESTRICT ON UPDATE RESTRICT is the default behavior for FK constraints, that is why you see no difference when viewing the schema. It is implied.

Related

MySQL inconsistently altering name of indexes associated with foreign keys on InnoDB tables

I seem to have encountered an inconsistency in the way an ALTER TABLE statement behaves when dropping and adding a foreign key. Sometimes the associated index will be renamed and other times it isn't. I have identified the situations under which this occurs:
APPROACH #1
A simple person table with an auto-incrementing primary key id and a foreign key column to itself self_id. Note: the behaviour would be the same for two separate tables, I have used one table to simplify the example.
CREATE TABLE `person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`self_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `self_id_fk` (`self_id`),
CONSTRAINT `self_id_fk` FOREIGN KEY (`self_id`) REFERENCES `person` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Next I rename the foreign key by dropping the existing one and then adding a new one. This is done in a single statement but the behaviour is the same if split into multiple ALTER TABLE statements.
ALTER TABLE `person`
DROP FOREIGN KEY `self_id_fk`,
ADD CONSTRAINT `a_new_fk_name` FOREIGN KEY (`self_id`) REFERENCES `person` (`id`);
After this statement the table is as follows:
CREATE TABLE `person` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`self_id` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `self_id_fk` (`self_id`),
CONSTRAINT `a_new_fk_name` FOREIGN KEY (`self_id`) REFERENCES `person` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Notice that the foreign key has been renamed but the index has not.
APPROACH #2
An alternative way of doing this would be to first create the table without any foreign keys or indexes:
CREATE TABLE `person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`self_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Next add the foreign key constraint:
ALTER TABLE `person` ADD CONSTRAINT `self_id_fk` FOREIGN KEY (`self_id`) REFERENCES `person` (`id`);
This results in the following table:
CREATE TABLE `person` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`self_id` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `self_id_fk` (`self_id`),
CONSTRAINT `self_id_fk` FOREIGN KEY (`self_id`) REFERENCES `person` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Note that an index is automatically created due to the behaviour described in the documentation
... an index is created on the referencing table automatically if it
does not exist
Next I rename the foreign key in the same way as APPROACH #1:
ALTER TABLE `person`
DROP FOREIGN KEY `self_id_fk`,
ADD CONSTRAINT `a_new_fk_name` FOREIGN KEY (`self_id`) REFERENCES `person` (`id`);
But this time both the foreign key and the index have been renamed:
CREATE TABLE `person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`self_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `a_new_fk_name` (`self_id`),
CONSTRAINT `a_new_fk_name` FOREIGN KEY (`self_id`) REFERENCES `person` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Is there any explanation into what's going on? It's almost as if MySQL is tracking which indexes are "auto created" and then renaming them when the foreign key is changed. The Table DDL is identical for both approaches before the ALTER TABLE statement is run so there must be some "internal engine state" that MySQL is tracking.
Looking at the DDL alone there is no way to predict in which way MySQL will behave when the ALTER TABLE statement is run. This means that two "schema identical" databases could end up with mismatched schema once a simple ALTER TABLE statement has run.
I have noticed the same thing, but I've never seen any official documentation that explains this.
I agree it seems like InnoDB "knows" which indexes were created implicitly and which were created explicitly. But I don't know where it tracks this information. InnoDB exposes much of the metadata in INFORMATION_SCHEMA tables, but it must store more information in the internal data dictionary.
This is the only documentation about the internal DD in MySQL 5.7 and earlier: https://dev.mysql.com/doc/refman/5.7/en/innodb-data-dictionary.html
The only suggestion I have is that if you need the index name to be predictable, you need to create the index explicitly, then create the foreign key constraint. Don't rely on implicit creation of indexes by foreign keys.
MySQL 8.0 has totally redesigned the data dictionary, so the behavior you observe might change yet again. https://dev.mysql.com/doc/refman/8.0/en/data-dictionary.html

Simple Relation between 2 tables

I have a problem here.
I cannot add this to my db because one table is dependent of another and vice-versa.
So I get
Cannot add foreign key constraint
on the first create table that I put
How can I add this 2 tables if they both have constraints??
-- User Roles
CREATE TABLE IF NOT EXISTS `user_roles` (
`user_role_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL,
`role` varchar(45) NOT NULL,
PRIMARY KEY (`user_role_id`),
UNIQUE KEY `uni_username_role` (`role`,`username`),
UNIQUE KEY `ix_auth_username` (`username`,`role`),
KEY `fk_username_idx` (`username`),
CONSTRAINT `fk_username` FOREIGN KEY (`username`) REFERENCES `users` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
-- Users
CREATE TABLE IF NOT EXISTS `users` (
`username` varchar(45) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`hashedPassword` varchar(500) NOT NULL,
`enabled` tinyint(1) NOT NULL DEFAULT '1',
`image` mediumblob,
`team` int(11) DEFAULT NULL,
`userRole` int(11) DEFAULT NULL,
PRIMARY KEY (`username`),
KEY `fkteam_idx` (`team`),
KEY `fkrole_idx` (`userRole`),
CONSTRAINT `fkrole` FOREIGN KEY (`userRole`) REFERENCES `user_roles` (`user_role_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fkteam` FOREIGN KEY (`team`) REFERENCES `team` (`idteam`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
To do this, you'll need to use deferrable constraint checks, but unfortunately MySQL does not implement this standard SQL feature.
As far as I know, only Oracle and PostgreSQL support this feature (deferrable constraints). These constraints are checked at the end of the transaction, and not on every single row insertion. That would solve your problem.
Therefore, you have two options:
Switch to Oracle or PostgreSQL (unlikely, I guess) or,
Change your table definition to allow one of the foreign key constraints to accept null values.
In the second case, you would:
Insert in the table that allow null in the FK, getting the generated ID.
Insert in the other table using the ID. Then, get the second generated ID.
Update the null in first table using the second ID.
Commit.
That's it.

Attempting to add a foreign key to a table fails?

I have two tables -
CREATE TABLE `FOO` (
`user_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
/*Nothing to see here*/
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=380 DEFAULT CHARSET=latin1;
CREATE TABLE `BAR` (
`ID` int(11) unsigned NOT NULL,
`UserID` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`ID`),
KEY `VSK_UserID_Index` (`UserID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I am attempting create a foreign key constraint on BAR.UserID referencing users.user_id -
ALTER TABLE `FOO`.`BAR`
ADD CONSTRAINT `BAR_UserID_FKey`
FOREIGN KEY (`UserID`)
REFERENCES `FOO`.`users` (`user_id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
I keep getting this error -
Operation failed: There was an error while applying the SQL script to the database.
Error 1452: Cannot add or update a child row: a foreign key constraint fails
Both of these tables have data in them - could this be the reason why this is happening, or is there something wrong with how the tables are being created?
Is there something I need to alter on one of these tables to make this work?
The data already in one of the tables (in particular, `FOO`.`BAR`, since that is the one you're adding a constraint to) is not consistent with the data in `FOO`.`users` (`user_id`).
You must ensure that the values un the `FOO`.`BAR`.`UserID` column all exist in `FOO`.`users` (`user_id`). There may be null values or other values that do not exist in the other column.

Constraints wrong according to mySQL

Not sure what I'm overseeing here, according to mySQL my constrains are malformed (the remarked part).
Didn't figure out yet what I did wrong using the allmighty internet search engine with G.
Advice greatly appreciated.
CREATE TABLE `documentsCustomers` (
`id` INT(12) NOT NULL AUTO_INCREMENT,
`document` INT(12) NOT NULL DEFAULT '0',
`customer` INT(12) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
INDEX `document` (`document`),
INDEX `customer` (`customer`)
/*,
CONSTRAINT `fk_document` FOREIGN KEY (`document`) REFERENCES `documents` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT,
CONSTRAINT `fk_customer` FOREIGN KEY (`customer`) REFERENCES `customers` (`ID`) ON UPDATE RESTRICT ON DELETE RESTRICT
*/
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1;
Note it is actually correct, one table having ID capital and the other one not.

What does it change between this two way of declaring a foreign key?

Good morning, I'm studing the SQL, and today I've found two ways of declaring a foreign key (for MySQL). I'd like to know what does it change between that two syntax and why should I need to set a name for the foreign key (Syntax 2).
Syntax 1:
CREATE TABLE `test2` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`idtest` int(10) unsigned NOT NULL,
`desc` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`idtest`) REFERENCES `test` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Syntax 2:
CREATE TABLE `test2` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`idtest` int(10) unsigned NOT NULL,
`desc` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_1` (`idtest`),
CONSTRAINT `FK_1` FOREIGN KEY (`idtest`) REFERENCES `test` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Thank you!
Functionally there is no difference.
The first example does name the Foreign Key, but it's the RDBMS that does the naming.
The second example lets you expressly name the Foreign Key yourself.
The ability to name the Foreign Key yourself allows you to communicate to other developers what the key means, and conform to standard naming conventions, etc.
The second syntax enables you to delete, modify or reuse that constraint at some point in the future.
The first syntax can not be changed as it is in the definition of the table.
The optional CONSTRAINT keyword allows you to specify a name for the foreign key. Without it, a name will be generated automatically.
This name can be seen in the INFORMATION_SCHEMA TABLE_CONSTRAINTS table.