List of usage examples for java.sql DatabaseMetaData getTables
ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String types[])
throws SQLException;
From source file:it.unibas.spicy.persistence.relational.DAORelational.java
public IDataSourceProxy loadSchema(int scenarioNo, AccessConfiguration accessConfiguration, DBFragmentDescription dataDescription, IConnectionFactory dataSourceDB, boolean source) throws DAOException { this.dataDescription = dataDescription; Connection connectionPostgres = null; INode root = null;/*w w w .j a v a 2s . c om*/ String catalog = null; String schemaName = accessConfiguration.getSchemaName(); DatabaseMetaData databaseMetaData = null; Connection connection = dataSourceDB.getConnection(accessConfiguration); IDataSourceProxy dataSource = null; AccessConfiguration accessConfigurationPostgres = new AccessConfiguration(); accessConfigurationPostgres.setDriver(SpicyEngineConstants.ACCESS_CONFIGURATION_DRIVER); accessConfigurationPostgres .setUri(SpicyEngineConstants.ACCESS_CONFIGURATION_URI + SpicyEngineConstants.MAPPING_TASK_DB_NAME); accessConfigurationPostgres.setLogin(SpicyEngineConstants.ACCESS_CONFIGURATION_LOGIN); accessConfigurationPostgres.setPassword(SpicyEngineConstants.ACCESS_CONFIGURATION_PASS); connectionPostgres = dataSourceDB.getConnection(accessConfigurationPostgres); try { Statement statement = connectionPostgres.createStatement(); databaseMetaData = connection.getMetaData(); catalog = connection.getCatalog(); if (catalog == null) { catalog = accessConfiguration.getUri(); if (logger.isDebugEnabled()) logger.debug("Catalog is null. Catalog name will be: " + catalog); } root = this.createRootNode(catalog); //giannisk postgres create schemas if (source) { String createSchemasQuery = "create schema if not exists " + SpicyEngineConstants.SOURCE_SCHEMA_NAME + scenarioNo + ";\n"; //createSchemasQuery += "create schema if not exists " + GenerateSQL.WORK_SCHEMA_NAME + ";\n"; createSchemasQuery += "create schema if not exists " + SpicyEngineConstants.TARGET_SCHEMA_NAME + scenarioNo + ";"; statement.executeUpdate(createSchemasQuery); } String[] tableTypes = new String[] { "TABLE" }; ResultSet tableResultSet = databaseMetaData.getTables(catalog, schemaName, null, tableTypes); while (tableResultSet.next()) { String tableName = tableResultSet.getString("TABLE_NAME"); if (!this.dataDescription.checkLoadTable(tableName)) { continue; } INode setTable = new SetNode(tableName); setTable.addChild( getTuple(databaseMetaData, catalog, schemaName, tableName, source, statement, scenarioNo)); setTable.setRequired(false); setTable.setNotNull(true); root.addChild(setTable); addNode(tableName, setTable); } dataSource = new ConstantDataSourceProxy(new DataSource(SpicyEngineConstants.TYPE_RELATIONAL, root)); dataSource.addAnnotation(SpicyEngineConstants.ACCESS_CONFIGURATION, accessConfiguration); dataSource.addAnnotation(SpicyEngineConstants.LOADED_INSTANCES_FLAG, false); for (Map.Entry<String, String> entry : changedColumnNames.entrySet()) { dataSource.putChangedValue(entry.getKey(), entry.getValue()); } loadPrimaryKeys(dataSource, databaseMetaData, catalog, schemaName, source, statement, scenarioNo, false); loadForeignKeys(dataSource, databaseMetaData, catalog, schemaName, source, scenarioNo); } catch (Throwable ex) { logger.error(ex); throw new DAOException(ex.getMessage()); } finally { if (connection != null) dataSourceDB.close(connection); if (connectionPostgres != null) dataSourceDB.close(connectionPostgres); } return dataSource; }
From source file:ro.nextreports.designer.dbviewer.DefaultDBViewer.java
public DBInfo getDBInfo(String schemaName, int mask, Connection con) throws NextSqlException { String info = ""; List<String> keywords = new ArrayList<String>(); List<DBTable> tables = new ArrayList<DBTable>(); List<DBProcedure> procedures = new ArrayList<DBProcedure>(); Dialect dialect;/*from w ww . j a v a2 s.c o m*/ try { dialect = DialectUtil.getDialect(con); } catch (Exception ex) { ex.printStackTrace(); throw new NextSqlException("Could not get Dialect.", ex); } try { DatabaseMetaData dbmd = con.getMetaData(); if ((mask & DBInfo.INFO) == DBInfo.INFO) { StringBuffer sb = new StringBuffer(); sb.append(I18NSupport.getString("database.product")).append(dbmd.getDatabaseProductName()) .append("\r\n"); sb.append(I18NSupport.getString("database.product.version")) .append(dbmd.getDatabaseProductVersion()).append("\r\n"); sb.append(I18NSupport.getString("database.driver.name")).append(dbmd.getDriverName()) .append("\r\n"); sb.append(I18NSupport.getString("database.driver.version")).append(dbmd.getDriverVersion()) .append("\r\n"); info = sb.toString(); } if ((mask & DBInfo.SUPPORTED_KEYWORDS) == DBInfo.SUPPORTED_KEYWORDS) { StringTokenizer st = new StringTokenizer(dbmd.getSQLKeywords(), ","); while (st.hasMoreTokens()) { keywords.add(st.nextToken()); } } // Get a ResultSet that contains all of the tables in this database // We specify a table_type of "TABLE" to prevent seeing system tables, // views and so forth boolean tableMask = ((mask & DBInfo.TABLES) == DBInfo.TABLES); boolean viewMask = ((mask & DBInfo.VIEWS) == DBInfo.VIEWS); if (tableMask || viewMask) { String[] tableTypes; if (tableMask && viewMask) { tableTypes = new String[] { "TABLE", "VIEW" }; } else if (tableMask) { tableTypes = new String[] { "TABLE" }; } else { tableTypes = new String[] { "VIEW" }; } String pattern = tableMask ? Globals.getTableNamePattern() : Globals.getViewNamePattern(); ResultSet allTables = dbmd.getTables(null, schemaName, pattern, tableTypes); try { while (allTables.next()) { String table_name = allTables.getString("TABLE_NAME"); String table_type = allTables.getString("TABLE_TYPE"); // discard recycle bin tables String ignoreTablePrefix = dialect.getRecycleBinTablePrefix(); if ((table_name == null) || ((ignoreTablePrefix != null) && table_name.startsWith(ignoreTablePrefix))) { continue; } if ((mask & DBInfo.INDEXES) == DBInfo.INDEXES) { ResultSet indexList = null; try { // Get a list of all the indexes for this table indexList = dbmd.getIndexInfo(null, schemaName, table_name, false, false); List<DBIndex> indexes = new ArrayList<DBIndex>(); while (indexList.next()) { String index_name = indexList.getString("INDEX_NAME"); String column_name = indexList.getString("COLUMN_NAME"); if (!index_name.equals("null")) { DBIndex index = new DBIndex(index_name, column_name); indexes.add(index); } } DBTable table = new DBTable(schemaName, table_name, table_type, indexes); tables.add(table); } catch (SQLException e) { throw new NextSqlException("SQL Exception: " + e.getMessage(), e); } finally { closeResultSet(indexList); } } else { DBTable table = new DBTable(schemaName, table_name, table_type); tables.add(table); } } } catch (SQLException e) { throw new NextSqlException("SQL Exception: " + e.getMessage(), e); } finally { closeResultSet(allTables); } } boolean procedureMask = ((mask & DBInfo.PROCEDURES) == DBInfo.PROCEDURES); if (procedureMask) { String pattern = Globals.getProcedureNamePattern(); if (pattern == null) { pattern = "%"; } ResultSet rs = dbmd.getProcedures(null, schemaName, pattern); try { while (rs.next()) { String spName = rs.getString("PROCEDURE_NAME"); int spType = rs.getInt("PROCEDURE_TYPE"); String catalog = rs.getString("PROCEDURE_CAT"); // System.out.println("Stored Procedure Name: " + spName); // if (spType == DatabaseMetaData.procedureReturnsResult) { // System.out.println("procedure Returns Result"); // } else if (spType == DatabaseMetaData.procedureNoResult) { // System.out.println("procedure No Result"); // } else { // System.out.println("procedure Result unknown"); // } procedures.add(new DBProcedure(schemaName, catalog, spName, spType)); } } catch (SQLException e) { throw new NextSqlException("SQL Exception: " + e.getMessage(), e); } finally { closeResultSet(rs); } } } catch (SQLException e) { LOG.error(e.getMessage(), e); e.printStackTrace(); throw new NextSqlException("SQL Exception: " + e.getMessage(), e); } return new DBInfo(info, tables, procedures, keywords); }
From source file:ua.utility.kfsdbupgrade.App.java
/** * Use the {@link DatabaseMetaData} from the given {@link Connection} to * generate the foreign key index information for each table * //from ww w. j a va 2s .c o m * @param conn * {@link Connection} to the database * @param stmt * {@link Statement} to use to execute SQL * @see {@link #loadForeignKeyIndexInformation(DatabaseMetaData, String)} */ private void createForeignKeyIndexes(Connection conn, Statement stmt) { logHeader2("creating indexes on foreign keys where required..."); ResultSet res = null; try { DatabaseMetaData dmd = conn.getMetaData(); res = dmd.getTables(null, getSchema(), null, new String[] { "TABLE" }); while (res.next()) { // TABLE_NAME String => table name String tname = res.getString(3); /* * for each table name, load foreign key index information to * get SQL updates to execute, then execute each SQL update * statement */ Set<String> sqllist = loadForeignKeyIndexInformation(dmd, tname); if ((sqllist != null) && !sqllist.isEmpty()) { LOGGER.info("creating required foreign key indexes on table " + tname + "..."); int cnt = 0; for (String sql : sqllist) { try { stmt.executeQuery(sql); cnt++; } catch (Exception ex) { LOGGER.error("create index failed: " + sql, ex); } } LOGGER.info(" " + cnt + " indexes created"); } } } catch (Exception ex) { LOGGER.info(ex); } finally { closeDbObjects(null, null, res); } }
From source file:jef.database.DbMetaData.java
private boolean innerExists(ObjectType type, String schema, String objectName) throws SQLException { if (schema == null) schema = this.getCurrentSchema();// ?schema? switch (type) { case FUNCTION: return existsFunction(schema, objectName); case PROCEDURE: return existsProcdure(schema, objectName); case SEQUENCE: List<SequenceInfo> seqs = this.getProfile().getSequenceInfo(this, schema, objectName); if (seqs != null) { return !seqs.isEmpty(); }/*from w ww . j a va2 s .c om*/ default: break; } Connection conn = getConnection(false); DatabaseDialect trans = info.profile; DatabaseMetaData databaseMetaData = conn.getMetaData(); ResultSet rs = databaseMetaData.getTables(trans.getCatlog(schema), trans.getSchema(schema), objectName, new String[] { type.name() }); try { return rs.next(); } finally { DbUtils.close(rs); releaseConnection(conn); } }
From source file:swp.bibjsf.persistence.Data.java
/** * Returns the lower-case names of all tables in the database. * * @return list of lower-case names of all tables in the database * @throws SQLException/*from ww w . ja v a 2s. com*/ * falls ein Fehler beim Zugriff auf die Datenbank auftritt */ private List<String> getTableNames() throws SQLException { logger.debug("get table names"); DatabaseMetaData dbMeta; List<String> result = new ArrayList<String>(); Connection dbConnection = dataSource.getConnection(); try { dbMeta = dbConnection.getMetaData(); logger.debug("URL of database " + dbMeta.getURL()); logger.debug("database version: major=" + dbMeta.getDatabaseMajorVersion() + " minor=" + dbMeta.getDatabaseMinorVersion() + " product_version=" + dbMeta.getDatabaseProductVersion() + " product_name=" + dbMeta.getDatabaseProductName()); ResultSet rs = dbMeta.getTables(null, null, null, new String[] { "TABLE" }); try { while (rs.next()) { String theTableName = rs.getString("TABLE_NAME"); result.add(theTableName.toLowerCase()); } } finally { rs.close(); } return result; } finally { try { dbConnection.close(); } catch (SQLException e) { logger.debug("error while trying to close the database connection."); // ignore, nothing to be done here anyway } } }
From source file:com.mirth.connect.donkey.server.data.jdbc.JdbcDao.java
private boolean tableExists(String tableName) { ResultSet resultSet = null;//from w w w . j a v a 2s . co m try { DatabaseMetaData metaData = connection.getMetaData(); resultSet = metaData.getTables(null, null, tableName, null); if (resultSet.next()) { return true; } resultSet = metaData.getTables(null, null, tableName.toUpperCase(), null); return resultSet.next(); } catch (SQLException e) { throw new DonkeyDaoException(e); } finally { close(resultSet); } }
From source file:jef.database.DbMetaData.java
/** * @param type/*from ww w.j av a2 s .c om*/ * ? "TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", * "LOCAL TEMPORARY", "ALIAS", "SYNONYM". * @param schema * Schema * @param matchName * ??? * @param oper * ??nullnull? * @return /?? * @throws SQLException * @see Operator */ public List<TableInfo> getDatabaseObject(ObjectType type, String schema, String matchName, Operator oper, boolean needRemark) throws SQLException { if (schema == null) schema = this.schema; if (matchName != null) { int n = matchName.indexOf('.'); if (n > -1) { schema = matchName.substring(0, n); matchName = matchName.substring(n + 1); } } if (oper != null && oper != Operator.EQUALS) { if (StringUtils.isEmpty(matchName)) { matchName = "%"; } else if (oper == Operator.MATCH_ANY) { matchName = "%" + matchName + "%"; } else if (oper == Operator.MATCH_END) { matchName = "%" + matchName; } else if (oper == Operator.MATCH_START) { matchName = matchName + "%"; } } Connection conn = getConnection(needRemark); DatabaseMetaData databaseMetaData = conn.getMetaData(); DatabaseDialect trans = info.profile; ResultSet rs = null; try { rs = databaseMetaData.getTables(trans.getCatlog(schema), trans.getSchema(schema), matchName, type == null ? null : new String[] { type.name() }); List<TableInfo> result = new ArrayList<TableInfo>(); while (rs.next()) { TableInfo info = new TableInfo(); info.setCatalog(rs.getString("TABLE_CAT")); info.setSchema(rs.getString("TABLE_SCHEM")); info.setName(rs.getString("TABLE_NAME")); info.setType(rs.getString("TABLE_TYPE"));// "TABLE","VIEW", // "SYSTEM TABLE", // "GLOBAL // TEMPORARY","LOCAL // TEMPORARY", // "ALIAS", // "SYNONYM". info.setRemarks(rs.getString("REMARKS")); result.add(info); } return result; } finally { DbUtils.close(rs); releaseConnection(conn); } }
From source file:com.mirth.connect.donkey.server.data.jdbc.JdbcDao.java
@Override public void checkAndCreateChannelTables() { Map<String, Long> channelIds = getLocalChannelIds(); Map<String, String> channelTablesMap = new LinkedHashMap<String, String>(); for (Long localChannelId : channelIds.values()) { channelTablesMap.put("d_m" + localChannelId, "createMessageTable"); channelTablesMap.put("d_mm" + localChannelId, "createConnectorMessageTable"); channelTablesMap.put("d_mc" + localChannelId, "createMessageContentTable"); channelTablesMap.put("d_mcm" + localChannelId, "createMessageCustomMetaDataTable"); channelTablesMap.put("d_ma" + localChannelId, "createMessageAttachmentTable"); channelTablesMap.put("d_ms" + localChannelId, "createMessageStatisticsTable"); channelTablesMap.put("d_msq" + localChannelId, "createMessageSequence"); }//from ww w . ja va 2 s . c o m ResultSet rs = null; Statement statement = null; try { DatabaseMetaData dbMetaData = connection.getMetaData(); rs = dbMetaData.getTables(null, null, "%", null); while (rs.next()) { String tableName = rs.getString("TABLE_NAME").toLowerCase(); channelTablesMap.remove(tableName); } close(rs); /* * MIRTH-2851 - Oracle does not return sequences in the DatabaseMetaData.getTables * method. If we dont remove the d_msq sequence from oracle then it will try to recreate * it which will throw an exception. If any database needs an additional query for * sequences then it could just be added for that database. */ if (querySource.queryExists("getSequenceMetadata")) { statement = connection.createStatement(); rs = statement.executeQuery(querySource.getQuery("getSequenceMetadata")); while (rs.next()) { String sequenceName = rs.getString("SEQUENCE_NAME").toLowerCase(); channelTablesMap.remove(sequenceName); } } } catch (Exception e) { throw new DonkeyDaoException(e); } finally { close(rs); close(statement); } for (Entry<String, String> entry : channelTablesMap.entrySet()) { Statement initSequenceStatement = null; try { Long localChannelId = Long.parseLong(entry.getKey().replaceAll("[^0-9]", "")); Map<String, Object> values = new HashMap<String, Object>(); values.put("localChannelId", localChannelId); createTable(entry.getValue(), values); if (entry.getKey().toLowerCase().contains("d_msq") && querySource.queryExists("initMessageSequence")) { initSequenceStatement = connection.createStatement(); initSequenceStatement.executeUpdate(querySource.getQuery("initMessageSequence", values)); } } catch (Exception e) { throw new DonkeyDaoException(e); } finally { close(initSequenceStatement); } } }
From source file:org.talend.metadata.managment.model.DBConnectionFillerImpl.java
@Override public List<TdView> fillViews(Package pack, DatabaseMetaData dbJDBCMetadata, List<String> viewFilter, String viewPattern, String[] tableType) { List<TdView> viewList = new ArrayList<TdView>(); if (dbJDBCMetadata == null) { return null; }/* w w w.ja va 2 s.co m*/ Package catalogOrSchema = PackageHelper.getCatalogOrSchema(pack); String catalogName = null; String schemaPattern = null; if (catalogOrSchema != null) { // catalog if (catalogOrSchema instanceof Catalog) { catalogName = catalogOrSchema.getName(); if (MetadataConnectionUtils.isAS400(catalogOrSchema)) { return viewList; } } else {// schema Package parentCatalog = PackageHelper.getParentPackage(catalogOrSchema); schemaPattern = catalogOrSchema.getName(); catalogName = parentCatalog == null ? null : parentCatalog.getName(); } } try { ResultSet tables = dbJDBCMetadata.getTables(catalogName, schemaPattern, viewPattern, tableType); while (tables.next()) { String tableName = getStringFromResultSet(tables, GetTable.TABLE_NAME.name()); String type = getStringFromResultSet(tables, GetTable.TABLE_TYPE.name()); // for special db. teradata_sql_model/db2_zos/as400 type = convertSpecialTableType(type); if (!isCreateElement(viewFilter, tableName)) { continue; } // common boolean flag = true; String tableComment = null; if (pack != null) { Connection c = ConnectionHelper.getConnection(pack); flag = MetadataConnectionUtils.isOracle8i(c); } if (!flag) { tableComment = getTableComment(dbJDBCMetadata, tables, tableName, catalogName, schemaPattern); } // create table TdView table = RelationalFactory.eINSTANCE.createTdView(); table.setName(tableName); table.setTableType(type); table.setLabel(table.getName()); if (tableComment != null) { ColumnSetHelper.setComment(tableComment, table); } viewList.add(table); } if (isLinked()) { PackageHelper.addMetadataTable(ListUtils.castList(MetadataTable.class, viewList), pack); } } catch (SQLException e) { log.error(e, e); } return viewList; }
From source file:org.ramadda.repository.database.DatabaseManager.java
/** * _more_/*from w ww . j av a2 s . com*/ * * @param connection _more_ * @param all _more_ * * @return _more_ * * @throws Exception _more_ */ public List<TableInfo> getTableInfos(Connection connection, boolean all) throws Exception { DatabaseMetaData dbmd = connection.getMetaData(); ResultSet tables = dbmd.getTables(null, null, null, new String[] { "TABLE" }); ResultSetMetaData rsmd = tables.getMetaData(); for (int col = 1; col <= rsmd.getColumnCount(); col++) { // System.err.println (rsmd.getColumnName(col)); } List<TableInfo> tableInfos = new ArrayList<TableInfo>(); HashSet<String> seen = new HashSet<String>(); while (tables.next()) { String tableName = tables.getString("TABLE_NAME"); String tn = tableName.toLowerCase(); if (tn.equals("participant")) { //a hack due to some old bad derby db I have continue; } //Just in case if (seen.contains(tn)) { System.err.println("Warning: duplicate table:" + tableName); continue; } seen.add(tn); boolean ok = true; for (TypeHandler typeHandler : getRepository().getTypeHandlers()) { if (!typeHandler.shouldExportTable(tn)) { ok = false; break; } } if (!ok) { continue; } String tableType = tables.getString("TABLE_TYPE"); if ((tableType == null) || tableType.startsWith("SYSTEM") || Misc.equals(tableType, "INDEX")) { continue; } ResultSet indices = dbmd.getIndexInfo(null, null, tableName, false, false); List<IndexInfo> indexList = new ArrayList<IndexInfo>(); while (indices.next()) { indexList.add(new IndexInfo(indices.getString("INDEX_NAME"), indices.getString("COLUMN_NAME"))); } ResultSet cols = dbmd.getColumns(null, null, tableName, null); rsmd = cols.getMetaData(); List<ColumnInfo> columns = new ArrayList<ColumnInfo>(); while (cols.next()) { String colName = cols.getString("COLUMN_NAME"); int type = cols.getInt("DATA_TYPE"); String typeName = cols.getString("TYPE_NAME"); int size = cols.getInt("COLUMN_SIZE"); if (type == -1) { if (typeName.toLowerCase().equals("mediumtext")) { type = java.sql.Types.CLOB; //Just come up with some size if (size <= 0) { size = 36000; } } else if (typeName.toLowerCase().equals("longtext")) { type = java.sql.Types.CLOB; //Just come up with some size if (size <= 0) { size = 36000; } } } if (typeName.equalsIgnoreCase("text")) { if (size <= 0) { size = 36000; } } columns.add(new ColumnInfo(colName, typeName, type, size)); if (tn.indexOf("wiki") >= 0) { System.err.println("COLS:" + columns); } } tableInfos.add(new TableInfo(tn, indexList, columns)); } return tableInfos; }