Java Code Examples for java.sql.DatabaseMetaData#getCatalogs()

The following examples show how to use java.sql.DatabaseMetaData#getCatalogs() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GetDatabaseInfoTests.java    From sqlhelper with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * catalog.schema.table
 *
 * @param dbMetaData
 * @throws SQLException
 */
void showCatalogs(DatabaseMetaData dbMetaData) throws SQLException {
    ResultSet catalogRs = dbMetaData.getCatalogs();
    List<String> catalogs = Collects.emptyArrayList();
    while (catalogRs.next()) {
        String catalog = catalogRs.getString("TABLE_CAT");
        catalogs.add(catalog);
    }

    String catalogSeparator = dbMetaData.getCatalogSeparator();
    String catalogTerm = dbMetaData.getCatalogTerm();
    boolean catalogAtStart = dbMetaData.isCatalogAtStart();
    int maxCatalogLength = dbMetaData.getMaxCatalogNameLength();

    System.out.println("maxCatalogNameLength: " + maxCatalogLength);
    System.out.println("catalogSeparator: " + catalogSeparator); // .
    System.out.println("catalogTerm: " + catalogTerm); //catalog
    System.out.println("catalogs: " + catalogs.toString());
    System.out.println("catalog at start ? :" + catalogAtStart);
}
 
Example 2
Source File: DbHelper.java    From crud-intellij-plugin with Apache License 2.0 6 votes vote down vote up
public List<String> getDatabases() {
    Connection conn = getConnection();
    try {
        DatabaseMetaData metaData = conn.getMetaData();
        ResultSet catalogs = metaData.getCatalogs();
        List<String> rs = new ArrayList<>();
        while (catalogs.next()) {
            String db = catalogs.getString("TABLE_CAT");
            if (org.apache.commons.lang3.StringUtils.equalsIgnoreCase(db, "information_schema")) {
                continue;
            }
            rs.add(db);
        }
        return rs;
    } catch (SQLException e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        closeConnection(conn);
    }
}
 
Example 3
Source File: MetaDataJavaPrinter.java    From aceql-http with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void printCatalogsAndSchemas() throws SQLException {

	System.out.println();
	System.out.println("printCatalogs: ");
	DatabaseMetaData databaseMetaData = connection.getMetaData();
	ResultSet rs = databaseMetaData.getCatalogs();
	while(rs.next()) {
	    System.out.println("databaseMetaData.getCatalogs(): " + rs.getString(1));
	}

	System.out.println();
	System.out.println("printSchemas: ");
	ResultSet rs2 = databaseMetaData.getSchemas();
	while(rs2.next()) {
	    System.out.println("databaseMetaData.getSchemas(): " + rs2.getString(1) + " " + rs2.getString(2));
	}


    }
 
Example 4
Source File: MetaDataRegressionTest.java    From r-course with MIT License 6 votes vote down vote up
/**
 * Tests fix for BUG#21215151 - DATABASEMETADATA.GETCATALOGS() FAILS TO SORT RESULTS.
 * 
 * DatabaseMetaData.GetCatalogs() relies on the results of 'SHOW DATABASES' which deliver a sorted list of databases except for 'information_schema' which
 * is always returned in the first position.
 * This test creates set of databases around the relative position of 'information_schema' and checks the ordering of the final ResultSet.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug21215151() throws Exception {
    createDatabase("z_testBug21215151");
    createDatabase("j_testBug21215151");
    createDatabase("h_testBug21215151");
    createDatabase("i_testBug21215151");
    createDatabase("a_testBug21215151");

    DatabaseMetaData dbmd = this.conn.getMetaData();
    this.rs = dbmd.getCatalogs();

    System.out.println("Catalogs:");
    System.out.println("--------------------------------------------------");
    while (this.rs.next()) {
        System.out.println("\t" + this.rs.getString(1));
    }
    this.rs.beforeFirst();

    // check the relative position of each element in the result set compared to the previous element.
    String previousDb = "";
    while (this.rs.next()) {
        assertTrue("'" + this.rs.getString(1) + "' is lexicographically lower than the previous catalog. Check the system output to see the catalogs list.",
                previousDb.compareTo(this.rs.getString(1)) < 0);
        previousDb = this.rs.getString(1);
    }
}
 
Example 5
Source File: SqlCompleter.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
/**
 * Return list of catalog names within the database.
 *
 * @param meta metadata from connection to database
 * @param schemaFilters a catalog name patterns; must match the catalog name
 *        as it is stored in the database; "" retrieves those without a catalog;
 *        <code>null</code> means that the schema name should not be used to narrow
 *        the search; supports '%'; for example "prod_v_%"
 * @return set of all catalog names in the database
 */
