Skip to content

Commit

Permalink
loop over multiple statments in a migration step
Browse files Browse the repository at this point in the history
  • Loading branch information
crschardt committed Dec 21, 2023
1 parent 5cf6841 commit 1499c6d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,17 @@ private void setUserVersion(Connection conn, int value) {
}

private void doMigration(int index) throws SQLException {
logger.debug("Running migration step " + index);
try (Connection conn = createConn();
Statement stmt = conn.createStatement()) {
stmt.execute(SqlMigrations.SQL[index]);
for (String sql : SqlMigrations.SQL[index].split(";")) {
stmt.addBatch(sql);
}
stmt.executeBatch();
setUserVersion(conn, index);
tryCommit(conn);
} catch (SQLException e) {
logger.error("Err with migration step" + index, e);
logger.error("Err with migration step " + index, e);
throw e;
}
}
Expand All @@ -165,6 +169,7 @@ private void initDatabase() {
// database must be from a newer version, so warn
} else if (currentSchema < SqlMigrations.SQL.length) {
// older database, run migrations
logger.debug("Older database version. Updating schema ... ");
for (int index = currentSchema; index < SqlMigrations.SQL.length; index++) {
try {
doMigration(index);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,23 @@
Add migrations by adding the SQL commands for each migration sequentially to this array.
DO NOT edit or delete existing SQL commands. That will lead to producing an icompatible
database.
You can use multiple SQL statements in one migration step as long as you separate them
with a semicolon (;).
*/
public final class SqlMigrations {
public static final String[] SQL = {
// #1 - initial schema
"CREATE TABLE IF NOT EXISTS global (\n"
+ " filename TINYTEXT PRIMARY KEY,\n"
+ " contents mediumtext NOT NULL\n"
+ ");"
+ "CREATE TABLE IF NOT EXISTS cameras (\n"
+ " unique_name TINYTEXT PRIMARY KEY,\n"
+ " config_json text NOT NULL,\n"
+ " drivermode_json text NOT NULL,\n"
+ " pipeline_jsons mediumtext NOT NULL\n"
+ ");",
+ " filename TINYTEXT PRIMARY KEY,\n"
+ " contents mediumtext NOT NULL\n"
+ ");\n"
+ "CREATE TABLE IF NOT EXISTS cameras (\n"
+ " unique_name TINYTEXT PRIMARY KEY,\n"
+ " config_json text NOT NULL,\n"
+ " drivermode_json text NOT NULL,\n"
+ " pipeline_jsons mediumtext NOT NULL\n"
+ ");",
// #2 - add column otherpaths_json
"ALTER TABLE cameras ADD COLUMN otherpaths_json TEXT NOT NULL DEFAULT '[]'",
// add future migrations here
Expand Down

0 comments on commit 1499c6d

Please sign in to comment.