1 56 package org.objectstyle.cayenne.dba.postgres; 57 58 import java.sql.Connection ; 59 import java.sql.ResultSet ; 60 import java.sql.SQLException ; 61 import java.sql.Statement ; 62 import java.util.ArrayList ; 63 import java.util.Collections ; 64 import java.util.List ; 65 66 import org.objectstyle.cayenne.CayenneRuntimeException; 67 import org.objectstyle.cayenne.access.DataNode; 68 import org.objectstyle.cayenne.access.QueryLogger; 69 import org.objectstyle.cayenne.dba.oracle.OraclePkGenerator; 70 import org.objectstyle.cayenne.map.DbEntity; 71 import org.objectstyle.cayenne.map.DbKeyGenerator; 72 73 76 public class PostgresPkGenerator extends OraclePkGenerator { 77 78 protected String createSequenceString(DbEntity ent) { 79 StringBuffer buf = new StringBuffer (); 83 buf 84 .append("CREATE SEQUENCE ") 85 .append(sequenceName(ent)) 86 .append(" INCREMENT ") 87 .append(pkCacheSize(ent)) 88 .append(" START 200"); 89 return buf.toString(); 90 } 91 92 100 protected int pkFromDatabase(DataNode node, DbEntity ent) throws Exception { 101 102 DbKeyGenerator pkGenerator = ent.getPrimaryKeyGenerator(); 103 String pkGeneratingSequenceName; 104 if (pkGenerator != null 105 && DbKeyGenerator.ORACLE_TYPE.equals(pkGenerator.getGeneratorType()) 106 && pkGenerator.getGeneratorName() != null) 107 pkGeneratingSequenceName = pkGenerator.getGeneratorName(); 108 else 109 pkGeneratingSequenceName = sequenceName(ent); 110 111 Connection con = node.getDataSource().getConnection(); 112 try { 113 Statement st = con.createStatement(); 114 try { 115 String sql = "SELECT nextval('" + pkGeneratingSequenceName + "')"; 116 QueryLogger.logQuery(QueryLogger.DEFAULT_LOG_LEVEL, 117 sql, 118 Collections.EMPTY_LIST); 119 ResultSet rs = st.executeQuery(sql); 120 try { 121 if (!rs.next()) { 123 throw new CayenneRuntimeException( 124 "Error generating pk for DbEntity " + ent.getName()); 125 } 126 return rs.getInt(1); 127 } 128 finally { 129 rs.close(); 130 } 131 } 132 finally { 133 st.close(); 134 } 135 } 136 finally { 137 con.close(); 138 } 139 } 140 141 144 protected List getExistingSequences(DataNode node) throws SQLException { 145 146 Connection con = node.getDataSource().getConnection(); 148 149 try { 150 Statement sel = con.createStatement(); 151 try { 152 String sql = "SELECT relname FROM pg_class WHERE relkind='S'"; 153 QueryLogger.logQuery(QueryLogger.DEFAULT_LOG_LEVEL, 154 sql, 155 Collections.EMPTY_LIST); 156 ResultSet rs = sel.executeQuery(sql); 157 try { 158 List sequenceList = new ArrayList (); 159 while (rs.next()) { 160 sequenceList.add(rs.getString(1)); 161 } 162 return sequenceList; 163 } 164 finally { 165 rs.close(); 166 } 167 } 168 finally { 169 sel.close(); 170 } 171 } 172 finally { 173 con.close(); 174 } 175 } 176 } | Popular Tags |