Example usage for java.sql DatabaseMetaData getIdentifierQuoteString

List of usage examples for java.sql DatabaseMetaData getIdentifierQuoteString

Introduction

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

Prototype

String getIdentifierQuoteString() throws SQLException;

Source Link

Document

Retrieves the string used to quote SQL identifiers.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getHSQLConnection();

    DatabaseMetaData md = conn.getMetaData();
    System.out.println(md.getIdentifierQuoteString());

    conn.close();/*  w  w  w  .  ja  v  a2 s.c  o m*/
}

From source file:com.hangum.tadpole.engine.manager.TadpoleSQLManager.java

/**
 * ? DB? metadata ?.//from   ww w.  ja va2s .co m
 * 
 * @param searchKey
 * @param userDB
 * @param dbMetadata
 * @return
 */
public static void setMetaData(String searchKey, final UserDBDAO userDB, DatabaseMetaData dbMetaData)
        throws Exception {
    //  ??  .
    if (userDB.getDBDefine() == DBDefine.TADPOLE_SYSTEM_DEFAULT
            || userDB.getDBDefine() == DBDefine.TADPOLE_SYSTEM_MYSQL_DEFAULT)
        return;

    String strIdentifierQuoteString = "";
    try {
        strIdentifierQuoteString = dbMetaData.getIdentifierQuoteString();
    } catch (Exception e) {
        // ignore exception, not support quoteString
    }

    // https://github.com/hangum/TadpoleForDBTools/issues/412 ? ??  .
    TadpoleMetaData tadpoleMetaData = null;
    switch (userDB.getDBDefine()) {
    case ORACLE_DEFAULT:
    case TIBERO_DEFAULT:
        tadpoleMetaData = new TadpoleMetaData(strIdentifierQuoteString,
                TadpoleMetaData.STORES_FIELD_TYPE.LOWCASE_BLANK);
        break;
    case MSSQL_DEFAULT:
    case MSSQL_8_LE_DEFAULT:
    case MYSQL_DEFAULT:
    case MARIADB_DEFAULT:
    case SQLite_DEFAULT:
        tadpoleMetaData = new TadpoleMetaData(strIdentifierQuoteString,
                TadpoleMetaData.STORES_FIELD_TYPE.BLANK);
        break;
    case POSTGRE_DEFAULT:
    case TAJO_DEFAULT:
        tadpoleMetaData = new TadpoleMetaData(strIdentifierQuoteString,
                TadpoleMetaData.STORES_FIELD_TYPE.UPPERCASE_BLANK);
        break;
    default:
        tadpoleMetaData = new TadpoleMetaData(strIdentifierQuoteString, TadpoleMetaData.STORES_FIELD_TYPE.NONE);
    }

    //      SQLConstantFactory factory = new SQLConstantFactory();
    //      SQLConstants sqlConstants = factory.getDB(userDB);
    //      tmd.setKeywords(
    //            StringUtils.replace(
    //                  sqlConstants.keyword() + "|" + sqlConstants.function() + "|" + sqlConstants.constant() + "|" +sqlConstants.variable(),
    //                  "|",
    //                  ","
    //                  )
    //            );
    // set keyword
    if (userDB.getDBDefine() == DBDefine.SQLite_DEFAULT) {
        // not support keyword http://sqlite.org/lang_keywords.html
        tadpoleMetaData.setKeywords(StringUtils.join(SQLConstants.QUOTE_SQLITE_KEYWORDS, ","));
    } else if (userDB.getDBDefine() == DBDefine.MYSQL_DEFAULT | userDB.getDBDefine() == DBDefine.MYSQL_DEFAULT
            | userDB.getDBDefine() == DBDefine.ORACLE_DEFAULT
            | userDB.getDBDefine() == DBDefine.TIBERO_DEFAULT) {
        String strFullKeywords = StringUtils.join(SQLConstants.QUOTE_MYSQL_KEYWORDS, ",") + "," + dbMetadata;
        tadpoleMetaData.setKeywords(strFullKeywords);
    } else if (userDB.getDBDefine() == DBDefine.MONGODB_DEFAULT) {
        // not support this method
        tadpoleMetaData.setKeywords("");
    } else if (userDB.getDBDefine() == DBDefine.MSSQL_8_LE_DEFAULT
            || userDB.getDBDefine() == DBDefine.MSSQL_DEFAULT) {
        String strFullKeywords = StringUtils.join(SQLConstants.QUOTE_MSSQL_KEYWORDS, ",") + ","
                + dbMetaData.getSQLKeywords();
        tadpoleMetaData.setKeywords(strFullKeywords);
    } else {
        tadpoleMetaData.setKeywords(dbMetaData.getSQLKeywords());
    }

    tadpoleMetaData.setDbMajorVersion(dbMetaData.getDatabaseMajorVersion());
    tadpoleMetaData.setMinorVersion(dbMetaData.getDatabaseMinorVersion());
    dbMetadata.put(searchKey, tadpoleMetaData);
}

