1 package net.jaekl.cfb.db;
3 import java.sql.Connection;
4 import java.sql.DatabaseMetaData;
5 import java.sql.ResultSet;
6 import java.sql.SQLException;
7 import java.util.ArrayList;
8 import java.util.HashSet;
9 import java.util.Locale;
11 import net.jaekl.cfb.db.driver.DbDriver;
16 ArrayList<Table> m_tables;
18 public Schema(String name, DbDriver driver) {
21 m_tables = new ArrayList<Table>();
24 public boolean ensureDbInitialized(Connection con) throws SQLException {
27 if (allTablesPresent(con)) {
31 if (!createAllTables(con)) {
38 boolean allTablesPresent(Connection con) throws SQLException
42 DatabaseMetaData dbmd = con.getMetaData();
43 HashSet<String> extantTables = new HashSet<String>();
45 try (ResultSet rs = dbmd.getTables(null, null, null, new String[]{"TABLE"})) {
47 extantTables.add(rs.getString(3).toUpperCase(Locale.CANADA));
51 for (Table table : m_tables) {
52 String name = table.getName().toUpperCase(Locale.CANADA);
53 if ( ! extantTables.contains(name) ) {
54 // One or more tables missing
59 // We could be more thorough here, and check that the expected columns are in place.
60 // Also, eventually, some sort of DB schema versioning will be needed.
65 boolean createAllTables(Connection con) throws SQLException {
66 for (Table table : m_tables) {
67 if (!m_driver.createTable(con, table)) {
74 void addTable(Table table) {
78 // Add a list of tables.
79 // Define each table in the list as follows:
82 // { column_name, type, width (-1 for default), null/not_null }
84 void addTables(Object[][][] tables)
86 for (Object[][] table : tables) {
87 addTable(Table.construct(table));