8 changed files with 97 additions and 96 deletions
@ -0,0 +1,64 @@
@@ -0,0 +1,64 @@
|
||||
package de.srsoftware.umbrella.core; |
||||
|
||||
import de.srsoftware.tools.jdbc.Query; |
||||
|
||||
import java.sql.Connection; |
||||
import java.sql.SQLException; |
||||
|
||||
import static de.srsoftware.tools.jdbc.Condition.equal; |
||||
import static de.srsoftware.tools.jdbc.Query.replaceInto; |
||||
import static de.srsoftware.umbrella.core.Constants.*; |
||||
import static de.srsoftware.umbrella.core.Constants.TABLE_SETTINGS; |
||||
import static java.lang.System.Logger.Level.ERROR; |
||||
import static java.lang.System.Logger.Level.INFO; |
||||
import static java.text.MessageFormat.format; |
||||
|
||||
public abstract class BaseDb { |
||||
private final System.Logger LOG = System.getLogger(getClass().getSimpleName()); |
||||
|
||||
protected final Connection db; |
||||
|
||||
public BaseDb(Connection connection) { |
||||
db = connection; |
||||
var version = createTables(); |
||||
LOG.log(INFO,"Updated db to version {0}",version); |
||||
|
||||
} |
||||
|
||||
protected abstract int createTables(); |
||||
|
||||
protected int createSettingsTable() { |
||||
var createTable = """ |
||||
CREATE TABLE IF NOT EXISTS {0} ( {1} VARCHAR(255) PRIMARY KEY, {2} VARCHAR(255) NOT NULL); |
||||
"""; |
||||
try { |
||||
var stmt = db.prepareStatement(format(createTable,TABLE_SETTINGS, KEY, VALUE)); |
||||
stmt.execute(); |
||||
stmt.close(); |
||||
} catch (SQLException e) { |
||||
LOG.log(ERROR,ERROR_FAILED_CREATE_TABLE,TABLE_SETTINGS,e); |
||||
throw new RuntimeException(e); |
||||
} |
||||
|
||||
var version = 0; |
||||
try { |
||||
var rs = Query.select(VALUE).from(TABLE_SETTINGS).where(KEY, equal(DB_VERSION)).exec(db); |
||||
if (rs.next()) version = rs.getInt(VALUE); |
||||
rs.close(); |
||||
|
||||
return version; |
||||
} catch (SQLException e) { |
||||
LOG.log(ERROR,ERROR_READ_TABLE,DB_VERSION,TABLE_SETTINGS,e); |
||||
throw new RuntimeException(e); |
||||
} |
||||
} |
||||
|
||||
protected int setCurrentVersion(int version) { |
||||
try { |
||||
replaceInto(TABLE_SETTINGS, KEY, VALUE).values(DB_VERSION,version).execute(db).close(); |
||||
} catch (SQLException e) { |
||||
throw new RuntimeException(e); |
||||
} |
||||
return version; |
||||
} |
||||
} |
||||
Loading…
Reference in new issue