Java Code Examples for java.sql.DatabaseMetaData#storesLowerCaseIdentifiers()

The following examples show how to use java.sql.DatabaseMetaData#storesLowerCaseIdentifiers() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UKTableMetaData.java    From youkefu with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param meta
 * @throws SQLException
 */
private void initColumns(DatabaseMetaData meta , boolean upcase) throws SQLException {
	ResultSet rs = null;

	try {
		if (meta.storesUpperCaseIdentifiers()) {
			rs = meta.getColumns(StringHelper.toUpperCase(catalog),
					StringHelper.toUpperCase(schema), StringHelper
							.toUpperCase(name), "%");
		} else if (meta.storesLowerCaseIdentifiers()) {
			rs = meta.getColumns(StringHelper.toLowerCase(catalog),
					StringHelper.toLowerCase(schema), StringHelper
							.toLowerCase(name), "%");
		} else {
			rs = meta.getColumns(catalog, schema, name, "%");
		}
		while (rs.next())
			addColumn(rs , upcase);
	}catch(Exception ex){
		ex.printStackTrace();
	}finally {
		if (rs != null)
			rs.close();
	}
}
 
Example 2
Source File: SqlDialectFactoryImpl.java    From Quicksql with MIT License 6 votes vote down vote up
private Casing getCasing(DatabaseMetaData databaseMetaData, boolean quoted) {
  try {
    if (quoted
        ? databaseMetaData.storesUpperCaseQuotedIdentifiers()
        : databaseMetaData.storesUpperCaseIdentifiers()) {
      return Casing.TO_UPPER;
    } else if (quoted
        ? databaseMetaData.storesLowerCaseQuotedIdentifiers()
        : databaseMetaData.storesLowerCaseIdentifiers()) {
      return Casing.TO_LOWER;
    } else if (quoted
        ? (databaseMetaData.storesMixedCaseQuotedIdentifiers()
            || databaseMetaData.supportsMixedCaseQuotedIdentifiers())
        : (databaseMetaData.storesMixedCaseIdentifiers()
            || databaseMetaData.supportsMixedCaseIdentifiers())) {
      return Casing.UNCHANGED;
    } else {
      return Casing.UNCHANGED;
    }
  } catch (SQLException e) {
    throw new IllegalArgumentException("cannot deduce casing", e);
  }
}
 
Example 3
Source File: MyBatisAccessor.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
public synchronized StorageCaseStrategy getCaseStrategy() {
	try {
		if (caseStrategy == null) {
			// 获取表名与列名是否需要转大写或者小写?
			DatabaseMetaData metaData = template.getConnection().getMetaData();
			if (metaData.storesLowerCaseIdentifiers()) {
				caseStrategy = StorageCaseStrategy.LOWER;
			} else if (metaData.storesUpperCaseIdentifiers()) {
				caseStrategy = StorageCaseStrategy.UPPER;
			} else {
				caseStrategy = StorageCaseStrategy.MIXED;
			}
		}
		return caseStrategy;
	} catch (Exception exception) {
		throw new StorageException(exception);
	}
}
 
Example 4
Source File: SQLIdentifiers.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static int getCaseRule(DatabaseMetaData dbmd) {
    int rule = UC_RULE;

    try {
        if ( dbmd.storesUpperCaseIdentifiers() ) {
            rule = UC_RULE;
        } else if ( dbmd.storesLowerCaseIdentifiers() ) {
            rule = LC_RULE;
        } else if ( dbmd.storesMixedCaseIdentifiers() ) {
            rule = MC_RULE;
        } else {
            rule = UC_RULE;
        }
    } catch ( SQLException sqle ) {
        LOGGER.log(Level.WARNING, "Exception trying to find out how " +
                "the database stores unquoted identifiers, assuming " +
                "upper case: " + sqle.getMessage());
        LOGGER.log(Level.FINE, null, sqle);
    }

    return rule;
}
 
Example 5
Source File: MetaDataRegressionTest.java    From r-course with MIT License 6 votes vote down vote up
public void testBug31187() throws Exception {
    createTable("testBug31187", "(field1 int)");

    Connection nullCatConn = getConnectionWithProps("nullCatalogMeansCurrent=false");
    DatabaseMetaData dbmd = nullCatConn.getMetaData();
    ResultSet dbTblCols = dbmd.getColumns(null, null, "testBug31187", "%");

    boolean found = false;

    while (dbTblCols.next()) {
        String catalog = dbTblCols.getString("TABLE_CAT");
        String table = dbTblCols.getString("TABLE_NAME");
        boolean useLowerCaseTableNames = dbmd.storesLowerCaseIdentifiers();

        if (catalog.equals(nullCatConn.getCatalog())
                && (((useLowerCaseTableNames && "testBug31187".equalsIgnoreCase(table)) || "testBug31187".equals(table)))) {
            found = true;
        }
    }

    assertTrue("Didn't find any columns for table named 'testBug31187' in database " + this.conn.getCatalog(), found);
}
 
