Example usage for java.sql Connection getCatalog

List of usage examples for java.sql Connection getCatalog

Introduction

In this page you can find the example usage for java.sql Connection getCatalog.

Prototype

String getCatalog() throws SQLException;

Source Link

Document

Retrieves this Connection object's current catalog name.

Usage

From source file:com.netflix.metacat.connector.snowflake.SnowflakeConnectorTableService.java

@Override
protected Connection getConnection(@Nonnull @NonNull final String schema) throws SQLException {
    final Connection connection = this.dataSource.getConnection();
    connection.setSchema(connection.getCatalog());
    return connection;
}

From source file:de.tudarmstadt.ukp.csniper.webapp.project.ProjectRepository.java

/**
 * Gets the maximum column length.<br>
 * Why is this method located here? For convenience reasons - we already have access to
 * projectRepository on the relevant pages (EvaluationPage, AnnotationTypePage).
 * // www  .  ja v a 2s  . c  o m
 * @param aColumn
 *            the column for which the maximum length shall be returned
 * @return the maximum length of the specified column in the specified table
 */
@Transactional
public int getDbColumnLength(String aEntityName, String aColumn) {
    BigInteger length = new BigInteger("255");

    final List<String> query = new ArrayList<String>();
    query.add("SELECT CHARACTER_MAXIMUM_LENGTH");
    query.add("FROM INFORMATION_SCHEMA.COLUMNS");

    Session session = entityManager.unwrap(Session.class);
    session.doWork(new Work() {
        @Override
        public void execute(Connection aConnection) throws SQLException {
            query.add("WHERE table_schema = '" + aConnection.getCatalog() + "'");
        }
    });

    query.add("AND table_name = '" + aEntityName + "'");
    query.add("AND column_name = '" + aColumn + "'");

    try {
        length = (BigInteger) entityManager.createNativeQuery(StringUtils.join(query, " ")).getSingleResult();
    } catch (NoResultException e) {
        // log.debug("No results for query: " + StringUtils.join(query, " "));
    }

    if (length.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) {
        return Integer.MAX_VALUE;
    } else {
        return length.intValue();
    }
}

From source file:com.netflix.metacat.connector.snowflake.SnowflakeConnectorTableService.java

@Override
protected ResultSet getColumns(@Nonnull @NonNull final Connection connection,
        @Nonnull @NonNull final QualifiedName name) throws SQLException {
    return connection.getMetaData().getColumns(connection.getCatalog(), name.getDatabaseName(),
            name.getTableName(), JdbcConnectorUtils.MULTI_CHARACTER_SEARCH);
}

From source file:com.dbsvg.models.JdbcMainDAO.java

/**
 * This method should be run after all the tables are created. It cross
 * references two tables to see if there is a foreign key between them. If
 * so, it transforms the parent column into a foreign key.
 * //from  ww w.j a v a 2s . c  om
 * @param t
 * @param fTable
 * @param meta
 * @throws java.lang.Exception
 */
