diff --git a/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/AbstractMetaDataDialect.java b/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/AbstractMetaDataDialect.java index dd4e1eada..46ed0ba75 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/AbstractMetaDataDialect.java +++ b/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/AbstractMetaDataDialect.java @@ -41,161 +41,169 @@ */ public abstract class AbstractMetaDataDialect implements RevengDialect { - protected final Logger log = Logger.getLogger(this.getClass()); - - private Connection connection; - private DatabaseMetaData metaData; - - private ConnectionProvider connectionProvider = null; - - public void configure( - ConnectionProvider connectionProvider) { - this.connectionProvider = connectionProvider; - } - - public void close() { - metaData = null; - if(connection != null) { - try { - connectionProvider.closeConnection(connection); - } - catch (SQLException e) { - throw new RuntimeException("Problem while closing connection", e); - } finally { - connection = null; - } - } - connectionProvider = null; - } - - protected DatabaseMetaData getMetaData() { - if (metaData == null) { - try { - metaData = getConnection().getMetaData(); - } - catch (SQLException e) { - throw new RuntimeException("Getting database metadata", e); - } - } - return metaData; - } - - protected String getDatabaseStructure(String catalog, String schema) { - ResultSet schemaRs = null; - ResultSet catalogRs = null; - String nl = System.lineSeparator(); - StringBuilder sb = new StringBuilder(nl); - // Let's give the user some feedback. The exception - // is probably related to incorrect schema configuration. - sb.append("Configured schema:").append(schema).append(nl); - sb.append("Configured catalog:").append(catalog ).append(nl); - - try { - schemaRs = getMetaData().getSchemas(); - sb.append("Available schemas:").append(nl); - while (schemaRs.next() ) { - sb.append(" ").append(schemaRs.getString("TABLE_SCHEM") ).append(nl); - } - } - catch (SQLException e2) { - log.warn("Could not get schemas", e2); - sb.append(" ").append(nl); - } - finally { - try { - if (schemaRs != null) { - schemaRs.close(); - } - } - catch (Exception ignore) { - } - } - - try { - catalogRs = getMetaData().getCatalogs(); - sb.append("Available catalogs:").append(nl); - while (catalogRs.next() ) { - sb.append(" ").append(catalogRs.getString("TABLE_CAT") ).append(nl); - } - } - catch (SQLException e2) { - log.warn("Could not get catalogs", e2); - sb.append(" ").append(nl); - } - finally { - try { - if (catalogRs != null) { - catalogRs.close(); - } - } - catch (Exception ignore) { - } - } - return sb.toString(); - } - - protected Connection getConnection() throws SQLException { - if(connection==null) { - connection = connectionProvider.getConnection(); - } - return connection; - } - - public void close(Iterator iterator) { - if(iterator instanceof ResultSetIterator) { - ((ResultSetIterator)iterator).close(); - } - } - - public boolean needQuote(String name) { - - if(name==null) return false; - - // TODO: use jdbc metadata to decide on this. but for now we just handle the most typical cases. - if(name.indexOf('-')>0) return true; - if(name.indexOf(' ')>0) return true; - return name.indexOf( '.' ) > 0; - } - - protected String caseForSearch(String value) throws SQLException { - // TODO: handle quoted requests (just strip it ?) - if(needQuote(value)) { - if ( getMetaData().storesMixedCaseQuotedIdentifiers() ) { - return value; - } else if ( getMetaData().storesUpperCaseQuotedIdentifiers() ) { - return toUpperCase( value ); - } else if( getMetaData().storesLowerCaseQuotedIdentifiers() ) { - return toLowerCase( value ); - } else { - return value; - } - } else if ( getMetaData().storesMixedCaseQuotedIdentifiers() ) { - return value; - } else if ( getMetaData().storesUpperCaseIdentifiers() ) { - return toUpperCase( value ); - } else if( getMetaData().storesLowerCaseIdentifiers() ) { - return toLowerCase( value ); - } else { - return value; - } - } - - private String toUpperCase(String str) { - return str==null ? null : str.toUpperCase(); - } - - private String toLowerCase(String str) { - return str == null ? null : str.toLowerCase(Locale.ENGLISH); - } - - public Iterator> getSuggestedPrimaryKeyStrategyName(String catalog, String schema, String table) { - Map m = new HashMap(); - m.put( "TABLE_CAT", catalog ); - m.put( "TABLE_SCHEMA", schema ); - m.put( "TABLE_NAME", table ); - m.put( "HIBERNATE_STRATEGY", null ); - List> l = new ArrayList>(); - l.add(m); - return l.iterator(); - } + protected final Logger log = Logger.getLogger(this.getClass()); + + private Connection connection; + private DatabaseMetaData metaData; + + private ConnectionProvider connectionProvider = null; + + public void configure( + ConnectionProvider connectionProvider) { + this.connectionProvider = connectionProvider; + } + + public void close() { + metaData = null; + if(connection != null) { + try { + connectionProvider.closeConnection(connection); + } + catch (SQLException e) { + throw new RuntimeException("Problem while closing connection", e); + } + finally { + connection = null; + } + } + connectionProvider = null; + } + + protected DatabaseMetaData getMetaData() { + if (metaData == null) { + try { + metaData = getConnection().getMetaData(); + } + catch (SQLException e) { + throw new RuntimeException("Getting database metadata", e); + } + } + return metaData; + } + + protected String getDatabaseStructure(String catalog, String schema) { + ResultSet schemaRs = null; + ResultSet catalogRs = null; + String nl = System.lineSeparator(); + StringBuilder sb = new StringBuilder(nl); + // Let's give the user some feedback. The exception + // is probably related to incorrect schema configuration. + sb.append("Configured schema:").append(schema).append(nl); + sb.append("Configured catalog:").append(catalog ).append(nl); + + try { + schemaRs = getMetaData().getSchemas(); + sb.append("Available schemas:").append(nl); + while (schemaRs.next() ) { + sb.append(" ").append(schemaRs.getString("TABLE_SCHEM") ).append(nl); + } + } + catch (SQLException e2) { + log.warn("Could not get schemas", e2); + sb.append(" ").append(nl); + } + finally { + try { + if (schemaRs != null) { + schemaRs.close(); + } + } + catch (Exception ignore) { + } + } + + try { + catalogRs = getMetaData().getCatalogs(); + sb.append("Available catalogs:").append(nl); + while (catalogRs.next() ) { + sb.append(" ").append(catalogRs.getString("TABLE_CAT") ).append(nl); + } + } + catch (SQLException e2) { + log.warn("Could not get catalogs", e2); + sb.append(" ").append(nl); + } + finally { + try { + if (catalogRs != null) { + catalogRs.close(); + } + } + catch (Exception ignore) { + } + } + return sb.toString(); + } + + protected Connection getConnection() throws SQLException { + if(connection==null) { + connection = connectionProvider.getConnection(); + } + return connection; + } + + public void close(Iterator iterator) { + if(iterator instanceof ResultSetIterator) { + ((ResultSetIterator)iterator).close(); + } + } + + public boolean needQuote(String name) { + + if(name==null) return false; + + // TODO: use jdbc metadata to decide on this. but for now we just handle the most typical cases. + if(name.indexOf('-')>0) return true; + if(name.indexOf(' ')>0) return true; + return name.indexOf( '.' ) > 0; + } + + protected String caseForSearch(String value) throws SQLException { + // TODO: handle quoted requests (just strip it ?) + if(needQuote(value)) { + if ( getMetaData().storesMixedCaseQuotedIdentifiers() ) { + return value; + } + else if ( getMetaData().storesUpperCaseQuotedIdentifiers() ) { + return toUpperCase( value ); + } + else if( getMetaData().storesLowerCaseQuotedIdentifiers() ) { + return toLowerCase( value ); + } + else { + return value; + } + } + else if ( getMetaData().storesMixedCaseQuotedIdentifiers() ) { + return value; + } + else if ( getMetaData().storesUpperCaseIdentifiers() ) { + return toUpperCase( value ); + } + else if( getMetaData().storesLowerCaseIdentifiers() ) { + return toLowerCase( value ); + } + else { + return value; + } + } + + private String toUpperCase(String str) { + return str==null ? null : str.toUpperCase(); + } + + private String toLowerCase(String str) { + return str == null ? null : str.toLowerCase(Locale.ENGLISH); + } + + public Iterator> getSuggestedPrimaryKeyStrategyName(String catalog, String schema, String table) { + Map m = new HashMap<>(); + m.put( "TABLE_CAT", catalog ); + m.put( "TABLE_SCHEMA", schema ); + m.put( "TABLE_NAME", table ); + m.put( "HIBERNATE_STRATEGY", null ); + List> l = new ArrayList<>(); + l.add(m); + return l.iterator(); + } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/CachedMetaDataDialect.java b/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/CachedMetaDataDialect.java index a80f1256c..14a801798 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/CachedMetaDataDialect.java +++ b/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/CachedMetaDataDialect.java @@ -28,195 +28,201 @@ public class CachedMetaDataDialect implements RevengDialect { - RevengDialect delegate; - private final Map>> cachedTables = new HashMap>>(); - private final Map>> cachedColumns = new HashMap>>(); - private final Map>> cachedExportedKeys = new HashMap>>(); - private final Map>> cachedPrimaryKeys = new HashMap>>(); - private final Map>> cachedIndexInfo = new HashMap>>(); - private final Map>> cachedPrimaryKeyStrategyName = new HashMap>>(); - - public CachedMetaDataDialect(RevengDialect realMetaData) { - this.delegate = realMetaData; - } - - public void close() { - delegate.close(); - } - - public void configure( - ConnectionProvider connectionProvider) { - delegate.configure(connectionProvider); - } - - public void close(Iterator iterator) { - if( iterator instanceof CachedIterator ci ) { - if(ci.getOwner()==this) { - ci.store(); - return; - } - } - delegate.close( iterator ); - } - - - - public Iterator> getColumns(String catalog, String schema, String table, String column) { - StringKey sk = new StringKey(new String[] { catalog, schema, table, column }); - List> cached = cachedColumns.get( sk ); - if(cached==null) { - cached = new ArrayList>(); - return new CachedIterator(this, cachedColumns, sk, cached, delegate.getColumns( catalog, schema, table, column )); - } else { - return cached.iterator(); - } - } - - public Iterator> getExportedKeys(String catalog, String schema, String table) { - StringKey sk = new StringKey(new String[] { catalog, schema, table }); - List> cached = cachedExportedKeys.get( sk ); - if(cached==null) { - cached = new ArrayList>(); - return new CachedIterator(this, cachedExportedKeys, sk, cached, delegate.getExportedKeys( catalog, schema, table )); - } else { - return cached.iterator(); - } - } - - public Iterator> getIndexInfo(String catalog, String schema, String table) { - StringKey sk = new StringKey(new String[] { catalog, schema, table }); - List> cached = cachedIndexInfo.get( sk ); - if(cached==null) { - cached = new ArrayList>(); - return new CachedIterator(this, cachedIndexInfo, sk, cached, delegate.getIndexInfo( catalog, schema, table )); - } else { - return cached.iterator(); - } - } - - public Iterator> getPrimaryKeys(String catalog, String schema, String name) { - StringKey sk = new StringKey(new String[] { catalog, schema, name }); - List> cached = cachedPrimaryKeys .get( sk ); - if(cached==null) { - cached = new ArrayList>(); - return new CachedIterator(this, cachedPrimaryKeys, sk, cached, delegate.getPrimaryKeys( catalog, schema, name )); - } else { - return cached.iterator(); - } - } - - public Iterator> getTables(String catalog, String schema, String table) { - StringKey sk = new StringKey(new String[] { catalog, schema, table }); - List> cached = cachedTables.get( sk ); - if(cached==null) { - cached = new ArrayList>(); - return new CachedIterator(this, cachedTables, sk, cached, delegate.getTables( catalog, schema, table )); - } else { - return cached.iterator(); - } - } - - public Iterator> getSuggestedPrimaryKeyStrategyName(String catalog, String schema, String table) { - StringKey sk = new StringKey(new String[] { catalog, schema, table }); - List> cached = cachedPrimaryKeyStrategyName.get( sk ); - if(cached==null) { - cached = new ArrayList>(); - return new CachedIterator(this, cachedPrimaryKeyStrategyName, sk, cached, delegate.getSuggestedPrimaryKeyStrategyName( catalog, schema, table )); - } else { - return cached.iterator(); - } - } - - public boolean needQuote(String name) { - return delegate.needQuote( name ); - } - - private static class StringKey { - String[] keys; - - StringKey(String[] key) { - this.keys=key; - } - - public int hashCode() { - if (keys == null) - return 0; - - int result = 1; - - for ( Object element : keys ) { - result = 31 * result + (element == null ? 0 : element.hashCode()); - } - - return result; - } - - public boolean equals(Object obj) { - if (!(obj instanceof StringKey other)) return false; - String[] otherKeys = other.keys; - if(otherKeys.length!=keys.length) { - return false; - } - - for (int i = otherKeys.length-1; i >= 0; i--) { - if(!safeEquals(otherKeys[i],(keys[i]))) { - return false; - } - } - - return true; - } - - private boolean safeEquals(Object obj1, Object obj2) { - if ( obj1 == null ) { - return obj2 == null; - } - return obj1.equals( obj2 ); - } - } - - private static class CachedIterator implements Iterator> { - - private List> cache; - private StringKey target; - private Map>> destination; - private Iterator> realIterator; - final CachedMetaDataDialect owner; - public CachedIterator(CachedMetaDataDialect owner, Map>> destination, StringKey sk, List> cache, Iterator> realIterator) { - this.owner = owner; - this.destination = destination; - this.target = sk; - this.realIterator = realIterator; - this.cache = cache; - } - - public CachedMetaDataDialect getOwner() { - return owner; - } - - public boolean hasNext() { - return realIterator.hasNext(); - } - - public Map next() { - Map map = realIterator.next(); - cache.add(new HashMap(map)); // need to copy since MetaDataDialect might reuse it. - return map; - } - - public void remove() { - realIterator.remove(); - } - - public void store() { - destination.put( target, cache ); - if(realIterator.hasNext()) throw new IllegalStateException("CachedMetaDataDialect have not been fully initialized!"); - cache = null; - target = null; - destination = null; - realIterator = null; - } - } + RevengDialect delegate; + private final Map>> cachedTables = new HashMap<>(); + private final Map>> cachedColumns = new HashMap<>(); + private final Map>> cachedExportedKeys = new HashMap<>(); + private final Map>> cachedPrimaryKeys = new HashMap<>(); + private final Map>> cachedIndexInfo = new HashMap<>(); + private final Map>> cachedPrimaryKeyStrategyName = new HashMap<>(); + + public CachedMetaDataDialect(RevengDialect realMetaData) { + this.delegate = realMetaData; + } + + public void close() { + delegate.close(); + } + + public void configure( + ConnectionProvider connectionProvider) { + delegate.configure(connectionProvider); + } + + public void close(Iterator iterator) { + if( iterator instanceof CachedIterator ci ) { + if(ci.getOwner()==this) { + ci.store(); + return; + } + } + delegate.close( iterator ); + } + + + + public Iterator> getColumns(String catalog, String schema, String table, String column) { + StringKey sk = new StringKey(new String[] { catalog, schema, table, column }); + List> cached = cachedColumns.get( sk ); + if(cached==null) { + cached = new ArrayList<>(); + return new CachedIterator(this, cachedColumns, sk, cached, delegate.getColumns( catalog, schema, table, column )); + } + else { + return cached.iterator(); + } + } + + public Iterator> getExportedKeys(String catalog, String schema, String table) { + StringKey sk = new StringKey(new String[] { catalog, schema, table }); + List> cached = cachedExportedKeys.get( sk ); + if(cached==null) { + cached = new ArrayList<>(); + return new CachedIterator(this, cachedExportedKeys, sk, cached, delegate.getExportedKeys( catalog, schema, table )); + } + else { + return cached.iterator(); + } + } + + public Iterator> getIndexInfo(String catalog, String schema, String table) { + StringKey sk = new StringKey(new String[] { catalog, schema, table }); + List> cached = cachedIndexInfo.get( sk ); + if(cached==null) { + cached = new ArrayList<>(); + return new CachedIterator(this, cachedIndexInfo, sk, cached, delegate.getIndexInfo( catalog, schema, table )); + } + else { + return cached.iterator(); + } + } + + public Iterator> getPrimaryKeys(String catalog, String schema, String name) { + StringKey sk = new StringKey(new String[] { catalog, schema, name }); + List> cached = cachedPrimaryKeys .get( sk ); + if(cached==null) { + cached = new ArrayList<>(); + return new CachedIterator(this, cachedPrimaryKeys, sk, cached, delegate.getPrimaryKeys( catalog, schema, name )); + } + else { + return cached.iterator(); + } + } + + public Iterator> getTables(String catalog, String schema, String table) { + StringKey sk = new StringKey(new String[] { catalog, schema, table }); + List> cached = cachedTables.get( sk ); + if(cached==null) { + cached = new ArrayList<>(); + return new CachedIterator(this, cachedTables, sk, cached, delegate.getTables( catalog, schema, table )); + } + else { + return cached.iterator(); + } + } + + public Iterator> getSuggestedPrimaryKeyStrategyName(String catalog, String schema, String table) { + StringKey sk = new StringKey(new String[] { catalog, schema, table }); + List> cached = cachedPrimaryKeyStrategyName.get( sk ); + if(cached==null) { + cached = new ArrayList<>(); + return new CachedIterator(this, cachedPrimaryKeyStrategyName, sk, cached, delegate.getSuggestedPrimaryKeyStrategyName( catalog, schema, table )); + } + else { + return cached.iterator(); + } + } + + public boolean needQuote(String name) { + return delegate.needQuote( name ); + } + + private static class StringKey { + String[] keys; + + StringKey(String[] key) { + this.keys=key; + } + + public int hashCode() { + if (keys == null) + return 0; + + int result = 1; + + for ( Object element : keys ) { + result = 31 * result + (element == null ? 0 : element.hashCode()); + } + + return result; + } + + public boolean equals(Object obj) { + if (!(obj instanceof StringKey other)) return false; + String[] otherKeys = other.keys; + if(otherKeys.length!=keys.length) { + return false; + } + + for (int i = otherKeys.length-1; i >= 0; i--) { + if(!safeEquals(otherKeys[i],(keys[i]))) { + return false; + } + } + + return true; + } + + private boolean safeEquals(Object obj1, Object obj2) { + if ( obj1 == null ) { + return obj2 == null; + } + return obj1.equals( obj2 ); + } + } + + private static class CachedIterator implements Iterator> { + + private List> cache; + private StringKey target; + private Map>> destination; + private Iterator> realIterator; + final CachedMetaDataDialect owner; + public CachedIterator(CachedMetaDataDialect owner, Map>> destination, StringKey sk, List> cache, Iterator> realIterator) { + this.owner = owner; + this.destination = destination; + this.target = sk; + this.realIterator = realIterator; + this.cache = cache; + } + + public CachedMetaDataDialect getOwner() { + return owner; + } + + public boolean hasNext() { + return realIterator.hasNext(); + } + + public Map next() { + Map map = realIterator.next(); + cache.add( new HashMap<>( map )); // need to copy since MetaDataDialect might reuse it. + return map; + } + + public void remove() { + realIterator.remove(); + } + + public void store() { + destination.put( target, cache ); + if(realIterator.hasNext()) throw new IllegalStateException("CachedMetaDataDialect have not been fully initialized!"); + cache = null; + target = null; + destination = null; + realIterator = null; + } + } diff --git a/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/H2MetaDataDialect.java b/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/H2MetaDataDialect.java index b6ed79f37..b655d94a3 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/H2MetaDataDialect.java +++ b/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/H2MetaDataDialect.java @@ -34,121 +34,122 @@ * */ public class H2MetaDataDialect extends JDBCMetaDataDialect { - - private static final String SPKSQ_H2_1_X = - "SELECT " + - " idx.TABLE_CATALOG TABLE_CAT, " + - " idx.TABLE_SCHEMA TABLE_SCHEM, " + - " idx.TABLE_NAME, " + - " idx.COLUMN_NAME " + - "FROM " + - " INFORMATION_SCHEMA.INDEXES idx, " + - " INFORMATION_SCHEMA.COLUMNS cols " + - "WHERE " + - " idx.TABLE_CATALOG = cols.TABLE_CATALOG AND " + - " idx.TABLE_SCHEMA = cols.TABLE_SCHEMA AND " + - " idx.TABLE_NAME = cols.TABLE_NAME AND " + - " idx.PRIMARY_KEY = TRUE AND " + - " cols.COLUMN_DEFAULT like '%NEXT VALUE FOR%' "; - - private static final String SPKSQ_H2_2_X = - "SELECT " + - " idx.TABLE_CATALOG TABLE_CAT, " + - " idx.TABLE_SCHEMA TABLE_SCHEM, " + - " idx.TABLE_NAME, " + - " cols.COLUMN_NAME " + - "FROM " + - " INFORMATION_SCHEMA.INDEXES idx, " + - " INFORMATION_SCHEMA.INDEX_COLUMNS idx_cols, " + - " INFORMATION_SCHEMA.COLUMNS cols " + - "WHERE " + - " idx.TABLE_CATALOG = cols.TABLE_CATALOG AND " + - " idx.TABLE_SCHEMA = cols.TABLE_SCHEMA AND " + - " idx.TABLE_NAME = cols.TABLE_NAME AND " + - " idx.INDEX_TYPE_NAME = 'PRIMARY KEY' AND " + - " cols.COLUMN_NAME = idx_cols.COLUMN_NAME AND " + - " cols.IS_IDENTITY = 'YES'"; - - private static boolean understandsCatalogName = true; - - private String suggested_primary_key_strategy_query = null; - - public H2MetaDataDialect() { - super(); - try { - Class constants = ReflectionUtil.classForName( "org.h2.engine.Constants" ); - Integer build = (Integer)constants.getDeclaredField( "BUILD_ID" ).get( null ); - if ( build.intValue() < 55 ) { - understandsCatalogName = false; - } - suggested_primary_key_strategy_query = build.intValue() > 200 ? SPKSQ_H2_2_X : SPKSQ_H2_1_X; - } + + private static final String SPKSQ_H2_1_X = + "SELECT " + + " idx.TABLE_CATALOG TABLE_CAT, " + + " idx.TABLE_SCHEMA TABLE_SCHEM, " + + " idx.TABLE_NAME, " + + " idx.COLUMN_NAME " + + "FROM " + + " INFORMATION_SCHEMA.INDEXES idx, " + + " INFORMATION_SCHEMA.COLUMNS cols " + + "WHERE " + + " idx.TABLE_CATALOG = cols.TABLE_CATALOG AND " + + " idx.TABLE_SCHEMA = cols.TABLE_SCHEMA AND " + + " idx.TABLE_NAME = cols.TABLE_NAME AND " + + " idx.PRIMARY_KEY = TRUE AND " + + " cols.COLUMN_DEFAULT like '%NEXT VALUE FOR%' "; + + private static final String SPKSQ_H2_2_X = + "SELECT " + + " idx.TABLE_CATALOG TABLE_CAT, " + + " idx.TABLE_SCHEMA TABLE_SCHEM, " + + " idx.TABLE_NAME, " + + " cols.COLUMN_NAME " + + "FROM " + + " INFORMATION_SCHEMA.INDEXES idx, " + + " INFORMATION_SCHEMA.INDEX_COLUMNS idx_cols, " + + " INFORMATION_SCHEMA.COLUMNS cols " + + "WHERE " + + " idx.TABLE_CATALOG = cols.TABLE_CATALOG AND " + + " idx.TABLE_SCHEMA = cols.TABLE_SCHEMA AND " + + " idx.TABLE_NAME = cols.TABLE_NAME AND " + + " idx.INDEX_TYPE_NAME = 'PRIMARY KEY' AND " + + " cols.COLUMN_NAME = idx_cols.COLUMN_NAME AND " + + " cols.IS_IDENTITY = 'YES'"; + + private static boolean understandsCatalogName = true; + + private String suggested_primary_key_strategy_query = null; + + public H2MetaDataDialect() { + super(); + try { + Class constants = ReflectionUtil.classForName( "org.h2.engine.Constants" ); + Integer build = (Integer)constants.getDeclaredField( "BUILD_ID" ).get( null ); + if ( build < 55 ) { + understandsCatalogName = false; + } + suggested_primary_key_strategy_query = build > 200 ? SPKSQ_H2_2_X : SPKSQ_H2_1_X; + } catch( Throwable e ) { // ignore (probably H2 not in the classpath) } - } - - protected void putTableType(Map element, ResultSet tableRs) throws SQLException { - String tableType = tableRs.getString("TABLE_TYPE"); - if ("BASE TABLE".equals(tableType)) { - tableType = "TABLE"; - } - element.put("TABLE_TYPE", tableType); - } - - protected void putTablePart(Map element, ResultSet tableRs) throws SQLException { - super.putTablePart( element, tableRs ); - if ( !understandsCatalogName ) { - element.put( "TABLE_CAT", null ); - } - } - - protected void putExportedKeysPart(Map element, ResultSet rs) throws SQLException { - super.putExportedKeysPart( element, rs ); - if ( !understandsCatalogName ) { - element.put( "PKTABLE_CAT", null ); - } - } - - public Iterator> getSuggestedPrimaryKeyStrategyName(String catalog, String schema, String table) { - try { - catalog = caseForSearch( catalog ); - schema = caseForSearch( schema ); - table = caseForSearch( table ); - - log.debug("geSuggestedPrimaryKeyStrategyName(" + catalog + "." + schema + "." + table + ")"); - - String sql = suggested_primary_key_strategy_query; - if(catalog!=null) { - sql += "AND idx.TABLE_CATALOG like '" + catalog + "' "; - } - if(schema!=null) { - sql += "AND idx.TABLE_SCHEMA like '" + schema + "' "; - } - if(table!=null) { - sql += "AND idx.TABLE_NAME like '" + table + "' "; - } - - PreparedStatement statement = getConnection().prepareStatement( sql ); - - return new ResultSetIterator(statement.executeQuery()) { - - Map element = new HashMap(); - protected Map convertRow(ResultSet tableRs) throws SQLException { - element.clear(); - putTablePart( element, tableRs ); - element.put("HIBERNATE_STRATEGY", "identity"); - return element; - } - protected Throwable handleSQLException(SQLException e) { - // schemaRs and catalogRs are only used for error reporting if - // we get an exception - throw new RuntimeException( - "Could not get list of suggested identity strategies from database. Probably a JDBC driver problem. ", e ); - } - }; - } catch (SQLException e) { - throw new RuntimeException("Could not get list of suggested identity strategies from database. Probably a JDBC driver problem.", e); - } - } + } + + protected void putTableType(Map element, ResultSet tableRs) throws SQLException { + String tableType = tableRs.getString("TABLE_TYPE"); + if ("BASE TABLE".equals(tableType)) { + tableType = "TABLE"; + } + element.put("TABLE_TYPE", tableType); + } + + protected void putTablePart(Map element, ResultSet tableRs) throws SQLException { + super.putTablePart( element, tableRs ); + if ( !understandsCatalogName ) { + element.put( "TABLE_CAT", null ); + } + } + + protected void putExportedKeysPart(Map element, ResultSet rs) throws SQLException { + super.putExportedKeysPart( element, rs ); + if ( !understandsCatalogName ) { + element.put( "PKTABLE_CAT", null ); + } + } + + public Iterator> getSuggestedPrimaryKeyStrategyName(String catalog, String schema, String table) { + try { + catalog = caseForSearch( catalog ); + schema = caseForSearch( schema ); + table = caseForSearch( table ); + + log.debug("geSuggestedPrimaryKeyStrategyName(" + catalog + "." + schema + "." + table + ")"); + + String sql = suggested_primary_key_strategy_query; + if(catalog!=null) { + sql += "AND idx.TABLE_CATALOG like '" + catalog + "' "; + } + if(schema!=null) { + sql += "AND idx.TABLE_SCHEMA like '" + schema + "' "; + } + if(table!=null) { + sql += "AND idx.TABLE_NAME like '" + table + "' "; + } + + PreparedStatement statement = getConnection().prepareStatement( sql ); + + return new ResultSetIterator(statement.executeQuery()) { + + final Map element = new HashMap<>(); + protected Map convertRow(ResultSet tableRs) throws SQLException { + element.clear(); + putTablePart( element, tableRs ); + element.put("HIBERNATE_STRATEGY", "identity"); + return element; + } + protected Throwable handleSQLException(SQLException e) { + // schemaRs and catalogRs are only used for error reporting if + // we get an exception + throw new RuntimeException( + "Could not get list of suggested identity strategies from database. Probably a JDBC driver problem. ", e ); + } + }; + } + catch (SQLException e) { + throw new RuntimeException("Could not get list of suggested identity strategies from database. Probably a JDBC driver problem.", e); + } + } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/HSQLMetaDataDialect.java b/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/HSQLMetaDataDialect.java index 245aca050..8e5c223d6 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/HSQLMetaDataDialect.java +++ b/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/HSQLMetaDataDialect.java @@ -33,84 +33,78 @@ */ public class HSQLMetaDataDialect extends JDBCMetaDataDialect { - private String quote(String columnName) { - if(columnName==null) return columnName; - if(needQuote(columnName)) { - if(columnName.length()>1 && columnName.charAt(0)=='\"' && columnName.charAt(columnName.length()-1)=='\"') { - return columnName; // avoid double quoting - } - return "\"" + columnName + "\""; - } else { - return columnName; - } - } - - public Iterator> getSuggestedPrimaryKeyStrategyName(String catalog, String schema, String table) { - try { - catalog = caseForSearch( catalog ); - schema = caseForSearch( schema ); - table = caseForSearch( table ); - - //log.debug("geSuggestedPrimaryKeyStrategyName(" + catalog + "." + schema + "." + table + ")"); - - final String sc = schema; - final String cat = catalog; - return new ResultSetIterator(getMetaData().getTables(catalog, schema, table, new String[]{"TABLE"})) { - - Map element = new HashMap(); - protected Map convertRow(ResultSet tableRs) throws SQLException{ - String table = tableRs.getString("TABLE_NAME"); - String fullTableName = TableNameQualifier.qualify(quote(cat), quote(sc), quote(table)); - - String sql ="SELECT * FROM " + fullTableName + " WHERE 0>1"; // can't use FALSE constant since it would not work with older HSQL versions. (JBIDE-5957) - boolean isAutoIncrement = false; - - PreparedStatement statement = null; - try { - statement = getConnection().prepareStatement( sql ); - element.clear(); - element.put("TABLE_NAME", table); - element.put("TABLE_SCHEM", sc); - element.put("TABLE_CAT", null); + private String quote(String columnName) { + if(columnName==null) return null; + if(needQuote(columnName)) { + if(columnName.length()>1 && columnName.charAt(0)=='\"' && columnName.charAt(columnName.length()-1)=='\"') { + return columnName; // avoid double quoting + } + return "\"" + columnName + "\""; + } + else { + return columnName; + } + } - ResultSet rs = statement.executeQuery(); - ResultSetMetaData rsmd = rs.getMetaData(); - for (int i = 0; i < rsmd.getColumnCount(); i++) { - isAutoIncrement = rsmd.isAutoIncrement(i + 1); - if (isAutoIncrement) break; - } + public Iterator> getSuggestedPrimaryKeyStrategyName(String catalog, String schema, String table) { + try { + catalog = caseForSearch( catalog ); + schema = caseForSearch( schema ); + table = caseForSearch( table ); - } catch(SQLException e) { - //log error and set HIBERNATE_STRATEGY to null - log.debug("Error while getting suggested primary key strategy for " + fullTableName + ". Falling back to default strategy.",e); - } finally { - if(statement!=null) { - try { - statement.close(); - } - catch (SQLException e) { - throw new RuntimeException( - "Problem while closing prepared statement", e); - } - } - } + //log.debug("geSuggestedPrimaryKeyStrategyName(" + catalog + "." + schema + "." + table + ")"); - if(isAutoIncrement) { - element.put("HIBERNATE_STRATEGY", "identity"); - } else { - element.put("HIBERNATE_STRATEGY", null); - } - return element; - } - protected Throwable handleSQLException(SQLException e) { - // schemaRs and catalogRs are only used for error reporting if - // we get an exception - throw new RuntimeException( - "Could not get list of suggested identity strategies from database. Probably a JDBC driver problem. ", e); - } - }; - } catch (SQLException e) { - throw new RuntimeException("Could not get list of suggested identity strategies from database. Probably a JDBC driver problem. ", e); - } - } + final String sc = schema; + final String cat = catalog; + return new ResultSetIterator(getMetaData().getTables(catalog, schema, table, new String[]{"TABLE"})) { + + final Map element = new HashMap<>(); + protected Map convertRow(ResultSet tableRs) throws SQLException{ + String table = tableRs.getString("TABLE_NAME"); + String fullTableName = TableNameQualifier.qualify(quote(cat), quote(sc), quote(table)); + + String sql ="SELECT * FROM " + fullTableName + " WHERE 0>1"; // can't use FALSE constant since it would not work with older HSQL versions. (JBIDE-5957) + boolean isAutoIncrement = false; + + try (PreparedStatement statement = getConnection().prepareStatement( sql )) { + element.clear(); + element.put( "TABLE_NAME", table ); + element.put( "TABLE_SCHEM", sc ); + element.put( "TABLE_CAT", null ); + + ResultSet rs = statement.executeQuery(); + ResultSetMetaData rsmd = rs.getMetaData(); + for ( int i = 0; i < rsmd.getColumnCount(); i++ ) { + isAutoIncrement = rsmd.isAutoIncrement( i + 1 ); + if ( isAutoIncrement ) break; + } + + } + catch (SQLException e) { + //log error and set HIBERNATE_STRATEGY to null + log.debug( + "Error while getting suggested primary key strategy for " + fullTableName + ". Falling back to default strategy.", + e ); + } + + if(isAutoIncrement) { + element.put("HIBERNATE_STRATEGY", "identity"); + } + else { + element.put("HIBERNATE_STRATEGY", null); + } + return element; + } + protected Throwable handleSQLException(SQLException e) { + // schemaRs and catalogRs are only used for error reporting if + // we get an exception + throw new RuntimeException( + "Could not get list of suggested identity strategies from database. Probably a JDBC driver problem. ", e); + } + }; + } + catch (SQLException e) { + throw new RuntimeException("Could not get list of suggested identity strategies from database. Probably a JDBC driver problem. ", e); + } + } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/JDBCMetaDataDialect.java b/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/JDBCMetaDataDialect.java index 319ab8351..1728b5bb1 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/JDBCMetaDataDialect.java +++ b/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/JDBCMetaDataDialect.java @@ -32,193 +32,197 @@ * */ public class JDBCMetaDataDialect extends AbstractMetaDataDialect { - - public Iterator> getTables(String xcatalog, String xschema, String xtable) { - try { - final String catalog = caseForSearch( xcatalog ); - final String schema = caseForSearch( xschema ); - final String table = caseForSearch( xtable ); - - log.debug("getTables(" + catalog + "." + schema + "." + table + ")"); - - ResultSet tableRs = getMetaData().getTables(catalog , schema , table, new String[] { "TABLE", "VIEW" }); - - return new ResultSetIterator(tableRs) { - - Map element = new HashMap(); - protected Map convertRow(ResultSet tableResultSet) throws SQLException { - element.clear(); - putTablePart( element, tableResultSet ); - putTableType(element, tableResultSet); - element.put("REMARKS", tableResultSet.getString("REMARKS")); - return element; - } - protected Throwable handleSQLException(SQLException e) { - // schemaRs and catalogRs are only used for error reporting if - // we get an exception - String databaseStructure = getDatabaseStructure( catalog, schema ); - throw new RuntimeException( - "Could not get list of tables from database. Probably a JDBC driver problem. " - + databaseStructure, - e ); - } - }; - } catch (SQLException e) { - // schemaRs and catalogRs are only used for error reporting if we get an exception - String databaseStructure = getDatabaseStructure(xcatalog,xschema); - throw new RuntimeException( - "Could not get list of tables from database. Probably a JDBC driver problem. " + databaseStructure, e); - } - } - - public Iterator> getIndexInfo(final String xcatalog, final String xschema, final String xtable) { - try { - final String catalog = caseForSearch( xcatalog ); - final String schema = caseForSearch( xschema ); - final String table = caseForSearch( xtable ); - - log.debug("getIndexInfo(" + catalog + "." + schema + "." + table + ")"); - ResultSet tableRs = getMetaData().getIndexInfo(catalog , schema , table, false, true); - - return new ResultSetIterator(tableRs) { - - Map element = new HashMap(); - protected Map convertRow(ResultSet rs) throws SQLException { - element.clear(); - putTablePart(element, rs); - element.put("INDEX_NAME", rs.getString("INDEX_NAME")); - element.put("COLUMN_NAME", rs.getString("COLUMN_NAME")); - element.put("NON_UNIQUE", Boolean.valueOf(rs.getBoolean("NON_UNIQUE"))); - element.put("TYPE", Short.valueOf(rs.getShort("TYPE"))); - return element; - } - protected Throwable handleSQLException(SQLException e) { - throw new RuntimeException( - "Exception while getting index info for " + TableNameQualifier.qualify(catalog, schema, table), e); - } - }; - } catch (SQLException e) { - throw new RuntimeException( - "Exception while getting index info for " + TableNameQualifier.qualify(xcatalog, xschema, xtable), e); - } - } - - protected void putTableType(Map element, ResultSet tableRs) throws SQLException { - element.put("TABLE_TYPE", tableRs.getString("TABLE_TYPE")); - } - - protected void putTablePart(Map element, ResultSet tableRs) throws SQLException { - element.put("TABLE_NAME", tableRs.getString("TABLE_NAME")); - element.put("TABLE_SCHEM", tableRs.getString("TABLE_SCHEM")); - element.put("TABLE_CAT", tableRs.getString("TABLE_CAT")); - } - - public Iterator> getColumns(final String xcatalog, final String xschema, final String xtable, String xcolumn) { - try { - final String catalog = caseForSearch( xcatalog ); - final String schema = caseForSearch( xschema ); - final String table = caseForSearch( xtable ); - final String column = caseForSearch( xcolumn ); - - log.debug("getColumns(" + catalog + "." + schema + "." + table + "." + column + ")"); - ResultSet tableRs = getMetaData().getColumns(catalog, schema, table, column); - - return new ResultSetIterator(tableRs) { - - Map element = new HashMap(); - protected Map convertRow(ResultSet rs) throws SQLException { - element.clear(); - putTablePart(element, rs); - element.put("DATA_TYPE", Integer.valueOf(rs.getInt("DATA_TYPE"))); - element.put("TYPE_NAME", rs.getString("TYPE_NAME")); - element.put("COLUMN_NAME", rs.getString("COLUMN_NAME")); - element.put("NULLABLE", Integer.valueOf(rs.getInt("NULLABLE"))); - element.put("COLUMN_SIZE", Integer.valueOf(rs.getInt("COLUMN_SIZE"))); - element.put("DECIMAL_DIGITS", Integer.valueOf(rs.getInt("DECIMAL_DIGITS"))); - element.put("REMARKS", rs.getString("REMARKS")); - return element; - } - protected Throwable handleSQLException(SQLException e) { - throw new RuntimeException("Error while reading column meta data for " + TableNameQualifier.qualify(catalog, schema, table), e); - } - }; - } catch (SQLException e) { - throw new RuntimeException("Error while reading column meta data for " + TableNameQualifier.qualify(xcatalog, xschema, xtable), e); - } - } - - public Iterator> getPrimaryKeys(final String xcatalog, final String xschema, final String xtable) { - try { - final String catalog = caseForSearch( xcatalog ); - final String schema = caseForSearch( xschema ); - final String table = caseForSearch( xtable ); - - log.debug("getPrimaryKeys(" + catalog + "." + schema + "." + table + ")"); - ResultSet tableRs = getMetaData().getPrimaryKeys(catalog, schema, table); - - return new ResultSetIterator(tableRs) { - - Map element = new HashMap(); - protected Map convertRow(ResultSet rs) throws SQLException { - element.clear(); - putTablePart(element, rs); - element.put("COLUMN_NAME", rs.getString("COLUMN_NAME")); - element.put("KEY_SEQ", Short.valueOf(rs.getShort("KEY_SEQ"))); - element.put("PK_NAME", rs.getString("PK_NAME")); - return element; - } - protected Throwable handleSQLException(SQLException e) { - throw new RuntimeException( - "Error while reading primary key meta data for " + TableNameQualifier.qualify(catalog, schema, table), - e); - } - }; - } catch (SQLException e) { - throw new RuntimeException( - "Error while reading primary key meta data for " + TableNameQualifier.qualify(xcatalog, xschema, xtable), e); - } - } - - public Iterator> getExportedKeys(final String xcatalog, final String xschema, final String xtable) { - try { - final String catalog = caseForSearch( xcatalog ); - final String schema = caseForSearch( xschema ); - final String table = caseForSearch( xtable ); - - log.debug("getExportedKeys(" + catalog + "." + schema + "." + table + ")"); - ResultSet tableRs = getMetaData().getExportedKeys(catalog, schema, table); - - return new ResultSetIterator(tableRs) { - - Map element = new HashMap(); - protected Map convertRow(ResultSet rs) throws SQLException { - element.clear(); - putExportedKeysPart( element, rs ); - return element; - } - protected Throwable handleSQLException(SQLException e) { - throw new RuntimeException( - "Error while reading exported keys meta data for " + TableNameQualifier.qualify(catalog, schema, table), e); - } - }; - } catch (SQLException e) { - throw new RuntimeException( - "Error while reading exported keys meta data for " + TableNameQualifier.qualify(xcatalog, xschema, xtable), e); - } - } - - protected void putExportedKeysPart(Map element, ResultSet rs) throws SQLException { - element.put( "PKTABLE_NAME", rs.getString("PKTABLE_NAME")); - element.put( "PKTABLE_SCHEM", rs.getString("PKTABLE_SCHEM")); - element.put( "PKTABLE_CAT", rs.getString("PKTABLE_CAT")); - element.put( "FKTABLE_CAT", rs.getString("FKTABLE_CAT")); - element.put( "FKTABLE_SCHEM",rs.getString("FKTABLE_SCHEM")); - element.put( "FKTABLE_NAME", rs.getString("FKTABLE_NAME")); - element.put( "FKCOLUMN_NAME", rs.getString("FKCOLUMN_NAME")); - element.put( "PKCOLUMN_NAME", rs.getString("PKCOLUMN_NAME")); - element.put( "FK_NAME", rs.getString("FK_NAME")); - element.put( "KEY_SEQ", Short.valueOf(rs.getShort("KEY_SEQ"))); - } - - + + public Iterator> getTables(String xcatalog, String xschema, String xtable) { + try { + final String catalog = caseForSearch( xcatalog ); + final String schema = caseForSearch( xschema ); + final String table = caseForSearch( xtable ); + + log.debug("getTables(" + catalog + "." + schema + "." + table + ")"); + + ResultSet tableRs = getMetaData().getTables(catalog , schema , table, new String[] { "TABLE", "VIEW" }); + + return new ResultSetIterator(tableRs) { + + final Map element = new HashMap<>(); + protected Map convertRow(ResultSet tableResultSet) throws SQLException { + element.clear(); + putTablePart( element, tableResultSet ); + putTableType(element, tableResultSet); + element.put("REMARKS", tableResultSet.getString("REMARKS")); + return element; + } + protected Throwable handleSQLException(SQLException e) { + // schemaRs and catalogRs are only used for error reporting if + // we get an exception + String databaseStructure = getDatabaseStructure( catalog, schema ); + throw new RuntimeException( + "Could not get list of tables from database. Probably a JDBC driver problem. " + + databaseStructure, + e ); + } + }; + } + catch (SQLException e) { + // schemaRs and catalogRs are only used for error reporting if we get an exception + String databaseStructure = getDatabaseStructure(xcatalog,xschema); + throw new RuntimeException( + "Could not get list of tables from database. Probably a JDBC driver problem. " + databaseStructure, e); + } + } + + public Iterator> getIndexInfo(final String xcatalog, final String xschema, final String xtable) { + try { + final String catalog = caseForSearch( xcatalog ); + final String schema = caseForSearch( xschema ); + final String table = caseForSearch( xtable ); + + log.debug("getIndexInfo(" + catalog + "." + schema + "." + table + ")"); + ResultSet tableRs = getMetaData().getIndexInfo(catalog , schema , table, false, true); + + return new ResultSetIterator(tableRs) { + + final Map element = new HashMap<>(); + protected Map convertRow(ResultSet rs) throws SQLException { + element.clear(); + putTablePart(element, rs); + element.put("INDEX_NAME", rs.getString("INDEX_NAME")); + element.put("COLUMN_NAME", rs.getString("COLUMN_NAME")); + element.put("NON_UNIQUE", rs.getBoolean( "NON_UNIQUE" ) ); + element.put("TYPE", rs.getShort( "TYPE" ) ); + return element; + } + protected Throwable handleSQLException(SQLException e) { + throw new RuntimeException( + "Exception while getting index info for " + TableNameQualifier.qualify(catalog, schema, table), e); + } + }; + } + catch (SQLException e) { + throw new RuntimeException( + "Exception while getting index info for " + TableNameQualifier.qualify(xcatalog, xschema, xtable), e); + } + } + + protected void putTableType(Map element, ResultSet tableRs) throws SQLException { + element.put("TABLE_TYPE", tableRs.getString("TABLE_TYPE")); + } + + protected void putTablePart(Map element, ResultSet tableRs) throws SQLException { + element.put("TABLE_NAME", tableRs.getString("TABLE_NAME")); + element.put("TABLE_SCHEM", tableRs.getString("TABLE_SCHEM")); + element.put("TABLE_CAT", tableRs.getString("TABLE_CAT")); + } + + public Iterator> getColumns(final String xcatalog, final String xschema, final String xtable, String xcolumn) { + try { + final String catalog = caseForSearch( xcatalog ); + final String schema = caseForSearch( xschema ); + final String table = caseForSearch( xtable ); + final String column = caseForSearch( xcolumn ); + + log.debug("getColumns(" + catalog + "." + schema + "." + table + "." + column + ")"); + ResultSet tableRs = getMetaData().getColumns(catalog, schema, table, column); + + return new ResultSetIterator(tableRs) { + + final Map element = new HashMap<>(); + protected Map convertRow(ResultSet rs) throws SQLException { + element.clear(); + putTablePart(element, rs); + element.put("DATA_TYPE", rs.getInt( "DATA_TYPE" ) ); + element.put("TYPE_NAME", rs.getString("TYPE_NAME")); + element.put("COLUMN_NAME", rs.getString("COLUMN_NAME")); + element.put("NULLABLE", rs.getInt( "NULLABLE" ) ); + element.put("COLUMN_SIZE", rs.getInt( "COLUMN_SIZE" ) ); + element.put("DECIMAL_DIGITS", rs.getInt( "DECIMAL_DIGITS" ) ); + element.put("REMARKS", rs.getString("REMARKS")); + return element; + } + protected Throwable handleSQLException(SQLException e) { + throw new RuntimeException("Error while reading column meta data for " + TableNameQualifier.qualify(catalog, schema, table), e); + } + }; + } + catch (SQLException e) { + throw new RuntimeException("Error while reading column meta data for " + TableNameQualifier.qualify(xcatalog, xschema, xtable), e); + } + } + + public Iterator> getPrimaryKeys(final String xcatalog, final String xschema, final String xtable) { + try { + final String catalog = caseForSearch( xcatalog ); + final String schema = caseForSearch( xschema ); + final String table = caseForSearch( xtable ); + + log.debug("getPrimaryKeys(" + catalog + "." + schema + "." + table + ")"); + ResultSet tableRs = getMetaData().getPrimaryKeys(catalog, schema, table); + + return new ResultSetIterator(tableRs) { + + final Map element = new HashMap<>(); + protected Map convertRow(ResultSet rs) throws SQLException { + element.clear(); + putTablePart(element, rs); + element.put("COLUMN_NAME", rs.getString("COLUMN_NAME")); + element.put("KEY_SEQ", rs.getShort( "KEY_SEQ" ) ); + element.put("PK_NAME", rs.getString("PK_NAME")); + return element; + } + protected Throwable handleSQLException(SQLException e) { + throw new RuntimeException( + "Error while reading primary key meta data for " + TableNameQualifier.qualify(catalog, schema, table), + e); + } + }; + } + catch (SQLException e) { + throw new RuntimeException( + "Error while reading primary key meta data for " + TableNameQualifier.qualify(xcatalog, xschema, xtable), e); + } + } + + public Iterator> getExportedKeys(final String xcatalog, final String xschema, final String xtable) { + try { + final String catalog = caseForSearch( xcatalog ); + final String schema = caseForSearch( xschema ); + final String table = caseForSearch( xtable ); + + log.debug("getExportedKeys(" + catalog + "." + schema + "." + table + ")"); + ResultSet tableRs = getMetaData().getExportedKeys(catalog, schema, table); + + return new ResultSetIterator(tableRs) { + + final Map element = new HashMap<>(); + protected Map convertRow(ResultSet rs) throws SQLException { + element.clear(); + putExportedKeysPart( element, rs ); + return element; + } + protected Throwable handleSQLException(SQLException e) { + throw new RuntimeException( + "Error while reading exported keys meta data for " + TableNameQualifier.qualify(catalog, schema, table), e); + } + }; + } + catch (SQLException e) { + throw new RuntimeException( + "Error while reading exported keys meta data for " + TableNameQualifier.qualify(xcatalog, xschema, xtable), e); + } + } + + protected void putExportedKeysPart(Map element, ResultSet rs) throws SQLException { + element.put( "PKTABLE_NAME", rs.getString("PKTABLE_NAME")); + element.put( "PKTABLE_SCHEM", rs.getString("PKTABLE_SCHEM")); + element.put( "PKTABLE_CAT", rs.getString("PKTABLE_CAT")); + element.put( "FKTABLE_CAT", rs.getString("FKTABLE_CAT")); + element.put( "FKTABLE_SCHEM",rs.getString("FKTABLE_SCHEM")); + element.put( "FKTABLE_NAME", rs.getString("FKTABLE_NAME")); + element.put( "FKCOLUMN_NAME", rs.getString("FKCOLUMN_NAME")); + element.put( "PKCOLUMN_NAME", rs.getString("PKCOLUMN_NAME")); + element.put( "FK_NAME", rs.getString("FK_NAME")); + element.put( "KEY_SEQ", rs.getShort( "KEY_SEQ" ) ); + } + } diff --git a/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/MySQLMetaDataDialect.java b/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/MySQLMetaDataDialect.java index 337fa990d..535b7e8bf 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/MySQLMetaDataDialect.java +++ b/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/MySQLMetaDataDialect.java @@ -26,74 +26,75 @@ public class MySQLMetaDataDialect extends JDBCMetaDataDialect { - /** - * Based on info from http://dev.mysql.com/doc/refman/5.0/en/show-table-status.html - * Should work on pre-mysql 5 too since it uses the "old" SHOW TABLE command instead of SELECT from infotable. - */ - public Iterator> getSuggestedPrimaryKeyStrategyName(String catalog, String schema, String table) { - String sql = null; - try { - catalog = caseForSearch( catalog ); - schema = caseForSearch( schema ); - table = caseForSearch( table ); - - log.debug("geSuggestedPrimaryKeyStrategyName(" + catalog + "." + schema + "." + table + ")"); - - sql = "show table status " + (catalog==null?"":" from " + catalog + " ") + (table==null?"":" like '" + table + "' "); - PreparedStatement statement = getConnection().prepareStatement( sql ); - - final String sc = schema; - final String cat = catalog; - return new ResultSetIterator(statement.executeQuery()) { - - Map element = new HashMap(); - protected Map convertRow(ResultSet tableRs) throws SQLException { - element.clear(); - element.put("TABLE_NAME", tableRs.getString("NAME")); - element.put("TABLE_SCHEM", sc); - element.put("TABLE_CAT", cat); - - String string = tableRs.getString("AUTO_INCREMENT"); - if(string==null) { - element.put("HIBERNATE_STRATEGY", null); - } else { - element.put("HIBERNATE_STRATEGY", "identity"); - } - return element; - } - protected Throwable handleSQLException(SQLException e) { - // schemaRs and catalogRs are only used for error reporting if - // we get an exception - throw new RuntimeException( - "Could not get list of suggested identity strategies from database. Probably a JDBC driver problem. ", e); - } - }; - } catch (SQLException e) { - throw new RuntimeException("Could not get list of suggested identity strategies from database. Probably a JDBC driver problem. ", e); - } - } - - @Override - public Iterator> getTables( - String xcatalog, - String xschema, - String xtable) { - // MySql JDBC Driver doesn't like 'null' values for the table search pattern, use '%' instead - return super.getTables(xcatalog, xschema, xtable != null ? xtable : "%"); - } + /** + * Based on info from ... + * Should work on pre-mysql 5 too since it uses the "old" SHOW TABLE command instead of SELECT from infotable. + */ + public Iterator> getSuggestedPrimaryKeyStrategyName(String catalog, String schema, String table) { + String sql; + try { + catalog = caseForSearch( catalog ); + schema = caseForSearch( schema ); + table = caseForSearch( table ); + + log.debug("geSuggestedPrimaryKeyStrategyName(" + catalog + "." + schema + "." + table + ")"); + + sql = "show table status " + (catalog==null?"":" from " + catalog + " ") + (table==null?"":" like '" + table + "' "); + PreparedStatement statement = getConnection().prepareStatement( sql ); + + final String sc = schema; + final String cat = catalog; + return new ResultSetIterator(statement.executeQuery()) { + + final Map element = new HashMap<>(); + protected Map convertRow(ResultSet tableRs) throws SQLException { + element.clear(); + element.put("TABLE_NAME", tableRs.getString("NAME")); + element.put("TABLE_SCHEM", sc); + element.put("TABLE_CAT", cat); + + String string = tableRs.getString("AUTO_INCREMENT"); + if(string==null) { + element.put("HIBERNATE_STRATEGY", null); + } + else { + element.put("HIBERNATE_STRATEGY", "identity"); + } + return element; + } + protected Throwable handleSQLException(SQLException e) { + // schemaRs and catalogRs are only used for error reporting if + // we get an exception + throw new RuntimeException( + "Could not get list of suggested identity strategies from database. Probably a JDBC driver problem. ", e); + } + }; + } + catch (SQLException e) { + throw new RuntimeException("Could not get list of suggested identity strategies from database. Probably a JDBC driver problem. ", e); + } + } + + @Override + public Iterator> getTables( + String xcatalog, + String xschema, + String xtable) { + // MySql JDBC Driver doesn't like 'null' values for the table search pattern, use '%' instead + return super.getTables(xcatalog, xschema, xtable != null ? xtable : "%"); + } + + public Iterator> getColumns( + String xcatalog, + String xschema, + String xtable, + String xcolumn) { + // MySql JDBC Driver doesn't like 'null' values for the table and column search patterns, use '%' instead + return super.getColumns( + xcatalog, + xschema, + xtable != null ? xtable : "%", + xcolumn != null ? xcolumn : "%"); + } - public Iterator> getColumns( - String xcatalog, - String xschema, - String xtable, - String xcolumn) { - // MySql JDBC Driver doesn't like 'null' values for the table and column search patterns, use '%' instead - return super.getColumns( - xcatalog, - xschema, - xtable != null ? xtable : "%", - xcolumn != null ? xcolumn : "%"); - } - } - diff --git a/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/OracleMetaDataDialect.java b/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/OracleMetaDataDialect.java index a912bb38a..fe24f18bf 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/OracleMetaDataDialect.java +++ b/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/OracleMetaDataDialect.java @@ -39,705 +39,717 @@ public class OracleMetaDataDialect extends AbstractMetaDataDialect { - - - public OracleMetaDataDialect() { - super(); - } - - /* ******* TABLE QUERIES ******* */ - private static final String SQL_TABLE_BASE = - "select a.table_name, a.owner, " - + "(SELECT b.comments\n" - + " FROM all_tab_comments b\n" - + " WHERE a.owner = b.owner\n" - + " AND a.table_name = b.table_name) AS comments, " - + "'TABLE' " - + "from all_tables a "; - - private static final String SQL_TABLE_VIEW = - " union all select view_name, owner, NULL, 'VIEW' from all_views "; - - private static final String SQL_TABLE_NONE = SQL_TABLE_BASE + SQL_TABLE_VIEW; - - private static final String SQL_TABLE_SCHEMA = SQL_TABLE_BASE - + "where a.owner like ? " + SQL_TABLE_VIEW + " where owner like ?"; - - private static final String SQL_TABLE_TABLE = SQL_TABLE_BASE - + "where a.table_name like ?" + SQL_TABLE_VIEW + "where view_name like ?"; - - private static final String SQL_TABLE_SCHEMA_AND_TABLE = - SQL_TABLE_BASE - + "where a.owner like ? and a.table_name like ?" - + SQL_TABLE_VIEW - + "where owner like ? and view_name like ?"; - - private PreparedStatement prepTableNone; - - private PreparedStatement prepTableSchema; - - private PreparedStatement prepTableTable; - - private PreparedStatement prepTableSchemaAndTable; - - /* ***************************** */ - /* ******* INDEX QUERIES ******* */ - /* ***************************** */ - private static final String SQL_INDEX_BASE = - "SELECT a.column_name\n" + - " ,decode((SELECT b.uniqueness\n" + - " FROM all_indexes b\n" + - " WHERE a.table_name = b.table_name\n" + - " AND a.table_owner = b.table_owner\n" + - " AND a.index_name = b.index_name\n" + - " AND b.index_type NOT LIKE 'FUNCTION-BASED%'), 'UNIQUE', 'false', 'true') AS uniqueness\n" + - " ,a.index_owner\n" + - " ,a.index_name\n" + - " ,a.table_name\n" + - " FROM all_ind_columns a\n " + - " WHERE 1 = 1\n "; - private static final String SQL_INDEX_ORDER = " order by a.table_name, a.column_position"; - private static final String SQL_INDEX_NONE = SQL_INDEX_BASE - + SQL_INDEX_ORDER; + public OracleMetaDataDialect() { + super(); + } + + /* ******* TABLE QUERIES ******* */ + private static final String SQL_TABLE_BASE = + """ + select a.table_name, a.owner, \ + (SELECT b.comments + FROM all_tab_comments b + WHERE a.owner = b.owner + AND a.table_name = b.table_name) AS comments, \ + 'TABLE' \ + from all_tables a\s"""; + + private static final String SQL_TABLE_VIEW = + " union all select view_name, owner, NULL, 'VIEW' from all_views "; + + private static final String SQL_TABLE_NONE = SQL_TABLE_BASE + SQL_TABLE_VIEW; + + private static final String SQL_TABLE_SCHEMA = SQL_TABLE_BASE + + "where a.owner like ? " + SQL_TABLE_VIEW + " where owner like ?"; + + private static final String SQL_TABLE_TABLE = SQL_TABLE_BASE + + "where a.table_name like ?" + SQL_TABLE_VIEW + "where view_name like ?"; + + private static final String SQL_TABLE_SCHEMA_AND_TABLE = + SQL_TABLE_BASE + + "where a.owner like ? and a.table_name like ?" + + SQL_TABLE_VIEW + + "where owner like ? and view_name like ?"; + + private PreparedStatement prepTableNone; + + private PreparedStatement prepTableSchema; + + private PreparedStatement prepTableTable; + + private PreparedStatement prepTableSchemaAndTable; + + /* ***************************** */ + /* ******* INDEX QUERIES ******* */ + /* ***************************** */ + private static final String SQL_INDEX_BASE = + """ + SELECT a.column_name + ,decode((SELECT b.uniqueness + FROM all_indexes b + WHERE a.table_name = b.table_name + AND a.table_owner = b.table_owner + AND a.index_name = b.index_name + AND b.index_type NOT LIKE 'FUNCTION-BASED%'), 'UNIQUE', 'false', 'true') AS uniqueness + ,a.index_owner + ,a.index_name + ,a.table_name + FROM all_ind_columns a + \ + WHERE 1 = 1 + \s"""; - private static final String SQL_INDEX_SCHEMA = SQL_INDEX_BASE - + "and a.table_owner like ? " + SQL_INDEX_ORDER; + private static final String SQL_INDEX_ORDER = " order by a.table_name, a.column_position"; - private static final String SQL_INDEX_TABLE = SQL_INDEX_BASE - + "and a.table_name like ? " + SQL_INDEX_ORDER; + private static final String SQL_INDEX_NONE = SQL_INDEX_BASE + + SQL_INDEX_ORDER; - private static final String SQL_INDEX_SCHEMA_AND_TABLE = SQL_INDEX_BASE - + "and a.table_owner like ? and a.table_name like ? " + SQL_INDEX_ORDER; + private static final String SQL_INDEX_SCHEMA = SQL_INDEX_BASE + + "and a.table_owner like ? " + SQL_INDEX_ORDER; - private PreparedStatement prepIndexNone; + private static final String SQL_INDEX_TABLE = SQL_INDEX_BASE + + "and a.table_name like ? " + SQL_INDEX_ORDER; - private PreparedStatement prepIndexSchema; + private static final String SQL_INDEX_SCHEMA_AND_TABLE = SQL_INDEX_BASE + + "and a.table_owner like ? and a.table_name like ? " + SQL_INDEX_ORDER; - private PreparedStatement prepIndexTable; + private PreparedStatement prepIndexNone; - private PreparedStatement prepIndexSchemaAndTable; + private PreparedStatement prepIndexSchema; - /* ****** COLUMN QUERIES ******* */ - private static final String SQL_COLUMN_BASE = - "SELECT a.column_name AS COLUMN_NAME\n" + - " ,a.owner AS TABLE_SCHEM\n" + - " ,decode(a.nullable, 'N', 0, 1) AS NULLABLE\n" + - " ,decode(a.data_type, 'FLOAT', decode(a.data_precision, NULL, a.data_length, a.data_precision), 'NUMBER',\n" + - " decode(a.data_precision, NULL, a.data_length, a.data_precision), 'VARCHAR2', a.char_length, 'VARCHAR',\n" + - " a.char_length, 'NVARCHAR2', a.char_length, 'CHAR', a.char_length, 'NCHAR', a.char_length, a.data_length) AS COLUMN_SIZE\n" + - " ,CASE\n" + - " WHEN a.data_type LIKE 'TIMESTAMP%' THEN\n" + - " 93\n" + - " ELSE\n" + - " decode(a.data_type, 'CHAR', 1, 'DATE', 91, 'FLOAT', 6, 'LONG', -1, 'NUMBER', 2, 'VARCHAR2', 12, 'BFILE', -13,\n" + - " 'BLOB', 2004, 'CLOB', 2005, 'MLSLABEL', 1111, 'NCHAR', 1, 'NCLOB', 2005, 'NVARCHAR2', 12, 'RAW', -3,\n" + - " 'ROWID', 1111, 'UROWID', 1111, 'LONG RAW', -4, 'XMLTYPE', 2005, 1111)\n" + - " END AS DATA_TYPE\n" + - " ,a.table_name AS TABLE_NAME\n" + - " ,a.data_type AS TYPE_NAME\n" + - " ,decode(a.data_scale, NULL, 0, a.data_scale) AS DECIMAL_DIGITS\n" + - " ,(SELECT b.comments\n" + - " FROM all_col_comments b\n" + - " WHERE a.owner = b.owner\n" + - " AND a.table_name = b.table_name\n" + - " AND a.column_name = b.column_name) AS COMMENTS\n" + - " FROM all_tab_columns a\n"; + private PreparedStatement prepIndexTable; - private static final String SQL_COLUMN_ORDER = " order by column_id "; + private PreparedStatement prepIndexSchemaAndTable; - private static final String SQL_COLUMN_NONE = SQL_COLUMN_BASE - + SQL_COLUMN_ORDER; + /* ****** COLUMN QUERIES ******* */ + private static final String SQL_COLUMN_BASE = + """ + SELECT a.column_name AS COLUMN_NAME + ,a.owner AS TABLE_SCHEM + ,decode(a.nullable, 'N', 0, 1) AS NULLABLE + ,decode(a.data_type, 'FLOAT', decode(a.data_precision, NULL, a.data_length, a.data_precision), 'NUMBER', + decode(a.data_precision, NULL, a.data_length, a.data_precision), 'VARCHAR2', a.char_length, 'VARCHAR', + a.char_length, 'NVARCHAR2', a.char_length, 'CHAR', a.char_length, 'NCHAR', a.char_length, a.data_length) AS COLUMN_SIZE + ,CASE + WHEN a.data_type LIKE 'TIMESTAMP%' THEN + 93 + ELSE + decode(a.data_type, 'CHAR', 1, 'DATE', 91, 'FLOAT', 6, 'LONG', -1, 'NUMBER', 2, 'VARCHAR2', 12, 'BFILE', -13, + 'BLOB', 2004, 'CLOB', 2005, 'MLSLABEL', 1111, 'NCHAR', 1, 'NCLOB', 2005, 'NVARCHAR2', 12, 'RAW', -3, + 'ROWID', 1111, 'UROWID', 1111, 'LONG RAW', -4, 'XMLTYPE', 2005, 1111) + END AS DATA_TYPE + ,a.table_name AS TABLE_NAME + ,a.data_type AS TYPE_NAME + ,decode(a.data_scale, NULL, 0, a.data_scale) AS DECIMAL_DIGITS + ,(SELECT b.comments + FROM all_col_comments b + WHERE a.owner = b.owner + AND a.table_name = b.table_name + AND a.column_name = b.column_name) AS COMMENTS + FROM all_tab_columns a + """; - private static final String SQL_COLUMN_SCHEMA = SQL_COLUMN_BASE - + "where a.owner like ? " + SQL_COLUMN_ORDER; + private static final String SQL_COLUMN_ORDER = " order by column_id "; - private static final String SQL_COLUMN_TABLE = SQL_COLUMN_BASE - + "where a.table_name like ? " + SQL_COLUMN_ORDER; + private static final String SQL_COLUMN_NONE = SQL_COLUMN_BASE + + SQL_COLUMN_ORDER; - private static final String SQL_COLUMN_COLUMN = SQL_COLUMN_BASE - + "where a.column_name like ? " + SQL_COLUMN_ORDER; + private static final String SQL_COLUMN_SCHEMA = SQL_COLUMN_BASE + + "where a.owner like ? " + SQL_COLUMN_ORDER; - private static final String SQL_COLUMN_SCHEMA_AND_TABLE = SQL_COLUMN_BASE - + "where a.owner like ? and a.table_name like ? " + SQL_COLUMN_ORDER; + private static final String SQL_COLUMN_TABLE = SQL_COLUMN_BASE + + "where a.table_name like ? " + SQL_COLUMN_ORDER; - private static final String SQL_COLUMN_SCHEMA_AND_COLUMN = SQL_COLUMN_BASE - + "where a.owner like ? and a.column_name like ? " + SQL_COLUMN_ORDER; + private static final String SQL_COLUMN_COLUMN = SQL_COLUMN_BASE + + "where a.column_name like ? " + SQL_COLUMN_ORDER; - private static final String SQL_COLUMN_TABLE_AND_COLUMN = SQL_COLUMN_BASE - + "where a.table_name like ? and a.column_name like ? " - + SQL_COLUMN_ORDER; + private static final String SQL_COLUMN_SCHEMA_AND_TABLE = SQL_COLUMN_BASE + + "where a.owner like ? and a.table_name like ? " + SQL_COLUMN_ORDER; - private static final String SQL_COLUMN_SCHEMA_AND_TABLE_AND_COLUMN = SQL_COLUMN_BASE - + "where a.owner like ? and a.table_name like ? and a.column_name like ? " - + SQL_COLUMN_ORDER; + private static final String SQL_COLUMN_SCHEMA_AND_COLUMN = SQL_COLUMN_BASE + + "where a.owner like ? and a.column_name like ? " + SQL_COLUMN_ORDER; - private PreparedStatement prepColumnNone; + private static final String SQL_COLUMN_TABLE_AND_COLUMN = SQL_COLUMN_BASE + + "where a.table_name like ? and a.column_name like ? " + + SQL_COLUMN_ORDER; - private PreparedStatement prepColumnSchema; + private static final String SQL_COLUMN_SCHEMA_AND_TABLE_AND_COLUMN = SQL_COLUMN_BASE + + "where a.owner like ? and a.table_name like ? and a.column_name like ? " + + SQL_COLUMN_ORDER; - private PreparedStatement prepColumnTable; + private PreparedStatement prepColumnNone; - private PreparedStatement prepColumnColumn; + private PreparedStatement prepColumnSchema; + + private PreparedStatement prepColumnTable; - private PreparedStatement prepColumnSchemaAndTable; + private PreparedStatement prepColumnColumn; - private PreparedStatement prepColumnSchemaAndColumn; + private PreparedStatement prepColumnSchemaAndTable; - private PreparedStatement prepColumnTableAndColumn; + private PreparedStatement prepColumnSchemaAndColumn; - private PreparedStatement prepColumnSchemaAndTableAndColumn; + private PreparedStatement prepColumnTableAndColumn; - /* ***************************** */ - /* ******** PK QUERIES ********* */ - /* ***************************** */ - private static final String SQL_PK_BASE = + private PreparedStatement prepColumnSchemaAndTableAndColumn; + + /* ***************************** */ + /* ******** PK QUERIES ********* */ + /* ***************************** */ + private static final String SQL_PK_BASE = "select c.table_name, c.column_name, c.position, c.constraint_name, " - + "c.owner from all_cons_columns c join all_constraints k on " - + "(k.owner = c.owner AND k.table_name = c.table_name AND k.constraint_name = c.constraint_name) " - + "where k.constraint_type = 'P' "; - - private static final String SQL_PK_ORDER = " order by c.table_name, c.constraint_name, c.position desc "; - - private static final String SQL_PK_NONE = SQL_PK_BASE + SQL_PK_ORDER; - - private static final String SQL_PK_SCHEMA = SQL_PK_BASE - + " and c.owner like ? escape '\\' " + SQL_PK_ORDER; - - private static final String SQL_PK_TABLE = SQL_PK_BASE - + " and c.table_name like ? escape '\\' " + SQL_PK_ORDER; - - private static final String SQL_PK_SCHEMA_AND_TABLE = SQL_PK_BASE - + " and c.owner like ? escape '\\' and c.table_name like ? escape '\\' " + SQL_PK_ORDER; - - private PreparedStatement prepPkNone; - - private PreparedStatement prepPkSchema; - - private PreparedStatement prepPkTable; - - private PreparedStatement prepPkSchemaAndTable; - - /* ***************************** */ - /* ******** FK QUERIES ********* */ - /* ***************************** */ - private static final String SQL_FK_BASE = - "SELECT p.table_name as p_table_name\n" + - " ,p.owner as p_owner\n" + - " ,f.owner as f_owner\n" + - " ,f.table_name as f_table_name\n" + - " ,(SELECT fc.column_name\n" + - " FROM all_cons_columns fc\n" + - " WHERE fc.owner = f.owner\n" + - " AND fc.constraint_name = f.constraint_name\n" + - " AND fc.table_name = f.table_name\n" + - " AND fc.position = pc.position) AS fc_column_name\n" + - " ,pc.column_name as pc_column_name\n" + - " ,f.constraint_name\n" + - " ,(SELECT fc.position\n" + - " FROM all_cons_columns fc\n" + - " WHERE fc.owner = f.owner\n" + - " AND fc.constraint_name = f.constraint_name\n" + - " AND fc.table_name = f.table_name\n" + - " AND fc.position = pc.position) AS fc_position\n" + - " FROM all_constraints p\n" + - " JOIN all_cons_columns pc\n" + - " ON pc.owner = p.owner\n" + - " AND pc.constraint_name = p.constraint_name\n" + - " AND pc.table_name = p.table_name\n" + - " JOIN all_constraints f\n" + - " ON p.owner = f.r_owner\n" + - " AND p.constraint_name = f.r_constraint_name\n" + - " WHERE f.constraint_type = 'R'\n" + - " AND p.constraint_type = 'P'\n"; - - private static final String SQL_FK_ORDER = " order by f.table_name, f.constraint_name, position "; - - private static final String SQL_FK_NONE = SQL_FK_BASE + SQL_FK_ORDER; - - private static final String SQL_FK_SCHEMA = SQL_FK_BASE - + " and p.owner like ? " + SQL_FK_ORDER; - - private static final String SQL_FK_TABLE = SQL_FK_BASE - + " and p.table_name like ? " + SQL_FK_ORDER; - - private static final String SQL_FK_SCHEMA_AND_TABLE = SQL_FK_BASE - + " and p.owner like ? and p.table_name like ? " + SQL_FK_ORDER; - - private PreparedStatement prepFkNone; - - private PreparedStatement prepFkSchema; - - private PreparedStatement prepFkTable; - - private PreparedStatement prepFkSchemaAndTable; - - public Iterator> getTables(final String catalog, final String schema, - String table) { - try { - log.debug("getTables(" + catalog + "." + schema + "." + table + ")"); - - ResultSet tableRs = getTableResultSet( schema, table ); - - return new ResultSetIterator(null, tableRs) { - - Map element = new HashMap(); - - - protected Map convertRow(ResultSet tableResultSet) - throws SQLException { - element.clear(); - element.put("TABLE_NAME", tableResultSet.getString(1)); - element.put("TABLE_SCHEM", tableResultSet.getString(2)); - element.put("TABLE_CAT", null); - element.put("TABLE_TYPE", tableResultSet.getString(4)); - element.put("REMARKS", tableResultSet.getString(3)); - log.info( element.toString() ); - return element; - } - - protected Throwable handleSQLException(SQLException e) { - // schemaRs and catalogRs are only used for error reporting - // if - // we get an exception - String databaseStructure = getDatabaseStructure(catalog, - schema); - throw new RuntimeException( - "Could not get list of tables from database. Probably a JDBC driver problem. " - + databaseStructure, - e); - } - }; - } catch (SQLException e) { - // schemaRs and catalogRs are only used for error reporting if we - // get an exception - String databaseStructure = getDatabaseStructure(catalog, schema); - throw new RuntimeException( - "Could not get list of tables from database. Probably a JDBC driver problem. " - + databaseStructure, - e); - } - } - - public Iterator> getIndexInfo(final String catalog, final String schema, - final String table) { - try { - log.debug("getIndexInfo(" + catalog + "." + schema + "." + table + ")"); - - ResultSet indexRs; - indexRs = getIndexInfoResultSet( schema, table ); - - return new ResultSetIterator(null, indexRs) { - - Map element = new HashMap(); - - - protected Map convertRow(ResultSet rs) throws SQLException { - element.clear(); - element.put("COLUMN_NAME", rs.getString(1)); - element.put("TYPE", Short.valueOf((short) 1)); // CLUSTERED - // INDEX - element.put("NON_UNIQUE", Boolean.valueOf(rs.getString(2))); - element.put("TABLE_SCHEM", rs.getString(3)); - element.put("INDEX_NAME", rs.getString(4)); - element.put("TABLE_CAT", null); - element.put("TABLE_NAME", rs.getString(5)); - - return element; - } - - protected Throwable handleSQLException(SQLException e) { - throw new RuntimeException( - "Exception while getting index info for " - + TableNameQualifier.qualify(catalog, schema, table), - e); - } - }; - } catch (SQLException e) { - throw new RuntimeException ( - "Exception while getting index info for " - + TableNameQualifier.qualify(catalog, schema, table) + ": " + e.getMessage(), - e); - } - } - - public Iterator> getColumns(final String catalog, final String schema, - final String table, String column) { - - try { - log.debug("getColumns(" + catalog + "." + schema + "." + table + "." + column + ")"); - - ResultSet columnRs; - columnRs = getColumnsResultSet( schema, table, column ); - - return new ResultSetIterator(null, columnRs) { - - Map element = new HashMap(); - - - protected Map convertRow(ResultSet rs) throws SQLException { - element.clear(); - element.put("COLUMN_NAME", rs.getString(1)); - element.put("TABLE_SCHEM", rs.getString(2)); - element.put("NULLABLE", Integer.valueOf(rs.getInt(3))); - element.put("COLUMN_SIZE", Integer.valueOf(rs.getInt(4))); - element.put("DATA_TYPE", Integer.valueOf(rs.getInt(5))); - element.put("TABLE_NAME", rs.getString(6)); - element.put("TYPE_NAME", rs.getString(7)); - element.put("DECIMAL_DIGITS", Integer.valueOf(rs.getInt(8))); - element.put("TABLE_CAT", null); - element.put("REMARKS", rs.getString(9)); - return element; - } - - protected Throwable handleSQLException(SQLException e) { - throw new RuntimeException( - "Error while reading column meta data for " - + TableNameQualifier.qualify(catalog, schema, table), - e); - } - }; - } catch (SQLException e) { - throw new RuntimeException( - "Error while reading column meta data for " - + TableNameQualifier.qualify(catalog, schema, table), - e); - } - } - - public Iterator> getPrimaryKeys(final String catalog, final String schema, - final String table) { - - try { - log.debug("getPrimaryKeys(" + catalog + "." + schema + "." + table - + ")"); - - ResultSet pkeyRs; - pkeyRs = getPrimaryKeysResultSet( schema, table ); - - return new ResultSetIterator(null, pkeyRs) { - - Map element = new HashMap(); - - - protected Map convertRow(ResultSet rs) throws SQLException { - element.clear(); - element.put("TABLE_NAME", rs.getString(1)); - element.put("COLUMN_NAME", rs.getString(2)); - element.put("KEY_SEQ", Short.valueOf(rs.getShort(3))); - element.put("PK_NAME", rs.getString(4)); - element.put("TABLE_SCHEM", rs.getString(5)); - element.put("TABLE_CAT", null); - return element; - } - - protected Throwable handleSQLException(SQLException e) { - throw new RuntimeException( - "Error while reading primary key meta data for " - + TableNameQualifier.qualify(catalog, schema, table), - e); - } - }; - } catch (SQLException e) { - throw new RuntimeException( - "Error while reading primary key meta data for " - + TableNameQualifier.qualify(catalog, schema, table), - e); - } - } - - public Iterator> getExportedKeys(final String catalog, final String schema, - final String table) { - - try { - log.debug("getExportedKeys(" + catalog + "." + schema + "." + table - + ")"); - - ResultSet pExportRs = getExportedKeysResultSet( schema, table ); - - return new ResultSetIterator(null, pExportRs) { - - Map element = new HashMap(); - - - protected Map convertRow(ResultSet rs) throws SQLException { - element.clear(); - element.put("PKTABLE_NAME", rs.getString(1)); - element.put("PKTABLE_SCHEM", rs.getString(2)); - element.put("PKTABLE_CAT", null); - element.put("FKTABLE_CAT", null); - element.put("FKTABLE_SCHEM", rs.getString(3)); - element.put("FKTABLE_NAME", rs.getString(4)); - element.put("FKCOLUMN_NAME", rs.getString(5)); - element.put("PKCOLUMN_NAME", rs.getString(6)); - element.put("FK_NAME", rs.getString(7)); - element.put("KEY_SEQ", Short.valueOf(rs.getShort(8))); - return element; - } - - protected Throwable handleSQLException(SQLException e) { - throw new RuntimeException( - "Error while reading exported keys meta data for " - + TableNameQualifier.qualify(catalog, schema, table), - e); - } - }; - } catch (SQLException e) { - throw new RuntimeException( - "Error while reading exported keys meta data for " - + TableNameQualifier.qualify(catalog, schema, table), - e); - } - } - - public void close() { - try { - prepTableNone = close( prepTableNone ); - prepTableSchema = close( prepTableSchema ); - prepTableTable = close( prepTableTable ); - prepTableSchemaAndTable = close( prepTableSchemaAndTable ); - prepIndexNone = close( prepIndexNone ); - prepIndexSchema = close( prepIndexSchema ); - prepIndexTable = close( prepIndexTable ); - prepIndexSchemaAndTable = close( prepIndexSchemaAndTable ); - prepColumnNone = close( prepColumnNone ); - prepColumnSchema = close( prepColumnSchema ); - prepColumnTable = close( prepColumnTable ); - prepColumnColumn = close( prepColumnColumn ); - prepColumnSchemaAndTable = close( prepColumnSchemaAndTable ); - prepColumnSchemaAndColumn = close( prepColumnSchemaAndColumn ); - prepColumnTableAndColumn = close( prepColumnTableAndColumn ); - prepColumnSchemaAndTableAndColumn = close( prepColumnSchemaAndTableAndColumn ); - prepPkNone = close( prepPkNone ); - prepPkSchema = close( prepPkSchema ); - prepPkTable = close( prepPkTable ); - prepPkSchemaAndTable = close( prepPkSchemaAndTable ); - prepFkNone = close( prepFkNone ); - prepFkSchema = close( prepFkSchema ); - prepFkTable = close( prepFkTable ); - prepFkSchemaAndTable = close( prepFkSchemaAndTable ); - } - finally { - super.close(); - } - } - - private PreparedStatement close(PreparedStatement ps) { - if(ps==null) { - return null; - } else { - try { - ps.close(); - } - catch (SQLException e) { - throw new RuntimeException( - "Problem while closing prepared statement", e); - } - return null; - } - - } - - private String escape(String str) { - return str.replace("_", "\\_"); - } - - private ResultSet getPrimaryKeysResultSet(final String schem, final String tab) throws SQLException { - String schema = escape(schem); - String table = escape(tab); - if(prepPkNone==null) { - // Prepare primary key queries - log.debug("Preparing primary key queries..."); - Connection con = getConnection(); - prepPkNone = con .prepareStatement(SQL_PK_NONE); - prepPkSchema = con.prepareStatement(SQL_PK_SCHEMA); - prepPkTable = con.prepareStatement(SQL_PK_TABLE); - prepPkSchemaAndTable = con - .prepareStatement(SQL_PK_SCHEMA_AND_TABLE); - log.debug(" primary key queries prepared!"); - } - - ResultSet pkeyRs; - if (schema == null && table == null) { - pkeyRs = prepPkNone.executeQuery(); - } else if (schema != null) { - if (table == null) { - prepPkSchema.setString(1, schema); - pkeyRs = prepPkSchema.executeQuery(); - } else { - prepPkSchemaAndTable.setString(1, schema); - prepPkSchemaAndTable.setString(2, table); - pkeyRs = prepPkSchemaAndTable.executeQuery(); - } - } else { - prepPkTable.setString(1, table); - pkeyRs = prepPkTable.executeQuery(); - } - return pkeyRs; - } - - private ResultSet getIndexInfoResultSet(final String schema, final String table) throws SQLException { - if(prepIndexNone==null) { - // Prepare index queries - log.debug("Preparing index queries..."); - Connection con = getConnection(); - prepIndexNone = con.prepareStatement(SQL_INDEX_NONE); - prepIndexSchema = con.prepareStatement(SQL_INDEX_SCHEMA); - prepIndexTable = con.prepareStatement(SQL_INDEX_TABLE); - prepIndexSchemaAndTable = con.prepareStatement(SQL_INDEX_SCHEMA_AND_TABLE); - log.debug(" ...index queries prepared!"); - } - ResultSet indexRs; - if (schema == null && table == null) { - indexRs = prepIndexNone.executeQuery(); - } else if (schema != null) { - if (table == null) { - prepIndexSchema.setString(1, schema); - indexRs = prepIndexSchema.executeQuery(); - } else { - prepIndexSchemaAndTable.setString(1, schema); - prepIndexSchemaAndTable.setString(2, table); - indexRs = prepIndexSchemaAndTable.executeQuery(); - } - } else { - prepIndexTable.setString(1, table); - indexRs = prepIndexTable.executeQuery(); - } - return indexRs; - } - - private ResultSet getExportedKeysResultSet(final String schema, final String table) throws SQLException { - if(prepFkNone==null) { - // Prepare foreign key queries - log.debug("Preparing foreign key queries..."); - Connection con = getConnection(); - prepFkNone = con .prepareStatement(SQL_FK_NONE); - prepFkSchema = con.prepareStatement(SQL_FK_SCHEMA); - prepFkTable = con.prepareStatement(SQL_FK_TABLE); - prepFkSchemaAndTable = con.prepareStatement(SQL_FK_SCHEMA_AND_TABLE); - log.debug(" foreign key queries prepared!"); - } - - ResultSet pExportRs; - if (schema == null && table == null) { - pExportRs = prepFkNone.executeQuery(); - } else if (schema != null) { - if (table == null) { - prepFkSchema.setString(1, schema); - pExportRs = prepFkSchema.executeQuery(); - } else { - prepFkSchemaAndTable.setString(1, schema); - prepFkSchemaAndTable.setString(2, table); - pExportRs = prepFkSchemaAndTable.executeQuery(); - } - } else { - prepFkTable.setString(1, table); - pExportRs = prepFkTable.executeQuery(); - } - return pExportRs; - } - private ResultSet getColumnsResultSet(final String schema, final String table, String column) throws SQLException { - - if(prepColumnNone==null) { - // Prepare column queries - log.debug("Preparing column queries..."); - Connection con = getConnection(); - prepColumnNone = con.prepareStatement(SQL_COLUMN_NONE); - prepColumnSchema = con.prepareStatement(SQL_COLUMN_SCHEMA); - prepColumnTable = con.prepareStatement(SQL_COLUMN_TABLE); - prepColumnColumn = con.prepareStatement(SQL_COLUMN_COLUMN); - prepColumnSchemaAndTable = con.prepareStatement(SQL_COLUMN_SCHEMA_AND_TABLE); - prepColumnSchemaAndColumn = con.prepareStatement(SQL_COLUMN_SCHEMA_AND_COLUMN); - prepColumnTableAndColumn = con.prepareStatement(SQL_COLUMN_TABLE_AND_COLUMN); - prepColumnSchemaAndTableAndColumn = con.prepareStatement(SQL_COLUMN_SCHEMA_AND_TABLE_AND_COLUMN); - log.debug(" ...column queries prepared!"); - } - - ResultSet columnRs; - // No parameters specified - if (schema == null && table == null && column == null) { - columnRs = prepColumnNone.executeQuery(); - } else if (schema != null) { - if (table == null) { - if (column == null) { - // Schema specified - prepColumnSchema.setString(1, schema); - columnRs = prepColumnSchema.executeQuery(); - } else { - // Schema and column specified - prepColumnSchemaAndColumn.setString(1, schema); - prepColumnSchemaAndColumn.setString(2, column); - columnRs = prepColumnSchemaAndColumn.executeQuery(); - } - } else { - if (column == null) { - // Schema and table specified - prepColumnSchemaAndTable.setString(1, schema); - prepColumnSchemaAndTable.setString(2, table); - columnRs = prepColumnSchemaAndTable.executeQuery(); - } else { - // Schema, table and column specified - prepColumnSchemaAndTableAndColumn.setString(1, schema); - prepColumnSchemaAndTableAndColumn.setString(2, table); - prepColumnSchemaAndTableAndColumn.setString(3, column); - columnRs = prepColumnSchemaAndTableAndColumn.executeQuery(); - } - } - } else { - if (table == null) { - // Column specified - prepColumnColumn.setString(1, column); - columnRs = prepColumnColumn.executeQuery(); - } else { - if (column == null) { - // Table specified - prepColumnTable.setString(1, table); - columnRs = prepColumnTable.executeQuery(); - } else { - // Table and column specified - prepColumnTableAndColumn.setString(1, table); - prepColumnTableAndColumn.setString(2, column); - columnRs = prepColumnTableAndColumn.executeQuery(); - - } - } - } - return columnRs; - } - - private ResultSet getTableResultSet(final String schema, String table) throws SQLException { - ResultSet tableRs; - if(prepTableNone==null) { - // Prepare table queries - log.debug("Preparing table queries..."); - Connection connection2 = getConnection(); - prepTableNone = connection2.prepareStatement(SQL_TABLE_NONE); - prepTableSchema = connection2.prepareStatement(SQL_TABLE_SCHEMA); - prepTableTable = connection2.prepareStatement(SQL_TABLE_TABLE); - prepTableSchemaAndTable = connection2.prepareStatement(SQL_TABLE_SCHEMA_AND_TABLE); - log.debug(" ...table queries prepared!"); - } - if (schema == null && table == null) { - tableRs = prepTableNone.executeQuery(); - } else if (schema != null) { - if (table == null) { - prepTableSchema.setString(1, schema); - prepTableSchema.setString(2, schema); - tableRs = prepTableSchema.executeQuery(); - } else { - prepTableSchemaAndTable.setString(1, schema); - prepTableSchemaAndTable.setString(2, table); - prepTableSchemaAndTable.setString(3, schema); - prepTableSchemaAndTable.setString(4, table); - tableRs = prepTableSchemaAndTable.executeQuery(); - } - } else { - prepTableTable.setString(1, table); - prepTableTable.setString(2, table); - tableRs = prepTableTable.executeQuery(); - } - return tableRs; - } + + "c.owner from all_cons_columns c join all_constraints k on " + + "(k.owner = c.owner AND k.table_name = c.table_name AND k.constraint_name = c.constraint_name) " + + "where k.constraint_type = 'P' "; + + private static final String SQL_PK_ORDER = " order by c.table_name, c.constraint_name, c.position desc "; + + private static final String SQL_PK_NONE = SQL_PK_BASE + SQL_PK_ORDER; + + private static final String SQL_PK_SCHEMA = SQL_PK_BASE + + " and c.owner like ? escape '\\' " + SQL_PK_ORDER; + + private static final String SQL_PK_TABLE = SQL_PK_BASE + + " and c.table_name like ? escape '\\' " + SQL_PK_ORDER; + + private static final String SQL_PK_SCHEMA_AND_TABLE = SQL_PK_BASE + + " and c.owner like ? escape '\\' and c.table_name like ? escape '\\' " + SQL_PK_ORDER; + + private PreparedStatement prepPkNone; + + private PreparedStatement prepPkSchema; + + private PreparedStatement prepPkTable; + + private PreparedStatement prepPkSchemaAndTable; + + /* ***************************** */ + /* ******** FK QUERIES ********* */ + /* ***************************** */ + private static final String SQL_FK_BASE = + """ + SELECT p.table_name as p_table_name + ,p.owner as p_owner + ,f.owner as f_owner + ,f.table_name as f_table_name + ,(SELECT fc.column_name + FROM all_cons_columns fc + WHERE fc.owner = f.owner + AND fc.constraint_name = f.constraint_name + AND fc.table_name = f.table_name + AND fc.position = pc.position) AS fc_column_name + ,pc.column_name as pc_column_name + ,f.constraint_name + ,(SELECT fc.position + FROM all_cons_columns fc + WHERE fc.owner = f.owner + AND fc.constraint_name = f.constraint_name + AND fc.table_name = f.table_name + AND fc.position = pc.position) AS fc_position + FROM all_constraints p + JOIN all_cons_columns pc + ON pc.owner = p.owner + AND pc.constraint_name = p.constraint_name + AND pc.table_name = p.table_name + JOIN all_constraints f + ON p.owner = f.r_owner + AND p.constraint_name = f.r_constraint_name + WHERE f.constraint_type = 'R' + AND p.constraint_type = 'P' + """; + + private static final String SQL_FK_ORDER = " order by f.table_name, f.constraint_name, position "; + + private static final String SQL_FK_NONE = SQL_FK_BASE + SQL_FK_ORDER; + + private static final String SQL_FK_SCHEMA = SQL_FK_BASE + + " and p.owner like ? " + SQL_FK_ORDER; + + private static final String SQL_FK_TABLE = SQL_FK_BASE + + " and p.table_name like ? " + SQL_FK_ORDER; + + private static final String SQL_FK_SCHEMA_AND_TABLE = SQL_FK_BASE + + " and p.owner like ? and p.table_name like ? " + SQL_FK_ORDER; + + private PreparedStatement prepFkNone; + + private PreparedStatement prepFkSchema; + + private PreparedStatement prepFkTable; + + private PreparedStatement prepFkSchemaAndTable; + + public Iterator> getTables(final String catalog, final String schema, + String table) { + try { + log.debug("getTables(" + catalog + "." + schema + "." + table + ")"); + + ResultSet tableRs = getTableResultSet( schema, table ); + + return new ResultSetIterator(null, tableRs) { + + final Map element = new HashMap<>(); + + + protected Map convertRow(ResultSet tableResultSet) + throws SQLException { + element.clear(); + element.put("TABLE_NAME", tableResultSet.getString(1)); + element.put("TABLE_SCHEM", tableResultSet.getString(2)); + element.put("TABLE_CAT", null); + element.put("TABLE_TYPE", tableResultSet.getString(4)); + element.put("REMARKS", tableResultSet.getString(3)); + log.info( element.toString() ); + return element; + } + + protected Throwable handleSQLException(SQLException e) { + // schemaRs and catalogRs are only used for error reporting + // if + // we get an exception + String databaseStructure = getDatabaseStructure(catalog, + schema); + throw new RuntimeException( + "Could not get list of tables from database. Probably a JDBC driver problem. " + + databaseStructure, + e); + } + }; + } + catch (SQLException e) { + // schemaRs and catalogRs are only used for error reporting if we + // get an exception + String databaseStructure = getDatabaseStructure(catalog, schema); + throw new RuntimeException( + "Could not get list of tables from database. Probably a JDBC driver problem. " + + databaseStructure, + e); + } + } + + public Iterator> getIndexInfo(final String catalog, final String schema, + final String table) { + try { + log.debug("getIndexInfo(" + catalog + "." + schema + "." + table + ")"); + + ResultSet indexRs; + indexRs = getIndexInfoResultSet( schema, table ); + + return new ResultSetIterator(null, indexRs) { + + final Map element = new HashMap<>(); + + + protected Map convertRow(ResultSet rs) throws SQLException { + element.clear(); + element.put("COLUMN_NAME", rs.getString(1)); + element.put("TYPE", (short) 1 ); // CLUSTERED + // INDEX + element.put("NON_UNIQUE", Boolean.valueOf(rs.getString(2))); + element.put("TABLE_SCHEM", rs.getString(3)); + element.put("INDEX_NAME", rs.getString(4)); + element.put("TABLE_CAT", null); + element.put("TABLE_NAME", rs.getString(5)); + + return element; + } + + protected Throwable handleSQLException(SQLException e) { + throw new RuntimeException( + "Exception while getting index info for " + + TableNameQualifier.qualify(catalog, schema, table), + e); + } + }; + } + catch (SQLException e) { + throw new RuntimeException ( + "Exception while getting index info for " + + TableNameQualifier.qualify(catalog, schema, table) + ": " + e.getMessage(), + e); + } + } + + public Iterator> getColumns(final String catalog, final String schema, + final String table, String column) { + + try { + log.debug("getColumns(" + catalog + "." + schema + "." + table + "." + column + ")"); + + ResultSet columnRs; + columnRs = getColumnsResultSet( schema, table, column ); + + return new ResultSetIterator(null, columnRs) { + + final Map element = new HashMap<>(); + + + protected Map convertRow(ResultSet rs) throws SQLException { + element.clear(); + element.put("COLUMN_NAME", rs.getString(1)); + element.put("TABLE_SCHEM", rs.getString(2)); + element.put("NULLABLE", rs.getInt( 3 ) ); + element.put("COLUMN_SIZE", rs.getInt( 4 ) ); + element.put("DATA_TYPE", rs.getInt( 5 ) ); + element.put("TABLE_NAME", rs.getString(6)); + element.put("TYPE_NAME", rs.getString(7)); + element.put("DECIMAL_DIGITS", rs.getInt( 8 ) ); + element.put("TABLE_CAT", null); + element.put("REMARKS", rs.getString(9)); + return element; + } + + protected Throwable handleSQLException(SQLException e) { + throw new RuntimeException( + "Error while reading column meta data for " + + TableNameQualifier.qualify(catalog, schema, table), + e); + } + }; + } + catch (SQLException e) { + throw new RuntimeException( + "Error while reading column meta data for " + + TableNameQualifier.qualify(catalog, schema, table), + e); + } + } + + public Iterator> getPrimaryKeys(final String catalog, final String schema, + final String table) { + + try { + log.debug("getPrimaryKeys(" + catalog + "." + schema + "." + table + + ")"); + + ResultSet pkeyRs; + pkeyRs = getPrimaryKeysResultSet( schema, table ); + + return new ResultSetIterator(null, pkeyRs) { + + final Map element = new HashMap<>(); + + + protected Map convertRow(ResultSet rs) throws SQLException { + element.clear(); + element.put("TABLE_NAME", rs.getString(1)); + element.put("COLUMN_NAME", rs.getString(2)); + element.put("KEY_SEQ", rs.getShort( 3 ) ); + element.put("PK_NAME", rs.getString(4)); + element.put("TABLE_SCHEM", rs.getString(5)); + element.put("TABLE_CAT", null); + return element; + } + + protected Throwable handleSQLException(SQLException e) { + throw new RuntimeException( + "Error while reading primary key meta data for " + + TableNameQualifier.qualify(catalog, schema, table), + e); + } + }; + } + catch (SQLException e) { + throw new RuntimeException( + "Error while reading primary key meta data for " + + TableNameQualifier.qualify(catalog, schema, table), + e); + } + } + + public Iterator> getExportedKeys(final String catalog, final String schema, + final String table) { + + try { + log.debug("getExportedKeys(" + catalog + "." + schema + "." + table + + ")"); + + ResultSet pExportRs = getExportedKeysResultSet( schema, table ); + + return new ResultSetIterator(null, pExportRs) { + + final Map element = new HashMap<>(); + + + protected Map convertRow(ResultSet rs) throws SQLException { + element.clear(); + element.put("PKTABLE_NAME", rs.getString(1)); + element.put("PKTABLE_SCHEM", rs.getString(2)); + element.put("PKTABLE_CAT", null); + element.put("FKTABLE_CAT", null); + element.put("FKTABLE_SCHEM", rs.getString(3)); + element.put("FKTABLE_NAME", rs.getString(4)); + element.put("FKCOLUMN_NAME", rs.getString(5)); + element.put("PKCOLUMN_NAME", rs.getString(6)); + element.put("FK_NAME", rs.getString(7)); + element.put("KEY_SEQ", rs.getShort( 8 ) ); + return element; + } + + protected Throwable handleSQLException(SQLException e) { + throw new RuntimeException( + "Error while reading exported keys meta data for " + + TableNameQualifier.qualify(catalog, schema, table), + e); + } + }; + } + catch (SQLException e) { + throw new RuntimeException( + "Error while reading exported keys meta data for " + + TableNameQualifier.qualify(catalog, schema, table), + e); + } + } + + public void close() { + try { + prepTableNone = close( prepTableNone ); + prepTableSchema = close( prepTableSchema ); + prepTableTable = close( prepTableTable ); + prepTableSchemaAndTable = close( prepTableSchemaAndTable ); + prepIndexNone = close( prepIndexNone ); + prepIndexSchema = close( prepIndexSchema ); + prepIndexTable = close( prepIndexTable ); + prepIndexSchemaAndTable = close( prepIndexSchemaAndTable ); + prepColumnNone = close( prepColumnNone ); + prepColumnSchema = close( prepColumnSchema ); + prepColumnTable = close( prepColumnTable ); + prepColumnColumn = close( prepColumnColumn ); + prepColumnSchemaAndTable = close( prepColumnSchemaAndTable ); + prepColumnSchemaAndColumn = close( prepColumnSchemaAndColumn ); + prepColumnTableAndColumn = close( prepColumnTableAndColumn ); + prepColumnSchemaAndTableAndColumn = close( prepColumnSchemaAndTableAndColumn ); + prepPkNone = close( prepPkNone ); + prepPkSchema = close( prepPkSchema ); + prepPkTable = close( prepPkTable ); + prepPkSchemaAndTable = close( prepPkSchemaAndTable ); + prepFkNone = close( prepFkNone ); + prepFkSchema = close( prepFkSchema ); + prepFkTable = close( prepFkTable ); + prepFkSchemaAndTable = close( prepFkSchemaAndTable ); + } + finally { + super.close(); + } + } + + private PreparedStatement close(PreparedStatement ps) { + try { + ps.close(); + } + catch (SQLException e) { + throw new RuntimeException( "Problem while closing prepared statement", e); + } + return null; + + } + + private String escape(String str) { + return str.replace("_", "\\_"); + } + + private ResultSet getPrimaryKeysResultSet(final String schem, final String tab) throws SQLException { + String schema = escape(schem); + String table = escape(tab); + if(prepPkNone==null) { + // Prepare primary key queries + log.debug("Preparing primary key queries..."); + Connection con = getConnection(); + prepPkNone = con .prepareStatement(SQL_PK_NONE); + prepPkSchema = con.prepareStatement(SQL_PK_SCHEMA); + prepPkTable = con.prepareStatement(SQL_PK_TABLE); + prepPkSchemaAndTable = con + .prepareStatement(SQL_PK_SCHEMA_AND_TABLE); + log.debug(" primary key queries prepared!"); + } + + ResultSet pkeyRs; + prepPkSchemaAndTable.setString( 1, schema ); + prepPkSchemaAndTable.setString( 2, table ); + pkeyRs = prepPkSchemaAndTable.executeQuery(); + return pkeyRs; + } + + private ResultSet getIndexInfoResultSet(final String schema, final String table) throws SQLException { + if(prepIndexNone==null) { + // Prepare index queries + log.debug("Preparing index queries..."); + Connection con = getConnection(); + prepIndexNone = con.prepareStatement(SQL_INDEX_NONE); + prepIndexSchema = con.prepareStatement(SQL_INDEX_SCHEMA); + prepIndexTable = con.prepareStatement(SQL_INDEX_TABLE); + prepIndexSchemaAndTable = con.prepareStatement(SQL_INDEX_SCHEMA_AND_TABLE); + log.debug(" ...index queries prepared!"); + } + ResultSet indexRs; + if (schema == null && table == null) { + indexRs = prepIndexNone.executeQuery(); + } + else if (schema != null) { + if (table == null) { + prepIndexSchema.setString(1, schema); + indexRs = prepIndexSchema.executeQuery(); + } + else { + prepIndexSchemaAndTable.setString(1, schema); + prepIndexSchemaAndTable.setString(2, table); + indexRs = prepIndexSchemaAndTable.executeQuery(); + } + } + else { + prepIndexTable.setString(1, table); + indexRs = prepIndexTable.executeQuery(); + } + return indexRs; + } + + private ResultSet getExportedKeysResultSet(final String schema, final String table) throws SQLException { + if(prepFkNone==null) { + // Prepare foreign key queries + log.debug("Preparing foreign key queries..."); + Connection con = getConnection(); + prepFkNone = con .prepareStatement(SQL_FK_NONE); + prepFkSchema = con.prepareStatement(SQL_FK_SCHEMA); + prepFkTable = con.prepareStatement(SQL_FK_TABLE); + prepFkSchemaAndTable = con.prepareStatement(SQL_FK_SCHEMA_AND_TABLE); + log.debug(" foreign key queries prepared!"); + } + + ResultSet pExportRs; + if (schema == null && table == null) { + pExportRs = prepFkNone.executeQuery(); + } + else if (schema != null) { + if (table == null) { + prepFkSchema.setString(1, schema); + pExportRs = prepFkSchema.executeQuery(); + } + else { + prepFkSchemaAndTable.setString(1, schema); + prepFkSchemaAndTable.setString(2, table); + pExportRs = prepFkSchemaAndTable.executeQuery(); + } + } + else { + prepFkTable.setString(1, table); + pExportRs = prepFkTable.executeQuery(); + } + return pExportRs; + } + private ResultSet getColumnsResultSet(final String schema, final String table, String column) throws SQLException { + + if(prepColumnNone==null) { + // Prepare column queries + log.debug("Preparing column queries..."); + Connection con = getConnection(); + prepColumnNone = con.prepareStatement(SQL_COLUMN_NONE); + prepColumnSchema = con.prepareStatement(SQL_COLUMN_SCHEMA); + prepColumnTable = con.prepareStatement(SQL_COLUMN_TABLE); + prepColumnColumn = con.prepareStatement(SQL_COLUMN_COLUMN); + prepColumnSchemaAndTable = con.prepareStatement(SQL_COLUMN_SCHEMA_AND_TABLE); + prepColumnSchemaAndColumn = con.prepareStatement(SQL_COLUMN_SCHEMA_AND_COLUMN); + prepColumnTableAndColumn = con.prepareStatement(SQL_COLUMN_TABLE_AND_COLUMN); + prepColumnSchemaAndTableAndColumn = con.prepareStatement(SQL_COLUMN_SCHEMA_AND_TABLE_AND_COLUMN); + log.debug(" ...column queries prepared!"); + } + + ResultSet columnRs; + // No parameters specified + if (schema == null && table == null && column == null) { + columnRs = prepColumnNone.executeQuery(); + } + else if (schema != null) { + if (table == null) { + if (column == null) { + // Schema specified + prepColumnSchema.setString(1, schema); + columnRs = prepColumnSchema.executeQuery(); + } + else { + // Schema and column specified + prepColumnSchemaAndColumn.setString(1, schema); + prepColumnSchemaAndColumn.setString(2, column); + columnRs = prepColumnSchemaAndColumn.executeQuery(); + } + } + else { + if (column == null) { + // Schema and table specified + prepColumnSchemaAndTable.setString(1, schema); + prepColumnSchemaAndTable.setString(2, table); + columnRs = prepColumnSchemaAndTable.executeQuery(); + } + else { + // Schema, table and column specified + prepColumnSchemaAndTableAndColumn.setString(1, schema); + prepColumnSchemaAndTableAndColumn.setString(2, table); + prepColumnSchemaAndTableAndColumn.setString(3, column); + columnRs = prepColumnSchemaAndTableAndColumn.executeQuery(); + } + } + } + else { + if (table == null) { + // Column specified + prepColumnColumn.setString(1, column); + columnRs = prepColumnColumn.executeQuery(); + } + else { + if (column == null) { + // Table specified + prepColumnTable.setString(1, table); + columnRs = prepColumnTable.executeQuery(); + } + else { + // Table and column specified + prepColumnTableAndColumn.setString(1, table); + prepColumnTableAndColumn.setString(2, column); + columnRs = prepColumnTableAndColumn.executeQuery(); + + } + } + } + return columnRs; + } + + private ResultSet getTableResultSet(final String schema, String table) throws SQLException { + ResultSet tableRs; + if(prepTableNone==null) { + // Prepare table queries + log.debug("Preparing table queries..."); + Connection connection2 = getConnection(); + prepTableNone = connection2.prepareStatement(SQL_TABLE_NONE); + prepTableSchema = connection2.prepareStatement(SQL_TABLE_SCHEMA); + prepTableTable = connection2.prepareStatement(SQL_TABLE_TABLE); + prepTableSchemaAndTable = connection2.prepareStatement(SQL_TABLE_SCHEMA_AND_TABLE); + log.debug(" ...table queries prepared!"); + } + if (schema == null && table == null) { + tableRs = prepTableNone.executeQuery(); + } + else if (schema != null) { + if (table == null) { + prepTableSchema.setString(1, schema); + prepTableSchema.setString(2, schema); + tableRs = prepTableSchema.executeQuery(); + } + else { + prepTableSchemaAndTable.setString(1, schema); + prepTableSchemaAndTable.setString(2, table); + prepTableSchemaAndTable.setString(3, schema); + prepTableSchemaAndTable.setString(4, table); + tableRs = prepTableSchemaAndTable.executeQuery(); + } + } + else { + prepTableTable.setString(1, table); + prepTableTable.setString(2, table); + tableRs = prepTableTable.executeQuery(); + } + return tableRs; + } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/SQLServerMetaDataDialect.java b/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/SQLServerMetaDataDialect.java index 7352b414c..b1557d691 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/SQLServerMetaDataDialect.java +++ b/orm/src/main/java/org/hibernate/tool/internal/reveng/dialect/SQLServerMetaDataDialect.java @@ -31,65 +31,68 @@ */ public class SQLServerMetaDataDialect extends JDBCMetaDataDialect { - public Iterator> getSuggestedPrimaryKeyStrategyName(String catalog, String schema, String table) { - String sql = null; - try { - catalog = caseForSearch( catalog ); - schema = caseForSearch( schema ); - table = caseForSearch( table ); - - log.debug("geSuggestedPrimaryKeyStrategyName(" + catalog + "." + schema + "." + table + ")"); + public Iterator> getSuggestedPrimaryKeyStrategyName(String catalog, String schema, String table) { + String sql; + try { + catalog = caseForSearch( catalog ); + schema = caseForSearch( schema ); + table = caseForSearch( table ); - sql = "SELECT a.TABLE_CATALOG, a.TABLE_SCHEMA, a.TABLE_NAME as table_name, c.DATA_TYPE as data_type, b.CONSTRAINT_TYPE, OBJECTPROPERTY(OBJECT_ID(a.TABLE_NAME),'TableHasIdentity') as hasIdentity " + - "FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE a " + - "INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS b on a.CONSTRAINT_NAME = b.CONSTRAINT_NAME " + - "INNER JOIN INFORMATION_SCHEMA.COLUMNS c on a.TABLE_CATALOG = c.TABLE_CATALOG AND a.TABLE_SCHEMA = c.TABLE_SCHEMA AND a.TABLE_NAME = c.TABLE_NAME AND a.COLUMN_NAME = c.COLUMN_NAME " + - "WHERE a.TABLE_NAME=? AND a.TABLE_SCHEMA=? AND a.TABLE_CATALOG=? AND b.CONSTRAINT_TYPE = 'Primary key'"; + log.debug("geSuggestedPrimaryKeyStrategyName(" + catalog + "." + schema + "." + table + ")"); - PreparedStatement statement = getConnection().prepareStatement( sql ); - statement.setString(1, table); - statement.setString( 2, schema ); - statement.setString( 3, catalog ); - - final String sc = schema; - final String cat = catalog; - return new ResultSetIterator(statement.executeQuery()) { - - Map element = new HashMap(); - protected Map convertRow(ResultSet tableRs) throws SQLException { - element.clear(); - element.put("TABLE_NAME", tableRs.getString("table_name")); - element.put("TABLE_SCHEM", sc); - element.put("TABLE_CAT", cat); - - String string = tableRs.getString("data_type"); - - boolean bool = tableRs.getBoolean("hasIdentity"); - if(string!=null) { - if(string.equalsIgnoreCase("uniqueidentifier")){ - element.put("HIBERNATE_STRATEGY", "guid"); - }else if(bool){ - element.put("HIBERNATE_STRATEGY", "identity"); - }else{ - element.put("HIBERNATE_STRATEGY", null); - } - }else { - element.put("HIBERNATE_STRATEGY", null); - } - return element; - } - protected Throwable handleSQLException(SQLException e) { - // schemaRs and catalogRs are only used for error reporting if - // we get an exception - throw new RuntimeException( - "Could not get list of suggested identity strategies from database. Probably a JDBC driver problem. ", e); - } - }; - } catch (SQLException e) { - throw new RuntimeException( - "Could not get list of suggested identity strategies from database. Probably a JDBC driver problem. ", e); - } - } + sql = "SELECT a.TABLE_CATALOG, a.TABLE_SCHEMA, a.TABLE_NAME as table_name, c.DATA_TYPE as data_type, b.CONSTRAINT_TYPE, OBJECTPROPERTY(OBJECT_ID(a.TABLE_NAME),'TableHasIdentity') as hasIdentity " + + "FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE a " + + "INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS b on a.CONSTRAINT_NAME = b.CONSTRAINT_NAME " + + "INNER JOIN INFORMATION_SCHEMA.COLUMNS c on a.TABLE_CATALOG = c.TABLE_CATALOG AND a.TABLE_SCHEMA = c.TABLE_SCHEMA AND a.TABLE_NAME = c.TABLE_NAME AND a.COLUMN_NAME = c.COLUMN_NAME " + + "WHERE a.TABLE_NAME=? AND a.TABLE_SCHEMA=? AND a.TABLE_CATALOG=? AND b.CONSTRAINT_TYPE = 'Primary key'"; - } - + PreparedStatement statement = getConnection().prepareStatement( sql ); + statement.setString(1, table); + statement.setString( 2, schema ); + statement.setString( 3, catalog ); + + final String sc = schema; + final String cat = catalog; + return new ResultSetIterator(statement.executeQuery()) { + + final Map element = new HashMap<>(); + protected Map convertRow(ResultSet tableRs) throws SQLException { + element.clear(); + element.put("TABLE_NAME", tableRs.getString("table_name")); + element.put("TABLE_SCHEM", sc); + element.put("TABLE_CAT", cat); + + String string = tableRs.getString("data_type"); + + boolean bool = tableRs.getBoolean("hasIdentity"); + if(string!=null) { + if(string.equalsIgnoreCase("uniqueidentifier")){ + element.put("HIBERNATE_STRATEGY", "guid"); + } + else if(bool){ + element.put("HIBERNATE_STRATEGY", "identity"); + } + else{ + element.put("HIBERNATE_STRATEGY", null); + } + } + else { + element.put("HIBERNATE_STRATEGY", null); + } + return element; + } + protected Throwable handleSQLException(SQLException e) { + // schemaRs and catalogRs are only used for error reporting if + // we get an exception + throw new RuntimeException( + "Could not get list of suggested identity strategies from database. Probably a JDBC driver problem. ", e); + } + }; + } + catch (SQLException e) { + throw new RuntimeException( + "Could not get list of suggested identity strategies from database. Probably a JDBC driver problem. ", e); + } + } + +}