Example 6
Source File: MetaDataRegressionTest.java    From Komondor with GNU General Public License v3.0 6 votes vote down vote up
public void testBug31187() throws Exception {
    createTable("testBug31187", "(field1 int)");

    Connection nullCatConn = getConnectionWithProps("nullCatalogMeansCurrent=false");
    DatabaseMetaData dbmd = nullCatConn.getMetaData();
    ResultSet dbTblCols = dbmd.getColumns(null, null, "testBug31187", "%");

    boolean found = false;

    while (dbTblCols.next()) {
        String catalog = dbTblCols.getString("TABLE_CAT");
        String table = dbTblCols.getString("TABLE_NAME");
        boolean useLowerCaseTableNames = dbmd.storesLowerCaseIdentifiers();

        if (catalog.equals(nullCatConn.getCatalog())
                && (((useLowerCaseTableNames && "testBug31187".equalsIgnoreCase(table)) || "testBug31187".equals(table)))) {
            found = true;
        }
    }

    assertTrue("Didn't find any columns for table named 'testBug31187' in database " + this.conn.getCatalog(), found);
}
 
Example 7
Source File: DatabaseUtil.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
public String getSchemaName(DatabaseMetaData dbData) throws SQLException {
    if (!isLegacy && this.datasourceInfo.getUseSchemas() && dbData.supportsSchemasInTableDefinitions()) {
        if (UtilValidate.isNotEmpty(this.datasourceInfo.getSchemaName())) {
            if (dbData.storesLowerCaseIdentifiers()) {
                return this.datasourceInfo.getSchemaName().toLowerCase();
            } else if (dbData.storesUpperCaseIdentifiers()) {
                return this.datasourceInfo.getSchemaName().toUpperCase();
            } else {
                return this.datasourceInfo.getSchemaName();
            }
        } else {
            return dbData.getUserName();
        }
    }
    return null;
}
 
Example 8
Source File: SqlDialectFactoryImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
private Casing getCasing(DatabaseMetaData databaseMetaData, boolean quoted) {
  try {
    if (quoted
        ? databaseMetaData.storesUpperCaseQuotedIdentifiers()
        : databaseMetaData.storesUpperCaseIdentifiers()) {
      return Casing.TO_UPPER;
    } else if (quoted
        ? databaseMetaData.storesLowerCaseQuotedIdentifiers()
        : databaseMetaData.storesLowerCaseIdentifiers()) {
      return Casing.TO_LOWER;
    } else if (quoted
        ? (databaseMetaData.storesMixedCaseQuotedIdentifiers()
            || databaseMetaData.supportsMixedCaseQuotedIdentifiers())
        : (databaseMetaData.storesMixedCaseIdentifiers()
            || databaseMetaData.supportsMixedCaseIdentifiers())) {
      return Casing.UNCHANGED;
    } else {
      return Casing.UNCHANGED;
    }
  } catch (SQLException e) {
    throw new IllegalArgumentException("cannot deduce casing", e);
  }
}
 
