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:org.verdictdb.connection.JdbcConnection.java

public static JdbcConnection create(Connection conn) throws VerdictDBDbmsException {
    String connectionString = null;
    try {//from  ww  w  .ja  v  a2 s.c  om
        connectionString = conn.getMetaData().getURL();
    } catch (SQLException e) {
        throw new VerdictDBDbmsException(e);
    }

    SqlSyntax syntax = SqlSyntaxList.getSyntaxFromConnectionString(connectionString);

    // This is temporary fix to have 'memory' catalog connection for unit tests
    try {
        if (syntax instanceof PrestoHiveSyntax && conn.getCatalog() != null
                && conn.getCatalog().equalsIgnoreCase("memory")) {
            syntax = new PrestoMemorySyntax();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

    JdbcConnection jdbcConn = null;
    if (syntax instanceof PrestoSyntax) {
        // To handle that Presto's JDBC driver is not compatible with JDK7,
        // we use Java's reflection-based instantiation.
        try {
            Class<?> prestoConnClass = Class.forName("org.verdictdb.connection.PrestoJdbcConnection");
            Constructor<?> prestoConnClsConstructor = prestoConnClass.getConstructor(Connection.class,
                    SqlSyntax.class);
            jdbcConn = (JdbcConnection) prestoConnClsConstructor.newInstance(conn, syntax);
            Method ensureMethod = prestoConnClass.getMethod("ensureCatalogSet");
            ensureMethod.invoke(jdbcConn);
        } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException
                | IllegalAccessException | IllegalArgumentException e) {
            throw new RuntimeException("Instantiating PrestoJdbcConnection failed.");

        } catch (InvocationTargetException e) {
            if (e.getTargetException() instanceof VerdictDBDbmsException) {
                throw new VerdictDBDbmsException(e.getMessage());
            } else {
                throw new RuntimeException("Instantiating PrestoJdbcConnection failed.");
            }
        }
    } else {
        jdbcConn = new JdbcConnection(conn, syntax);
    }

    return jdbcConn;
}

From source file:org.vivoweb.harvester.util.DatabaseClone.java

/**
 * Clone a database/*from   www.j a v a2s  .  co  m*/
 * @throws SQLException error connecting
 * @throws DatabaseUnitException error
 * @throws IOException error resolving connections
 */
public void execute() throws SQLException, DatabaseUnitException, IOException {
    String[] tableTypes = new String[] { "TABLE" };
    if (this.dbUnitFeatures != null) {
        for (String feature : this.dbUnitFeatures.keySet()) {
            if (feature.trim().equals("http://www.dbunit.org/properties/tableType")) {
                tableTypes = this.dbUnitFeatures.get(feature).toString().split(",");
            }
        }
    }
    IDataSet data = getDataSet();
    if (this.db2 != null) {
        log.info("Preparing Output Database");
        Connection db1conn = this.db1.getConnection();
        Connection db2conn = this.db2.getConnection();
        Map<Integer, Map<String, String>> inputDbTypes = getDbTypes(db1conn, "input");
        Map<Integer, Map<String, String>> outputDbTypes = getDbTypes(db2conn, "output");
        ResultSet tableData = db2conn.getMetaData().getTables(db2conn.getCatalog(), null, "%", tableTypes);
        while (tableData.next()) {
            String db2tableName = tableData.getString("TABLE_NAME");
            for (String db1table : data.getTableNames()) {
                if (db1table.trim().equalsIgnoreCase(db2tableName.trim())) {
                    log.debug("Droping table '" + db2tableName + "' from output database");
                    String sql = "DROP TABLE " + db2tableName;
                    log.trace("Drop Table SQL Query:\n" + sql);
                    db2conn.createStatement().executeUpdate(sql);
                }
            }
        }
        for (String table : data.getTableNames()) {
            // get record set
            log.debug("Creating table '" + table + "' in output database");
            ResultSet columnRS = db1conn.getMetaData().getColumns(null, null, table, null);
            int count = 0;
            StringBuilder createTableSB = new StringBuilder();
            createTableSB.append("CREATE TABLE " + table + " (");
            while (columnRS.next()) {
                if (columnRS.getString("TABLE_NAME").equals(table)) {
                    String colName = columnRS.getString("COLUMN_NAME");
                    log.debug("Getting column information for '" + colName + "'");
                    Integer typeCode = Integer.valueOf(columnRS.getInt("DATA_TYPE"));
                    int size = columnRS.getInt("COLUMN_SIZE");
                    if (!outputDbTypes.containsKey(typeCode)) {
                        if (typeCode.intValue() == Types.BIT) {
                            typeCode = Integer.valueOf(Types.BOOLEAN);
                            size = 0;
                        } else { //TODO: more type conversion issues possible, make this if/else more exhaustive
                            if (inputDbTypes.containsKey(typeCode)) {
                                log.warn("Output database does not support datatype '"
                                        + inputDbTypes.get(typeCode).get("TYPE_NAME") + "': using VARCHAR");
                            } else {
                                log.error("Unknown datatype code '" + typeCode + "': using VARCHAR");
                            }
                            typeCode = Integer.valueOf(Types.VARCHAR);
                        }
                    } else {
                        //                     log.trace("typeCode: "+typeCode);
                    }
                    Map<String, String> map = outputDbTypes.get(typeCode);
                    String typeName = map.get("TYPE_NAME");
                    String params = map.get("CREATE_PARAMS");
                    if (StringUtils.isBlank(params)) {
                        params = map.get("PARAMS");
                    }
                    boolean needParam = (StringUtils.isNotBlank(params) && (size != 0));
                    //                  log.trace("column '"+colName+"': "+typeCode+" => '"+typeName+((needParam)?"("+size+")":"")+"'");
                    if (count != 0) {
                        createTableSB.append(',');
                    }
                    createTableSB.append("\n  ");
                    createTableSB.append(colName);
                    createTableSB.append(" ");
                    createTableSB.append(typeName);
                    if (needParam) {
                        createTableSB.append("(");
                        createTableSB.append(size);
                        createTableSB.append(")");
                    }
                    count++;
                }
            }
            createTableSB.append("\n)");
            log.trace("Create Table SQL Query:\n" + createTableSB);
            db2conn.createStatement().executeUpdate(createTableSB.toString());
        }
        log.info("Dumping Dataset To Output");
        DatabaseOperation.INSERT.execute(this.db2, data);
        log.info("Dataset Output Complete");
    }
    if (this.outFile != null) {
        FlatDtdDataSet.write(data, this.outFile);
    }
}

From source file:org.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java

/**
 * This method initializes metadata./*from   ww  w .j ava 2  s  .  c om*/
 *
 * @throws ODataServiceFault
 */
private void initializeMetaData() throws ODataServiceFault {
    this.tableMetaData = new HashMap<>();
    this.primaryKeys = new HashMap<>();
    this.navigationProperties = new HashMap<>();
    Connection connection = null;
    try {
        connection = initializeConnection();
        DatabaseMetaData metadata = connection.getMetaData();
        String catalog = connection.getCatalog();
        for (String tableName : this.tableList) {
            this.tableMetaData.put(tableName, readTableColumnMetaData(tableName, metadata));
            this.navigationProperties.put(tableName, readForeignKeys(tableName, metadata, catalog));
            this.primaryKeys.put(tableName, readTablePrimaryKeys(tableName, metadata, catalog));
        }
    } catch (SQLException e) {
        throw new ODataServiceFault(e, "Error in reading tables from the database. :" + e.getMessage());
    } finally {
        releaseConnection(connection);
    }
}

From source file:org.wso2.carbon.event.output.adaptor.mysql.MysqlEventAdaptorType.java

private TableInfo initializeDatabaseTableInfo(String tableName, String executionMode, String updateColumnKeys,
        Object message, OutputEventAdaptorConfiguration adaptorConfig) throws SQLException {
    TableInfo tableInfo = new TableInfo();
    tableInfo.setTableName(tableName);/* w w w .  ja v a  2s . c om*/
    if (resourceBundle.getString(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_EXECUTION_MODE_UPDATE)
            .equalsIgnoreCase(executionMode)) {
        tableInfo.setUpdateMode(true);
    }
    Connection con = null;
    Statement stmt = null;

    try {
        DataSource dataSource = pooledDataSources.get(adaptorConfig.getOutputProperties()
                .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_DATASOURCE_NAME));
        if (dataSource == null) {
            CarbonDataSource carbonDataSource = EventAdaptorValueHolder.getDataSourceService()
                    .getDataSource(adaptorConfig.getOutputProperties()
                            .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_DATASOURCE_NAME));
            if (carbonDataSource == null) {
                throw new OutputEventAdaptorEventProcessingException(
                        "There is no any data-source found called : " + adaptorConfig.getOutputProperties()
                                .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_DATASOURCE_NAME));
            } else {
                dataSource = (DataSource) carbonDataSource.getDSObject();
                pooledDataSources.put(adaptorConfig, dataSource);
            }
        }

        con = dataSource.getConnection();
        String databaseName = con.getCatalog();
        tableInfo.setDatabaseName(databaseName);

        // create the table.
        StringBuilder statementBuilder = new StringBuilder("CREATE TABLE IF NOT EXISTS ");
        statementBuilder.append(databaseName + "." + tableName);
        statementBuilder.append(" (");
        boolean appendComma = false;
        for (Map.Entry<String, Object> entry : (((Map<String, Object>) message).entrySet())) {
            if (appendComma) {
                statementBuilder.append(",");
            } else {
                appendComma = true;
            }
            statementBuilder.append(entry.getKey()).append("  ");
            if (entry.getValue() instanceof Integer) {
                statementBuilder.append("INT");
            } else if (entry.getValue() instanceof Long) {
                statementBuilder.append("BIGINT");
            } else if (entry.getValue() instanceof Float) {
                statementBuilder.append("FLOAT");
            } else if (entry.getValue() instanceof Double) {
                statementBuilder.append("DOUBLE");
            } else if (entry.getValue() instanceof String) {
                statementBuilder.append("VARCHAR(255)");
            } else if (entry.getValue() instanceof Boolean) {
                statementBuilder.append("BOOL");
            }
        }
        statementBuilder.append(")");

        stmt = con.createStatement();
        stmt.execute("CREATE SCHEMA IF NOT EXISTS " + databaseName);
        stmt.executeUpdate(statementBuilder.toString());

        ArrayList<Attribute> tableInsertColumnList = new ArrayList<Attribute>();
        statementBuilder = new StringBuilder("INSERT INTO ");
        statementBuilder.append(databaseName + "." + tableName);
        statementBuilder.append(" ( ");

        StringBuilder valuePositionsBuilder = new StringBuilder("");

        appendComma = false;
        DatabaseMetaData databaseMetaData = con.getMetaData();
        ResultSet rs = databaseMetaData.getColumns(databaseName, null, tableName, null);
        while (rs.next()) {
            AttributeType type = null;
            int colType = rs.getInt("DATA_TYPE");
            switch (colType) {
            case Types.VARCHAR:
                type = AttributeType.STRING;
                break;
            case Types.INTEGER:
                type = AttributeType.INT;
                break;
            case Types.BIGINT:
                type = AttributeType.LONG;
                break;
            case Types.DOUBLE:
                type = AttributeType.DOUBLE;
                break;
            case Types.FLOAT:
                type = AttributeType.FLOAT;
                break;
            case Types.TINYINT:
            case Types.BOOLEAN:
            case MysqlEventAdaptorConstants.TINYINT_MYSQL_VALUE:
                type = AttributeType.BOOL;
                break;

            }
            Attribute attribute = new Attribute(rs.getString("COLUMN_NAME"), type);
            tableInsertColumnList.add(attribute);

            if (appendComma) {
                statementBuilder.append(",");
                valuePositionsBuilder.append(",");
            } else {
                appendComma = true;
            }
            statementBuilder.append(attribute.getName());
            valuePositionsBuilder.append("?");
        }
        statementBuilder.append(") VALUES (");
        statementBuilder.append(valuePositionsBuilder.toString());
        statementBuilder.append(")");
        tableInfo.setPreparedInsertStatement(statementBuilder.toString());
        tableInfo.setInsertColumnOrder(tableInsertColumnList);

        if (executionMode.equalsIgnoreCase(
                resourceBundle.getString(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_EXECUTION_MODE_UPDATE))) {

            // existence check query.
            StringBuilder existenceQueryBuilder = new StringBuilder("SELECT 1 FROM ");
            existenceQueryBuilder.append(databaseName + "." + tableName);
            existenceQueryBuilder.append(" WHERE ");
            String[] queryAttributes = updateColumnKeys.trim().split(",");
            ArrayList<Attribute> queryAttributeList = new ArrayList<Attribute>(queryAttributes.length);

            for (int i = 0; i < queryAttributes.length; i++) {
                if (i > 0) {
                    existenceQueryBuilder.append(" AND ");
                }
                existenceQueryBuilder.append(queryAttributes[i]);
                existenceQueryBuilder.append(" = ? ");
                for (Attribute at : tableInfo.getInsertColumnOrder()) {
                    if (queryAttributes[i].equalsIgnoreCase(at.getName())) {
                        queryAttributeList.add(at);
                        break;
                    }
                }
            }
            tableInfo.setExistenceCheckColumnOrder(queryAttributeList);
            tableInfo.setPreparedExistenceCheckStatement(existenceQueryBuilder.toString());

            // update query.
            StringBuilder updateQueryBuilder = new StringBuilder("UPDATE  ");
            ArrayList<Attribute> updateAttributes = new ArrayList<Attribute>();
            updateQueryBuilder.append(tableInfo.getDatabaseName() + "." + tableInfo.getTableName());
            updateQueryBuilder.append(" SET ");
            appendComma = false;
            for (Attribute at : tableInfo.getInsertColumnOrder()) {
                if (!tableInfo.getExistenceCheckColumnOrder().contains(at)) {
                    if (appendComma) {
                        updateQueryBuilder.append(" , ");
                    }
                    updateQueryBuilder.append(at.getName());
                    updateQueryBuilder.append(" = ? ");
                    updateAttributes.add(at);
                    appendComma = true;
                }
            }
            updateQueryBuilder.append(" WHERE ");
            boolean appendAnd = false;
            for (Attribute at : tableInfo.getExistenceCheckColumnOrder()) {
                if (appendAnd) {
                    updateQueryBuilder.append(" AND ");
                }
                updateQueryBuilder.append(at.getName());
                updateQueryBuilder.append(" = ? ");
                updateAttributes.add(at);
                appendAnd = true;
            }
            tableInfo.setUpdateColumnOrder(updateAttributes);
            tableInfo.setPreparedUpdateStatement(updateQueryBuilder.toString());

        }
        return tableInfo;
    } catch (SQLException e) {
        pooledDataSources.remove(adaptorConfig.getOutputProperties()
                .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_DATASOURCE_NAME));
        log.error("error while initializing the table", e);
    } catch (DataSourceException e) {
        pooledDataSources.remove(adaptorConfig.getOutputProperties()
                .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_DATASOURCE_NAME));
        log.error("error while accessing the datasource:", e);
    } finally {
        cleanupConnections(stmt, con);
    }
    return null;
}

