]> jaekl.net Git - cfb.git/blob - prod/net/jaekl/cfb/db/driver/DbDriver.java
fa3886248522012a5b8069c9e0c600ab7c36a92f
[cfb.git] / prod / net / jaekl / cfb / db / driver / DbDriver.java
1 package net.jaekl.cfb.db.driver;
2
3 import static net.jaekl.cfb.db.Column.Null.*;
4
5 import java.sql.Connection;
6 import java.sql.PreparedStatement;
7 import java.sql.ResultSet;
8 import java.sql.SQLException;
9
10 import net.jaekl.cfb.db.Column;
11 import net.jaekl.cfb.db.Column.Type;
12 import net.jaekl.cfb.db.Table;
13
14 public abstract class DbDriver {
15         DbDriver() {
16                 
17         }
18         
19         // Load the JDBC driver
20         public abstract void load() throws ClassNotFoundException;
21         
22         public abstract Connection connect(String host, int port, String dbName, String user, String pass) throws SQLException;
23         
24         public boolean createTable(Connection con, Table table) throws SQLException {
25                 String sql = createTableSql(table);
26                 try (PreparedStatement ps = con.prepareStatement(sql)) {
27                         ps.executeUpdate();
28                 }
29                 
30                 return true;
31         }
32         
33         public abstract ResultSet selectColumnsFromWhere(Column[] columns, Table[] tables, String where);
34         
35         protected String typeName(Type type) {
36                 return type.toString();
37         }
38         
39         protected String createColumnSql(Column column) 
40         {
41                 String result = column.getName() + " " + typeName(column.getType());
42                 if (column.getWidth() > 0) {
43                         result += "(" + column.getWidth() + ")";
44                 }
45                 
46                 if (NOT_NULL == column.getNull()) {
47                         result += " NOT NULL";
48                 }
49                 else {
50                         result += " NULL";
51                 }
52             
53                 return result;
54         }
55         
56         protected String createTableSql(Table table) 
57         {
58                 assert(null != table);
59                 assert(null != table.getName());
60                 assert(table.getNumColumns() > 0);
61                 
62                 StringBuilder sb = new StringBuilder();
63                 
64                 sb.append("CREATE TABLE ")
65                   .append(table.getName())
66                   .append("(");
67                 
68                 for (int idx = 0; idx < table.getNumColumns(); ++idx) {
69                         if (idx > 0) {
70                                 sb.append(", ");
71                         }
72                         sb.append(createColumnSql(table.getColumn(idx)));
73                 }
74                 
75                 sb.append(")");
76                 
77                 return sb.toString();
78         }       
79 }