1 19 20 package org.apache.cayenne.dba.postgres; 21 22 import java.sql.Connection ; 23 import java.sql.ResultSet ; 24 import java.sql.SQLException ; 25 import java.sql.Statement ; 26 import java.util.ArrayList ; 27 import java.util.Collections ; 28 import java.util.List ; 29 30 import org.apache.cayenne.CayenneRuntimeException; 31 import org.apache.cayenne.access.DataNode; 32 import org.apache.cayenne.access.QueryLogger; 33 import org.apache.cayenne.dba.oracle.OraclePkGenerator; 34 import org.apache.cayenne.map.DbEntity; 35 import org.apache.cayenne.map.DbKeyGenerator; 36 37 40 public class PostgresPkGenerator extends OraclePkGenerator { 41 42 protected String createSequenceString(DbEntity ent) { 43 StringBuffer buf = new StringBuffer (); 47 buf 48 .append("CREATE SEQUENCE ") 49 .append(sequenceName(ent)) 50 .append(" INCREMENT ") 51 .append(pkCacheSize(ent)) 52 .append(" START 200"); 53 return buf.toString(); 54 } 55 56 64 protected int pkFromDatabase(DataNode node, DbEntity ent) throws Exception { 65 66 DbKeyGenerator pkGenerator = ent.getPrimaryKeyGenerator(); 67 String pkGeneratingSequenceName; 68 if (pkGenerator != null 69 && DbKeyGenerator.ORACLE_TYPE.equals(pkGenerator.getGeneratorType()) 70 && pkGenerator.getGeneratorName() != null) 71 pkGeneratingSequenceName = pkGenerator.getGeneratorName(); 72 else 73 pkGeneratingSequenceName = sequenceName(ent); 74 75 Connection con = node.getDataSource().getConnection(); 76 try { 77 Statement st = con.createStatement(); 78 try { 79 String sql = "SELECT nextval('" + pkGeneratingSequenceName + "')"; 80 QueryLogger.logQuery(sql, Collections.EMPTY_LIST); 81 ResultSet rs = st.executeQuery(sql); 82 try { 83 if (!rs.next()) { 85 throw new CayenneRuntimeException( 86 "Error generating pk for DbEntity " + ent.getName()); 87 } 88 return rs.getInt(1); 89 } 90 finally { 91 rs.close(); 92 } 93 } 94 finally { 95 st.close(); 96 } 97 } 98 finally { 99 con.close(); 100 } 101 } 102 103 106 protected List getExistingSequences(DataNode node) throws SQLException { 107 108 Connection con = node.getDataSource().getConnection(); 110 111 try { 112 Statement sel = con.createStatement(); 113 try { 114 String sql = "SELECT relname FROM pg_class WHERE relkind='S'"; 115 QueryLogger.logQuery(sql, Collections.EMPTY_LIST); 116 ResultSet rs = sel.executeQuery(sql); 117 try { 118 List sequenceList = new ArrayList (); 119 while (rs.next()) { 120 sequenceList.add(rs.getString(1)); 121 } 122 return sequenceList; 123 } 124 finally { 125 rs.close(); 126 } 127 } 128 finally { 129 sel.close(); 130 } 131 } 132 finally { 133 con.close(); 134 } 135 } 136 } 137 | Popular Tags |