From source file:org.xenei.bloomgraph.bloom.MysqlBigLoadTest.java

@Override
protected BloomIO getBloomIO() throws SQLException {
    LoggingConfig.setLogger("org.xenei.bloomgraph.bloom", Level.INFO);

    final DataSource ds = MySQLBloomGraphTest.getMySQLDataSource(URL, USR, PWD);
    final Connection c = ds.getConnection();
    final Statement stmt = c.createStatement();
    ResultSet rs = null;/*from  ww  w . j a  v a  2s  . c o m*/
    try {
        final SQLCommands sqlCmd = new MySQLCommands();
        final DatabaseMetaData metaData = c.getMetaData();
        rs = metaData.getTables(c.getCatalog(), c.getSchema(), sqlCmd.getPageIndexTableName(),
                new String[] { "TABLE" });
        while (rs.next()) {
            stmt.execute("TRUNCATE " + rs.getString(3));
        }
        DbUtils.closeQuietly(rs);
        rs = metaData.getTables(c.getCatalog(), c.getSchema(), sqlCmd.getPageStatsTableName(),
                new String[] { "TABLE" });
        while (rs.next()) {
            stmt.execute("TRUNCATE " + rs.getString(3));
        }
        DbUtils.closeQuietly(rs);
        rs = metaData.getTables(c.getCatalog(), c.getSchema(), "Page\\_%", new String[] { "TABLE" });
        while (rs.next()) {
            stmt.execute("DROP TABLE " + rs.getString(3));
        }
        return new DBIO(ds, sqlCmd);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(c);
    }
}

