Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

H2 add multiple column MySQL syntax

I have the following table:

CREATE TABLE users (
  id   INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(256)
);

I would like to add multiple columns in one query. I am using H2 a lot in testing but in production I use MySQL. Both are using same DDL scripts.

Is there any common syntax for H2 and MySQL that allows adding several columns?

MySQL syntax:

ALTER TABLE users
  ADD `col1` INT,
  ADD `col2` INT,
  ADD `col3` INT
  AFTER id;

H2 syntax:

ALTER TABLE users
  ADD (
    `col1` INT,
    `col2` INT,
    `col3` INT
  ) AFTER `id`;

If it helps, my H2 JDBC URL is:

// note MODE=MYSQL in the end
jdbc:h2:users;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL

Patch to H2 was applied in scope of this discussion.

EDIT:

Of course I can use this syntax (which is horrible for large tables) and I have to manage these AFTER statements to save columns order:

ALTER TABLE `users`
  ADD `col1` INT AFTER `id`;

ALTER TABLE `users`
  ADD `col2` INT AFTER `col1`;

ALTER TABLE `users`
  ADD `col3` INT AFTER `col2`;
like image 705
Andrii Abramov Avatar asked Feb 01 '18 14:02

Andrii Abramov


1 Answers

As far as I know, there is no common syntax for that. There are some things that don't translate from MySQL to H2 and "multiple add columns in one statement" is one of those things. I agree that adding the individual columns is horrible for large tables, which is why when we are in situations like this on my project, we run separate migrations for test (H2) and prod (MySQL).

like image 199
LConrad Avatar answered Oct 13 '22 23:10

LConrad