private static Set<String> getCatalogNames(DatabaseMetaData meta, List<String> schemaFilters) {
  Set<String> res = new HashSet<>();
  try {
    ResultSet schemas = meta.getCatalogs();
    try {
      while (schemas.next()) {
        String schemaName = schemas.getString("TABLE_CAT");
        for (String schemaFilter : schemaFilters) {
          if (schemaFilter.equals("") || schemaName.matches(schemaFilter.replace("%", ".*?"))) {
            res.add(schemaName);
          }
        }
      }
    } finally {
      schemas.close();
    }
  } catch (SQLException t) {
    logger.error("Failed to retrieve the schema names", t);
  }
  return res;
}
 
Example 6
Source File: MetaDataRegressionTest.java    From Komondor with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Tests fix for BUG#21215151 - DATABASEMETADATA.GETCATALOGS() FAILS TO SORT RESULTS.
 * 
 * DatabaseMetaData.GetCatalogs() relies on the results of 'SHOW DATABASES' which deliver a sorted list of databases except for 'information_schema' which
 * is always returned in the first position.
 * This test creates set of databases around the relative position of 'information_schema' and checks the ordering of the final ResultSet.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug21215151() throws Exception {
    createDatabase("z_testBug21215151");
    createDatabase("j_testBug21215151");
    createDatabase("h_testBug21215151");
    createDatabase("i_testBug21215151");
    createDatabase("a_testBug21215151");

    DatabaseMetaData dbmd = this.conn.getMetaData();
    this.rs = dbmd.getCatalogs();

    System.out.println("Catalogs:");
    System.out.println("--------------------------------------------------");
    while (this.rs.next()) {
        System.out.println("\t" + this.rs.getString(1));
    }
    this.rs.beforeFirst();

    // check the relative position of each element in the result set compared to the previous element.
    String previousDb = "";
    while (this.rs.next()) {
        assertTrue("'" + this.rs.getString(1) + "' is lexicographically lower than the previous catalog. Check the system output to see the catalogs list.",
                previousDb.compareTo(this.rs.getString(1)) < 0);
        previousDb = this.rs.getString(1);
    }
}
 
Example 7
Source File: MetaDataExample.java    From JavaTutorial with Apache License 2.0 5 votes vote down vote up
private static void showCatalogs(DatabaseMetaData dbMeta) throws SQLException {
        ResultSet catalogsRs = null;
        try {
            catalogsRs = dbMeta.getCatalogs();
//             JDBCUtils.showResultSetInfo(catalogsRs);
            while (catalogsRs.next()) {
                String catalog = catalogsRs.getString("TABLE_CAT");
                showTables(dbMeta, catalog);
            }
        } finally {
            JDBCUtils.close(catalogsRs);
        }
    }
 
Example 8
Source File: Show.java    From jsqsh with Apache License 2.0 5 votes vote down vote up
private ResultSet doCatalogs(Session session, Connection con, Options options)
    throws SQLException {
    
    if (options.arguments.size() != 1) {
        
        session.err.println("Use: \\show catalogs");
        return null;
    }
    
    DatabaseMetaData meta = con.getMetaData();
    return meta.getCatalogs();
}
 