From source file:net.ontopia.topicmaps.cmdlineutils.rdbms.RDBMSIndexTool.java

protected static Map getPrimaryKeys(String table_name, DatabaseMetaData dbm) throws SQLException {
    // returns { table_name(colname,...) : index_name }
    Map result = new HashMap(5);
    ResultSet rs = dbm.getPrimaryKeys(null, null, table_name);
    String prev_index_name = null;
    String columns = null;//from  ww  w.j ava2  s .  c  o  m

    while (rs.next()) {
        String index_name = rs.getString(6);
        if (prev_index_name != null && !prev_index_name.equals(index_name)) {
            result.put(table_name + '(' + columns + ')', prev_index_name);
            columns = null;
        }
        // column_name might be quoted, so unquote it before proceeding
        String column_name = unquote(rs.getString(4), dbm.getIdentifierQuoteString());
        if (columns == null)
            columns = column_name;
        else
            columns = columns + "," + column_name;

        prev_index_name = index_name;
    }
    rs.close();

    if (prev_index_name != null)
        result.put(table_name + '(' + columns + ')', prev_index_name);

    return result;
}

From source file:net.ontopia.topicmaps.cmdlineutils.rdbms.RDBMSIndexTool.java

protected static Map getIndexes(String table_name, DatabaseMetaData dbm) throws SQLException {
    // returns { table_name(colname,...) : index_name }
    Map result = new HashMap(5);
    ResultSet rs = dbm.getIndexInfo(null, null, table_name, false, false);
    String prev_index_name = null;
    String columns = null;// w w  w.j a  v a  2  s .  com

    while (rs.next()) {
        String index_name = rs.getString(6);

        if (prev_index_name != null && !prev_index_name.equals(index_name)) {
            result.put(table_name + '(' + columns + ')', prev_index_name);
            columns = null;
        }
        // column_name might be quoted, so unquote it before proceeding
        String column_name = unquote(rs.getString(9), dbm.getIdentifierQuoteString());

        if (columns == null)
            columns = column_name;
        else
            columns = columns + "," + column_name;

        prev_index_name = index_name;
    }
    rs.close();

    if (prev_index_name != null)
        result.put(table_name + '(' + columns + ')', prev_index_name);

    return result;
}

From source file:com.migratebird.database.IdentifierProcessorFactory.java

/**
 * Determines the string used to quote identifiers to make them case-sensitive. This will use the connections
 * database metadata to determine the quote string.
 *
 * @param customIdentifierQuoteString If not null, it specifies a custom identifier quote string that replaces the one
 *                                    specified by the JDBC DatabaseMetaData object
 * @param dataSource                  The datas ource, not null
 * @return The quote string, null if quoting is not supported
 *//*w  ww.j ava  2s . co  m*/
protected String determineIdentifierQuoteString(String customIdentifierQuoteString, DataSource dataSource) {
    if (customIdentifierQuoteString != null) {
        return trimToNull(customIdentifierQuoteString);
    }

    Connection connection = null;
    try {
        connection = dataSource.getConnection();

        DatabaseMetaData databaseMetaData = connection.getMetaData();
        String quoteString = databaseMetaData.getIdentifierQuoteString();
        return trimToNull(quoteString);

    } catch (SQLException e) {
        throw new DatabaseException("Unable to determine identifier quote string.", e);
    } finally {
        closeQuietly(connection, null, null);
    }
}

From source file:com.jaspersoft.jasperserver.api.engine.common.virtualdatasourcequery.VirtualSQLDataSource.java

private void testConnection() throws SQLException {
    DatabaseMetaData dbMetaData = connection.getMetaData();
    System.out.println("MetaDataConstants.DATASOURCE_VENDOR = [" + dbMetaData.getDatabaseProductName() + "]");
    System.out.println("MetaDataConstants.NAME_QUOTE_CHAR = [" + dbMetaData.getIdentifierQuoteString() + "]");
    Set set = discoverSchemas(connection);
    for (Object val : set)
        System.out.println("SCHEMA = " + val);
}