Example 9
Source File: MetadataSource.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * If the metadata schema does not exist in the database, creates it and inserts the pre-defined metadata values.
 * The current implementation has the following restrictions:
 *
 * <ul>
 *   <li>Metadata standard must be {@link MetadataStandard#ISO_19115} or compatible.</li>
 *   <li>The schema name must be {@code "metadata"}, as this is the name used unquoted in SQL scripts.</li>
 * </ul>
 *
 * Maintenance note: this method is invoked by reflection in {@code non-free:sis-embedded-data} module.
 * If we make this method public in a future Apache SIS version, then we can remove the reflection code.
 *
 * @throws SQLException if an error occurred while inserting the metadata.
 */
final synchronized void install() throws IOException, SQLException {
    final Connection connection = connection();
    final DatabaseMetaData md = connection.getMetaData();
    if (md.storesUpperCaseIdentifiers()) {
        schema = schema.toUpperCase(Locale.US);
    } else if (md.storesLowerCaseIdentifiers()) {
        schema = schema.toLowerCase(Locale.US);
    }
    quoteSchema = false;
    try (ResultSet result = md.getTables(catalog, schema, "Citation", null)) {
        if (result.next()) {
            return;
        }
    }
    final Installer installer = new Installer(connection);
    installer.run();
}
 
Example 10
Source File: DatabaseInformationImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public int getColumnStringLength(String tableName, String columnName) throws DatabaseInformationException {
	columnName = columnName.toUpperCase();
	
	TableAndColumn tableAndColumn = new TableAndColumn(tableName, columnName);
	Integer columnLength = columnLengthMap.get(tableAndColumn);
	
	if(columnLength != null) {
		return columnLength;
	} else {
		try(Connection connection = datasource.getConnection()) {
			DatabaseMetaData metaData = connection.getMetaData();

			if (metaData.storesLowerCaseIdentifiers()) {
				tableName = tableName.toLowerCase();
			} else if (metaData.storesUpperCaseIdentifiers()) {
				tableName = tableName.toUpperCase();
			}

			try(ResultSet resultSet = metaData.getColumns(null, null, tableName, columnName)) {
				if(!resultSet.next()) {
					throw new UnknownTableOrColumnException(tableName, columnName);
				}
				
				int length = resultSet.getInt("COLUMN_SIZE");		// According to JDBC API, "COLUMN_SIZE" has type "int"
				
				if(resultSet.next()) {
					throw new TooMuchColumnsException(tableName, columnName);
				}
				
				columnLengthMap.put(tableAndColumn, length);
				
				return length;
			}
		} catch(SQLException e) {
			throw new DatabaseInformationException(String.format("Error reading column information (table: %s, column: %s)", tableName, columnName), e);
		}
	}
}
 
Example 11
Source File: TableMetaGenerator.java    From yugong with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 根据{@linkplain DatabaseMetaData}获取正确的表名
 *
 * <pre>
 * metaData中的storesUpperCaseIdentifiers,storesUpperCaseQuotedIdentifiers,storesLowerCaseIdentifiers,
 * storesLowerCaseQuotedIdentifiers,storesMixedCaseIdentifiers,storesMixedCaseQuotedIdentifiers
 * </pre>
 */
private static String getIdentifierName(String name, DatabaseMetaData metaData) throws SQLException {
    if (metaData.storesMixedCaseIdentifiers()) {
        return name; // 保留原始名
    } else if (metaData.storesUpperCaseIdentifiers()) {
        return StringUtils.upperCase(name);
    } else if (metaData.storesLowerCaseIdentifiers()) {
        return StringUtils.lowerCase(name);
    } else {
        return name;
    }
}
 
Example 12
Source File: DBMetadataUtils.java    From DBMetadata with MIT License 5 votes vote down vote up
private void initLetterCase() {
    try {
        DatabaseMetaData databaseMetaData = getConnection().getMetaData();
        if (databaseMetaData.storesLowerCaseIdentifiers()) {
            letterCase = LetterCase.LOWER;
        } else if (databaseMetaData.storesUpperCaseIdentifiers()) {
            letterCase = LetterCase.UPPER;
        } else {
            letterCase = LetterCase.NORMAL;
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
 
Example 13
Source File: Analyzer.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new analyzer for the database described by given metadata.
 *
 * @param  source     the data source, usually given by user at {@code SQLStore} creation time.
 * @param  metadata   Value of {@code source.getConnection().getMetaData()}.
 * @param  listeners  Value of {@code SQLStore.listeners}.
 * @param  locale     Value of {@code SQLStore.getLocale()}.
 */
Analyzer(final DataSource source, final DatabaseMetaData metadata, final StoreListeners listeners,
         final Locale locale) throws SQLException
{
    this.source      = source;
    this.metadata    = metadata;
    this.listeners   = listeners;
    this.locale      = locale;
    this.strings     = new HashMap<>();
    this.escape      = metadata.getSearchStringEscape();
    this.functions   = new SpatialFunctions(metadata);
    this.nameFactory = DefaultFactories.forBuildin(NameFactory.class);
    /*
     * The following tables are defined by ISO 19125 / OGC Simple feature access part 2.
     * Note that the standard specified those names in upper-case letters, which is also
     * the default case specified by the SQL standard.  However some databases use lower
     * cases instead.
     */
    String crs  = "SPATIAL_REF_SYS";
    String geom = "GEOMETRY_COLUMNS";
    if (metadata.storesLowerCaseIdentifiers()) {
        crs  = crs .toLowerCase(Locale.US).intern();
        geom = geom.toLowerCase(Locale.US).intern();
    }
    ignoredTables = new HashSet<>(4);
    ignoredTables.add(crs);
    ignoredTables.add(geom);
    final Dialect dialect = Dialect.guess(metadata);
    if (dialect == Dialect.POSTGRESQL) {
        ignoredTables.add("geography_columns");     // Postgis 1+
        ignoredTables.add("raster_columns");        // Postgis 2
        ignoredTables.add("raster_overviews");
    }
    /*
     * Information to be collected during table analysis.
     */
    tables   = new HashMap<>();
    warnings = new LinkedHashSet<>();
}
 
Example 14
Source File: IdentifierHelperBuilder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public void applyIdentifierCasing(DatabaseMetaData metaData) throws SQLException {
	if ( metaData == null ) {
		return;
	}

	final int unquotedAffirmatives = ArrayHelper.countTrue(
			metaData.storesLowerCaseIdentifiers(),
			metaData.storesUpperCaseIdentifiers(),
			metaData.storesMixedCaseIdentifiers()
	);

	if ( unquotedAffirmatives == 0 ) {
		log.debug( "JDBC driver metadata reported database stores unquoted identifiers in neither upper, lower nor mixed case" );
	}
	else {
		// NOTE : still "dodgy" if more than one is true
		if ( unquotedAffirmatives > 1 ) {
			log.debug( "JDBC driver metadata reported database stores unquoted identifiers in more than one case" );
		}

		if ( metaData.storesUpperCaseIdentifiers() ) {
			this.unquotedCaseStrategy = IdentifierCaseStrategy.UPPER;
		}
		else if ( metaData.storesLowerCaseIdentifiers() ) {
			this.unquotedCaseStrategy = IdentifierCaseStrategy.LOWER;
		}
		else {
			this.unquotedCaseStrategy = IdentifierCaseStrategy.MIXED;
		}
	}


	final int quotedAffirmatives = ArrayHelper.countTrue(
			metaData.storesLowerCaseQuotedIdentifiers(),
			metaData.storesUpperCaseQuotedIdentifiers(),
			metaData.storesMixedCaseQuotedIdentifiers()
	);

	if ( quotedAffirmatives == 0 ) {
		log.debug( "JDBC driver metadata reported database stores quoted identifiers in neither upper, lower nor mixed case" );
	}
	else {
		// NOTE : still "dodgy" if more than one is true
		if ( quotedAffirmatives > 1 ) {
			log.debug( "JDBC driver metadata reported database stores quoted identifiers in more than one case" );
		}

		if ( metaData.storesMixedCaseQuotedIdentifiers() ) {
			this.quotedCaseStrategy = IdentifierCaseStrategy.MIXED;
		}
		else if ( metaData.storesLowerCaseQuotedIdentifiers() ) {
			this.quotedCaseStrategy = IdentifierCaseStrategy.LOWER;
		}
		else {
			this.quotedCaseStrategy = IdentifierCaseStrategy.UPPER;
		}
	}
}
 
Example 15
Source File: FrameworkUtils.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Check whether the specified column of the specified table exists in the Identity database.
 *
 * @param tableName name of the table.
 * @param columnName name of the column.
 * @return true if column exists.
 */
public static boolean isTableColumnExists(String tableName, String columnName) {

    try (Connection connection = IdentityDatabaseUtil.getDBConnection()) {

        DatabaseMetaData metaData = connection.getMetaData();
        if (metaData.storesLowerCaseIdentifiers()) {
            tableName = tableName.toLowerCase();
            columnName = columnName.toLowerCase();
        }

        String schemaPattern = null;
        if (metaData.getDriverName().contains("Oracle")){
            if (log.isDebugEnabled()) {
                log.debug("DB type detected as Oracle. Setting schemaPattern to " + metaData.getUserName());
            }
            // Oracle checks the availability of the table column
            // in all users in the DB unless specified.
            schemaPattern = metaData.getUserName();
        }
        try (ResultSet resultSet = metaData.getColumns(null, schemaPattern, tableName, columnName)) {
            if (resultSet.next()) {
                if (log.isDebugEnabled()) {
                    log.debug("Column - " + columnName + " in table - " + tableName + " is available in the " +
                            "Identity database.");
                }
                IdentityDatabaseUtil.commitTransaction(connection);
                return true;
            }
            IdentityDatabaseUtil.commitTransaction(connection);
        } catch (SQLException ex) {
            IdentityDatabaseUtil.rollbackTransaction(connection);
            if (log.isDebugEnabled()) {
                log.debug("Column - " + columnName + " in table - " + tableName + " is not available in the " +
                        "Identity database.");
            }
            return false;
        }

    } catch (SQLException e) {
        if (log.isDebugEnabled()) {
            log.debug("Column - " + columnName + " in table - " + tableName + " is not available in the " +
                    "Identity database.");
        }
        return false;
    }
    if (log.isDebugEnabled()) {
        log.debug("Column - " + columnName + " in table - " + tableName + " is not available in the " +
                "Identity database.");
    }
    return false;
}