Example usage for java.sql DatabaseMetaData getFunctions

List of usage examples for java.sql DatabaseMetaData getFunctions

Introduction

In this page you can find the example usage for java.sql DatabaseMetaData getFunctions.

Prototype

ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) throws SQLException;

Source Link

Document

Retrieves a description of the system and user functions available in the given catalog.

Usage

From source file:net.solarnetwork.node.dao.jdbc.derby.DerbyCustomFunctionsInitializer.java

private static void registerBitwiseFunctions(final Connection con, String schema) throws SQLException {
    DatabaseMetaData dbMeta = con.getMetaData();
    ResultSet rs = dbMeta.getFunctions(null, null, null);
    Set<String> functionNames = new HashSet<String>(Arrays.asList(BITWISE_AND, BITWISE_OR));
    while (rs.next()) {
        String schemaName = rs.getString(2);
        String functionName = rs.getString(3).toUpperCase();
        if (schema.equalsIgnoreCase(schemaName) && functionNames.contains(functionName)) {
            functionNames.remove(functionName);
        }/*from   w  ww . ja va 2s. c o  m*/
    }

    // at this point, functionNames contains the functions we need to create
    if (functionNames.size() > 0) {
        final String sqlTemplate = "CREATE FUNCTION %s.%s( parm1 INTEGER, param2 INTEGER ) "
                + "RETURNS INTEGER LANGUAGE JAVA DETERMINISTIC PARAMETER STYLE JAVA NO SQL "
                + "EXTERNAL NAME 'net.solarnetwork.node.dao.jdbc.derby.ext.DerbyBitwiseFunctions.%s'";
        if (functionNames.contains(BITWISE_AND)) {
            final String sql = String.format(sqlTemplate, schema, BITWISE_AND, "bitwiseAnd");
            con.createStatement().execute(sql);
        }
        if (functionNames.contains(BITWISE_OR)) {
            final String sql = String.format(sqlTemplate, schema, BITWISE_OR, "bitwiseOr");
            con.createStatement().execute(sql);
        }
    }
}

From source file:jef.database.DbMetaData.java

private List<Function> innerGetFunctions(String schema, String name) throws SQLException {
    if (schema == null) {
        schema = this.schema;
    }/*from w  w  w. j av  a 2 s . com*/

    Connection conn = getConnection(false);
    DatabaseDialect profile = getProfile();
    if (profile.has(Feature.NOT_SUPPORT_USER_FUNCTION)) {
        return Collections.emptyList();
    }
    List<Function> result = new ArrayList<Function>();
    DatabaseMetaData databaseMetaData = conn.getMetaData();
    ResultSet rs = null;
    try {
        rs = databaseMetaData.getFunctions(profile.getCatlog(schema), profile.getSchema(schema), name);
        while (rs.next()) {
            Function function = new Function();
            function.setCatalog(rs.getString(1));
            function.setSchema(rs.getString(2));
            function.setName(rs.getString(3));
            function.setRemarks(rs.getString(4));
            function.setType(rs.getShort(5));
            function.setSpecificName(rs.getString(6));
            result.add(function);
        }
    } catch (java.sql.SQLFeatureNotSupportedException e) {
        LogUtil.warn(databaseMetaData.getDriverName() + " doesn't supprt getFunctions() defined in JDDBC 4.0.");
    } catch (AbstractMethodError e) { // Driver version is too old...
        StringBuilder sb = new StringBuilder("The driver ").append(databaseMetaData.getDriverName());
        sb.append(' ').append(databaseMetaData.getDriverVersion()).append(' ')
                .append(databaseMetaData.getDatabaseMinorVersion());
        sb.append(" not implements JDBC 4.0, please upgrade you JDBC Driver.");
        throw new SQLException(sb.toString());
    } finally {
        DbUtils.close(rs);
        releaseConnection(conn);
    }
    return result;
}

From source file:org.apache.bigtop.itest.hive.TestJdbc.java

