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;
19 ArrayList<Sequence> m_sequences;
21 public Schema(String name, DbDriver driver) {
24 m_tables = new ArrayList<Table>();
25 m_sequences = new ArrayList<Sequence>();
28 public boolean ensureDbInitialized(Connection con) throws SQLException {
31 if (allTablesPresent(con)) {
35 if (!createAllTables(con)) {
39 if (!createAllSequences(con)) {
46 boolean allTablesPresent(Connection con) throws SQLException
50 DatabaseMetaData dbmd = con.getMetaData();
51 HashSet<String> extantTables = new HashSet<String>();
53 try (ResultSet rs = dbmd.getTables(null, null, null, new String[]{"TABLE"})) {
55 extantTables.add(rs.getString(3).toUpperCase(Locale.CANADA));
59 for (Table table : m_tables) {
60 String name = table.getName().toUpperCase(Locale.CANADA);
61 if ( ! extantTables.contains(name) ) {
62 // One or more tables missing
67 // We could be more thorough here, and check that the expected columns are in place.
68 // Also, eventually, some sort of DB schema versioning will be needed.
73 boolean createAllTables(Connection con) throws SQLException {
74 for (Table table : m_tables) {
75 if (!m_driver.createTable(con, table)) {
82 boolean createAllSequences(Connection con) throws SQLException {
83 for (Sequence seq : m_sequences) {
84 if (!m_driver.createSequence(con, seq)) {
91 void addTable(Table table) {
95 // Add a list of tables.
96 // Define each table in the list as follows:
99 // { column_name, type, width (-1 for default), null/not_null }
101 void addTables(Object[][][] tables)
103 for (Object[][] table : tables) {
104 addTable(Table.construct(table));
108 void addSequence(Sequence seq) {
109 m_sequences.add(seq);