1 22 23 28 29 package org.xquark.mapper.metadata; 30 31 import java.sql.ResultSet ; 32 import java.sql.SQLException ; 33 import java.sql.Statement ; 34 import java.util.HashMap ; 35 import java.util.Map ; 36 37 import org.xquark.mapper.RepositoryException; 38 import org.xquark.mapper.dbms.Sequence; 39 import org.xquark.mapper.dbms.TableInfo; 40 import org.xquark.mapper.dbms.TableSpec; 41 42 47 public class UserTableManager 48 { 49 private static final String RCSRevision = "$Revision: 1.1 $"; 50 private static final String RCSName = "$Name: $"; 51 52 private Repository rep; 53 private Sequence userTablesSeq; 54 private Map tableIDs = new HashMap (); 55 private String selectStmt; 56 private String insertStmt; 57 58 59 public UserTableManager(Repository rep) 60 throws RepositoryException 61 { 62 this.rep = rep; 63 userTablesSeq = new Sequence(rep.getTableInfo(TableSpec.TYPE_TABLE_SEQ), (short)1); 64 initStatements(rep); 65 refresh(); 66 } 67 68 private void initStatements(Repository rep) 69 { 70 TableInfo userTablesTable = rep.getTableInfo(TableSpec.TYPE_TABLES); 71 selectStmt = userTablesTable.getSelectAllStatement(); 72 insertStmt = "INSERT INTO " + userTablesTable.getName() + " VALUES("; 73 } 74 75 private synchronized void refresh() throws RepositoryException 76 { 77 tableIDs.clear(); 78 Statement stmt = null; 79 ResultSet rs = null; 80 try 81 { 82 stmt = rep.getMetadataConnection().getConnection().createStatement(); 83 rs = stmt.executeQuery(selectStmt); 84 while (rs.next()) 85 tableIDs.put(rs.getString(1), new Short (rs.getShort(2))); 86 } 87 catch (SQLException e) 88 { 89 throw new RepositoryException(RepositoryException.DB_ERROR, 90 "Could not read the user tables system table", e); 91 } 92 finally 93 { 94 try 95 { 96 if (rs != null) 97 rs.close(); 98 if (stmt != null) 99 stmt.close(); 100 } 101 catch (SQLException e) 102 { 103 } 105 } 106 } 107 108 public synchronized short getTableID(String tableName) 109 throws RepositoryException 110 { 111 short ret = -1; 112 113 114 ret = getID(tableName); 115 if (ret == -1) 116 { 117 refresh(); 119 ret = getID(tableName); 121 if (ret == -1) 122 { 123 short newTableID = -1; 125 newTableID = (short)userTablesSeq.nextValue(rep.getMetadataConnection()); 126 try 128 { 129 rep.getMetadataConnection().executeUpdate(insertStmt + "'" + tableName + "'," + newTableID + ')'); 130 tableIDs.put(tableName, new Short (newTableID)); 131 ret = newTableID; 132 } 133 catch (SQLException e) 134 { 135 refresh(); 137 ret = getID(tableName); 138 if (ret == -1) 139 throw new RepositoryException(RepositoryException.DB_CONSISTENCY_ERROR, 140 "Could not insert a row in the user tables system table", e); 141 } 142 } 143 } 144 145 return ret; 146 } 147 148 private short getID(String tableName) 149 { 150 short ret = -1; 151 Short mapID = (Short )tableIDs.get(tableName); 152 if (mapID != null) 153 ret = mapID.shortValue(); 154 return ret; 155 } 156 } 157 | Popular Tags |