1 package com.randomnoun.common.db;
2
3
4
5
6
7 import java.util.HashMap;
8
9 import javax.sql.DataSource;
10
11 import org.springframework.jdbc.core.JdbcTemplate;
12
13 import com.randomnoun.common.db.to.SchemaTO;
14 import com.randomnoun.common.db.to.TableColumnTO;
15 import com.randomnoun.common.db.to.TableTO;
16
17
18
19
20
21
22
23
24
25
26
27
28 public abstract class DatabaseReader {
29
30 protected com.randomnoun.common.db.to.DatabaseTO db;
31
32
33 public DataSource ds;
34 public JdbcTemplate jt;
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82 public DatabaseReader(DataSource dataSource ) {
83 this.ds = dataSource;
84 this.jt = new JdbcTemplate(dataSource);
85 this.db = new com.randomnoun.common.db.to.DatabaseTO();
86 db.setDatabaseType(null);
87 db.setSchemaMap(new HashMap<String, SchemaTO>());
88 }
89
90
91
92 public SchemaTO getSchema(String schemaName) {
93
94
95 if (schemaName==null) {
96 switch (db.getDatabaseType()) {
97 case ORACLE:
98 throw new UnsupportedOperationException("Not supported for this database type");
99
100 case MYSQL:
101 schemaName = (String) jt.queryForObject("SELECT DATABASE();", java.lang.String.class);
102 break;
103
104 case SQLSERVER:
105 throw new UnsupportedOperationException("Not supported for this database type");
106
107 default:
108 throw new IllegalStateException("Unknown database type " + db.getDatabaseType());
109 }
110 }
111
112 SchemaTO schema = db.getSchemaMap().get(db.upper(schemaName));
113 if (schema == null) {
114 schema = readSchema(db.upper(schemaName));
115 db.getSchemaMap().put(db.upper(schemaName), schema);
116 }
117 return schema;
118 }
119
120 abstract public SchemaTO readSchema(String schemaName);
121
122
123
124 public TableColumnTO getColumn(com.randomnoun.common.db.to.DatabaseTO db, String identifier) {
125 String schemaName = null;
126 String tableName = null;
127 String columnName = null;
128 String[] bits = identifier.split("\\.");
129 if (bits.length > 3) { throw new IllegalArgumentException("Too many components in column identifier '" + identifier + "'"); }
130 if (bits.length < 1) { throw new IllegalArgumentException("Too few components in column identifier '" + identifier + "'"); }
131 if (bits.length > 2) { schemaName = bits[bits.length - 3]; }
132 if (bits.length > 1) { tableName = bits[bits.length - 2]; }
133 columnName = bits[bits.length - 1];
134 SchemaTO schema = db.getSchemaMap().get(schemaName);
135 TableTO table = schema.getTable(tableName);
136 return table.getTableColumn(columnName);
137 }
138
139 }