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:com.amazon.carbonado.repo.jdbc.JDBCStorableIntrospector.java

/**
 * Uses the given database connection to query database metadata. This is
 * used to bind storables to tables, and properties to columns. Other
 * checks are performed to ensure that storable type matches well with the
 * definition in the database./*from w  ww.j  a  v  a  2  s.  com*/
 */
private static <S extends Storable> JDBCStorableInfo<S> examine(StorableInfo<S> mainInfo, Connection con,
        final String searchCatalog, final String searchSchema, SchemaResolver resolver,
        boolean primaryKeyCheckDisabled) throws SQLException, SupportException {
    final DatabaseMetaData meta = con.getMetaData();

    final String databaseProductName = meta.getDatabaseProductName();
    final String userName = meta.getUserName();

    String[] tableAliases;
    if (mainInfo.getAliasCount() > 0) {
        tableAliases = mainInfo.getAliases();
    } else {
        String name = mainInfo.getStorableType().getSimpleName();
        tableAliases = generateAliases(name);
    }

    // Try to find matching table from aliases.
    String catalog = null, schema = null, tableName = null, tableType = null;
    findName: {
        // The call to getTables may return several matching tables. This
        // map defines the "best" table type we'd like to use. The higher
        // the number the better.
        Map<String, Integer> fitnessMap = new HashMap<String, Integer>();
        fitnessMap.put("LOCAL TEMPORARY", 1);
        fitnessMap.put("GLOBAL TEMPORARY", 2);
        fitnessMap.put("VIEW", 3);
        fitnessMap.put("SYSTEM TABLE", 4);
        fitnessMap.put("TABLE", 5);
        fitnessMap.put("ALIAS", 6);
        fitnessMap.put("SYNONYM", 7);

        for (int i = 0; i < tableAliases.length; i++) {
            ResultSet rs = meta.getTables(searchCatalog, searchSchema, tableAliases[i], null);
            try {
                int bestFitness = 0;
                while (rs.next()) {
                    String type = rs.getString("TABLE_TYPE");
                    Integer fitness = fitnessMap.get(type);
                    if (fitness != null) {
                        String rsSchema = rs.getString("TABLE_SCHEM");

                        if (searchSchema == null) {
                            if (userName != null && userName.equalsIgnoreCase(rsSchema)) {
                                // Favor entities whose schema name matches
                                // the user name.
                                fitness += 7;
                            }
                        }

                        if (fitness > bestFitness) {
                            bestFitness = fitness;
                            catalog = rs.getString("TABLE_CAT");
                            schema = rsSchema;
                            tableName = rs.getString("TABLE_NAME");
                            tableType = type;
                        }
                    }
                }
            } finally {
                rs.close();
            }

            if (tableName != null) {
                // Found a match, so stop checking aliases.
                break;
            }
        }
    }

    if (tableName == null && !mainInfo.isIndependent()) {
        StringBuilder buf = new StringBuilder();
        buf.append("Unable to find matching table name for type \"");
        buf.append(mainInfo.getStorableType().getName());
        buf.append("\" by looking for ");
        appendToSentence(buf, tableAliases);
        buf.append(" with catalog " + searchCatalog + " and schema " + searchSchema);
        throw new MismatchException(buf.toString());
    }

    String qualifiedTableName = tableName;
    String resolvedTableName = tableName;

    // Oracle specific stuff...
    // TODO: Migrate this to OracleSupportStrategy.
    if (tableName != null && databaseProductName.toUpperCase().contains("ORACLE")) {
        if ("TABLE".equals(tableType) && searchSchema != null) {
            // Qualified table name references the schema. Used by SQL statements.
            qualifiedTableName = searchSchema + '.' + tableName;
        } else if ("SYNONYM".equals(tableType)) {
            // Try to get the real schema. This call is Oracle specific, however.
            String select = "SELECT TABLE_OWNER,TABLE_NAME " + "FROM ALL_SYNONYMS "
                    + "WHERE OWNER=? AND SYNONYM_NAME=?";
            PreparedStatement ps = con.prepareStatement(select);
            ps.setString(1, schema); // in Oracle, schema is the owner
            ps.setString(2, tableName);
            try {
                ResultSet rs = ps.executeQuery();
                try {
                    if (rs.next()) {
                        schema = rs.getString("TABLE_OWNER");
                        resolvedTableName = rs.getString("TABLE_NAME");
                    }
                } finally {
                    rs.close();
                }
            } finally {
                ps.close();
            }
        }
    }

    // Gather information on all columns such that metadata only needs to
    // be retrieved once.
    Map<String, ColumnInfo> columnMap = new TreeMap<String, ColumnInfo>(String.CASE_INSENSITIVE_ORDER);

    if (resolvedTableName != null) {
        ResultSet rs = meta.getColumns(catalog, schema, resolvedTableName, null);
        rs.setFetchSize(1000);
        try {
            while (rs.next()) {
                ColumnInfo info = new ColumnInfo(rs);
                columnMap.put(info.columnName, info);
            }
        } finally {
            rs.close();
        }
    }

    // Make sure that all properties have a corresponding column.
    Map<String, ? extends StorableProperty<S>> mainProperties = mainInfo.getAllProperties();
    Map<String, String> columnToProperty = new HashMap<String, String>();
    Map<String, JDBCStorableProperty<S>> jProperties = new LinkedHashMap<String, JDBCStorableProperty<S>>(
            mainProperties.size());

    ArrayList<String> errorMessages = new ArrayList<String>();

    for (StorableProperty<S> mainProperty : mainProperties.values()) {
        if (mainProperty.isDerived() || mainProperty.isJoin() || tableName == null) {
            jProperties.put(mainProperty.getName(), new JProperty<S>(mainProperty, primaryKeyCheckDisabled));
            continue;
        }

        String[] columnAliases;
        if (mainProperty.getAliasCount() > 0) {
            columnAliases = mainProperty.getAliases();
        } else {
            columnAliases = generateAliases(mainProperty.getName());
        }

        JDBCStorableProperty<S> jProperty = null;
        boolean addedError = false;

        findName: for (int i = 0; i < columnAliases.length; i++) {
            ColumnInfo columnInfo = columnMap.get(columnAliases[i]);
            if (columnInfo != null) {
                AccessInfo accessInfo = getAccessInfo(mainProperty, columnInfo.dataType,
                        columnInfo.dataTypeName, columnInfo.columnSize, columnInfo.decimalDigits);

                if (accessInfo == null) {
                    TypeDesc propertyType = TypeDesc.forClass(mainProperty.getType());
                    String message = "Property \"" + mainProperty.getName() + "\" has type \""
                            + propertyType.getFullName() + "\" which is incompatible with database type \""
                            + columnInfo.dataTypeName + '"';

                    if (columnInfo.decimalDigits > 0) {
                        message += " (decimal digits = " + columnInfo.decimalDigits + ')';
                    }

                    errorMessages.add(message);
                    addedError = true;
                    break findName;
                }

                if (columnInfo.nullable) {
                    if (!mainProperty.isNullable() && !mainProperty.isIndependent()) {
                        errorMessages.add(
                                "Property \"" + mainProperty.getName() + "\" must have a Nullable annotation");
                    }
                } else {
                    if (mainProperty.isNullable() && !mainProperty.isIndependent()) {
                        errorMessages.add("Property \"" + mainProperty.getName()
                                + "\" must not have a Nullable annotation");
                    }
                }

                boolean autoIncrement = mainProperty.isAutomatic();
                if (autoIncrement) {
                    // Need to execute a little query to check if column is
                    // auto-increment or not. This information is not available in
                    // the regular database metadata prior to jdk1.6.

                    PreparedStatement ps = con.prepareStatement(
                            "SELECT " + columnInfo.columnName + " FROM " + tableName + " WHERE 1=0");

                    try {
                        ResultSet rs = ps.executeQuery();
                        try {
                            autoIncrement = rs.getMetaData().isAutoIncrement(1);
                        } finally {
                            rs.close();
                        }
                    } finally {
                        ps.close();
                    }
                }

                jProperty = new JProperty<S>(mainProperty, columnInfo, autoIncrement, primaryKeyCheckDisabled,
                        accessInfo.mResultSetGet, accessInfo.mPreparedStatementSet, accessInfo.getAdapter());

                break findName;
            }
        }

        if (jProperty != null) {
            jProperties.put(mainProperty.getName(), jProperty);
            columnToProperty.put(jProperty.getColumnName(), jProperty.getName());
        } else {
            if (mainProperty.isIndependent()) {
                jProperties.put(mainProperty.getName(),
                        new JProperty<S>(mainProperty, primaryKeyCheckDisabled));
            } else if (!addedError) {
                StringBuilder buf = new StringBuilder();
                buf.append("Unable to find matching database column for property \"");
                buf.append(mainProperty.getName());
                buf.append("\" by looking for ");
                appendToSentence(buf, columnAliases);
                errorMessages.add(buf.toString());
            }
        }
    }

    if (errorMessages.size() > 0) {
        throw new MismatchException(mainInfo.getStorableType(), errorMessages);
    }

    // Now verify that primary or alternate keys match.

    if (resolvedTableName != null)
        checkPrimaryKey: {
            ResultSet rs;
            try {
                rs = meta.getPrimaryKeys(catalog, schema, resolvedTableName);
            } catch (SQLException e) {
                getLog().info("Unable to get primary keys for table \"" + resolvedTableName + "\" with catalog "
                        + catalog + " and schema " + schema + ": " + e);
                break checkPrimaryKey;
            }

            List<String> pkProps = new ArrayList<String>();

            try {
                while (rs.next()) {
                    String columnName = rs.getString("COLUMN_NAME");
                    String propertyName = columnToProperty.get(columnName);

                    if (propertyName == null) {
                        errorMessages
                                .add("Column \"" + columnName + "\" must be part of primary or alternate key");
                        continue;
                    }

                    pkProps.add(propertyName);
                }
            } finally {
                rs.close();
            }

            if (errorMessages.size() > 0) {
                // Skip any extra checks.
                break checkPrimaryKey;
            }

            if (pkProps.size() == 0) {
                // If no primary keys are reported, don't even bother checking.
                // There's no consistent way to get primary keys, and entities
                // like views and synonyms don't usually report primary keys.
                // A primary key might even be logically defined as a unique
                // constraint.
                break checkPrimaryKey;
            }

            if (matchesKey(pkProps, mainInfo.getPrimaryKey())) {
                // Good. Primary key in database is same as in Storable.
                break checkPrimaryKey;
            }

            // Check if Storable has an alternate key which matches the
            // database's primary key.
            boolean foundAnyAltKey = false;
            for (StorableKey<S> altKey : mainInfo.getAlternateKeys()) {
                if (matchesKey(pkProps, altKey)) {
                    // Okay. Primary key in database matches a Storable
                    // alternate key.
                    foundAnyAltKey = true;

                    // Also check that declared primary key is a strict subset
                    // of the alternate key. If not, keep checking alt keys.

                    if (matchesSubKey(pkProps, mainInfo.getPrimaryKey())) {
                        break checkPrimaryKey;
                    }
                }
            }

            if (foundAnyAltKey) {
                errorMessages.add("Actual primary key matches a declared alternate key, "
                        + "but declared primary key must be a strict subset. "
                        + mainInfo.getPrimaryKey().getProperties() + " is not a subset of " + pkProps);
            } else {
                errorMessages.add("Actual primary key does not match any "
                        + "declared primary or alternate key: " + pkProps);
            }
        }

    if (errorMessages.size() > 0) {
        if (primaryKeyCheckDisabled) {
            for (String errorMessage : errorMessages) {
                getLog().warn("Suppressed error: " + errorMessage);
            }
            errorMessages.clear();
        } else {
            throw new MismatchException(mainInfo.getStorableType(), errorMessages);
        }
    }

    // IndexInfo is empty, as querying for it tends to cause a table analyze to run.
    IndexInfo[] indexInfo = new IndexInfo[0];

    if (needsQuotes(tableName)) {
        String quote = meta.getIdentifierQuoteString();
        if (quote != null && !quote.equals(" ")) {
            tableName = quote + tableName + quote;
            qualifiedTableName = quote + qualifiedTableName + quote;
        }
    }

    return new JInfo<S>(mainInfo, catalog, schema, tableName, qualifiedTableName, indexInfo, jProperties);
}

