Mercurial Hosting > nabble
diff src/nabble/model/DbUpdater.java @ 0:7ecd1a4ef557
add content
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Thu, 21 Mar 2019 19:15:52 -0600 |
parents | |
children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/nabble/model/DbUpdater.java Thu Mar 21 19:15:52 2019 -0600 @@ -0,0 +1,108 @@ +package nabble.model; + +import java.sql.Connection; +import java.sql.Statement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import fschmidt.db.DbDatabase; + + +final class DbUpdater { + private static final Logger logger = LoggerFactory.getLogger(DbUpdater.class); + + final DbDatabase db; + final String schema; + private int dbVersion; + Connection con; + Statement stmt; + + DbUpdater(DbDatabase db,String schema) { + this.db = db; + this.schema = schema; + dbVersion = databaseVersion(); + } + + int databaseVersion() { + return databaseVersion(db,schema); + } + + static int databaseVersion(DbDatabase db,String schema) { + try { + Connection con = db.getConnection(); + try { + Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery( + "select version from "+schema+".version" + ); + rs.next(); + int dbVersion = rs.getInt("version"); + stmt.close(); + return dbVersion; + } finally { + con.close(); + } + } catch(SQLException e) { + throw new RuntimeException(e); + } + } + + int dbVersion() { + return dbVersion; + } + + void begin() + throws SQLException + { + con = db.getConnection(); + con.setAutoCommit(false); + stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE); + logger.error(schema+" step "+dbVersion); + } + + void commit() + throws SQLException + { + stmt.executeUpdate( + "update "+schema+".version set version=" + (++dbVersion) + ); + stmt.close(); + con.commit(); + con.close(); + con = null; + } + + void exec(String sql) + throws SQLException + { + if( sql != null ) { + if( sql.trim().toLowerCase().startsWith("select ") ) { + stmt.executeQuery(sql); + } else { + stmt.executeUpdate(sql); + } + } + } + + void execStep(String sql) + throws SQLException + { + begin(); + exec(sql); + commit(); + } + + void close() { + if( con != null ) { + try { + con.close(); + } catch(SQLException e) { + logger.error(schema,e); + } + con = null; + } + } + +}