1 package net.jaekl.cfb.db;
3 // Copyright (C) 2015 Christian Jaekl
5 import java.sql.Connection;
6 import java.sql.DatabaseMetaData;
7 import java.sql.ResultSet;
8 import java.sql.SQLException;
9 import java.util.ArrayList;
10 import java.util.HashSet;
11 import java.util.Locale;
13 import net.jaekl.cfb.db.driver.DbDriver;
18 ArrayList<Table> m_tables;
20 public Schema(String name, DbDriver driver) {
23 m_tables = new ArrayList<Table>();
26 public boolean ensureDbInitialized(Connection con) throws SQLException {
29 if (allTablesPresent(con)) {
33 if (!createAllTables(con)) {
40 boolean allTablesPresent(Connection con) throws SQLException
44 DatabaseMetaData dbmd = con.getMetaData();
45 HashSet<String> extantTables = new HashSet<String>();
47 try (ResultSet rs = dbmd.getTables(null, null, null, new String[]{"TABLE"})) {
49 extantTables.add(rs.getString(3).toUpperCase(Locale.CANADA));
53 for (Table table : m_tables) {
54 String name = table.getName().toUpperCase(Locale.CANADA);
55 if ( ! extantTables.contains(name) ) {
56 // One or more tables missing
61 // We could be more thorough here, and check that the expected columns are in place.
62 // Also, eventually, some sort of DB schema versioning will be needed.
67 boolean createAllTables(Connection con) throws SQLException {
68 for (Table table : m_tables) {
69 if (!m_driver.createTable(con, table)) {
76 void addTable(Table table) {
80 // Add a list of tables.
81 // Define each table in the list as follows:
84 // { column_name, type, width (-1 for default), null/not_null }
86 void addTables(Object[][][] tables)
88 for (Object[][] table : tables) {
89 addTable(Table.construct(table));