Mercurial Hosting > nabble
comparison 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 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:7ecd1a4ef557 |
---|---|
1 package nabble.model; | |
2 | |
3 import java.sql.Connection; | |
4 import java.sql.Statement; | |
5 import java.sql.ResultSet; | |
6 import java.sql.SQLException; | |
7 import java.util.Map; | |
8 import org.slf4j.Logger; | |
9 import org.slf4j.LoggerFactory; | |
10 import fschmidt.db.DbDatabase; | |
11 | |
12 | |
13 final class DbUpdater { | |
14 private static final Logger logger = LoggerFactory.getLogger(DbUpdater.class); | |
15 | |
16 final DbDatabase db; | |
17 final String schema; | |
18 private int dbVersion; | |
19 Connection con; | |
20 Statement stmt; | |
21 | |
22 DbUpdater(DbDatabase db,String schema) { | |
23 this.db = db; | |
24 this.schema = schema; | |
25 dbVersion = databaseVersion(); | |
26 } | |
27 | |
28 int databaseVersion() { | |
29 return databaseVersion(db,schema); | |
30 } | |
31 | |
32 static int databaseVersion(DbDatabase db,String schema) { | |
33 try { | |
34 Connection con = db.getConnection(); | |
35 try { | |
36 Statement stmt = con.createStatement(); | |
37 ResultSet rs = stmt.executeQuery( | |
38 "select version from "+schema+".version" | |
39 ); | |
40 rs.next(); | |
41 int dbVersion = rs.getInt("version"); | |
42 stmt.close(); | |
43 return dbVersion; | |
44 } finally { | |
45 con.close(); | |
46 } | |
47 } catch(SQLException e) { | |
48 throw new RuntimeException(e); | |
49 } | |
50 } | |
51 | |
52 int dbVersion() { | |
53 return dbVersion; | |
54 } | |
55 | |
56 void begin() | |
57 throws SQLException | |
58 { | |
59 con = db.getConnection(); | |
60 con.setAutoCommit(false); | |
61 stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE); | |
62 logger.error(schema+" step "+dbVersion); | |
63 } | |
64 | |
65 void commit() | |
66 throws SQLException | |
67 { | |
68 stmt.executeUpdate( | |
69 "update "+schema+".version set version=" + (++dbVersion) | |
70 ); | |
71 stmt.close(); | |
72 con.commit(); | |
73 con.close(); | |
74 con = null; | |
75 } | |
76 | |
77 void exec(String sql) | |
78 throws SQLException | |
79 { | |
80 if( sql != null ) { | |
81 if( sql.trim().toLowerCase().startsWith("select ") ) { | |
82 stmt.executeQuery(sql); | |
83 } else { | |
84 stmt.executeUpdate(sql); | |
85 } | |
86 } | |
87 } | |
88 | |
89 void execStep(String sql) | |
90 throws SQLException | |
91 { | |
92 begin(); | |
93 exec(sql); | |
94 commit(); | |
95 } | |
96 | |
97 void close() { | |
98 if( con != null ) { | |
99 try { | |
100 con.close(); | |
101 } catch(SQLException e) { | |
102 logger.error(schema,e); | |
103 } | |
104 con = null; | |
105 } | |
106 } | |
107 | |
108 } |