From source file:org.acmsl.queryj.tools.handlers.DatabaseMetaDataRetrievalHandler.java

/**
 * Retrieves the product's identifier quote string.
 * @param metaData the database metadata.
 * @return the quote string./*from   w  ww  .j a va2s  .c o m*/
 * @throws QueryJBuildException if the product quote information is not available.
 */
@SuppressWarnings("unused")
protected String retrieveProductQuote(@NotNull final DatabaseMetaData metaData) throws QueryJBuildException {
    @NotNull
    String result = "";

    @Nullable
    QueryJBuildException t_ExceptionToThrow = null;

    try {
        result = metaData.getIdentifierQuoteString();
    } catch (@NotNull final SQLException sqlException) {
        @Nullable
        final Log t_Log = UniqueLogFactory.getLog(DatabaseMetaDataRetrievalHandler.class);

        if (t_Log != null) {
            t_Log.error("Cannot retrieve database vendor's quote string.", sqlException);
        }

        t_ExceptionToThrow = new CannotRetrieveDatabaseInformationException(sqlException);
    }

    if (t_ExceptionToThrow != null) {
        throw t_ExceptionToThrow;
    }

    return result;
}

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

/**
 * Test simple DatabaseMetaData calls.  getColumns is tested elsewhere, as we need to call
 * that on a valid table.  Same with getFunctions.
 *
 * @throws SQLException/*from  w ww. j  ava 2s  .  c  o m*/
 */