@Test
public void setSchema() throws SQLException {
    try (Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) {

        final String dbName = "bigtop_jdbc_test_db";

        final String tableName = "bigtop_jdbc_test_table";
        stmt.execute("drop table if exists " + tableName);

        stmt.execute("drop database if exists " + dbName + " cascade");
        stmt.execute("create database " + dbName);

        conn.setSchema(dbName);//from  www  . j a v  a 2  s.  com

        DatabaseMetaData md = conn.getMetaData();

        ResultSet rs = md.getSchemas(null, dbName);

        while (rs.next()) {
            String schemaName = rs.getString(2);
            LOG.debug("Schema name is " + schemaName);
        }

        stmt.execute("create table " + tableName + " (i int, s varchar(32))");

        rs = md.getTables(null, dbName, tableName, null);
        while (rs.next()) {
            String tName = rs.getString(3);
            LOG.debug("Schema name is " + tName);
        }

        rs = md.getColumns(null, dbName, tableName, "i");
        while (rs.next()) {
            String colName = rs.getString(4);
            LOG.debug("Schema name is " + colName);
        }

        rs = md.getFunctions(null, dbName, "foo");
        while (rs.next()) {
            String funcName = rs.getString(3);
            LOG.debug("Schema name is " + funcName);
        }
    }
}

From source file:org.apache.hive.jdbc.TestJdbcDriver2.java