From source file:org.xenei.bloomgraph.bloom.MySQLBloomGraphTest.java

@Override
protected BloomIO getBloomIO() throws SQLException {
    final DataSource ds = getMySQLDataSource(URL, USR, PWD);
    final Connection c = ds.getConnection();
    final Statement stmt = c.createStatement();
    ResultSet rs = null;//from   w w w  .ja  va 2  s .  c  o  m
    try {
        final SQLCommands sqlCmd = new MySQLCommands();
        final DatabaseMetaData metaData = c.getMetaData();
        rs = metaData.getTables(c.getCatalog(), c.getSchema(), sqlCmd.getPageIndexTableName(),
                new String[] { "TABLE" });
        while (rs.next()) {
            stmt.execute("TRUNCATE " + rs.getString(3));
        }
        DbUtils.closeQuietly(rs);
        rs = metaData.getTables(c.getCatalog(), c.getSchema(), sqlCmd.getPageStatsTableName(),
                new String[] { "TABLE" });
        while (rs.next()) {
            stmt.execute("TRUNCATE " + rs.getString(3));
        }
        DbUtils.closeQuietly(rs);
        rs = metaData.getTables(c.getCatalog(), c.getSchema(), "Page\\_%", new String[] { "TABLE" });
        while (rs.next()) {
            stmt.execute("DROP TABLE " + rs.getString(3));
        }
        return new DBIO(ds, sqlCmd);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(c);
    }
}