@Test
public void databaseMetaDataCalls() throws SQLException {
    DatabaseMetaData md = conn.getMetaData();

    boolean boolrc = md.allTablesAreSelectable();
    LOG.debug("All tables are selectable? " + boolrc);

    String strrc = md.getCatalogSeparator();
    LOG.debug("Catalog separator " + strrc);

    strrc = md.getCatalogTerm();
    LOG.debug("Catalog term " + strrc);

    ResultSet rs = md.getCatalogs();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found catalog " + strrc);
    }

    Connection c = md.getConnection();

    int intrc = md.getDatabaseMajorVersion();
    LOG.debug("DB major version is " + intrc);

    intrc = md.getDatabaseMinorVersion();
    LOG.debug("DB minor version is " + intrc);

    strrc = md.getDatabaseProductName();
    LOG.debug("DB product name is " + strrc);

    strrc = md.getDatabaseProductVersion();
    LOG.debug("DB product version is " + strrc);

    intrc = md.getDefaultTransactionIsolation();
    LOG.debug("Default transaction isolation is " + intrc);

    intrc = md.getDriverMajorVersion();
    LOG.debug("Driver major version is " + intrc);

    intrc = md.getDriverMinorVersion();
    LOG.debug("Driver minor version is " + intrc);

    strrc = md.getDriverName();
    LOG.debug("Driver name is " + strrc);

    strrc = md.getDriverVersion();
    LOG.debug("Driver version is " + strrc);

    strrc = md.getExtraNameCharacters();
    LOG.debug("Extra name characters is " + strrc);

    strrc = md.getIdentifierQuoteString();
    LOG.debug("Identifier quote string is " + strrc);

    // In Hive 1.2 this always returns an empty RS
    rs = md.getImportedKeys("a", "b", "d");

    // In Hive 1.2 this always returns an empty RS
    rs = md.getIndexInfo("a", "b", "d", true, true);

    intrc = md.getJDBCMajorVersion();
    LOG.debug("JDBC major version is " + intrc);

    intrc = md.getJDBCMinorVersion();
    LOG.debug("JDBC minor version is " + intrc);

    intrc = md.getMaxColumnNameLength();
    LOG.debug("Maximum column name length is " + intrc);

    strrc = md.getNumericFunctions();
    LOG.debug("Numeric functions are " + strrc);

    // In Hive 1.2 this always returns an empty RS
    rs = md.getPrimaryKeys("a", "b", "d");

    // In Hive 1.2 this always returns an empty RS
    rs = md.getProcedureColumns("a", "b", "d", "e");

    strrc = md.getProcedureTerm();
    LOG.debug("Procedures are called " + strrc);

    // In Hive 1.2 this always returns an empty RS
    rs = md.getProcedures("a", "b", "d");

    strrc = md.getSchemaTerm();
    LOG.debug("Schemas are called " + strrc);

    rs = md.getSchemas();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found schema " + strrc);
    }

    strrc = md.getSearchStringEscape();
    LOG.debug("Search string escape is " + strrc);

    strrc = md.getStringFunctions();
    LOG.debug("String functions are " + strrc);

    strrc = md.getSystemFunctions();
    LOG.debug("System functions are " + strrc);

    rs = md.getTableTypes();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found table type " + strrc);
    }

    strrc = md.getTimeDateFunctions();
    LOG.debug("Time/date functions are " + strrc);

    rs = md.getTypeInfo();
    while (rs.next()) {
        strrc = rs.getString(1);
        LOG.debug("Found type " + strrc);
    }

    // In Hive 1.2 this always returns an empty RS
    rs = md.getUDTs("a", "b", "d", null);

    boolrc = md.supportsAlterTableWithAddColumn();
    LOG.debug("Supports alter table with add column? " + boolrc);

    boolrc = md.supportsAlterTableWithDropColumn();
    LOG.debug("Supports alter table with drop column? " + boolrc);

    boolrc = md.supportsBatchUpdates();
    LOG.debug("Supports batch updates? " + boolrc);

    boolrc = md.supportsCatalogsInDataManipulation();
    LOG.debug("Supports catalogs in data manipulation? " + boolrc);

    boolrc = md.supportsCatalogsInIndexDefinitions();
    LOG.debug("Supports catalogs in index definition? " + boolrc);

    boolrc = md.supportsCatalogsInPrivilegeDefinitions();
    LOG.debug("Supports catalogs in privilege definition? " + boolrc);

    boolrc = md.supportsCatalogsInProcedureCalls();
    LOG.debug("Supports catalogs in procedure calls? " + boolrc);

    boolrc = md.supportsCatalogsInTableDefinitions();
    LOG.debug("Supports catalogs in table definition? " + boolrc);

    boolrc = md.supportsColumnAliasing();
    LOG.debug("Supports column aliasing? " + boolrc);

    boolrc = md.supportsFullOuterJoins();
    LOG.debug("Supports full outer joins? " + boolrc);

    boolrc = md.supportsGroupBy();
    LOG.debug("Supports group by? " + boolrc);

    boolrc = md.supportsLimitedOuterJoins();
    LOG.debug("Supports limited outer joins? " + boolrc);

    boolrc = md.supportsMultipleResultSets();
    LOG.debug("Supports limited outer joins? " + boolrc);

    boolrc = md.supportsNonNullableColumns();
    LOG.debug("Supports non-nullable columns? " + boolrc);

    boolrc = md.supportsOuterJoins();
    LOG.debug("Supports outer joins? " + boolrc);

    boolrc = md.supportsPositionedDelete();
    LOG.debug("Supports positioned delete? " + boolrc);

    boolrc = md.supportsPositionedUpdate();
    LOG.debug("Supports positioned update? " + boolrc);

    boolrc = md.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
    LOG.debug("Supports result set holdability? " + boolrc);

    boolrc = md.supportsResultSetType(ResultSet.HOLD_CURSORS_OVER_COMMIT);
    LOG.debug("Supports result set type? " + boolrc);

    boolrc = md.supportsSavepoints();
    LOG.debug("Supports savepoints? " + boolrc);

    boolrc = md.supportsSchemasInDataManipulation();
    LOG.debug("Supports schemas in data manipulation? " + boolrc);

    boolrc = md.supportsSchemasInIndexDefinitions();
    LOG.debug("Supports schemas in index definitions? " + boolrc);

    boolrc = md.supportsSchemasInPrivilegeDefinitions();
    LOG.debug("Supports schemas in privilege definitions? " + boolrc);

    boolrc = md.supportsSchemasInProcedureCalls();
    LOG.debug("Supports schemas in procedure calls? " + boolrc);

    boolrc = md.supportsSchemasInTableDefinitions();
    LOG.debug("Supports schemas in table definitions? " + boolrc);

    boolrc = md.supportsSelectForUpdate();
    LOG.debug("Supports select for update? " + boolrc);

    boolrc = md.supportsStoredProcedures();
    LOG.debug("Supports stored procedures? " + boolrc);

    boolrc = md.supportsTransactions();
    LOG.debug("Supports transactions? " + boolrc);

    boolrc = md.supportsUnion();
    LOG.debug("Supports union? " + boolrc);

    boolrc = md.supportsUnionAll();
    LOG.debug("Supports union all? " + boolrc);

}