Example 9
Source File: BasicSqlConnection.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected List<String> getMetaCatalogs() throws SQLException {
	DatabaseMetaData dbMeta = connection.getMetaData();
	List<String> ret = new ArrayList<String>();
	ResultSet result = dbMeta.getCatalogs();
	String tmp;
	while (result.next()) {
		tmp = result.getString(1);
		if (tmp != null) {
			ret.add(tmp);
		}
	}
	result.close();
	return ret;
}
 
Example 10
Source File: ClientServerDUnit.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private void checkDBMetadata(Connection conn, String url) throws Exception {
  DatabaseMetaData dbmd = conn.getMetaData();
  String actualUrl = dbmd.getURL();
  // remove any trailing slash
  getLogWriter().info("Got DB " + dbmd.getDatabaseProductName() + ' '
      + dbmd.getDatabaseProductVersion() + " using URL " + actualUrl);
  assertEquals("Expected the provided URL to match", url.replaceFirst("/$",
      ""), actualUrl.replaceFirst("/$", ""));
  ResultSet rs = dbmd.getCatalogs();
  while (rs.next()) {
    getLogWriter().info("Got DB catalog: " + rs.getString(1));
  }
  rs.close();
  rs = dbmd.getSchemas();
  while (rs.next()) {
    getLogWriter().info("Got DB schema: " + rs.getString(1)
        + " in catalog=" + rs.getString(2));
  }
  rs.close();
  rs = dbmd.getProcedures(null, null, null);
  while (rs.next()) {
    getLogWriter().info("Got Procedure " + rs.getString(3) + " in catalog="
        + rs.getString(1) + ", schema=" + rs.getString(2));
  }
  rs.close();
  // also check for a few flags that are failing over network connection
  assertTrue(dbmd.othersInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY));
  assertTrue(dbmd.othersDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY));
}
 
Example 11
Source File: DBView.java    From ralasafe with MIT License 5 votes vote down vote up
public static String[] getAllSchemasFromDB(String dsName) {
	Connection conn = null;
	ResultSet rs = null;

	try {
		conn = DBPower.getConnection(dsName);

		DatabaseMetaData metaData = conn.getMetaData();

		String databaseProductName = DBUtil.getDatabaseProductName(conn);
		if (databaseProductName == DBUtil.MYSQL
				|| databaseProductName == DBUtil.SQLSERVER) {
			rs = metaData.getCatalogs();
		} else {
			rs = metaData.getSchemas();
		}

		List result = new LinkedList();
		while (rs.next()) {
			String name = rs.getString(1);
			result.add(name);
		}

		String[] names = new String[result.size()];
		Iterator itr = result.iterator();
		for (int i = 0; i < names.length; i++) {
			names[i] = (String) itr.next();
		}
		return names;
	} catch (SQLException e) {
		log.error( "", e );
		throw new DBLevelException(e);
	} finally {
		DBUtil.close(rs);
		DBUtil.close(conn);
	}
}
 
Example 12
Source File: ClientServerDUnit.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private void checkDBMetadata(Connection conn, String url) throws Exception {
  DatabaseMetaData dbmd = conn.getMetaData();
  String actualUrl = dbmd.getURL();
  // remove any trailing slash
  getLogWriter().info("Got DB " + dbmd.getDatabaseProductName() + ' '
      + dbmd.getDatabaseProductVersion() + " using URL " + actualUrl);
  assertEquals("Expected the provided URL to match", url.replaceFirst("/$",
      ""), actualUrl.replaceFirst("/$", ""));
  ResultSet rs = dbmd.getCatalogs();
  while (rs.next()) {
    getLogWriter().info("Got DB catalog: " + rs.getString(1));
  }
  rs.close();
  rs = dbmd.getSchemas();
  while (rs.next()) {
    getLogWriter().info("Got DB schema: " + rs.getString(1)
        + " in catalog=" + rs.getString(2));
  }
  rs.close();
  rs = dbmd.getProcedures(null, null, null);
  while (rs.next()) {
    getLogWriter().info("Got Procedure " + rs.getString(3) + " in catalog="
        + rs.getString(1) + ", schema=" + rs.getString(2));
  }
  rs.close();
  // also check for a few flags that are failing over network connection
  assertTrue(dbmd.othersInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY));
  assertTrue(dbmd.othersDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY));
}
 