@Test
public void testParentReferences() throws Exception {
    /* Test parent references from Statement */
    Statement s = this.con.createStatement();
    ResultSet rs = s.executeQuery("SELECT * FROM " + dataTypeTableName);

    assertTrue(s.getConnection() == this.con);
    assertTrue(rs.getStatement() == s);/*w w  w .  j a va2 s  .co m*/

    rs.close();
    s.close();

    /* Test parent references from PreparedStatement */
    PreparedStatement ps = this.con.prepareStatement("SELECT * FROM " + dataTypeTableName);
    rs = ps.executeQuery();

    assertTrue(ps.getConnection() == this.con);
    assertTrue(rs.getStatement() == ps);

    rs.close();
    ps.close();

    /* Test DatabaseMetaData queries which do not have a parent Statement */
    DatabaseMetaData md = this.con.getMetaData();

    assertTrue(md.getConnection() == this.con);

    rs = md.getCatalogs();
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getColumns(null, null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getFunctions(null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getImportedKeys(null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getPrimaryKeys(null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getProcedureColumns(null, null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getProcedures(null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getSchemas();
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getTableTypes();
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getTables(null, null, null, null);
    assertNull(rs.getStatement());
    rs.close();

    rs = md.getTypeInfo();
    assertNull(rs.getStatement());
    rs.close();
}

From source file:org.apache.tajo.catalog.store.XMLCatalogSchemaManager.java

protected boolean checkExistence(Connection conn, DatabaseObjectType type, String... params)
        throws SQLException {
    boolean result = false;
    DatabaseMetaData metadata = null;
    PreparedStatement pstmt = null;
    BaseSchema baseSchema = catalogStore.getSchema();

    if (params == null || params.length < 1) {
        throw new IllegalArgumentException("checkExistence function needs at least one argument.");
    }/*from w  w  w . ja v a 2s .c  o m*/

    switch (type) {
    case DATA:
        metadata = conn.getMetaData();
        ResultSet data = metadata.getUDTs(null,
                baseSchema.getSchemaName() != null && !baseSchema.getSchemaName().isEmpty()
                        ? baseSchema.getSchemaName().toUpperCase()
                        : null,
                params[0].toUpperCase(), null);
        result = data.next();
        CatalogUtil.closeQuietly(data);
        break;
    case FUNCTION:
        metadata = conn.getMetaData();
        ResultSet functions = metadata.getFunctions(null,
                baseSchema.getSchemaName() != null && !baseSchema.getSchemaName().isEmpty()
                        ? baseSchema.getSchemaName().toUpperCase()
                        : null,
                params[0].toUpperCase());
        result = functions.next();
        CatalogUtil.closeQuietly(functions);
        break;
    case INDEX:
        if (params.length != 2) {
            throw new IllegalArgumentException(
                    "Finding index object is needed two strings, table name and index name");
        }

        pstmt = getExistQuery(conn, type);
        if (pstmt != null) {
            result = checkExistenceByQuery(pstmt, baseSchema, params);
        } else {
            metadata = conn.getMetaData();
            ResultSet indexes = metadata.getIndexInfo(null,
                    baseSchema.getSchemaName() != null && !baseSchema.getSchemaName().isEmpty()
                            ? baseSchema.getSchemaName().toUpperCase()
                            : null,
                    params[0].toUpperCase(), false, true);
            while (indexes.next()) {
                if (indexes.getString("INDEX_NAME").equals(params[1].toUpperCase())) {
                    result = true;
                    break;
                }
            }
            CatalogUtil.closeQuietly(indexes);
        }
        break;
    case TABLE:
        pstmt = getExistQuery(conn, type);
        if (pstmt != null) {
            result = checkExistenceByQuery(pstmt, baseSchema, params);
        } else {
            metadata = conn.getMetaData();
            ResultSet tables = metadata.getTables(null,
                    baseSchema.getSchemaName() != null && !baseSchema.getSchemaName().isEmpty()
                            ? baseSchema.getSchemaName().toUpperCase()
                            : null,
                    params[0].toUpperCase(), new String[] { "TABLE" });
            result = tables.next();
            CatalogUtil.closeQuietly(tables);
        }
        break;
    case DOMAIN:
    case OPERATOR:
    case RULE:
    case SEQUENCE:
    case TRIGGER:
    case VIEW:
        pstmt = getExistQuery(conn, type);

        if (pstmt == null) {
            throw new TajoInternalError(
                    "Finding " + type + " type of database object is not supported on this database system.");
        }

        result = checkExistenceByQuery(pstmt, baseSchema, params);
        break;
    }

    return result;
}

From source file:org.executequery.databaseobjects.impl.DefaultDatabaseMetaTag.java

private ResultSet getFunctionsResultSet() throws SQLException {

    try {//from   w w w .  java2  s.  c  o m

        String catalogName = catalogNameForQuery();
        String schemaName = schemaNameForQuery();

        DatabaseMetaData dmd = getHost().getDatabaseMetaData();
        return dmd.getFunctions(catalogName, schemaName, null);

    } catch (Throwable e) {

        // possible SQLFeatureNotSupportedException

        Log.warning("Error retrieving database functions - " + e.getMessage());
        Log.warning("Reverting to old function retrieval implementation");

        return getFunctionResultSetOldImpl();
    }
}

From source file:org.executequery.gui.editor.autocomplete.AutoCompleteSelectionsFactory.java

@SuppressWarnings("resource")
private void databaseExecutableForHost(DatabaseHost databaseHost, String type, String databaseObjectDescription,
        AutoCompleteListItemType autocompleteType) {

    trace("Building autocomplete object list using [ " + databaseHost.getName() + " ] for type - " + type);

    ResultSet rs = null;//from   w  w  w . j  av a2  s.  c o  m
    try {

        DatabaseMetaData databaseMetaData = databaseHost.getDatabaseMetaData();
        String catalog = databaseHost.getCatalogNameForQueries(defaultCatalogForHost(databaseHost));
        String schema = databaseHost.getSchemaNameForQueries(defaultSchemaForHost(databaseHost));

        List<String> names = new ArrayList<String>();
        List<AutoCompleteListItem> list = new ArrayList<AutoCompleteListItem>();

        if (autocompleteType == AutoCompleteListItemType.DATABASE_FUNCTION) {

            try {

                rs = databaseMetaData.getFunctions(catalog, schema, null);

            } catch (Throwable e) {

                trace("Functions not available using [ getFunctions() ] - reverting to [ getProcedures() ] - "
                        + e.getMessage());
                rs = getProcedures(databaseMetaData, catalog, schema);
            }

        } else {

            rs = getProcedures(databaseMetaData, catalog, schema);
        }

        if (rs != null) {

            int count = 0;
            while (rs.next()) {

                try {
                    if (Thread.interrupted() || databaseMetaData.getConnection().isClosed()) {

                        return;
                    }
                } catch (SQLException e) {
                }

                names.add(rs.getString(3));
                count++;

                if (count >= INCREMENT) {

                    addTablesToProvider(databaseObjectDescription, autocompleteType, names, list);
                    count = 0;
                    list.clear();
                    names.clear();
                }

            }

            addTablesToProvider(databaseObjectDescription, autocompleteType, names, list);

        }

    } catch (Exception 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);
    }

}