From source file:org.apache.openjpa.jdbc.sql.DBDictionaryFactory.java

/**
 * Return a string containing all the property values of the given
 * database metadata./*  w  w  w.j a va 2s . co m*/
 */
public static String toString(DatabaseMetaData meta) throws SQLException {
    String lineSep = J2DoPrivHelper.getLineSeparator();
    StringBuilder buf = new StringBuilder(4096);
    try {
        buf.append("catalogSeparator: ").append(meta.getCatalogSeparator()).append(lineSep)
                .append("catalogTerm: ").append(meta.getCatalogTerm()).append(lineSep)
                .append("databaseProductName: ").append(meta.getDatabaseProductName()).append(lineSep)
                .append("databaseProductVersion: ").append(meta.getDatabaseProductVersion()).append(lineSep)
                .append("driverName: ").append(meta.getDriverName()).append(lineSep).append("driverVersion: ")
                .append(meta.getDriverVersion()).append(lineSep).append("extraNameCharacters: ")
                .append(meta.getExtraNameCharacters()).append(lineSep).append("identifierQuoteString: ")
                .append(meta.getIdentifierQuoteString()).append(lineSep).append("numericFunctions: ")
                .append(meta.getNumericFunctions()).append(lineSep).append("procedureTerm: ")
                .append(meta.getProcedureTerm()).append(lineSep).append("schemaTerm: ")
                .append(meta.getSchemaTerm()).append(lineSep).append("searchStringEscape: ")
                .append(meta.getSearchStringEscape()).append(lineSep).append("sqlKeywords: ")
                .append(meta.getSQLKeywords()).append(lineSep).append("stringFunctions: ")
                .append(meta.getStringFunctions()).append(lineSep).append("systemFunctions: ")
                .append(meta.getSystemFunctions()).append(lineSep).append("timeDateFunctions: ")
                .append(meta.getTimeDateFunctions()).append(lineSep).append("url: ").append(meta.getURL())
                .append(lineSep).append("userName: ").append(meta.getUserName()).append(lineSep)
                .append("defaultTransactionIsolation: ").append(meta.getDefaultTransactionIsolation())
                .append(lineSep).append("driverMajorVersion: ").append(meta.getDriverMajorVersion())
                .append(lineSep).append("driverMinorVersion: ").append(meta.getDriverMinorVersion())
                .append(lineSep).append("maxBinaryLiteralLength: ").append(meta.getMaxBinaryLiteralLength())
                .append(lineSep).append("maxCatalogNameLength: ").append(meta.getMaxCatalogNameLength())
                .append(lineSep).append("maxCharLiteralLength: ").append(meta.getMaxCharLiteralLength())
                .append(lineSep).append("maxColumnNameLength: ").append(meta.getMaxColumnNameLength())
                .append(lineSep).append("maxColumnsInGroupBy: ").append(meta.getMaxColumnsInGroupBy())
                .append(lineSep).append("maxColumnsInIndex: ").append(meta.getMaxColumnsInIndex())
                .append(lineSep).append("maxColumnsInOrderBy: ").append(meta.getMaxColumnsInOrderBy())
                .append(lineSep).append("maxColumnsInSelect: ").append(meta.getMaxColumnsInSelect())
                .append(lineSep).append("maxColumnsInTable: ").append(meta.getMaxColumnsInTable())
                .append(lineSep).append("maxConnections: ").append(meta.getMaxConnections()).append(lineSep)
                .append("maxCursorNameLength: ").append(meta.getMaxCursorNameLength()).append(lineSep)
                .append("maxIndexLength: ").append(meta.getMaxIndexLength()).append(lineSep)
                .append("maxProcedureNameLength: ").append(meta.getMaxProcedureNameLength()).append(lineSep)
                .append("maxRowSize: ").append(meta.getMaxRowSize()).append(lineSep)
                .append("maxSchemaNameLength: ").append(meta.getMaxSchemaNameLength()).append(lineSep)
                .append("maxStatementLength: ").append(meta.getMaxStatementLength()).append(lineSep)
                .append("maxStatements: ").append(meta.getMaxStatements()).append(lineSep)
                .append("maxTableNameLength: ").append(meta.getMaxTableNameLength()).append(lineSep)
                .append("maxTablesInSelect: ").append(meta.getMaxTablesInSelect()).append(lineSep)
                .append("maxUserNameLength: ").append(meta.getMaxUserNameLength()).append(lineSep)
                .append("isCatalogAtStart: ").append(meta.isCatalogAtStart()).append(lineSep)
                .append("isReadOnly: ").append(meta.isReadOnly()).append(lineSep)
                .append("nullPlusNonNullIsNull: ").append(meta.nullPlusNonNullIsNull()).append(lineSep)
                .append("nullsAreSortedAtEnd: ").append(meta.nullsAreSortedAtEnd()).append(lineSep)
                .append("nullsAreSortedAtStart: ").append(meta.nullsAreSortedAtStart()).append(lineSep)
                .append("nullsAreSortedHigh: ").append(meta.nullsAreSortedHigh()).append(lineSep)
                .append("nullsAreSortedLow: ").append(meta.nullsAreSortedLow()).append(lineSep)
                .append("storesLowerCaseIdentifiers: ").append(meta.storesLowerCaseIdentifiers())
                .append(lineSep).append("storesLowerCaseQuotedIdentifiers: ")
                .append(meta.storesLowerCaseQuotedIdentifiers()).append(lineSep)
                .append("storesMixedCaseIdentifiers: ").append(meta.storesMixedCaseIdentifiers())
                .append(lineSep).append("storesMixedCaseQuotedIdentifiers: ")
                .append(meta.storesMixedCaseQuotedIdentifiers()).append(lineSep)
                .append("storesUpperCaseIdentifiers: ").append(meta.storesUpperCaseIdentifiers())
                .append(lineSep).append("storesUpperCaseQuotedIdentifiers: ")
                .append(meta.storesUpperCaseQuotedIdentifiers()).append(lineSep)
                .append("supportsAlterTableWithAddColumn: ").append(meta.supportsAlterTableWithAddColumn())
                .append(lineSep).append("supportsAlterTableWithDropColumn: ")
                .append(meta.supportsAlterTableWithDropColumn()).append(lineSep)
                .append("supportsANSI92EntryLevelSQL: ").append(meta.supportsANSI92EntryLevelSQL())
                .append(lineSep).append("supportsANSI92FullSQL: ").append(meta.supportsANSI92FullSQL())
                .append(lineSep).append("supportsANSI92IntermediateSQL: ")
                .append(meta.supportsANSI92IntermediateSQL()).append(lineSep)
                .append("supportsCatalogsInDataManipulation: ")
                .append(meta.supportsCatalogsInDataManipulation()).append(lineSep)
                .append("supportsCatalogsInIndexDefinitions: ")
                .append(meta.supportsCatalogsInIndexDefinitions()).append(lineSep)
                .append("supportsCatalogsInPrivilegeDefinitions: ")
                .append(meta.supportsCatalogsInPrivilegeDefinitions()).append(lineSep)
                .append("supportsCatalogsInProcedureCalls: ").append(meta.supportsCatalogsInProcedureCalls())
                .append(lineSep).append("supportsCatalogsInTableDefinitions: ")
                .append(meta.supportsCatalogsInTableDefinitions()).append(lineSep)
                .append("supportsColumnAliasing: ").append(meta.supportsColumnAliasing()).append(lineSep)
                .append("supportsConvert: ").append(meta.supportsConvert()).append(lineSep)
                .append("supportsCoreSQLGrammar: ").append(meta.supportsCoreSQLGrammar()).append(lineSep)
                .append("supportsCorrelatedSubqueries: ").append(meta.supportsCorrelatedSubqueries())
                .append(lineSep).append("supportsDataDefinitionAndDataManipulationTransactions: ")
                .append(meta.supportsDataDefinitionAndDataManipulationTransactions()).append(lineSep)
                .append("supportsDataManipulationTransactionsOnly: ")
                .append(meta.supportsDataManipulationTransactionsOnly()).append(lineSep)
                .append("supportsDifferentTableCorrelationNames: ")
                .append(meta.supportsDifferentTableCorrelationNames()).append(lineSep)
                .append("supportsExpressionsInOrderBy: ").append(meta.supportsExpressionsInOrderBy())
                .append(lineSep).append("supportsExtendedSQLGrammar: ")
                .append(meta.supportsExtendedSQLGrammar()).append(lineSep).append("supportsFullOuterJoins: ")
                .append(meta.supportsFullOuterJoins()).append(lineSep).append("supportsGroupBy: ")
                .append(meta.supportsGroupBy()).append(lineSep).append("supportsGroupByBeyondSelect: ")
                .append(meta.supportsGroupByBeyondSelect()).append(lineSep).append("supportsGroupByUnrelated: ")
                .append(meta.supportsGroupByUnrelated()).append(lineSep)
                .append("supportsIntegrityEnhancementFacility: ")
                .append(meta.supportsIntegrityEnhancementFacility()).append(lineSep)
                .append("supportsLikeEscapeClause: ").append(meta.supportsLikeEscapeClause()).append(lineSep)
                .append("supportsLimitedOuterJoins: ").append(meta.supportsLimitedOuterJoins()).append(lineSep)
                .append("supportsMinimumSQLGrammar: ").append(meta.supportsMinimumSQLGrammar()).append(lineSep)
                .append("supportsMixedCaseIdentifiers: ").append(meta.supportsMixedCaseIdentifiers())
                .append(lineSep).append("supportsMixedCaseQuotedIdentifiers: ")
                .append(meta.supportsMixedCaseQuotedIdentifiers()).append(lineSep)
                .append("supportsMultipleResultSets: ").append(meta.supportsMultipleResultSets())
                .append(lineSep).append("supportsMultipleTransactions: ")
                .append(meta.supportsMultipleTransactions()).append(lineSep)
                .append("supportsNonNullableColumns: ").append(meta.supportsNonNullableColumns())
                .append(lineSep).append("supportsOpenCursorsAcrossCommit: ")
                .append(meta.supportsOpenCursorsAcrossCommit()).append(lineSep)
                .append("supportsOpenCursorsAcrossRollback: ").append(meta.supportsOpenCursorsAcrossRollback())
                .append(lineSep).append("supportsOpenStatementsAcrossCommit: ")
                .append(meta.supportsOpenStatementsAcrossCommit()).append(lineSep)
                .append("supportsOpenStatementsAcrossRollback: ")
                .append(meta.supportsOpenStatementsAcrossRollback()).append(lineSep)
                .append("supportsOrderByUnrelated: ").append(meta.supportsOrderByUnrelated()).append(lineSep)
                .append("supportsOuterJoins: ").append(meta.supportsOuterJoins()).append(lineSep)
                .append("supportsPositionedDelete: ").append(meta.supportsPositionedDelete()).append(lineSep)
                .append("supportsPositionedUpdate: ").append(meta.supportsPositionedUpdate()).append(lineSep)
                .append("supportsSchemasInDataManipulation: ").append(meta.supportsSchemasInDataManipulation())
                .append(lineSep).append("supportsSchemasInIndexDefinitions: ")
                .append(meta.supportsSchemasInIndexDefinitions()).append(lineSep)
                .append("supportsSchemasInPrivilegeDefinitions: ")
                .append(meta.supportsSchemasInPrivilegeDefinitions()).append(lineSep)
                .append("supportsSchemasInProcedureCalls: ").append(meta.supportsSchemasInProcedureCalls())
                .append(lineSep).append("supportsSchemasInTableDefinitions: ")
                .append(meta.supportsSchemasInTableDefinitions()).append(lineSep)
                .append("supportsSelectForUpdate: ").append(meta.supportsSelectForUpdate()).append(lineSep)
                .append("supportsStoredProcedures: ").append(meta.supportsStoredProcedures()).append(lineSep)
                .append("supportsSubqueriesInComparisons: ").append(meta.supportsSubqueriesInComparisons())
                .append(lineSep).append("supportsSubqueriesInExists: ")
                .append(meta.supportsSubqueriesInExists()).append(lineSep).append("supportsSubqueriesInIns: ")
                .append(meta.supportsSubqueriesInIns()).append(lineSep)
                .append("supportsSubqueriesInQuantifieds: ").append(meta.supportsSubqueriesInQuantifieds())
                .append(lineSep).append("supportsTableCorrelationNames: ")
                .append(meta.supportsTableCorrelationNames()).append(lineSep).append("supportsTransactions: ")
                .append(meta.supportsTransactions()).append(lineSep).append("supportsUnion: ")
                .append(meta.supportsUnion()).append(lineSep).append("supportsUnionAll: ")
                .append(meta.supportsUnionAll()).append(lineSep).append("usesLocalFilePerTable: ")
                .append(meta.usesLocalFilePerTable()).append(lineSep).append("usesLocalFiles: ")
                .append(meta.usesLocalFiles()).append(lineSep).append("allProceduresAreCallable: ")
                .append(meta.allProceduresAreCallable()).append(lineSep).append("allTablesAreSelectable: ")
                .append(meta.allTablesAreSelectable()).append(lineSep)
                .append("dataDefinitionCausesTransactionCommit: ")
                .append(meta.dataDefinitionCausesTransactionCommit()).append(lineSep)
                .append("dataDefinitionIgnoredInTransactions: ")
                .append(meta.dataDefinitionIgnoredInTransactions()).append(lineSep)
                .append("doesMaxRowSizeIncludeBlobs: ").append(meta.doesMaxRowSizeIncludeBlobs())
                .append(lineSep).append("supportsBatchUpdates: ").append(meta.supportsBatchUpdates());
    } catch (Throwable t) {
        // maybe abstract method error for jdbc 3 metadata method, or
        // other error
        buf.append(lineSep).append("Caught throwable: ").append(t);
    }

    return buf.toString();
}