From source file:org.xenei.bloomgraph.bloom.sql.MySQLCommands.java

/**
 * Create any necessary procedures.//from  w  w w  .j  a v  a2 s . c  o  m
 * 
 * @param metadata
 *            the metadata for the database.
 * @throws SQLException
 *             on error
 */
private void createProcedures(final DatabaseMetaData metadata) throws SQLException {
    ResultSet rs = null;
    Statement stmt = null;
    final Connection connection = metadata.getConnection();
    try {
        rs = metadata.getProcedures(connection.getCatalog(), connection.getSchema(), "add_triple");
        if (!rs.next()) {
            stmt = connection.createStatement();
            stmt.executeUpdate(CREATE_ADD_TRIPLE_PROCEDURE);
        }
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(stmt);
    }
}

From source file:org.xenei.bloomgraph.bloom.sql.MySQLCommands.java

/**
 * Create the page index table./*from   ww  w.  j av a 2 s . com*/
 * 
 * @param metadata
 *            the metadata for the database.
 * @throws SQLException
 */
private void createPageIndexTable(final DatabaseMetaData metadata) throws SQLException {
    ResultSet rs = null;
    Statement stmt = null;
    final Connection connection = metadata.getConnection();
    try {
        rs = metadata.getTables(connection.getCatalog(), connection.getSchema(), getPageIndexTableName(),
                new String[] { "TABLE" });
        if (!rs.next()) {
            // table does not exist
            stmt = connection.createStatement();

            stmt.executeUpdate(CREAT_PAGE_INDEX_TABLE_FMT);
            String stmtStr = String.format(CREATE_PAGE_INDX_TRIGGER, "INSERT");
            stmt.executeUpdate(stmtStr);
            stmtStr = String.format(CREATE_PAGE_INDX_TRIGGER, "UPDATE");
            stmt.executeUpdate(stmtStr);
        }
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(stmt);
    }
}

