H2 fails when altering table for 2 foreign keys (MYSQL syntax)

Charly :

Working on adding testing to an existing project that uses Flyway. The tables are in Versioned flyway files, so they can't change, but trying to figure out what the cause of this basic use-case is.

CREATE TABLE table1
(
    id LONG PRIMARY KEY AUTO_INCREMENT
);

CREATE TABLE table2
(
    id LONG PRIMARY KEY AUTO_INCREMENT
);

CREATE TABLE table3
(
    id LONG PRIMARY KEY AUTO_INCREMENT,
    t1_id LONG,
    t2_id LONG
);

ALTER TABLE table3
    ADD FOREIGN KEY (t1_id) REFERENCES table1 (id),
    ADD FOREIGN KEY (t2_id) REFERENCES table2 (id);

Causes:

SQL State  : 42000
Error Code : 42000
Message    : Syntax error in SQL statement "ALTER TABLE TABLE3
    ADD FOREIGN KEY (T1_ID) REFERENCES TABLE1 (ID),[*]
    ADD FOREIGN KEY (T2_ID) REFERENCES TABLE2 (ID)"; SQL statement:
ALTER TABLE table3
    ADD FOREIGN KEY (t1_id) REFERENCES table1 (id),
    ADD FOREIGN KEY (t2_id) REFERENCES table2 (id) [42000-200]
Location   : db/migration/V1_0__init.sql ...V1_0__init.sql)
Line       : 18
Statement  : ALTER TABLE table3
    ADD FOREIGN KEY (t1_id) REFERENCES table1 (id),
    ADD FOREIGN KEY (t2_id) REFERENCES table2 (id)

In testing, the following two scenarios are successful though..

-- Only 1 foreign key
ALTER TABLE table3
    ADD FOREIGN KEY (t1_id) REFERENCES table1 (id);

-- Inlined foreign keys in table creation
CREATE TABLE table3
(
    id LONG PRIMARY KEY AUTO_INCREMENT,
    t1_id LONG,
    t2_id LONG,

    FOREIGN KEY (t1_id) REFERENCES table1 (id),
    FOREIGN KEY (t2_id) REFERENCES table2 (id)
);

Is there a limitation in H2 to add multiple foreign keys at the same time?

Evgenij Ryazanov :

It's not a limitation of H2. In the SQL Standard you can't define multiple constraints at once in the ALTER TABLE statement, you can define them all at once only in the definition of the table. If they weren't already defined in the CREATE TABLE command, you need to use two separate ALTER TABLE commands:

ALTER TABLE table3
    ADD FOREIGN KEY (t1_id) REFERENCES table1 (id);
ALTER TABLE table3
    ADD FOREIGN KEY (t2_id) REFERENCES table2 (id)

Some databases, such as MySQL, have their own vendor-specific syntax, but such syntax is not compatible with other databases, including the H2 (even in MySQL compatibility mode).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=319441&siteId=1