private void checkForForeignKeys(Table t, DatabaseMetaData meta, Connection conn, Map<String, Table> tablemap)
        throws Exception {
    ResultSet rs = meta.getExportedKeys(conn.getCatalog(), null, t.getName());
    while (rs.next()) {
        String parentColumn = rs.getString("PKCOLUMN_NAME");
        String fkTableName = rs.getString("FKTABLE_NAME");
        String foreignColumn = rs.getString("FKCOLUMN_NAME");
        Table fTable = tablemap.get(fkTableName);

        ForeignKey fk = fTable.getColumns().get(foreignColumn).transformToFK();
        fTable.getColumns().put(foreignColumn, fk);
        fTable.getForeignKeys().put(foreignColumn, fk);
        // increase the width of the table so that FK->table.column will fit
        // also
        int newWidth = CHAR_WIDTH * parentColumn.length() + CHAR_WIDTH * t.getName().length() + PAD_WIDTH
                + 8 * CHAR_WIDTH + CHAR_WIDTH * foreignColumn.length();
        if (newWidth > fTable.getWidth())
            fTable.setWidth(newWidth);
        t.getReferencingTables().put(fTable.getName(), fTable);
        fk.setReferencedColumn(parentColumn);
        fk.setReferencedTable(t.getName());
        fk.setUpdateRule(rs.getString("UPDATE_RULE"));
        fk.setDeleteRule(rs.getString("DELETE_RULE"));
        try {
            fk.setReference(t.getColumns().get(parentColumn));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.qualogy.qafe.business.integration.rdb.SQLQueryDAO.java

/**
 * @param ds/*  ww  w.  ja  v a2 s.c om*/
 * @param tableName
 * @throws SQLException
 */
private void populateTableColumnSet(DataSource ds, String tableName) throws SQLException {
    Connection conn = ds.getConnection();
    DatabaseMetaData dbmd = conn.getMetaData();
    ResultSet rsc = dbmd.getColumns(conn.getCatalog(), null, tableName, "%");
    Set<String> foundColumnSet = new HashSet<String>();
    while (rsc.next()) {
        String columnName = rsc.getString("COLUMN_NAME");
        foundColumnSet.add(columnName);
    }
    tableColumnSet.put(tableName, foundColumnSet);
    DataSourceUtils.releaseConnection(conn, ds);
}

From source file:azkaban.database.AzkabanDatabaseSetup.java

private void loadInstalledTables() throws SQLException {
    logger.info("Searching for installed tables");
    Connection conn = null;
    try {/* ww w  .java2 s .  c  o m*/
        conn = dataSource.getConnection();
        ResultSet rs = conn.getMetaData().getTables(conn.getCatalog(), null, null, new String[] { "TABLE" });

        while (rs.next()) {
            tables.put(rs.getString("TABLE_NAME").toLowerCase(), "2.1");
        }
    } finally {
        DbUtils.commitAndCloseQuietly(conn);
    }
}

From source file:jp.co.tis.gsp.tools.dba.dialect.MysqlDialect.java

@Override
public void createUser(String user, String password, String adminUser, String adminPassword)
        throws MojoExecutionException {
    Connection conn = null;
    Statement stmt = null;//from ww  w.j a  v  a 2  s  . co m
    try {
        conn = DriverManager.getConnection(url, adminUser, adminPassword);
        stmt = conn.createStatement();
        String db = normalizeSchemaName(conn.getCatalog());

        if (existsUser(conn, user)) {
            // ???????????????
            stmt.execute("GRANT ALL ON " + db + ".* TO '" + user + "'");
            return;
        }
        stmt.execute("CREATE USER '" + user + "' IDENTIFIED BY '" + password + "'");
        stmt.execute("GRANT ALL ON " + db + ".* TO '" + user + "'");
    } catch (SQLException e) {
        throw new MojoExecutionException("CREATE USER?", e);
    } finally {
        StatementUtil.close(stmt);
        ConnectionUtil.close(conn);
    }
}

From source file:com.netflix.metacat.connector.snowflake.SnowflakeConnectorTableService.java

/**
 * {@inheritDoc}// w w w . j  av a 2s . co m
 */
@Override
protected ResultSet getTables(@Nonnull @NonNull final Connection connection,
        @Nonnull @NonNull final QualifiedName name, @Nullable final QualifiedName prefix) throws SQLException {
    final String schema = name.getDatabaseName();
    final DatabaseMetaData metaData = connection.getMetaData();
    return prefix == null || StringUtils.isEmpty(prefix.getTableName())
            ? metaData.getTables(connection.getCatalog(), schema, null, TABLE_TYPES)
            : metaData.getTables(connection.getCatalog(), schema,
                    prefix.getTableName() + JdbcConnectorUtils.MULTI_CHARACTER_SEARCH, TABLE_TYPES);
}

From source file:net.certifi.audittablegen.AuditTableGen.java

/**
 * Validates the provided dataSource and gets a DataSourceDMR
 * object to manage database interaction.  Sets initialized flag
 * to true if initialization is successful.
 * @throws SQLException /*from  w w  w  .  j  a va  2s.  com*/
 */
void initialize() throws SQLException {

    Connection connection = dataSource.getConnection();
    //Properties connectionProperties = connection.getClientInfo();
    DatabaseMetaData dmd = connection.getMetaData();

    logger.debug("DatabaseProduct: {}", dmd.getDatabaseProductName());

    try {
        catalog = connection.getCatalog();

        if (schema.isEmpty() || schema == null) {
            try {
                schema = connection.getSchema();
            } catch (AbstractMethodError e) {
                logger.error("Abstract method getSchema() not implemented", e);
                schema = "";
            }
        }
    } catch (SQLException e) {
        logger.error("Error getting catalog/schema", e);

    }

    if (dmd.getDriverName().toLowerCase().contains("postgresql")) {
        dmr = new PostgresqlDMR(dataSource, schema);
        //known dataSource with specific implementation requirements
        //ie PostgrresDMR, HsqldbDMR...            
    } else if (dmd.getDriverName().toLowerCase().contains("hsqldb")) {
        dmr = new HsqldbDMR(dataSource, schema);
        //known dataSource with specific implementation requirements
        //ie PostgrresDMR, HsqldbDMR...            
    } else {
        //generic implementation
        dmr = new GenericDMR(dataSource, schema);
        logger.info("attempting to run against unknown database product");
    }

    if (dmr != null) {
        this.initialized = true;
    }

    if (schema != null && !schema.isEmpty()) {
        dmr.setSchema(schema);

        if (dmr.getSchema() == null) {
            throw new RuntimeException("Schema could not be found.");
        }
    }

}

From source file:com.adaptris.jdbc.connection.FailoverDatasourceTest.java

@Test
public void testInfo() throws Exception {
    Connection conn = new MyProxy();

    try {//from   w ww. j a v a 2s.co  m
        try {
            conn.getMetaData();
        } catch (SQLException e) {

        }
        try {
            conn.setCatalog(conn.getCatalog());
        } catch (SQLException e) {

        }
        try {
            conn.setReadOnly(conn.isReadOnly());
        } catch (SQLException e) {

        }
        try {
            conn.setTransactionIsolation(conn.getTransactionIsolation());
        } catch (SQLException e) {

        }
        try {
            conn.setTransactionIsolation(conn.getTransactionIsolation());
        } catch (SQLException e) {

        }
        try {
            conn.getWarnings();
        } catch (SQLException e) {

        }
        try {
            conn.clearWarnings();
        } catch (SQLException e) {

        }
        try {
            conn.setHoldability(conn.getHoldability());
        } catch (SQLException e) {

        }

        try {
            conn.setSchema(conn.getSchema());
        } catch (SQLException e) {

        }

    } finally {
        JdbcUtil.closeQuietly(conn);
    }

}