Here is an example of stored procedure truncate_all_tables
that disables foreign keys, then truncates all tables in current schema and then enables foreign keys back:
DROP ALIAS IF EXISTS truncate_all_tables;
CREATE ALIAS truncate_all_tables AS $$
void truncateAllTables(Connection conn) throws SQLException {
conn.createStatement().executeUpdate("SET FOREIGN_KEY_CHECKS=0");
ResultSet rs = conn.createStatement().
executeQuery("SELECT table_name FROM information_schema.tables WHERE table_schema = SCHEMA()");
while (rs.next()) {
String tableName = rs.getString(1);
conn.createStatement().executeUpdate("TRUNCATE TABLE \"" + tableName + "\" RESTART IDENTITY");
}
conn.createStatement().executeUpdate("SET FOREIGN_KEY_CHECKS=1");
}
$$;
CALL truncate_all_tables();
Or you can define the function in your code:
public class H2Functions {
public static void truncateAllTables(Connection conn) throws SQLException {
conn.createStatement().executeUpdate("SET FOREIGN_KEY_CHECKS=0");
ResultSet rs = conn.createStatement().
executeQuery("SELECT table_name FROM information_schema.tables WHERE table_schema = SCHEMA()");
while (rs.next()) {
String tableName = rs.getString(1);
conn.createStatement().executeUpdate("TRUNCATE TABLE \"" + tableName + "\" RESTART IDENTITY");
}
conn.createStatement().executeUpdate("SET FOREIGN_KEY_CHECKS=1");
}
}
and then use as alias:
SET MODE REGULAR;
CREATE ALIAS IF NOT EXISTS truncate_all_tables FOR "com.yourcompany.H2Functions.truncateAllTables";
CALL truncate_all_tables();
SET MODE MySQL;
Here I added SET MODE
statements as an example if you are using H2 in MySQL mode you have to switch back to H2 mode, then declare the function and then switch back to MySQL mode.
Unfortunately the truncate_all_tables
doesn't resets auto_inc columns. See Spring test with H2 in memory database truncate all tables for details.
setChecks
beSET REFERENTIAL_INTEGRITY = ?
instead ofSET FOREIGN_KEY_CHECKS = ?
? The latter one is not mentioned in the official documentat at h2database.com/html/commands.html – Patchouli