From source file:com.nextep.designer.sqlclient.ui.services.impl.SQLClientService.java

@Override
public void deleteQueryValue(ISQLQuery query, ISQLRowResult row) throws SQLException {
    ISQLRowModificationStatus status = computeRowModificationStatus(query, row, -1);
    if (status.isModifiable()) {
        final ISQLResult result = query.getResult();
        final Connection conn = query.getConnection();
        final DatabaseMetaData md = conn.getMetaData();
        final String deleteStmt = buildDeleteStatement(status, md.getIdentifierQuoteString());
        PreparedStatement stmt = null;
        try {//w w  w . j  a v  a  2  s  .co m
            stmt = conn.prepareStatement(deleteStmt);
            fillPreparedStatement(stmt, false, false, row, null);
            stmt.execute();
            if (stmt.getUpdateCount() > 0) {
                result.removeRow(row);
            }
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }

    }

}

From source file:mondrian.spi.impl.JdbcDialectImpl.java

protected String deduceIdentifierQuoteString(DatabaseMetaData databaseMetaData) {
    try {/*from www .j  a v a 2 s .c o m*/
        final String quoteIdentifierString = databaseMetaData.getIdentifierQuoteString();
        return "".equals(quoteIdentifierString)
                // quoting not supported
                ? null
                : quoteIdentifierString;
    } catch (SQLException e) {
        throw Util.newInternal(e, "while quoting identifier");
    }
}

From source file:com.nextep.designer.sqlclient.ui.services.impl.SQLClientService.java

@Override
public ISQLRowModificationStatus updateQueryValue(ISQLQuery query, ISQLRowResult row, int modifiedColumnIndex,
        Object newValue) throws SQLException {
    final Connection conn = query.getConnection();
    final DatabaseMetaData md = conn.getMetaData();
    // For pending rows, we set the new column value
    if (row.isPending()) {
        row.setValue(modifiedColumnIndex, newValue);
    }/*ww w.  ja  v  a  2 s.com*/
    final ISQLRowModificationStatus status = computeRowModificationStatus(query, row, modifiedColumnIndex);
    // Now processing database update if we can
    if (status.isModifiable()) {
        // Now we can build our query
        String sqlStatement = null;
        final boolean insertNeeded = status.isInsertNeeded();
        if (insertNeeded) {
            sqlStatement = buildInsertStatement(status, md.getIdentifierQuoteString());
        } else {
            sqlStatement = buildUpdateStatement(status, md.getIdentifierQuoteString());
        }
        PreparedStatement stmt = null;
        try {
            stmt = conn.prepareStatement(sqlStatement);
            fillPreparedStatement(stmt, !insertNeeded, insertNeeded, row, newValue);
            stmt.execute();
            // Everything was OK, we can unflag any pending row
            if (row.isPending()) {
                row.setPending(false);
            }
        } finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    LOGGER.error("Unable to close SQL update statement: " + e.getMessage(), e);
                }
            }
        }
    }
    return status;
}

From source file:it.eng.spagobi.meta.initializer.PhysicalModelInitializer.java

