List of usage examples for java.sql DatabaseMetaData getIndexInfo
ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException;
From source file:de.griffel.confluence.plugins.plantuml.AbstractDatabaseStructureMacroImpl.java
private void addIndexDetails(DatabaseMetaData dbmd, TableDef t) { final List<IndexDef> result = new LinkedList<IndexDef>(); if (_errorMessage == null && (_macroParams.isShowIndexes() || _macroParams.getTableTypes().contains("INDEX"))) { ResultSet rs = null;/*from ww w . j ava2 s .c o m*/ try { rs = dbmd.getIndexInfo(t.getTableCatalog(), t.getTableSchema(), t.getTableName(), false, true); while (rs.next()) { IndexDef tmp = new IndexDef(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(5), rs.getString(6), rs.getShort(8), rs.getString(9)); result.add(tmp); if (log.isDebugEnabled()) { log.debug(tmp.getIndexId()); } } } catch (SQLException e) { sqlException(_macroParams.getDatasource(), e); } finally { closeResource(rs); } } t.setIndices(result); }
From source file:jp.co.tis.gsp.tools.dba.s2jdbc.gen.DbTableMetaReaderWithView.java
@Override protected List<DbUniqueKeyMeta> getDbUniqueKeyMetaList(DatabaseMetaData metaData, DbTableMeta tableMeta) { if (!dialect.supportsGetIndexInfo(tableMeta.getCatalogName(), tableMeta.getSchemaName(), tableMeta.getName())) {/* w ww.j a v a 2 s.c o m*/ logger.log("WS2JDBCGen0002", new Object[] { tableMeta.getCatalogName(), tableMeta.getSchemaName(), tableMeta.getName() }); return Collections.emptyList(); } @SuppressWarnings("unchecked") Map<String, DbUniqueKeyMeta> map = new ArrayMap(); try { // ???????? String typeName = getObjectTypeName(metaData, tableMeta); String tableName = tableMeta.getName(); if (!StringUtils.equals(typeName, "TABLE")) { return Collections.emptyList(); } ResultSet rs = metaData.getIndexInfo(tableMeta.getCatalogName(), tableMeta.getSchemaName(), tableName, true, false); try { while (rs.next()) { String name = rs.getString("INDEX_NAME"); if (!map.containsKey(name)) { DbUniqueKeyMeta ukMeta = new DbUniqueKeyMeta(); ukMeta.setName(name); map.put(name, ukMeta); } DbUniqueKeyMeta ukMeta = map.get(name); ukMeta.addColumnName(rs.getString("COLUMN_NAME")); } } finally { ResultSetUtil.close(rs); } DbUniqueKeyMeta[] array = map.values().toArray(new DbUniqueKeyMeta[map.size()]); return Arrays.asList(array); } catch (SQLException ex) { throw new SQLRuntimeException(ex); } }
From source file:com.nextep.designer.sqlgen.generic.impl.JDBCCapturer.java
/** * Returns a <code>Collection</code> of the indexes for the specified table * present in the data source pointed to by the connection object provided * by the specified <code>context</code> and notifies the specified * <code>monitor</code> while capturing. * //from www . j a va2 s . c o m * @param context * a {@link ICaptureContext} to store the captured objects * @param monitor * the {@link IProgressMonitor} to notify while capturing objects * @param table * the {@link IBasicTable} for which foreign keys must be * captured * @return a {@link Collection} of {@link IIndex} objects if the specified * table has indexes, an empty <code>Collection</code> otherwise */ private Collection<IIndex> getTableIndexes(ICaptureContext context, IProgressMonitor monitor, IBasicTable table) { Collection<IIndex> indexes = new ArrayList<IIndex>(); IFormatter formatter = getConnectionVendor(context).getNameFormatter(); final String tableName = table.getName(); try { final DatabaseMetaData md = ((Connection) context.getConnectionObject()).getMetaData(); ResultSet rset = null; if (md != null) { rset = md.getIndexInfo(getObjectOrContextCatalog(context, table), getObjectOrContextSchema(context, table), tableName, false, false); CaptureHelper.updateMonitor(monitor, getCounter(), 1, 1); } if (rset != null) { IIndex currIndex = null; String currIndexName = null; boolean indexIsValid = false; try { while (rset.next()) { final String indexName = rset.getString(COLUMN_NAME_INDEX_NAME); final boolean nonUnique = rset.getBoolean(COLUMN_NAME_NON_UNIQUE); final String indexColumnName = rset.getString(COLUMN_NAME_COLUMN_NAME); final String ascOrDesc = rset.getString(COLUMN_NAME_ASC_OR_DESC); final short indexType = rset.getShort(COLUMN_NAME_TYPE); if (indexName != null && !"".equals(indexName.trim())) { //$NON-NLS-1$ if (LOGGER.isDebugEnabled()) { String logPrefix = "[" + indexName + "]"; //$NON-NLS-1$ //$NON-NLS-2$ LOGGER.debug("= " + logPrefix + " Index Metadata ="); //$NON-NLS-1$ //$NON-NLS-2$ LOGGER.debug(logPrefix + "[" + COLUMN_NAME_INDEX_NAME + "] " //$NON-NLS-1$ //$NON-NLS-2$ + indexName); LOGGER.debug(logPrefix + "[" + COLUMN_NAME_NON_UNIQUE + "] " //$NON-NLS-1$ //$NON-NLS-2$ + nonUnique); LOGGER.debug(logPrefix + "[" + COLUMN_NAME_COLUMN_NAME + "] " //$NON-NLS-1$ //$NON-NLS-2$ + indexColumnName); LOGGER.debug(logPrefix + "[" + COLUMN_NAME_ASC_OR_DESC + "] " //$NON-NLS-1$ //$NON-NLS-2$ + ascOrDesc); LOGGER.debug(logPrefix + "[" + COLUMN_NAME_TYPE + "] " + indexType); //$NON-NLS-1$ //$NON-NLS-2$ } if (null == currIndexName || !currIndexName.equals(indexName) || indexIsValid) { currIndexName = indexName; final String formatIndexName = formatter.format(indexName); final String formatIndexColumnName = formatter.format(indexColumnName); if (null == currIndex || !formatIndexName.equals(currIndex.getIndexName())) { IVersionable<IIndex> v = VersionableFactory.createVersionable(IIndex.class, context.getConnection().getDBVendor()); currIndex = v.getVersionnedObject().getModel(); currIndex.setName(formatIndexName); currIndex.setIndexType( nonUnique ? CaptureHelper.getIndexType(indexType) : IndexType.UNIQUE); indexes.add(currIndex); indexIsValid = true; } final IBasicColumn column = (IBasicColumn) context.getCapturedObject( IElementType.getInstance(IBasicColumn.TYPE_ID), CaptureHelper.getUniqueObjectName(tableName, formatIndexColumnName)); if (column != null) { /* * Columns are ordered by INDEX_NAME, * ORDINAL_POSITION in the returned * ResultSet, so we don't have to specify * the position of the index column when * adding it to the index. */ currIndex.addColumnRef(column.getReference()); } else { LOGGER.warn("Index [" + formatIndexName + "] has been partially captured during import because the referencing column [" + tableName + "[" + formatIndexColumnName //$NON-NLS-1$ + "]] could not be found in the current workspace"); indexIsValid = false; /* * Now the index is invalid, we remove it * from the indexes list that will be * returned to the caller of this method. */ indexes.remove(currIndex); } } } } } finally { CaptureHelper.safeClose(rset, null); } } } catch (SQLException sqle) { LOGGER.error("Unable to fetch indexes for table [" + tableName + "] from " + getConnectionVendorName(context) + " server: " + sqle.getMessage(), sqle); } return indexes; }
From source file:de.erdesignerng.dialect.JDBCReverseEngineeringStrategy.java
protected void reverseEngineerIndexes(Model aModel, TableEntry aTableEntry, DatabaseMetaData aMetaData, Table aTable, ReverseEngineeringNotifier aNotifier) throws SQLException, ReverseEngineeringException { ResultSet theIndexResults = aMetaData.getIndexInfo(aTableEntry.getCatalogName(), aTableEntry.getSchemaName(), aTableEntry.getTableName(), false, true); Index theIndex = null;//from w ww . j a va 2 s . c o m while (theIndexResults.next()) { String theIndexName = convertIndexNameFor(aTable, theIndexResults.getString("INDEX_NAME")); if ((theIndexName != null) && ((theIndex == null) || (!theIndex.getOriginalName().equals(theIndexName)))) { String theNewIndexName = dialect.getCastType().cast(theIndexName); if (aTable.getIndexes().findByName(theNewIndexName) == null) { theIndex = new Index(); theIndex.setName(theNewIndexName); theIndex.setOriginalName(theIndexName); boolean isNonUnique = theIndexResults.getBoolean("NON_UNIQUE"); if (isNonUnique) { theIndex.setIndexType(IndexType.NONUNIQUE); } else { theIndex.setIndexType(IndexType.UNIQUE); } aNotifier.notifyMessage(ERDesignerBundle.ENGINEERINGINDEX, theIndex.getName()); try { aTable.addIndex(aModel, theIndex); } catch (ElementAlreadyExistsException | ElementInvalidNameException e) { throw new ReverseEngineeringException("Cannot add index " + theIndexName + " in table " + aTable.getName() + " : " + e.getMessage(), e); } } else { theIndex = null; } } if (theIndex != null) { short aPosition = theIndexResults.getShort("ORDINAL_POSITION"); String theColumnName = theIndexResults.getString("COLUMN_NAME"); String theASCorDESC = theIndexResults.getString("ASC_OR_DESC"); reverseEngineerIndexAttribute(aMetaData, aTableEntry, aTable, aNotifier, theIndex, theColumnName, aPosition, theASCorDESC); } } theIndexResults.close(); // Remove duplicate unique indexes Index thePrimaryKey = aTable.getPrimarykey(); if (thePrimaryKey != null) { Set<Index> theDuplicateIndexes = new HashSet<>(); for (Index theInd : aTable.getIndexes()) { if ((theInd.getIndexType() == IndexType.UNIQUE) && (thePrimaryKey.getExpressions().containsAllExpressions(theInd.getExpressions()))) { theDuplicateIndexes.add(theInd); } } aTable.getIndexes().removeAll(theDuplicateIndexes); } }
From source file:com.jaxio.celerio.configuration.database.support.MetadataExtractor.java
private void loadIndexes(JdbcConnectivity configuration, DatabaseMetaData databaseMetaData, Table table) throws SQLException { if (!configuration.shouldReverseIndexes()) { log.warn("Skipping reverse for indexes of table " + table.getName()); return;/*from w ww . ja v a 2s. c om*/ } boolean retreiveOnlyUniques = configuration.shouldReverseOnlyUniqueIndexes(); if (retreiveOnlyUniques) { log.info("Extracting only unique indexes for table: " + table.getName()); } else { log.info("Extracting all indexes for table: " + table.getName()); } // index reverse can be pretty slow, so we need to warn the user in such cases. long thresholdAlertMillisec = 5 * 1000l; // 5 secs long t0 = System.currentTimeMillis(); // unique or not boolean useApproximation = true; // / when true, result is allowed to reflect approximate or out of data values; when false, results are requested to be // accurate ResultSet resultSet = databaseMetaData.getIndexInfo(configuration.getCatalog(), configuration.getSchemaName(), table.getName(), retreiveOnlyUniques, useApproximation); ResultSetWrapper rsw = new ResultSetIndexInfo(resultSet, useLabel); while (resultSet.next()) { Index index = new Index(); index.setIndexName(getString(rsw, "INDEX_NAME")); index.setColumnName(getString(rsw, "COLUMN_NAME")); index.setNonUnique(rsw.getBoolean("NON_UNIQUE")); table.addIndex(index); } resultSet.close(); long t1 = System.currentTimeMillis(); if ((t1 - t0) >= thresholdAlertMillisec) { if (retreiveOnlyUniques) { log.warn("Table " + table.getName() + ": Index reverse seems long, you can disable it by setting <jdbc.reverseIndexes>false</jdbc.reverseIndexes> maven property."); } else { log.warn("Table " + table.getName() + ": Index reverse seems long, you may want to restrict it by setting <jdbc.reverseOnlyUniqueIndexes>true</jdbc.reverseOnlyUniqueIndexes> maven property"); } } }
From source file:com.glaf.core.util.DBUtils.java
public static void createIndex(String systemName, String tableName, String columnName, String indexName) { Connection connection = null; DatabaseMetaData dbmd = null; Statement stmt = null;//from www .j av a 2 s . c om ResultSet rs = null; boolean hasIndex = false; try { connection = DBConnectionFactory.getConnection(systemName); dbmd = connection.getMetaData(); rs = dbmd.getIndexInfo(null, null, tableName, false, false); while (rs.next()) { String col = rs.getString("COLUMN_NAME"); if (StringUtils.equalsIgnoreCase(columnName, col)) { hasIndex = true; break; } } JdbcUtils.close(rs); if (!hasIndex) { String sql = " create index " + indexName.toUpperCase() + " on " + tableName + " (" + columnName + ") "; connection.setAutoCommit(false); stmt = connection.createStatement(); stmt.executeUpdate(sql); JdbcUtils.close(stmt); connection.commit(); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); JdbcUtils.close(connection); } }
From source file:com.glaf.core.util.DBUtils.java
public static void createIndex(Connection connection, String tableName, String columnName, String indexName) { DatabaseMetaData dbmd = null; Statement stmt = null;//from www.j a v a2s. c o m ResultSet rs = null; boolean hasIndex = false; boolean autoCommit = false; try { autoCommit = connection.getAutoCommit(); dbmd = connection.getMetaData(); rs = dbmd.getIndexInfo(null, null, tableName, false, false); while (rs.next()) { String col = rs.getString("COLUMN_NAME"); if (StringUtils.equalsIgnoreCase(columnName, col)) { hasIndex = true; break; } } JdbcUtils.close(rs); if (!hasIndex) { String sql = " create index " + indexName.toUpperCase() + " on " + tableName + " (" + columnName + ") "; connection.setAutoCommit(false); stmt = connection.createStatement(); stmt.executeUpdate(sql); JdbcUtils.close(stmt); connection.commit(); connection.setAutoCommit(autoCommit); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); } }
From source file:com.ccl.jersey.codegen.SimpleMetaDataExporter.java
@SuppressWarnings("unchecked") private void handleTable(DatabaseMetaData md, ResultSet tables, Statement stmt) throws SQLException { String catalog = tables.getString("TABLE_CAT"); String schema = tables.getString("TABLE_SCHEM"); String schemaName = normalize(tables.getString("TABLE_SCHEM")); String tableName = normalize(tables.getString("TABLE_NAME")); String comment = getTableComment(stmt, tableName); String normalizedTableName = namingStrategy.normalizeTableName(tableName); String className = namingStrategy.getClassName(normalizedTableName); EntityType classModel = createEntityType(schemaName, normalizedTableName, className); EntityType modelClassModel = createVOEntityType(schemaName, normalizedTableName, className); tableModelMapper.put(normalizedTableName, modelClassModel.getFullName()); if (exportPrimaryKeys) { // collect primary keys Map<String, PrimaryKeyData> primaryKeyData = keyDataFactory.getPrimaryKeys(md, catalog, schema, tableName);// w w w .j a v a 2 s . c o m if (!primaryKeyData.isEmpty()) { classModel.getData().put(PrimaryKeyData.class, primaryKeyData.values()); } } Map<String, UniqueKeyData> uniqueKeyDatas = new HashMap<>(); ResultSet indexInfo = md.getIndexInfo(catalog, schema, tableName, true, false); while (indexInfo.next()) { String indexName = indexInfo.getString("INDEX_NAME"); if (!"PRIMARY".equals(indexName)) { UniqueKeyData uniqueKeyData = uniqueKeyDatas.get(indexName); if (null == uniqueKeyData) { uniqueKeyData = new UniqueKeyData(indexName); } uniqueKeyDatas.put(indexName, uniqueKeyData); String columnName = indexInfo.getString("COLUMN_NAME"); String normalizedColumnName = namingStrategy.normalizeColumnName(columnName); String propertyName = namingStrategy.getPropertyName(normalizedColumnName, classModel); uniqueKeyData.add(propertyName); } } indexInfo.close(); if (!uniqueKeyDatas.isEmpty()) { Collection<UniqueKeyData> values = uniqueKeyDatas.values(); classModel.getData().put(UniqueKeyData.class, values); List<Unique> uniques = new ArrayList<>(); for (UniqueKeyData uniqueKeyData : values) { UniqueImpl unique = new UniqueImpl( uniqueKeyData.getColumns().toArray(new String[uniqueKeyData.getColumns().size()])); uniques.add(unique); } classModel.addAnnotation(new UniquesImpl(uniques.toArray(new Unique[uniques.size()]))); } if (exportForeignKeys) { // collect foreign keys Map<String, ForeignKeyData> foreignKeyData = keyDataFactory.getImportedKeys(md, catalog, schema, tableName); if (!foreignKeyData.isEmpty()) { classModel.getData().put(ForeignKeyData.class, foreignKeyData.values()); } // collect inverse foreign keys Map<String, InverseForeignKeyData> inverseForeignKeyData = keyDataFactory.getExportedKeys(md, catalog, schema, tableName); if (!inverseForeignKeyData.isEmpty()) { classModel.getData().put(InverseForeignKeyData.class, inverseForeignKeyData.values()); } } // collect columns ResultSet columns = md.getColumns(catalog, schema, tableName.replace("/", "//"), null); try { while (columns.next()) { handleColumn(classModel, tableName, columns); } } finally { columns.close(); } // serialize model LabelImpl label = new LabelImpl(StringUtils.isBlank(comment) ? className : comment); classModel.addAnnotation(label); Set<Property> properties = classModel.getProperties(); Map<String, Type> dataTypeMap = registerDataTypes.get(modelClassModel.getFullName()); String modelPackageName = basePackageName + ".model"; List<BelongsToImpl> belongsTos = new ArrayList<BelongsToImpl>(); for (Property property : properties) { Type propertyType = property.getType(); boolean customType = false; String propertyName = property.getName(); if (null != dataTypeMap) { Type propertyCls = dataTypeMap.get(propertyName); if (null != propertyCls) { propertyType = propertyCls; customType = true; } } Collection<ForeignKeyData> foreignKeyDatas = (Collection<ForeignKeyData>) classModel.getData() .get(ForeignKeyData.class); boolean isForeignKey = false; if (exportBelongsTos && null != foreignKeyDatas && !foreignKeyDatas.isEmpty()) { for (ForeignKeyData foreignKey : foreignKeyDatas) { String propertyName2 = namingStrategy.getPropertyName(foreignKey.getForeignColumns().get(0), classModel); if (propertyName.equals(propertyName2)) { String simpleName = foreignKey.getType().getSimpleName(); simpleName = simpleName.substring(module.getBeanPrefix().length(), simpleName.length()); propertyType = new SimpleType(modelPackageName + "." + simpleName, modelPackageName, simpleName); propertyName = propertyName2.substring(0, propertyName2.length() - 2); belongsTos.add(new BelongsToImpl(propertyName, propertyName2)); isForeignKey = true; break; } } } Property property2 = createProperty(modelClassModel, propertyName, propertyName, propertyName, propertyType); Collection<Annotation> annotations = property.getAnnotations(); for (Annotation annotation : annotations) { if ((isForeignKey || customType) && Size.class.equals(annotation.annotationType())) { continue; } property2.addAnnotation(annotation); } modelClassModel.addProperty(property2); if (customType) { property.addAnnotation(new DictDataTypeImpl((Class<? extends Enum>) propertyType.getJavaClass())); } } Collection<InverseForeignKeyData> inverseForeignKeyDatas = (Collection<InverseForeignKeyData>) classModel .getData().get(InverseForeignKeyData.class); List<HasManyImpl> hasManys = new ArrayList<HasManyImpl>(); if (exportHasManys && null != inverseForeignKeyDatas && !inverseForeignKeyDatas.isEmpty()) { for (InverseForeignKeyData inverseForeignKeyData : inverseForeignKeyDatas) { String simpleName = inverseForeignKeyData.getType().getSimpleName(); simpleName = simpleName.substring(module.getBeanPrefix().length(), simpleName.length()); Type propertyType = new SimpleType(modelPackageName + "." + simpleName, modelPackageName, simpleName); Type propertyListType = new ClassType(TypeCategory.LIST, List.class, propertyType); String propertyName2 = namingStrategy.getPropertyName(inverseForeignKeyData.getTable(), classModel); String propertyName = propertyName2 + "s"; Set<String> propertyNames = modelClassModel.getPropertyNames(); int index = 0; while (propertyNames.contains(propertyName)) { index++; propertyName = propertyName2 + index + "s"; } Property property2 = createProperty(modelClassModel, propertyName, propertyName, propertyName, propertyListType); String tableComment = getTableComment(stmt, inverseForeignKeyData.getTable()); LabelImpl tableLabel = new LabelImpl(StringUtils.isBlank(tableComment) ? propertyName : tableComment + "" + (0 < index ? index : "")); property2.addAnnotation(tableLabel); modelClassModel.addProperty(property2); hasManys.add(new HasManyImpl(propertyName, namingStrategy .getPropertyName(inverseForeignKeyData.getParentColumns().get(0), classModel))); } } if (!belongsTos.isEmpty()) { modelClassModel .addAnnotation(new BelongsTosImpl(belongsTos.toArray(new BelongsToImpl[belongsTos.size()]))); } if (!hasManys.isEmpty()) { modelClassModel.addAnnotation(new HasManysImpl(hasManys.toArray(new HasManyImpl[hasManys.size()]))); } modelClassModel.addAnnotation(label); serialize(classModel, modelClassModel); logger.info("Exported " + tableName + " successfully"); }
From source file:jef.database.DbMetaData.java
/** * /*from w ww. jav a2 s . co m*/ * * @param tableName * ?? * @return ? * @see Index */ public Collection<Index> getIndexes(String tableName) throws SQLException { // JDBC?? if (info.profile.has(Feature.NOT_SUPPORT_INDEX_META)) { LogUtil.warn("Current JDBC version doesn't suppoer fetch index info."); return Collections.emptyList(); } tableName = info.profile.getObjectNameToUse(tableName); String schema = this.schema; int n = tableName.indexOf('.'); if (n > -1) { schema = tableName.substring(0, n); tableName = tableName.substring(n + 1); } Connection conn = getConnection(false); ResultSet rs = null; try { DatabaseMetaData databaseMetaData = conn.getMetaData(); rs = databaseMetaData.getIndexInfo(null, schema, tableName, false, false); Map<String, Index> map = new HashMap<String, Index>(); while (rs.next()) { String indexName = rs.getString("INDEX_NAME"); String cName = rs.getString("COLUMN_NAME"); if (indexName == null || cName == null) continue; Index index = map.get(indexName); if (index == null) { index = new Index(); index.setIndexName(indexName); index.setTableName(rs.getString("TABLE_NAME")); index.setTableSchema(rs.getString("TABLE_SCHEM")); index.setIndexQualifier(rs.getString("INDEX_QUALIFIER")); index.setUnique(!rs.getBoolean("NON_UNIQUE")); index.setType(rs.getInt("TYPE")); map.put(indexName, index); } String asc = rs.getString("ASC_OR_DESC"); int order = rs.getInt("ORDINAL_POSITION"); index.addColumn(cName, asc == null ? true : asc.startsWith("A"), order); } return map.values(); } finally { DbUtils.close(rs); releaseConnection(conn); } }
From source file:com.oltpbenchmark.catalog.Catalog.java
/** * Construct the set of Table objects from a given Connection handle * @param conn// ww w . ja v a 2 s . c o m * @return * @throws SQLException * @see http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html */ protected void init() throws SQLException { // Load the database's DDL this.benchmark.createDatabase(DB_TYPE, this.conn); // TableName -> ColumnName -> <FkeyTable, FKeyColumn> Map<String, Map<String, Pair<String, String>>> foreignKeys = new HashMap<String, Map<String, Pair<String, String>>>(); DatabaseMetaData md = conn.getMetaData(); ResultSet table_rs = md.getTables(null, null, null, new String[] { "TABLE" }); while (table_rs.next()) { if (LOG.isDebugEnabled()) LOG.debug(SQLUtil.debug(table_rs)); String internal_table_name = table_rs.getString(3); String table_name = origTableNames.get(table_rs.getString(3).toUpperCase()); assert (table_name != null) : "Unexpected table '" + table_rs.getString(3) + "' from catalog"; LOG.debug(String.format("ORIG:%s -> CATALOG:%s", internal_table_name, table_name)); String table_type = table_rs.getString(4); if (table_type.equalsIgnoreCase("TABLE") == false) continue; Table catalog_tbl = new Table(table_name); // COLUMNS if (LOG.isDebugEnabled()) LOG.debug("Retrieving COLUMN information for " + table_name); ResultSet col_rs = md.getColumns(null, null, internal_table_name, null); while (col_rs.next()) { if (LOG.isTraceEnabled()) LOG.trace(SQLUtil.debug(col_rs)); String col_name = col_rs.getString(4); int col_type = col_rs.getInt(5); String col_typename = col_rs.getString(6); Integer col_size = col_rs.getInt(7); String col_defaultValue = col_rs.getString(13); boolean col_nullable = col_rs.getString(18).equalsIgnoreCase("YES"); boolean col_autoinc = false; // FIXME col_rs.getString(22).toUpperCase().equals("YES"); Column catalog_col = new Column(catalog_tbl, col_name, col_type, col_typename, col_size); catalog_col.setDefaultValue(col_defaultValue); catalog_col.setAutoincrement(col_autoinc); catalog_col.setNullable(col_nullable); // FIXME col_catalog.setSigned(); if (LOG.isDebugEnabled()) LOG.debug( String.format("Adding %s.%s [%s / %d]", table_name, col_name, col_typename, col_type)); catalog_tbl.addColumn(catalog_col); } // WHILE col_rs.close(); // PRIMARY KEYS if (LOG.isDebugEnabled()) LOG.debug("Retrieving PRIMARY KEY information for " + table_name); ResultSet pkey_rs = md.getPrimaryKeys(null, null, internal_table_name); SortedMap<Integer, String> pkey_cols = new TreeMap<Integer, String>(); while (pkey_rs.next()) { String col_name = pkey_rs.getString(4); assert (catalog_tbl.getColumnByName(col_name) != null) : String .format("Unexpected primary key column %s.%s", table_name, col_name); int col_idx = pkey_rs.getShort(5); // HACK: SQLite doesn't return the KEY_SEQ, so if we get back // a zero for this value, then we'll just length of the pkey_cols map if (col_idx == 0) col_idx = pkey_cols.size(); LOG.debug(String.format("PKEY[%02d]: %s.%s", col_idx, table_name, col_name)); assert (pkey_cols.containsKey(col_idx) == false); pkey_cols.put(col_idx, col_name); } // WHILE pkey_rs.close(); catalog_tbl.setPrimaryKeyColumns(pkey_cols.values()); // INDEXES if (LOG.isDebugEnabled()) LOG.debug("Retrieving INDEX information for " + table_name); ResultSet idx_rs = md.getIndexInfo(null, null, internal_table_name, false, false); while (idx_rs.next()) { if (LOG.isDebugEnabled()) LOG.debug(SQLUtil.debug(idx_rs)); boolean idx_unique = (idx_rs.getBoolean(4) == false); String idx_name = idx_rs.getString(6); int idx_type = idx_rs.getShort(7); int idx_col_pos = idx_rs.getInt(8) - 1; String idx_col_name = idx_rs.getString(9); String sort = idx_rs.getString(10); SortDirectionType idx_direction; if (sort != null) { idx_direction = sort.equalsIgnoreCase("A") ? SortDirectionType.ASC : SortDirectionType.DESC; } else idx_direction = null; Index catalog_idx = catalog_tbl.getIndex(idx_name); if (catalog_idx == null) { catalog_idx = new Index(catalog_tbl, idx_name, idx_type, idx_unique); catalog_tbl.addIndex(catalog_idx); } assert (catalog_idx != null); catalog_idx.addColumn(idx_col_name, idx_direction, idx_col_pos); } // WHILE idx_rs.close(); // FOREIGN KEYS if (LOG.isDebugEnabled()) LOG.debug("Retrieving FOREIGN KEY information for " + table_name); ResultSet fk_rs = md.getImportedKeys(null, null, internal_table_name); foreignKeys.put(table_name, new HashMap<String, Pair<String, String>>()); while (fk_rs.next()) { if (LOG.isDebugEnabled()) LOG.debug(table_name + " => " + SQLUtil.debug(fk_rs)); assert (fk_rs.getString(7).equalsIgnoreCase(table_name)); String colName = fk_rs.getString(8); String fk_tableName = origTableNames.get(fk_rs.getString(3).toUpperCase()); String fk_colName = fk_rs.getString(4); foreignKeys.get(table_name).put(colName, Pair.of(fk_tableName, fk_colName)); } // WHILE fk_rs.close(); tables.put(table_name, catalog_tbl); } // WHILE table_rs.close(); // FOREIGN KEYS if (LOG.isDebugEnabled()) LOG.debug("Foreign Key Mappings:\n" + StringUtil.formatMaps(foreignKeys)); for (Table catalog_tbl : tables.values()) { Map<String, Pair<String, String>> fk = foreignKeys.get(catalog_tbl.getName()); for (Entry<String, Pair<String, String>> e : fk.entrySet()) { String colName = e.getKey(); Column catalog_col = catalog_tbl.getColumnByName(colName); assert (catalog_col != null); Pair<String, String> fkey = e.getValue(); assert (fkey != null); Table fkey_tbl = tables.get(fkey.first); if (fkey_tbl == null) { throw new RuntimeException("Unexpected foreign key parent table " + fkey); } Column fkey_col = fkey_tbl.getColumnByName(fkey.second); if (fkey_col == null) { throw new RuntimeException("Unexpected foreign key parent column " + fkey); } if (LOG.isDebugEnabled()) LOG.debug(catalog_col.fullName() + " -> " + fkey_col.fullName()); catalog_col.setForeignKey(fkey_col); } // FOR } // FOR return; }