0
|
1 /* Copyright (c) 2012 Tomislav Gountchev <tomi@gountchev.net> */
|
|
2
|
|
3 package jdbcpgbackup;
|
|
4
|
|
5 import java.sql.Connection;
|
|
6 import java.sql.PreparedStatement;
|
|
7 import java.sql.ResultSet;
|
|
8 import java.sql.SQLException;
|
|
9 import java.util.Collections;
|
|
10 import java.util.HashMap;
|
|
11 import java.util.Map;
|
|
12
|
|
13 public abstract class CachingDBOFactory<T extends DbBackupObject> implements DBOFactory<T> {
|
|
14
|
|
15 protected final Schema.CachingSchemaFactory schemaFactory;
|
|
16
|
|
17 protected Map<String,Map<String,T>> map = null;
|
|
18
|
|
19 protected CachingDBOFactory(Schema.CachingSchemaFactory schemaFactory) {
|
|
20 this.schemaFactory = schemaFactory;
|
|
21 }
|
|
22
|
|
23 @Override
|
|
24 public Iterable<T> getDbBackupObjects(Connection con, Schema schema) throws SQLException {
|
|
25 if (map == null) {
|
|
26 loadMap(con);
|
|
27 }
|
|
28 Map<String,T> dbos = map.get(schema.getName());
|
|
29 if (dbos == null) return Collections.emptyList();
|
|
30 else return Collections.unmodifiableCollection(dbos.values());
|
|
31 }
|
|
32
|
|
33 @Override
|
|
34 public T getDbBackupObject(Connection con, String name, Schema schema) throws SQLException {
|
|
35 if (map == null) {
|
|
36 loadMap(con);
|
|
37 }
|
|
38 Map<String,T> dbos = map.get(schema.getName());
|
|
39 return dbos == null ? null : dbos.get(name);
|
|
40 }
|
|
41
|
|
42 protected void loadMap(Connection con) throws SQLException {
|
|
43 map = new HashMap<String,Map<String,T>>();
|
|
44 PreparedStatement stmt = null;
|
|
45 try {
|
|
46 stmt = getAllStatement(con);
|
|
47 ZipBackup.debug("loading map in " + CachingDBOFactory.this.getClass());
|
|
48 ResultSet rs = stmt.executeQuery();
|
|
49 while (rs.next()) {
|
|
50 Schema schema = schemaFactory.getFromCurrentBatch(rs.getInt("schema_oid"));
|
|
51 if (schema == null) continue;
|
|
52 Map<String,T> dbos = map.get(schema.getName());
|
|
53 if (dbos == null) {
|
|
54 dbos = new HashMap<String,T>();
|
|
55 map.put(schema.getName(), dbos);
|
|
56 }
|
|
57 T dbo = newDbBackupObject(con, rs, schema);
|
|
58 dbos.put(dbo.getName(), dbo);
|
|
59 }
|
|
60 rs.close();
|
|
61 } finally {
|
|
62 if (stmt != null) stmt.close();
|
|
63 }
|
|
64 }
|
|
65
|
|
66 protected abstract PreparedStatement getAllStatement(Connection con) throws SQLException;
|
|
67
|
|
68 protected abstract T newDbBackupObject(Connection con, ResultSet rs, Schema schema) throws SQLException;
|
|
69
|
|
70 }
|