List of usage examples for java.sql Connection getCatalog
String getCatalog() throws SQLException;
Connection
object's current catalog name. From source file:org.apache.openjpa.jdbc.schema.ForeignKey.java
public DBIdentifier loadIdentifierFromDB(DBDictionary dbdict, Connection conn) { if (isLogical() || getTable() == null) return DBIdentifier.NULL; DBIdentifier retVal = DBIdentifier.NULL; try {//from w w w. j a v a 2 s. c o m Schema schema = getTable().getSchema(); ForeignKey[] fks = dbdict.getImportedKeys(conn.getMetaData(), DBIdentifier.newCatalog(conn.getCatalog()), schema.getIdentifier(), getTable().getIdentifier(), conn, false); for (int i = 0; i < fks.length; i++) { Table localtable = schema.getTable(fks[i].getTableIdentifier()); Table pkTable = schema.getTable(fks[i].getPrimaryKeyTableIdentifier()); boolean addFK = false; ForeignKey fkTemp = localtable.getForeignKey(fks[i].getIdentifier()); if (fkTemp == null) { addFK = true; fkTemp = localtable.addForeignKey(fks[i].getIdentifier()); fkTemp.setDeferred(fks[i].isDeferred()); fkTemp.setDeleteAction(fks[i].getDeleteAction()); } if (fks[i].getColumns() == null || fks[i].getColumns().length == 0) { // Singular column foreign key if (!fkTemp.containsColumn(localtable.getColumn(fks[i].getColumnIdentifier()))) fkTemp.join(localtable.getColumn(fks[i].getColumnIdentifier()), pkTable.getColumn(fks[i].getPrimaryKeyColumnIdentifier())); } else { // Add the multi-column foreign key, joining local and pk columns in // the temporary key Column[] locCols = fks[i].getColumns(); Column[] pkCols = fks[i].getPrimaryKeyColumns(); // Column counts must match if (locCols != null && pkCols != null && locCols.length != pkCols.length) { Log log = dbdict.getLog(); if (log.isTraceEnabled()) { log.trace(_loc.get("fk-column-mismatch")); } } for (int j = 0; j < locCols.length; j++) { if (!fkTemp.containsColumn(localtable.getColumn(locCols[j].getIdentifier()))) { fkTemp.join(localtable.getColumn(locCols[j].getIdentifier()), pkTable.getColumn(pkCols[j].getIdentifier())); } } } if (equalsForeignKey(fkTemp)) { if (addFK) localtable.removeForeignKey(fkTemp); retVal = fks[i].getIdentifier(); break; } if (addFK) localtable.removeForeignKey(fkTemp); } } catch (Exception ex) { Log log = dbdict.getLog(); if (log.isTraceEnabled()) { log.trace(_loc.get("except-read-fk-name"), ex); } } return retVal; }
From source file:org.apache.syncope.core.persistence.jpa.content.XMLContentExporter.java
private List<String> sortByForeignKeys(final String dbSchema, final Connection conn, final Set<String> tableNames) throws SQLException { Set<MultiParentNode<String>> roots = new HashSet<>(); final DatabaseMetaData meta = conn.getMetaData(); final Map<String, MultiParentNode<String>> exploited = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); final Set<String> pkTableNames = new HashSet<>(); for (String tableName : tableNames) { MultiParentNode<String> node = exploited.get(tableName); if (node == null) { node = new MultiParentNode<>(tableName); roots.add(node);/*ww w . ja v a 2 s . com*/ exploited.put(tableName, node); } pkTableNames.clear(); ResultSet rs = null; try { rs = meta.getImportedKeys(conn.getCatalog(), dbSchema, tableName); // this is to avoid repetition while (rs.next()) { pkTableNames.add(rs.getString("PKTABLE_NAME")); } } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.error("While closing tables result set", e); } } } for (String pkTableName : pkTableNames) { if (!tableName.equalsIgnoreCase(pkTableName)) { MultiParentNode<String> pkNode = exploited.get(pkTableName); if (pkNode == null) { pkNode = new MultiParentNode<>(pkTableName); roots.add(pkNode); exploited.put(pkTableName, pkNode); } pkNode.addChild(node); if (roots.contains(node)) { roots.remove(node); } } } } final List<String> sortedTableNames = new ArrayList<>(tableNames.size()); MultiParentNodeOp.traverseTree(roots, sortedTableNames); // remove from sortedTableNames any table possibly added during lookup // but matching some item in this.tablePrefixesToBeExcluded sortedTableNames.retainAll(tableNames); LOG.debug("Tables after retainAll {}", sortedTableNames); Collections.reverse(sortedTableNames); return sortedTableNames; }
From source file:org.apache.syncope.core.persistence.jpa.content.XMLContentExporter.java
private void doExportTable(final TransformerHandler handler, final String dbSchema, final Connection conn, final String tableName, final String whereClause) throws SQLException, SAXException { LOG.debug("Export table {}", tableName); AttributesImpl attrs = new AttributesImpl(); PreparedStatement stmt = null; ResultSet rs = null;/* w ww . j av a 2 s .c om*/ try { StringBuilder orderBy = new StringBuilder(); DatabaseMetaData meta = conn.getMetaData(); // ------------------------------------ // retrieve foreign keys (linked to the same table) to perform an ordered select ResultSet pkeyRS = null; try { pkeyRS = meta.getImportedKeys(conn.getCatalog(), dbSchema, tableName); while (pkeyRS.next()) { if (tableName.equals(pkeyRS.getString("PKTABLE_NAME"))) { String columnName = pkeyRS.getString("FKCOLUMN_NAME"); if (columnName != null) { if (orderBy.length() > 0) { orderBy.append(","); } orderBy.append(columnName); } } } } finally { if (pkeyRS != null) { try { pkeyRS.close(); } catch (SQLException e) { LOG.error("While closing result set", e); } } } // retrieve primary keys to perform an ordered select try { pkeyRS = meta.getPrimaryKeys(null, null, tableName); while (pkeyRS.next()) { String columnName = pkeyRS.getString("COLUMN_NAME"); if (columnName != null) { if (orderBy.length() > 0) { orderBy.append(","); } orderBy.append(columnName); } } } finally { if (pkeyRS != null) { try { pkeyRS.close(); } catch (SQLException e) { LOG.error("While closing result set", e); } } } // ------------------------------------ StringBuilder query = new StringBuilder(); query.append("SELECT * FROM ").append(tableName).append(" a"); if (StringUtils.isNotBlank(whereClause)) { query.append(" WHERE ").append(whereClause); } if (orderBy.length() > 0) { query.append(" ORDER BY ").append(orderBy); } stmt = conn.prepareStatement(query.toString()); rs = stmt.executeQuery(); while (rs.next()) { attrs.clear(); final ResultSetMetaData rsMeta = rs.getMetaData(); for (int i = 0; i < rsMeta.getColumnCount(); i++) { final String columnName = rsMeta.getColumnName(i + 1); final Integer columnType = rsMeta.getColumnType(i + 1); // Retrieve value taking care of binary values. String value = getValues(rs, columnName, columnType); if (value != null && (!COLUMNS_TO_BE_NULLIFIED.containsKey(tableName) || !COLUMNS_TO_BE_NULLIFIED.get(tableName).contains(columnName))) { attrs.addAttribute("", "", columnName, "CDATA", value); } } handler.startElement("", "", tableName, attrs); handler.endElement("", "", tableName); LOG.debug("Add record {}", attrs); } } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.error("While closing result set", e); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { LOG.error("While closing result set", e); } } } }
From source file:org.apache.syncope.core.util.ContentExporter.java
private List<String> sortByForeignKeys(final Connection conn, final Set<String> tableNames) throws SQLException { Set<MultiParentNode<String>> roots = new HashSet<MultiParentNode<String>>(); final DatabaseMetaData meta = conn.getMetaData(); final Map<String, MultiParentNode<String>> exploited = new TreeMap<String, MultiParentNode<String>>( String.CASE_INSENSITIVE_ORDER); final Set<String> pkTableNames = new HashSet<String>(); for (String tableName : tableNames) { MultiParentNode<String> node = exploited.get(tableName); if (node == null) { node = new MultiParentNode<String>(tableName); roots.add(node);//from ww w . ja v a 2 s. c om exploited.put(tableName, node); } pkTableNames.clear(); ResultSet rs = null; try { rs = meta.getImportedKeys(conn.getCatalog(), dbSchema, tableName); // this is to avoid repetition while (rs.next()) { pkTableNames.add(rs.getString("PKTABLE_NAME")); } } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.error("While closing tables result set", e); } } } for (String pkTableName : pkTableNames) { if (!tableName.equalsIgnoreCase(pkTableName)) { MultiParentNode<String> pkNode = exploited.get(pkTableName); if (pkNode == null) { pkNode = new MultiParentNode<String>(pkTableName); roots.add(pkNode); exploited.put(pkTableName, pkNode); } pkNode.addChild(node); if (roots.contains(node)) { roots.remove(node); } } } } final List<String> sortedTableNames = new ArrayList<String>(tableNames.size()); MultiParentNodeOp.traverseTree(roots, sortedTableNames); // remove from sortedTableNames any table possibly added during lookup // but matching some item in this.tablePrefixesToBeExcluded sortedTableNames.retainAll(tableNames); LOG.debug("Tables after retainAll {}", sortedTableNames); Collections.reverse(sortedTableNames); return sortedTableNames; }
From source file:org.apache.zeppelin.jdbc.SqlCompleter.java
/** * Initializes all local completers from database connection * * @param connection database connection * @param schemaFilter a schema name pattern; must match the schema name * as it is stored in the database; "" retrieves those without a schema; * <code>null</code> means that the schema name should not be used to narrow * the search; supports '%' and '_' symbols; for example "prod_v_%" *//*from ww w .j ava 2 s . c om*/ public void initFromConnection(Connection connection, String schemaFilter) { try { Map<String, Set<String>> tables = new HashMap<>(); Map<String, Set<String>> columns = new HashMap<>(); Set<String> schemas = new HashSet<>(); Set<String> catalogs = new HashSet<>(); Set<String> keywords = getSqlKeywordsCompletions(connection); if (connection != null) { schemas = getSchemaNames(connection.getMetaData(), schemaFilter); catalogs = getCatalogNames(connection.getMetaData(), schemaFilter); if (!"".equals(connection.getCatalog())) { if (schemas.size() == 0) schemas.add(connection.getCatalog()); fillTableAndColumnNames(connection.getCatalog(), connection.getMetaData(), schemaFilter, tables, columns); } else { if (schemas.size() == 0) schemas.addAll(catalogs); for (String catalog : catalogs) { fillTableAndColumnNames(catalog, connection.getMetaData(), schemaFilter, tables, columns); } } } init(schemas, tables, columns, keywords); logger.info("Completer initialized with " + schemas.size() + " schemas, " + columns.size() + " tables and " + keywords.size() + " keywords"); } catch (SQLException | IOException e) { logger.error("Failed to update the metadata conmpletions", e); } }
From source file:org.biomart.configurator.controller.MartController.java
private Map<String, Map<String, List<String>>> getDBTableColsMap(Connection con) throws SQLException { Map<String, Map<String, List<String>>> dbTableColMap = new HashMap<String, Map<String, List<String>>>(); Map<String, List<String>> tblColMap = new HashMap<String, List<String>>(); List<String> colList = new ArrayList<String>(); final String catalog = con.getCatalog(); StringBuffer sqlSB = new StringBuffer( "select table_schema,table_name,column_name,column_key from information_schema.columns where "); sqlSB.append("table_schema='" + catalog + "' order by table_schema,table_name, ordinal_position"); try {//from w ww .j a v a 2s . c om Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sqlSB.toString()); String schemaName; String tableName; String lastTableName = null; String lastSchemaName = null; while (rs.next()) { schemaName = rs.getString("table_schema"); tableName = rs.getString("table_name"); // finish all columns in one table and move to the next, if previous table doesn't have a PK, // create using keyguessing if (!tableName.equals(lastTableName)) { if (lastTableName != null) { tblColMap.put(lastTableName, colList); colList = new ArrayList<String>(); } // change schema if (lastSchemaName != null) { if (!lastSchemaName.equals(schemaName)) { dbTableColMap.put(lastSchemaName, tblColMap); tblColMap = new HashMap<String, List<String>>(); } } // move to next table // clean flags lastTableName = tableName; lastSchemaName = schemaName; } colList.add(rs.getString("column_name")); } if (null == dbTableColMap.get(lastSchemaName)) { dbTableColMap.put(lastSchemaName, tblColMap); } rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return dbTableColMap; }
From source file:org.cloudfoundry.identity.uaa.db.TestSchemaValidation.java
public void validate_index_existence(String[] tableNames, String lookupIndexName) throws Exception { Connection connection = dataSource.getConnection(); try {//from ww w . j a v a 2s . co m DatabaseMetaData meta = connection.getMetaData(); boolean foundIndex = false; for (String tableName : tableNames) { ResultSet rs = meta.getIndexInfo(connection.getCatalog(), null, tableName, false, false); while ((!foundIndex) && rs.next()) { String indexName = rs.getString("INDEX_NAME"); if (lookupIndexName.equalsIgnoreCase(indexName)) { foundIndex = true; } } rs.close(); if (foundIndex) { break; } } assertTrue("I was expecting to find index " + lookupIndexName, foundIndex); } finally { connection.close(); } }
From source file:org.hsweb.ezorm.rdb.executor.AbstractJdbcSqlExecutor.java
@Override public boolean tableExists(String tname) throws SQLException { Connection connection = getConnection(); try {//from w w w . j av a 2 s . c o m DatabaseMetaData metaData = connection.getMetaData(); ResultSet resultSet = metaData.getTables(connection.getCatalog(), null, tname.toUpperCase(), null); if (resultSet.next()) return true; else { resultSet = metaData.getTables(connection.getCatalog(), null, tname.toLowerCase(), null); } if (resultSet.next()) return true; } finally { releaseConnection(connection); } return false; }
From source file:org.jboss.dashboard.ui.panel.dataSourceManagement.DataSourceManagementHandler.java
/** * Get all tables of the datasource selected. *//*w ww .j a v a 2 s. c o m*/ public List getIntrospectedTables(String datasource) throws Exception { List result = new ArrayList(); Connection connection = getConnection(); ResultSet tables = null; try { DatabaseMetaData metadata = connection.getMetaData(); String catalog = connection.getCatalog(); String[] types = { "TABLE" }; tables = metadata.getTables(catalog, null, "%", types); while (tables.next()) { String schema = tables.getString(TABLE_SCHEMA); String tableName = tables.getString(TABLE_NAME); DataSourceTableEntry dataSourceTableEntry = new DataSourceTableEntry(); dataSourceTableEntry.setDatasource(getName()); dataSourceTableEntry.setName(tableName); result.add(dataSourceTableEntry); } } finally { try { if (tables != null) tables.close(); if (connection != null) connection.close(); } catch (SQLException ignore) { } } return result; }
From source file:org.kawanfw.sql.servlet.DatabaseMetaDataExecutor.java
/** * Execute the MetaData request/*www . j a v a 2 s .c o m*/ */ public void execute() throws Exception { // String action = request.getParameter(SqlAction.ACTION) ; String username = request.getParameter(Parameter.USERNAME); String methodName = request.getParameter(Parameter.METHOD_NAME); String connectionId = request.getParameter(ConnectionParms.CONNECTION_ID); // methodName = HtmlConverter.fromHtml(methodName); debug("Parameter.METHOD_NAME: " + methodName); Connection connection = null; if (connectionId.equals("0")) { try { connection = commonsConfigurator.getConnection(); boolean isAllowed = SqlConfiguratorCall.allowGetMetaData(sqlConfigurator, username, connection); if (!isAllowed) { String message = Tag.PRODUCT_SECURITY + " Database Catalog Query not authorized."; throw new SecurityException(message); } DatabaseMetaData databaseMetaData = connection.getMetaData(); // If methodName is getMetaData ==> just return the // DatabaseMetaData if (methodName.equals("getMetaData")) { DatabaseMetaDataHolder databaseMetaDataHolder = new DatabaseMetaDataHolder(); databaseMetaDataHolder.setDatabaseMetaDataHolder(databaseMetaData); String jsonString = DatabaseMetaDataHolderTransport.toJson(databaseMetaDataHolder); jsonString = HtmlConverter.toHtml(jsonString); //out.println(TransferStatus.SEND_OK); //out.println(jsonString); ServerSqlManager.writeLine(out, TransferStatus.SEND_OK); ServerSqlManager.writeLine(out, jsonString); return; } else if (methodName.equals("getCatalog")) { String catalog = connection.getCatalog(); catalog = HtmlConverter.toHtml(catalog); //out.println(TransferStatus.SEND_OK); //out.println(catalog); ServerSqlManager.writeLine(out, TransferStatus.SEND_OK); ServerSqlManager.writeLine(out, catalog); } else { // Call the DatabaseMetaData.method with reflection: callMetaDataFunction(request, out, connection); } } finally { // Release the connection ConnectionCloser.freeConnection(connection, sqlConfigurator); } } else { ConnectionStore connectionStore = new ConnectionStore(username, connectionId); connection = connectionStore.get(); if (connection == null) { //out.println(TransferStatus.SEND_OK); //out.println(SqlReturnCode.SESSION_INVALIDATED); ServerSqlManager.writeLine(out, TransferStatus.SEND_OK); ServerSqlManager.writeLine(out, SqlReturnCode.SESSION_INVALIDATED); return; } boolean isAllowed = SqlConfiguratorCall.allowGetMetaData(sqlConfigurator, username, connection); if (!isAllowed) { String message = Tag.PRODUCT_SECURITY + " Database Catalog Query not authorized."; throw new SecurityException(message); } DatabaseMetaData databaseMetaData = connection.getMetaData(); // If methodName is getMetaData ==> just return the // DatabaseMetaData if (methodName.equals("getMetaData")) { DatabaseMetaDataHolder databaseMetaDataHolder = new DatabaseMetaDataHolder(); databaseMetaDataHolder.setDatabaseMetaDataHolder(databaseMetaData); String jsonString = DatabaseMetaDataHolderTransport.toJson(databaseMetaDataHolder); jsonString = HtmlConverter.toHtml(jsonString); //out.println(TransferStatus.SEND_OK); //out.println(jsonString); ServerSqlManager.writeLine(out, TransferStatus.SEND_OK); ServerSqlManager.writeLine(out, jsonString); return; } else if (methodName.equals("getCatalog")) { String catalog = connection.getCatalog(); catalog = HtmlConverter.toHtml(catalog); //out.println(TransferStatus.SEND_OK); //out.println(catalog); ServerSqlManager.writeLine(out, TransferStatus.SEND_OK); ServerSqlManager.writeLine(out, catalog); } else { // Call the DatabaseMetaData.method with reflection: callMetaDataFunction(request, out, connection); } } }