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)) {
43 if (!postCreationInit(con)) {
50 public void purge(Connection con) throws SQLException {
52 dropAllSequences(con);
55 boolean postCreationInit(Connection con) throws SQLException {
57 // Override this in a derived class if you need to initialize something
58 // after the tables and sequences are created.
62 boolean allTablesPresent(Connection con) throws SQLException
66 DatabaseMetaData dbmd = con.getMetaData();
67 HashSet<String> extantTables = new HashSet<String>();
69 try (ResultSet rs = dbmd.getTables(null, null, null, new String[]{"TABLE"})) {
71 extantTables.add(rs.getString(3).toUpperCase(Locale.CANADA));
75 for (Table table : m_tables) {
76 String name = table.getName().toUpperCase(Locale.CANADA);
77 if ( ! extantTables.contains(name) ) {
78 // One or more tables missing
83 // We could be more thorough here, and check that the expected columns are in place.
84 // Also, eventually, some sort of DB schema versioning will be needed.
89 boolean createAllTables(Connection con) throws SQLException {
90 for (Table table : m_tables) {
91 if (!m_driver.createTable(con, table)) {
98 void dropAllTables(Connection con) {
99 for (Table table : m_tables) {
101 m_driver.dropTable(con, table);
103 catch (SQLException e) {
109 boolean createAllSequences(Connection con) throws SQLException {
110 for (Sequence seq : m_sequences) {
111 if (!m_driver.createSequence(con, seq)) {
118 void dropAllSequences(Connection con) {
119 for (Sequence seq : m_sequences) {
121 m_driver.dropSequence(con, seq);
123 catch (SQLException e) {
129 void addTable(Table table) {
133 // Add a list of tables.
134 // Define each table in the list as follows:
137 // { column_name, type, width (-1 for default), null/not_null }
139 void addTables(Table[] tables)
141 for (Table table : tables) {
146 void addSequence(Sequence seq) {
147 m_sequences.add(seq);
150 void addSequences(Sequence[] sequences) {
151 for (Sequence sequence : sequences) {
152 addSequence(sequence);