Example 13
Source File: MetaResultSetTest.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
@Test public void testGetCatalogs() throws SQLException {
  DatabaseMetaData metadata = getDatabaseMetadata();
  try (ResultSet rs = metadata.getCatalogs()) {
    ResultSetMetaData rsMeta = rs.getMetaData();

    assertEquals(1, rsMeta.getColumnCount());
    assertColumn(rsMeta, 1, "TABLE_CAT", Types.VARCHAR, DatabaseMetaData.columnNoNulls);
  }
}
 
Example 14
Source File: TestDatabaseMetaData.java    From evosql with Apache License 2.0 5 votes vote down vote up
/**
 * Basic test of DatabaseMetaData functions that access system tables
 */
public void testTwo() throws Exception {

    Connection conn = newConnection();
    int        updateCount;

    try {
        TestUtil.testScript(conn, "testrun/hsqldb/TestSelf.txt");

        DatabaseMetaData dbmeta = conn.getMetaData();

        dbmeta.allProceduresAreCallable();
        dbmeta.getBestRowIdentifier(null, null, "T_1",
                                    DatabaseMetaData.bestRowTransaction,
                                    true);
        dbmeta.getCatalogs();
        dbmeta.getColumnPrivileges(null, "PUBLIC", "T_1", "%");
        dbmeta.getColumns("PUBLIC", "PUBLIC", "T_1", "%");
        dbmeta.getCrossReference(null, null, "T_1", null, null, "T_1");
        dbmeta.getExportedKeys(null, null, "T_1");
        dbmeta.getFunctionColumns(null, "%", "%", "%");
        dbmeta.getFunctions(null, "%", "%");
        dbmeta.getImportedKeys("PUBLIC", "PUBLIC", "T_1");
        dbmeta.getIndexInfo("PUBLIC", "PUBLIC", "T1", true, true);
        dbmeta.getPrimaryKeys("PUBLIC", "PUBLIC", "T_1");
        dbmeta.getProcedureColumns(null, null, "%", "%");
        dbmeta.getProcedures("PUBLIC", "%", "%");
        dbmeta.getSchemas(null, "#");
        dbmeta.getTablePrivileges(null, "%", "%");
        dbmeta.getUDTs(null, "%", "%", new int[]{ Types.DISTINCT });
    } catch (Exception e) {
        assertTrue("unable to prepare or execute DDL", false);
    } finally {
        conn.close();
    }
}
 
Example 15
Source File: AceQLMetaData.java    From aceql-http with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
    * Returns the Catalogs
    *
    * @return the Catalogs
    * @throws SQLException
    */
   public List<String> getCatalogs() throws SQLException {
DatabaseMetaData databaseMetaData = connection.getMetaData();
ResultSet rs = databaseMetaData.getCatalogs();
String columnLabel = "TABLE_CAT";
List<String> schemas = new ArrayList<>();
while (rs.next()) {

    schemas.add(rs.getString(columnLabel));
}
return schemas;
   }
 
Example 16
Source File: DatabaseMetaDataTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Test methods that describe attributes of SQL Objects
 * that are not supported by derby. In each case the
 * metadata should return an empty ResultSet of the
 * correct shape, and with correct names, datatypes and
 * nullability for the columns in the ResultSet.
 *
 */
