vitessio / vitess

Vitess is a database clustering system for horizontal scaling of MySQL.
http://vitess.io
Apache License 2.0
18.18k stars 2.06k forks source link

CopySchemaShard should disable FOREIGN_KEY_CHECKS when applying schema #8206

Open bnu0 opened 3 years ago

bnu0 commented 3 years ago

Problem Description

CopySchemaShard will error out if the schema has any foreign keys, where any table that has a lexicographically lesser name references a table that has a lexicographically greater name.

For example:

create table b (
  id int not null primary key
);

create table a (
  id int not null primary key, 
  b_ref int, 
  foreign key (b_ref) references b (id)
);

When you use CopySchemaShard to copy this to a new keyspace, it will try to create a before b, but error with a SQL error Foreign key constraint is incorrectly formed.

Proposal

Vitess should wrap each CREATE TABLE (or the entire batch) with

SET FOREIGN_KEY_CHECKS = 0;
-- tables created here --
SET FOREIGN_KEY_CHECKS = 1;

Workarounds

You can use GetSchema <tablet-alias> and pipe to jq or similar to pull out the definitions:

 vtctlclient -server x:y GetSchema foo-12345 | jq -r '. table_definitions[] | .schema'

And loop over them, using:

vtctl ExecuteFetchAsDba "SET FOREIGN_KEY_CHECKS = 0; ${SQL}; SET FOREIGN_KEY_CHECKS = 1;"

or similar to copy schema.

deepthi commented 3 years ago

Seems reasonable :+1:

dweitzman commented 3 years ago

There was an old PR for this: https://github.com/vitessio/vitess/pull/4722

derekperkins commented 2 years ago

This would be very helpful for us