From source file:org.xenei.bloomgraph.bloom.sql.MySQLCommands.java

/**
 * Create the page stats table.//from ww  w .j  a  v  a2 s  . c o  m
 * 
 * @param metadata
 *            the metadata for the database.
 * @throws SQLException
 *             on error
 */
private void createPageStatsTable(final DatabaseMetaData metadata) throws SQLException {
    ResultSet rs = null;
    Statement stmt = null;
    final Connection connection = metadata.getConnection();
    try {
        rs = metadata.getTables(connection.getCatalog(), connection.getSchema(), getPageStatsTableName(),
                new String[] { "TABLE" });
        if (!rs.next()) {
            stmt = connection.createStatement();
            stmt.execute(
                    "CREATE TABLE PageStats ( idx INT PRIMARY KEY, records INT, deletes INT, bytes INT ) ENGINE MyISAM");
        }
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(stmt);
    }
}

From source file:uk.ac.ed.epcc.webapp.model.data.Repository.java

/** Set the table References for the fields  
 * /*w  w  w  .  j av  a2s  . c o  m*/
 * @param ctx
 * @param c
 * @throws SQLException 
 */
private void setReferences(AppContext ctx, Connection c) throws SQLException {
    //Logger log = ctx.getService(LoggerService.class).getLogger(getClass());
    //log.debug("SetReferences for "+getTable());
    // look for foreign keys to identify remote tables.
    DatabaseMetaData meta = c.getMetaData();
    ResultSet rs = meta.getImportedKeys(c.getCatalog(), null, table_name);
    if (rs.first()) {
        //log.debug("Have foreign key");
        do {
            String field = rs.getString("FKCOLUMN_NAME");
            String table = rs.getString("PKTABLE_NAME");
            String key_name = rs.getString("FK_NAME");
            short seq = rs.getShort("KEY_SEQ");
            if (seq == 1) {
                FieldInfo info = fields.get(field);
                if (info.isNumeric()) {
                    String name = REFERENCE_PREFIX + param_name + "." + info.getName(false);
                    table = ctx.getInitParameter(name, table); // use param in preference because of windows case mangle
                    String tag = TableToTag(ctx, table);
                    //log.debug("field "+field+" references "+table);
                    info.setReference(true, key_name, tag);
                }
            }
        } while (rs.next());
    }
    // now try explicit references set from properties
    for (FieldInfo i : fields.values()) {
        if (i.getReferencedTable() == null) {
            //use param name for table rename
            String tag = REFERENCE_PREFIX + param_name + "." + i.getName(false);
            String table = ctx.getInitParameter(tag);
            //log.debug("tag "+tag+" resolves to "+table);
            i.setReference(false, null, table);
        }
    }
}