public void testUnimplementedSQLObjectAttributes() throws SQLException
{
    DatabaseMetaData dmd = getDMD();

    ResultSet rs;

    rs = dmd.getAttributes(null,null,null,null);

    String [] columnNames = {
            "TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME", "ATTR_NAME", "DATA_TYPE",
            "ATTR_TYPE_NAME", "ATTR_SIZE", "DECIMAL_DIGITS", "NUM_PREC_RADIX",
            "NULLABLE", "REMARKS", "ATTR_DEF", "SQL_DATA_TYPE",
            "SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH", "ORDINAL_POSITION",
            "IS_NULLABLE", "SCOPE_CATALOG", "SCOPE_SCHEMA", "SCOPE_TABLE",
            "SOURCE_DATA_TYPE"
    };
    int [] columnTypes = {
            Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
            Types.INTEGER, Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.INTEGER,
            Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.INTEGER,
            Types.INTEGER, Types.INTEGER, Types.INTEGER,
            Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.SMALLINT
    };
    // DERBY-3171; we get a different value back for nullability for
    // a number of the columns with networkserver/client vs. embedded
    boolean nullval = true;
    if (usingDerbyNetClient())
        nullval = false;
    boolean [] nullability = {
            true, true, false, nullval, nullval, nullval, nullval,
            nullval, nullval, nullval, true, true, nullval, nullval,
            nullval, nullval, nullval, true, true, true, true
    };

    assertMetaDataResultSet(rs, columnNames, columnTypes, nullability);
    JDBC.assertEmpty(rs);

    rs = dmd.getCatalogs();
    checkCatalogsShape(rs);
    JDBC.assertEmpty(rs);

    rs = dmd.getSuperTables(null,null,null);
    columnNames = new String[] {
            "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "SUPERTABLE_NAME"};
    columnTypes = new int[] {
            Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR};
    nullability = new boolean[] {
            true, true, false, false};
    assertMetaDataResultSet(rs, columnNames, columnTypes, nullability);
    JDBC.assertEmpty(rs);

    rs = dmd.getSuperTypes(null,null,null);
    columnNames = new String[] {
            "TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME", "SUPERTYPE_CAT",
            "SUPERTYPE_SCHEM", "SUPERTYPE_NAME"};
    columnTypes = new int[] {
            Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
            Types.VARCHAR, Types.VARCHAR};
    nullability = new boolean[] {
            true, true, false, true, true, false};
    assertMetaDataResultSet(rs, columnNames, columnTypes, nullability);
    JDBC.assertEmpty(rs);

    ResultSet rss[] = getVersionColumns(null,null, "No_such_table");
    checkVersionColumnsShape(rss);
    JDBC.assertEmpty(rss[0]);
    JDBC.assertEmpty(rss[1]);

    rs.close();
    rss[0].close();
    rss[1].close();
}
 
Example 17
Source File: DatabaseMetaDataTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Test methods that describe attributes of SQL Objects
 * that are not supported by derby. In each case the
 * metadata should return an empty ResultSet of the
 * correct shape, and with correct names, datatypes and
 * nullability for the columns in the ResultSet.
 *
 */
public void testUnimplementedSQLObjectAttributes() throws SQLException
{
    DatabaseMetaData dmd = getDMD();

    ResultSet rs;

    rs = dmd.getAttributes(null,null,null,null);

    String [] columnNames = {
            "TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME", "ATTR_NAME", "DATA_TYPE",
            "ATTR_TYPE_NAME", "ATTR_SIZE", "DECIMAL_DIGITS", "NUM_PREC_RADIX",
            "NULLABLE", "REMARKS", "ATTR_DEF", "SQL_DATA_TYPE",
            "SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH", "ORDINAL_POSITION",
            "IS_NULLABLE", "SCOPE_CATALOG", "SCOPE_SCHEMA", "SCOPE_TABLE",
            "SOURCE_DATA_TYPE"
    };
    int [] columnTypes = {
            Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
            Types.INTEGER, Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.INTEGER,
            Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.INTEGER,
            Types.INTEGER, Types.INTEGER, Types.INTEGER,
            Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.SMALLINT
    };
    // DERBY-3171; we get a different value back for nullability for
    // a number of the columns with networkserver/client vs. embedded
    boolean nullval = true;
    if (usingDerbyNetClient())
        nullval = false;
    boolean [] nullability = {
            true, true, false, nullval, nullval, nullval, nullval,
            nullval, nullval, nullval, true, true, nullval, nullval,
            nullval, nullval, nullval, true, true, true, true
    };

    assertMetaDataResultSet(rs, columnNames, columnTypes, nullability);
    JDBC.assertEmpty(rs);

    rs = dmd.getCatalogs();
    checkCatalogsShape(rs);
    JDBC.assertEmpty(rs);

    rs = dmd.getSuperTables(null,null,null);
    columnNames = new String[] {
            "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "SUPERTABLE_NAME"};
    columnTypes = new int[] {
            Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR};
    nullability = new boolean[] {
            true, true, false, false};
    assertMetaDataResultSet(rs, columnNames, columnTypes, nullability);
    JDBC.assertEmpty(rs);

    rs = dmd.getSuperTypes(null,null,null);
    columnNames = new String[] {
            "TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME", "SUPERTYPE_CAT",
            "SUPERTYPE_SCHEM", "SUPERTYPE_NAME"};
    columnTypes = new int[] {
            Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
            Types.VARCHAR, Types.VARCHAR};
    nullability = new boolean[] {
            true, true, false, true, true, false};
    assertMetaDataResultSet(rs, columnNames, columnTypes, nullability);
    JDBC.assertEmpty(rs);

    ResultSet rss[] = getVersionColumns(null,null, "No_such_table");
    checkVersionColumnsShape(rss);
    JDBC.assertEmpty(rss[0]);
    JDBC.assertEmpty(rss[1]);

    rs.close();
    rss[0].close();
    rss[1].close();
}
 
Example 18
Source File: dbInfo.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
private cfData typeDbnames(cfSession _session, cfDataSource datasource) throws cfmRunTimeException{
	Connection c = null;
	try {
		c = datasource.getPooledConnection();
		
		DatabaseMetaData metaData = c.getMetaData();
		
		cfQueryResultData queryResult = new cfQueryResultData(new String[] { "database_name", "type" }, "DBINFO");
		
		cfStringData	catalogSD = new cfStringData("catalog");
		cfStringData	schemaSD = new cfStringData("schema");
		
		ResultSet rset = metaData.getCatalogs();
		int row=1;
		while ( rset.next() ){
			queryResult.addRow(1);
			queryResult.setCell(row, 1, new cfStringData(rset.getString(1)) );
			queryResult.setCell(row, 2, catalogSD );
			row++;
		}
		rset.close();
		
		
		rset = metaData.getSchemas();
		while ( rset.next() ){
			queryResult.addRow(1);
			queryResult.setCell(row, 1, new cfStringData(rset.getString(1)) );
			queryResult.setCell(row, 2, schemaSD );
			row++;
		}
		rset.close();
		
		return queryResult;
		
	} catch (SQLException e) {
		throwException(_session,  e.getMessage() );
	} finally {
		datasource.close(c);
	}
	
	return null;
}
 
Example 19
Source File: PhysicalModelInitializer.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
private void addCatalog(Connection conn, PhysicalModel model, String defaultCatalog) {
	String catalog = defaultCatalog;
	List<String> catalogs;
	DatabaseMetaData dbMeta;
	ResultSet rs;
	Iterator<String> it;

	try {
		if (catalog == null) {
			dbMeta = conn.getMetaData();

			rs = dbMeta.getCatalogs();
			catalogs = new ArrayList<>();
			while (rs.next()) {
				String catalogName = rs.getString(1);
				if (catalogName != null) {
					catalogs.add(catalogName);
				}
			}
			if (catalogs.size() == 0) {
				log("No schema [" + dbMeta.getSchemaTerm() + "] defined");
			} else if (catalogs.size() == 1) {
				catalog = catalogs.get(0);
			} else {
				String targetCatalog = null;
				it = catalogs.iterator();
				while (it.hasNext()) {
					String s = it.next();
					log("s [" + s + "]");
					if (s.equalsIgnoreCase(defaultCatalog)) {
						targetCatalog = defaultCatalog;
						break;
					}
				}
				if (targetCatalog == null) {
					throw new RuntimeException("No catalog named [" + defaultCatalog + "] is available on db");
				}
				catalog = targetCatalog;
			}
			rs.close();
		}

		model.setCatalog(catalog);
	} catch (Throwable t) {
		throw new RuntimeException("Impossible to initialize catalog metadata", t);
	}
}