public PhysicalModel initialize(String modelName, Connection conn, String connectionName,
        String connectionDriver, String connectionUrl, String connectionUsername, String connectionPassword,
        String connectionDatabaseName, String defaultCatalog, String defaultSchema,
        List<String> selectedTables) {
    PhysicalModel model;//  w ww  .j  a va 2s . c  om
    DatabaseMetaData dbMeta;

    try {
        model = FACTORY.createPhysicalModel();
        model.setName(modelName);

        if (getRootModel() != null) {
            model.setParentModel(getRootModel());
        }

        dbMeta = conn.getMetaData();

        addDatabase(dbMeta, model);
        addCatalog(conn, model, defaultCatalog);
        addSchema(dbMeta, model, defaultSchema);

        addTables(dbMeta, model, selectedTables);

        for (int i = 0; i < model.getTables().size(); i++) {
            addPrimaryKey(dbMeta, model, model.getTables().get(i));
            addForeignKeys(dbMeta, model, model.getTables().get(i));
        }

        getPropertiesInitializer().addProperties(model);

        // Setting Connection properties values
        model.setProperty(PhysicalModelPropertiesFromFileInitializer.CONNECTION_NAME, connectionName);
        logger.debug("PhysicalModel Property: Connection name is [{}]", model.getProperties()
                .get(PhysicalModelPropertiesFromFileInitializer.CONNECTION_NAME).getValue());

        model.setProperty(PhysicalModelPropertiesFromFileInitializer.CONNECTION_DRIVER, connectionDriver);
        logger.debug("PhysicalModel Property: Connection driver is [{}]", model.getProperties()
                .get(PhysicalModelPropertiesFromFileInitializer.CONNECTION_DRIVER).getValue());

        model.setProperty(PhysicalModelPropertiesFromFileInitializer.CONNECTION_URL, connectionUrl);
        logger.debug("PhysicalModel Property: Connection url is [{}]", model.getProperties()
                .get(PhysicalModelPropertiesFromFileInitializer.CONNECTION_URL).getValue());

        model.setProperty(PhysicalModelPropertiesFromFileInitializer.CONNECTION_USERNAME, connectionUsername);
        logger.debug("PhysicalModel Property: Connection username is [{}]", model.getProperties()
                .get(PhysicalModelPropertiesFromFileInitializer.CONNECTION_USERNAME).getValue());

        model.setProperty(PhysicalModelPropertiesFromFileInitializer.CONNECTION_PASSWORD, connectionPassword);
        logger.debug("PhysicalModel Property: Connection password is [{}]", model.getProperties()
                .get(PhysicalModelPropertiesFromFileInitializer.CONNECTION_PASSWORD).getValue());

        model.setProperty(PhysicalModelPropertiesFromFileInitializer.CONNECTION_DATABASENAME,
                connectionDatabaseName);
        logger.debug("PhysicalModel Property: Connection databasename is [{}]", model.getProperties()
                .get(PhysicalModelPropertiesFromFileInitializer.CONNECTION_DATABASENAME).getValue());

        // Quote string identification
        String quote = dbMeta.getIdentifierQuoteString();
        // check if escaping is needed
        if (quote.equals("\"")) {
            quote = "\\\"";
        }
        model.setProperty(PhysicalModelPropertiesFromFileInitializer.CONNECTION_DATABASE_QUOTESTRING, quote);
        logger.debug("PhysicalModel Property: Connection databasequotestring is [{}]", model.getProperties()
                .get(PhysicalModelPropertiesFromFileInitializer.CONNECTION_DATABASE_QUOTESTRING).getValue());

        /*
         * model.getPropertyType("connection.name").setDefaultValue(connectionName); logger.debug("PhysicalModel Property: Connection name is [{}]",
         * model.getPropertyType("connection.name").getDefaultValue());
         * 
         * model.getPropertyType("connection.driver").setDefaultValue(connectionDriver); logger.debug("PhysicalModel Property: Connection driver is [{}]",
         * model.getPropertyType("connection.driver").getDefaultValue());
         * 
         * model.getPropertyType("connection.url").setDefaultValue(connectionUrl); logger.debug("PhysicalModel Property: Connection url is [{}]",
         * model.getPropertyType("connection.url").getDefaultValue());
         * 
         * model.getPropertyType("connection.username").setDefaultValue(connectionUsername);
         * logger.debug("PhysicalModel Property: Connection username is [{}]", model.getPropertyType("connection.username").getDefaultValue());
         * 
         * model.getPropertyType("connection.password").setDefaultValue(connectionPassword);
         * logger.debug("PhysicalModel Property: Connection password is [{}]", model.getPropertyType("connection.password").getDefaultValue());
         * 
         * model.getPropertyType("connection.databasename").setDefaultValue(connectionDatabaseName);
         * logger.debug("PhysicalModel Property: Connection databasename is [{}]", model.getPropertyType("connection.databasename").getDefaultValue());
         * 
         * // Quote string identification String quote = dbMeta.getIdentifierQuoteString(); // check if escaping is needed if (quote.equals("\"")) { quote =
         * "\\\""; } model.getPropertyType("connection.databasequotestring").setDefaultValue(quote);
         * logger.debug("PhysicalModel Property: Connection databasequotestring is [{}]", model.getPropertyType("connection.databasequotestring")
         * .getDefaultValue());
         */
    } catch (Throwable t) {
        throw new RuntimeException("Impossible to initialize physical model", t);
    }

    return model;

}