From source file:org.jtester.module.database.support.DbSupport.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.//from w w  w . j av  a 2 s  .com
 * 
 * @param identifierQuoteStringProperty
 *            The string to quote identifiers, 'none' if quoting is not
 *            supported, 'auto' for auto detection
 * @return The quote string, null if quoting is not supported
 */
private String determineIdentifierQuoteString(String identifierQuoteStringProperty) {
    if ("none".equals(identifierQuoteStringProperty)) {
        return null;
    } else if (!"auto".equals(identifierQuoteStringProperty)) {
        return identifierQuoteStringProperty;
    }

    Connection connection = null;
    try {
        connection = getSQLHandler().getDataSource().getConnection();

        DatabaseMetaData databaseMetaData = connection.getMetaData();
        String quoteString = databaseMetaData.getIdentifierQuoteString();
        if (quoteString == null || "".equals(quoteString.trim())) {
            return null;
        }
        return quoteString;

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

From source file:org.talend.metadata.managment.model.DBConnectionFillerImpl.java

@Override
public DatabaseConnection fillUIConnParams(IMetadataConnection metadataBean, DatabaseConnection connection) {
    DatabaseConnection newConnection = null;
    if (connection == null) {
        newConnection = ConnectionFactory.eINSTANCE.createDatabaseConnection();
    }/*from w w  w .j a  v a  2s .  co m*/
    if (super.fillUIConnParams(metadataBean, newConnection == null ? connection : newConnection) == null) {
        return null;
    }
    DatabaseConnection dbconn = null;
    if (newConnection != null) {
        dbconn = newConnection;
    } else {
        dbconn = connection;
    }
    if (newConnection != null && dbconn != null) {
        dbconn.setDriverJarPath(metadataBean.getDriverJarPath());
        dbconn.setProductId(metadataBean.getProduct());
        dbconn.setDbmsId(metadataBean.getMapping());
        dbconn.setAdditionalParams(metadataBean.getAdditionalParams());
        dbconn.setDriverClass(metadataBean.getDriverClass());
        dbconn.setDatabaseType(metadataBean.getDbType());
        dbconn.setName(metadataBean.getLabel());
        dbconn.setLabel(metadataBean.getLabel());
        dbconn.setVersion(metadataBean.getVersion());
        // MOD klliu bug 21074 2011-05-19
        dbconn.setUiSchema(metadataBean.getUiSchema());
        dbconn.setSQLMode(metadataBean.isSqlMode());
        dbconn.setSID(metadataBean.getDatabase());
        // MOD copy parameter from metadata to dbconn
        for (Map.Entry<String, Object> parameter : metadataBean.getOtherParameters().entrySet()) {
            dbconn.getParameters().put(parameter.getKey(),
                    parameter.getValue() == null ? StringUtils.EMPTY : parameter.getValue().toString());
        }
    }
    java.sql.Connection sqlConnection = null;
    try {
        sqlConnection = MetadataConnectionUtils.createConnection(metadataBean).getObject();
        // MetadataConnectionUtils.setMetadataCon(metadataBean);
        // fill some base parameter
        if (newConnection != null) {
            fillMetadataParams(metadataBean, newConnection);
        }

        DatabaseMetaData dbMetadata = null;
        // Added by Marvin Wang on Mar. 13, 2013 for loading hive jars dynamically, refer to TDI-25072.
        if (EDatabaseTypeName.HIVE.getXmlName().equalsIgnoreCase(metadataBean.getDbType())) {
            dbMetadata = HiveConnectionManager.getInstance().extractDatabaseMetaData(metadataBean);
        } else {
            // software
            dbMetadata = ExtractMetaDataUtils.getInstance().getDatabaseMetaData(sqlConnection, dbconn, false);
        }

        if (dbMetadata != null) {
            // MOD sizhaoliu TDQ-6316 The 2 tagged values should be added for all database including Hive
            String productName = dbMetadata.getDatabaseProductName() == null ? PluginConstant.EMPTY_STRING
                    : dbMetadata.getDatabaseProductName();
            String productVersion = dbMetadata.getDatabaseProductVersion() == null ? PluginConstant.EMPTY_STRING
                    : dbMetadata.getDatabaseProductVersion();
            TaggedValueHelper.setTaggedValue(dbconn, TaggedValueHelper.DB_PRODUCT_NAME, productName);
            TaggedValueHelper.setTaggedValue(dbconn, TaggedValueHelper.DB_PRODUCT_VERSION, productVersion);

            boolean isHive = dbconn.getDatabaseType().equals(EDatabaseTypeName.HIVE.getDisplayName());
            boolean isHiveJdbc = dbconn.getDatabaseType()
                    .equals(EDatabaseTypeName.GENERAL_JDBC.getDisplayName()) && dbconn.getDriverClass() != null
                    && dbconn.getDriverClass().equals(EDatabase4DriverClassName.HIVE.getDriverClass());
            boolean isImpala = dbconn.getDatabaseType().equals(EDatabaseTypeName.IMPALA.getDisplayName());
            boolean isImpalaJdbc = dbconn.getDatabaseType().equals(EDatabaseTypeName.IMPALA.getDisplayName())
                    && dbconn.getDriverClass() != null
                    && dbconn.getDriverClass().equals(EDatabase4DriverClassName.IMPALA.getDriverClass());
            if (!isHive && !isHiveJdbc && !isImpala && !isImpalaJdbc) {
                String identifierQuote = dbMetadata.getIdentifierQuoteString();
                ConnectionHelper.setIdentifierQuoteString(identifierQuote == null ? "" : identifierQuote, //$NON-NLS-1$
                        dbconn);
            }
        }
    } catch (SQLException e) {
        log.error(e, e);
    } catch (ClassNotFoundException e) {
        CommonExceptionHandler.process(e);
    } catch (InstantiationException e) {
        CommonExceptionHandler.process(e);
    } catch (IllegalAccessException e) {
        CommonExceptionHandler.process(e);
    } finally {
        if (sqlConnection != null) {
            ConnectionUtils.closeConnection(sqlConnection);
        }
        if (driver != null && MetadataConnectionUtils.isDerbyRelatedDb(metadataBean.getDriverClass(),
                metadataBean.getDbType())) {
            try {
                driver.connect("jdbc:derby:;shutdown=true", null); //$NON-NLS-1$
            } catch (SQLException e) {
                // exception of shutdown success. no need to catch.
            }
        }
    }
    if (newConnection != null) {
        return newConnection;
    } else {
        return connection;
    }
}

From source file:org.unitils.core.dbsupport.DbSupport.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 identifierQuoteStringProperty The string to quote identifiers, 'none' if quoting is not supported, 'auto' for auto detection
 * @return The quote string, null if quoting is not supported
 *///www . java2  s . c om
private String determineIdentifierQuoteString(String identifierQuoteStringProperty) {
    if ("none".equals(identifierQuoteStringProperty)) {
        return null;
    } else if (!"auto".equals(identifierQuoteStringProperty)) {
        return identifierQuoteStringProperty;
    }

    Connection connection = null;
    try {
        connection = getSQLHandler().getDataSource().getConnection();

        DatabaseMetaData databaseMetaData = connection.getMetaData();
        String quoteString = databaseMetaData.getIdentifierQuoteString();
        if (quoteString == null || "".equals(quoteString.trim())) {
            return null;
        }
        return quoteString;

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

From source file:rapture.postgres.connection.cache.ConnectionCacheLoader.java

public static PostgresSanitizer createSanitizer(DataSource dataSource) {
    DatabaseMetaDataCallback callback = new DatabaseMetaDataCallback() {
        @Override/*from  w  ww. ja  v  a 2 s  .c  o  m*/
        public String processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
            return dbmd.getIdentifierQuoteString();
        }
    };
    try {
        return new PostgresSanitizer(JdbcUtils.extractDatabaseMetaData(dataSource, callback).toString());
    } catch (MetaDataAccessException e) {
        throw RaptureExceptionFactory.create("Unable to get quote identifier: " + ExceptionToString.format(e));
    }
}