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
private void loadPrimaryKeys(IDataSourceProxy dataSource, DatabaseMetaData databaseMetaData, String catalog, String schemaName, boolean source, Statement statement, int scenarioNo, boolean web) throws SQLException { 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)) { logger.debug("Excluding table: " + tableName); continue; }/* w ww . j a v a2s .c om*/ if (logger.isDebugEnabled()) logger.debug("Searching primary keys. ANALYZING TABLE = " + tableName); ResultSet resultSet = databaseMetaData.getPrimaryKeys(catalog, null, tableName); List<PathExpression> listOfPath = new ArrayList<PathExpression>(); List<String> PKcolumnNames = new ArrayList<String>(); while (resultSet.next()) { String columnName = resultSet.getString("COLUMN_NAME"); if (logger.isDebugEnabled()) logger.debug("Analyzing primary key: " + columnName); if (!this.dataDescription.checkLoadAttribute(tableName, columnName)) { continue; } if (logger.isDebugEnabled()) logger.debug("Found a Primary Key: " + columnName); String keyPrimary = tableName + "." + columnName; listOfPath.add(DAORelationalUtility.generatePath(keyPrimary)); //giannisk alter table, add primary key ////un-comment the following if Primary Key Constraints are to be considered PKcolumnNames.add("\"" + columnName + "\""); } if (!web && !PKcolumnNames.isEmpty()) { String table; if (source) { table = SpicyEngineConstants.SOURCE_SCHEMA_NAME + scenarioNo + ".\"" + tableName + "\""; } else { String newSchemaName = SpicyEngineConstants.TARGET_SCHEMA_NAME + scenarioNo; table = newSchemaName + ".\"" + tableName + "\""; statement.execute( GenerateSQL.createTriggerFunction(table, newSchemaName, tableName, PKcolumnNames)); statement.execute(GenerateSQL.createTriggerBeforeInsert(table, newSchemaName, tableName)); } String primaryKeys = String.join(",", PKcolumnNames); statement.executeUpdate("ALTER TABLE " + table + " ADD PRIMARY KEY (" + primaryKeys + ");"); } //// //} if (!listOfPath.isEmpty()) { KeyConstraint keyConstraint = new KeyConstraint(listOfPath, true); dataSource.addKeyConstraint(keyConstraint); } } }
From source file:org.openconcerto.sql.model.JDBCStructureSource.java
@Override protected void getNames(final Connection conn) throws SQLException { final DatabaseMetaData metaData = conn.getMetaData(); // les tables de tous les schemas // don't use getSchemas() since we can't limit to a particular db and it returns db private // schemas/*from w ww. j a v a 2 s . c o m*/ // les tables de la base final CollectionMap<SQLName, String> tableNames = new CollectionMap<SQLName, String>( new ArrayList<String>(2)); // to find empty schemas (with no tables) : all schemas - system schemas final Set<String> schemas = this.getJDBCSchemas(metaData); this.filterOutOfScope(schemas); // getTables() only supports pattern (eg LIKE) so we must make multiple calls // copy schemas so we can remove system schemas directly for (final String s : new HashSet<String>(schemas)) { final ResultSet rs = metaData.getTables(this.getBase().getMDName(), s, "%", new String[] { "TABLE", "SYSTEM TABLE", "VIEW" }); while (rs.next()) { final String tableType = rs.getString("TABLE_TYPE"); final String schemaName = rs.getString("TABLE_SCHEM"); if (tableType.equals("SYSTEM TABLE")) schemas.remove(schemaName); else { final String tableName = rs.getString("TABLE_NAME"); // MySQL needs this.addConnectionProperty("useInformationSchema", "true"); // but the time goes from 3.5s to 20s tableNames.putAll(new SQLName(schemaName, tableName), asList(rs.getString("TABLE_TYPE"), rs.getString("REMARKS"))); } } } // keep only tables in remaining schemas final Iterator<SQLName> iter = getTablesNames().iterator(); while (iter.hasNext()) { final SQLName tableName = iter.next(); if (!schemas.contains(tableName.getItemLenient(-2))) iter.remove(); } this.schemas.clear(); this.schemas.addAll(schemas); this.tableNames.clear(); this.tableNames.putAll(tableNames); }
From source file:org.dbmfs.DatabaseAccessor.java
/** * ??.<br>/*from w w w . j av a 2 s. c o m*/ * * @return ??? */ public List<String> getTableList() throws Exception { if (tableListCacheFolder.containsKey("tablelist")) return (List<String>) tableListCacheFolder.get("tablelist"); List<String> tableNameList = new ArrayList(); try { String table = "%"; String types[] = { "TABLE", "VIEW", "SYSTEM TABLE" }; DatabaseMetaData dbmd = injectConn.getMetaData(); ResultSet rs = dbmd.getTables(null, null, table, types); while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); tableNameList.add(tableName); } tableListCacheFolder.put("tablelist", tableNameList); rs.close(); } catch (Exception e) { e.printStackTrace(); throw e; } return tableNameList; }
From source file:org.dbmfs.DatabaseAccessor.java
/** * ???????.<br>// w w w . jav a 2 s. c o m * * @param targetTableName ?? * @return */ public boolean exsistTable(String targetTableName) throws Exception { if (tableExsistCacheFolder.containsKey(targetTableName)) return true; boolean ret = false; try { String table = "%"; String types[] = { "TABLE", "VIEW", "SYSTEM TABLE" }; DatabaseMetaData dbmd = injectConn.getMetaData(); ResultSet rs = dbmd.getTables(null, null, table, types); while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); if (targetTableName.equals(tableName)) { ret = true; tableExsistCacheFolder.put(targetTableName, "true"); break; } } rs.close(); } catch (Exception e) { e.printStackTrace(); throw e; } return ret; }
From source file:io.bibleget.BibleGetDB.java
public boolean renewMetaData() { if (instance.connect()) { try {/*from ww w .java2s . c o m*/ DatabaseMetaData dbMeta; dbMeta = instance.conn.getMetaData(); try (ResultSet rs3 = dbMeta.getTables(null, null, "METADATA", null)) { if (rs3.next()) { //System.out.println("Table METADATA exists..."); try (Statement stmt = instance.conn.createStatement()) { HTTPCaller myHTTPCaller = new HTTPCaller(); String myResponse; myResponse = myHTTPCaller.getMetaData("biblebooks"); if (myResponse != null) { JsonReader jsonReader = Json.createReader(new StringReader(myResponse)); JsonObject json = jsonReader.readObject(); JsonArray arrayJson = json.getJsonArray("results"); if (arrayJson != null) { ListIterator pIterator = arrayJson.listIterator(); while (pIterator.hasNext()) { try (Statement stmt1 = instance.conn.createStatement()) { int index = pIterator.nextIndex(); JsonArray currentJson = (JsonArray) pIterator.next(); String biblebooks_str = currentJson.toString(); //.replaceAll("\"", "\\\\\""); //System.out.println("BibleGetDB line 267: BIBLEBOOKS"+Integer.toString(index)+"='"+biblebooks_str+"'"); String stmt_str = "UPDATE METADATA SET BIBLEBOOKS" + Integer.toString(index) + "='" + biblebooks_str + "' WHERE ID=0"; //System.out.println("executing update: "+stmt_str); int update = stmt1.executeUpdate(stmt_str); //System.out.println("executeUpdate resulted in: "+Integer.toString(update)); stmt1.close(); } } } arrayJson = json.getJsonArray("languages"); if (arrayJson != null) { try (Statement stmt2 = instance.conn.createStatement()) { String languages_str = arrayJson.toString(); //.replaceAll("\"", "\\\\\""); String stmt_str = "UPDATE METADATA SET LANGUAGES='" + languages_str + "' WHERE ID=0"; int update = stmt2.executeUpdate(stmt_str); stmt2.close(); } } } myResponse = myHTTPCaller.getMetaData("bibleversions"); if (myResponse != null) { JsonReader jsonReader = Json.createReader(new StringReader(myResponse)); JsonObject json = jsonReader.readObject(); JsonObject objJson = json.getJsonObject("validversions_fullname"); if (objJson != null) { String bibleversions_str = objJson.toString(); //.replaceAll("\"", "\\\\\""); try (Statement stmt3 = instance.conn.createStatement()) { String stmt_str = "UPDATE METADATA SET VERSIONS='" + bibleversions_str + "' WHERE ID=0"; int update = stmt3.executeUpdate(stmt_str); stmt3.close(); } Set<String> versionsabbrev = objJson.keySet(); if (!versionsabbrev.isEmpty()) { String versionsabbrev_str = ""; for (String s : versionsabbrev) { versionsabbrev_str += ("".equals(versionsabbrev_str) ? "" : ",") + s; } myResponse = myHTTPCaller .getMetaData("versionindex&versions=" + versionsabbrev_str); if (myResponse != null) { jsonReader = Json.createReader(new StringReader(myResponse)); json = jsonReader.readObject(); objJson = json.getJsonObject("indexes"); if (objJson != null) { for (String name : objJson.keySet()) { JsonObjectBuilder tempBld = Json.createObjectBuilder(); JsonObject book_num = objJson.getJsonObject(name); tempBld.add("book_num", book_num.getJsonArray("book_num")); tempBld.add("chapter_limit", book_num.getJsonArray("chapter_limit")); tempBld.add("verse_limit", book_num.getJsonArray("verse_limit")); JsonObject temp = tempBld.build(); String versionindex_str = temp.toString(); //.replaceAll("\"", "\\\\\""); //add new column to METADATA table name+"IDX" VARCHAR(5000) //update METADATA table SET name+"IDX" = versionindex_str try (ResultSet rs1 = dbMeta.getColumns(null, null, "METADATA", name + "IDX")) { boolean updateFlag = false; if (rs1.next()) { //column already exists updateFlag = true; } else { try (Statement stmt4 = instance.conn .createStatement()) { String sql = "ALTER TABLE METADATA ADD COLUMN " + name + "IDX VARCHAR(5000)"; boolean colAdded = stmt4.execute(sql); if (colAdded == false) { int count = stmt4.getUpdateCount(); if (count == -1) { //System.out.println("The result is a ResultSet object or there are no more results."); } else if (count == 0) { //0 rows affected updateFlag = true; } } stmt4.close(); } } if (updateFlag) { try (Statement stmt5 = instance.conn .createStatement()) { String sql1 = "UPDATE METADATA SET " + name + "IDX='" + versionindex_str + "' WHERE ID=0"; boolean rowsUpdated = stmt5.execute(sql1); stmt5.close(); } } } } } } } } } stmt.close(); } } rs3.close(); } instance.disconnect(); } catch (SQLException ex) { Logger.getLogger(BibleGetDB.class.getName()).log(Level.SEVERE, null, ex); return false; } return true; } return false; }
From source file:org.apache.kylin.rest.service.QueryService.java
protected List<TableMeta> getMetadata(CubeManager cubeMgr, String project, boolean cubedOnly) throws SQLException { Connection conn = null;/* w w w .ja v a 2s . c om*/ ResultSet columnMeta = null; List<TableMeta> tableMetas = null; if (StringUtils.isBlank(project)) { return Collections.emptyList(); } ResultSet JDBCTableMeta = null; try { DataSource dataSource = cacheService.getOLAPDataSource(project); conn = dataSource.getConnection(); DatabaseMetaData metaData = conn.getMetaData(); JDBCTableMeta = metaData.getTables(null, null, null, null); tableMetas = new LinkedList<TableMeta>(); Map<String, TableMeta> tableMap = new HashMap<String, TableMeta>(); while (JDBCTableMeta.next()) { String catalogName = JDBCTableMeta.getString(1); String schemaName = JDBCTableMeta.getString(2); // Not every JDBC data provider offers full 10 columns, e.g., PostgreSQL has only 5 TableMeta tblMeta = new TableMeta(catalogName == null ? Constant.FakeCatalogName : catalogName, schemaName == null ? Constant.FakeSchemaName : schemaName, JDBCTableMeta.getString(3), JDBCTableMeta.getString(4), JDBCTableMeta.getString(5), null, null, null, null, null); if (!cubedOnly || getProjectManager().isExposedTable(project, schemaName + "." + tblMeta.getTABLE_NAME())) { tableMetas.add(tblMeta); tableMap.put(tblMeta.getTABLE_SCHEM() + "#" + tblMeta.getTABLE_NAME(), tblMeta); } } columnMeta = metaData.getColumns(null, null, null, null); while (columnMeta.next()) { String catalogName = columnMeta.getString(1); String schemaName = columnMeta.getString(2); // kylin(optiq) is not strictly following JDBC specification ColumnMeta colmnMeta = new ColumnMeta(catalogName == null ? Constant.FakeCatalogName : catalogName, schemaName == null ? Constant.FakeSchemaName : schemaName, columnMeta.getString(3), columnMeta.getString(4), columnMeta.getInt(5), columnMeta.getString(6), columnMeta.getInt(7), getInt(columnMeta.getString(8)), columnMeta.getInt(9), columnMeta.getInt(10), columnMeta.getInt(11), columnMeta.getString(12), columnMeta.getString(13), getInt(columnMeta.getString(14)), getInt(columnMeta.getString(15)), columnMeta.getInt(16), columnMeta.getInt(17), columnMeta.getString(18), columnMeta.getString(19), columnMeta.getString(20), columnMeta.getString(21), getShort(columnMeta.getString(22)), columnMeta.getString(23)); if (!cubedOnly || getProjectManager().isExposedColumn(project, schemaName + "." + colmnMeta.getTABLE_NAME(), colmnMeta.getCOLUMN_NAME())) { tableMap.get(colmnMeta.getTABLE_SCHEM() + "#" + colmnMeta.getTABLE_NAME()).addColumn(colmnMeta); } } } finally { close(columnMeta, null, conn); if (JDBCTableMeta != null) { JDBCTableMeta.close(); } } return tableMetas; }
From source file:org.executequery.gui.editor.autocomplete.AutoCompleteSelectionsFactory.java
private void databaseObjectsForHost(DatabaseHost databaseHost, String type, String databaseObjectDescription, AutoCompleteListItemType autocompleteType) { trace("Building autocomplete object list using [ " + databaseHost.getName() + " ] for type - " + type); ResultSet rs = null;/*from ww w .ja v a2 s .c o m*/ DatabaseMetaData databaseMetaData = databaseHost.getDatabaseMetaData(); try { String catalog = databaseHost.getCatalogNameForQueries(defaultCatalogForHost(databaseHost)); String schema = databaseHost.getSchemaNameForQueries(defaultSchemaForHost(databaseHost)); String typeName = null; List<String> tableNames = new ArrayList<String>(); List<AutoCompleteListItem> list = new ArrayList<AutoCompleteListItem>(); String[] types = new String[] { type }; int count = 0; rs = databaseMetaData.getTables(catalog, schema, null, types); while (rs.next()) { try { if (Thread.interrupted() || databaseMetaData.getConnection().isClosed()) { return; } } catch (SQLException e) { } typeName = rs.getString(4); // only include if the returned reported type matches if (type != null && type.equalsIgnoreCase(typeName)) { tableNames.add(rs.getString(3)); count++; } if (count >= INCREMENT) { addTablesToProvider(databaseObjectDescription, autocompleteType, tableNames, list); count = 0; list.clear(); tableNames.clear(); } } addTablesToProvider(databaseObjectDescription, autocompleteType, tableNames, list); } catch (SQLException e) { error("Tables not available for type " + type + " - driver returned: " + e.getMessage()); } finally { releaseResources(rs); trace("Finished autocomplete object list using [ " + databaseHost.getName() + " ] for type - " + type); } }
From source file:org.openmrs.web.filter.initialization.InitializationFilter.java
/** * Check whether openmrs database is empty. Having just one non-liquibase table in the given * database qualifies this as a non-empty database. * * @param props the runtime properties/* w ww. j a v a 2 s. co m*/ * @return true/false whether openmrs database is empty or doesn't exist yet */ private static boolean isDatabaseEmpty(Properties props) { if (props != null) { String databaseConnectionFinalUrl = props.getProperty("connection.url"); if (databaseConnectionFinalUrl == null) { return true; } String connectionUsername = props.getProperty("connection.username"); if (connectionUsername == null) { return true; } String connectionPassword = props.getProperty("connection.password"); if (connectionPassword == null) { return true; } Connection connection = null; try { DatabaseUtil.loadDatabaseDriver(databaseConnectionFinalUrl); connection = DriverManager.getConnection(databaseConnectionFinalUrl, connectionUsername, connectionPassword); DatabaseMetaData dbMetaData = (DatabaseMetaData) connection.getMetaData(); String[] types = { "TABLE" }; //get all tables ResultSet tbls = dbMetaData.getTables(null, null, null, types); while (tbls.next()) { String tableName = tbls.getString("TABLE_NAME"); //if any table exist besides "liquibasechangelog" or "liquibasechangeloglock", return false if (!("liquibasechangelog".equals(tableName)) && !("liquibasechangeloglock".equals(tableName))) { return false; } } return true; } catch (Exception e) { //pass } finally { try { if (connection != null) { connection.close(); } } catch (Exception e) { //pass } } //if catch an exception while query database, then consider as database is empty. return true; } else { return true; } }
From source file:com.nextep.designer.sqlgen.generic.impl.JDBCCapturer.java
/** * This implementation is very basic since views SQL definition cannot be * retrieved with {@link DatabaseMetaData} methods. Returned views will only * have their name and columns defined./*from ww w .j a v a2 s . co m*/ */ @Override public Collection<IView> getViews(ICaptureContext context, IProgressMonitor monitor) { Map<String, IView> views = new HashMap<String, IView>(); ISQLCommandWriter commandWriter = SQLGenPlugin.getService(IGenerationService.class) .getSQLCommandWriter(getConnectionVendor(context)); try { final DatabaseMetaData md = ((Connection) context.getConnectionObject()).getMetaData(); ResultSet rset = null; if (md != null) { rset = md.getTables(context.getCatalog(), context.getSchema(), null, DB_VIEW_TYPE); CaptureHelper.updateMonitor(monitor, getCounter(), 1, 1); } if (rset != null) { try { while (rset.next()) { final IView view = getColumnableFromResultSet(context, IView.class, rset); view.setSql(commandWriter .comment("View SQL definition not available with the default JDBC capturer")); views.put(view.getName(), view); CaptureHelper.updateMonitor(monitor, getCounter(), 2, 1); } } finally { CaptureHelper.safeClose(rset, null); } } } catch (SQLException sqle) { LOGGER.error("Unable to fetch views from " + getConnectionVendorName(context) + " server: " + sqle.getMessage(), sqle); } List<String> invalidViewNames = new ArrayList<String>(); for (IView view : views.values()) { final String viewName = view.getName(); // monitor.subTask("Retrieving column aliases for view " + viewName + "..."); //$NON-NLS-2$ if (LOGGER.isDebugEnabled()) LOGGER.debug("== Retrieving column aliases for view [" + viewName + "] =="); //$NON-NLS-1$ //$NON-NLS-2$ final IBasicColumn[] columns = getColumns(context, monitor, view); if (columns.length > 0) { for (IBasicColumn column : columns) { view.addColumnAlias(column.getName()); } } else { LOGGER.warn("View [" + viewName + "] has been ignored during import because the view's columns " + "could not be retrieved"); /* * Since the view's columns could not be retrieved, we mark the * view as invalid so can remove it from the captured list. */ invalidViewNames.add(viewName); } } // Removes from the list the views marked as invalid before returning it for (String viewName : invalidViewNames) { views.remove(viewName); } return views.values(); }
From source file:com.nextep.designer.sqlgen.generic.impl.JDBCCapturer.java
@Override public Collection<IBasicTable> getTables(ICaptureContext context, IProgressMonitor monitor) { Map<String, IBasicTable> tables = new HashMap<String, IBasicTable>(); Map<String, IBasicColumn> allTablesColumns = new HashMap<String, IBasicColumn>(); try {//w w w .j a va2 s . c o m final DatabaseMetaData md = ((Connection) context.getConnectionObject()).getMetaData(); ResultSet rset = null; if (md != null) { rset = md.getTables(context.getCatalog(), context.getSchema(), null, DB_TABLE_TYPE); CaptureHelper.updateMonitor(monitor, getCounter(), 1, 1); } if (rset != null) { try { while (rset.next()) { final IBasicTable table = getColumnableFromResultSet(context, IBasicTable.class, rset); tables.put(table.getName(), table); CaptureHelper.updateMonitor(monitor, getCounter(), 2, 1); } } finally { CaptureHelper.safeClose(rset, null); } } } catch (SQLException sqle) { LOGGER.error("Unable to fetch tables from " + getConnectionVendorName(context) + " server: " + sqle.getMessage(), sqle); } monitor.subTask("Retrieving tables columns and primary keys..."); List<String> invalidTableNames = new ArrayList<String>(); for (IBasicTable table : tables.values()) { final String tableName = table.getName(); // monitor.subTask("Retrieving columns for table " + tableName + "..."); //$NON-NLS-2$ if (LOGGER.isDebugEnabled()) LOGGER.debug("== Retrieving columns for table [" + tableName + "] =="); //$NON-NLS-1$ //$NON-NLS-2$ final IBasicColumn[] columns = getColumns(context, monitor, table); if (columns.length > 0) { for (IBasicColumn column : columns) { column.setParent(table); table.addColumn(column); allTablesColumns.put(CaptureHelper.getUniqueColumnName(column), column); } // monitor.subTask("Retrieving primary key for table " + tableName + "..."); //$NON-NLS-2$ if (LOGGER.isDebugEnabled()) LOGGER.debug("== Retrieving primary key for table [" + tableName + "] =="); //$NON-NLS-1$ //$NON-NLS-2$ final UniqueKeyConstraint pk = getTablePrimaryKey(context, monitor, allTablesColumns, table); if (pk != null) { pk.setConstrainedTable(table); table.addConstraint(pk); CaptureHelper.updateMonitor(monitor, getCounter(), 2, 1); } } else { LOGGER.warn("Table [" + tableName + "] has been ignored during import because the table's columns " + "could not be retrieved"); /* * Since the table's columns could not be retrieved, we mark the * table as invalid so can remove it from the captured list. */ invalidTableNames.add(tableName); } } /* * Removes from the list the tables marked as invalid before retrieving * foreign keys information. */ for (String tableName : invalidTableNames) { tables.remove(tableName); } /* * We need to initialize all tables with their columns and primary key * before retrieving foreign keys because each foreign key might * reference the primary key of any other table. */ monitor.subTask("Retrieving tables foreign keys..."); for (IBasicTable table : tables.values()) { final String tableName = table.getName(); // monitor.subTask("Retrieving foreign keys for table " + tableName + "..."); //$NON-NLS-2$ if (LOGGER.isDebugEnabled()) LOGGER.debug("== Retrieving foreign keys for table [" + tableName + "] =="); //$NON-NLS-1$ //$NON-NLS-2$ final Collection<ForeignKeyConstraint> keys = getTableForeignKeys(context, monitor, tables, allTablesColumns, table); for (IKeyConstraint fk : keys) { table.addConstraint(fk); CaptureHelper.updateMonitor(monitor, getCounter(), 2, 1); } } return tables.values(); }