List of usage examples for java.sql DatabaseMetaData getColumns
ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern)
throws SQLException;
From source file:com.linuxbox.enkive.audit.sqldb.SqlDbAuditService.java
/** * Since the description column is of finite size, we may need to truncate * long descriptions to fit in the column. We need to determine the size of * the column, which is likely to be described in a Liquibase changelog XML * file. Rather than try to keep the Java and XML copies in sync, this just * retrieves the current column size from the databases metadata. * /* w w w .java 2 s .c om*/ * @return * @throws AuditServiceException */ public int getDescriptionColumnSize() throws AuditServiceException { AuditOperation<Integer> op = new AuditOperation<Integer>() { @Override public Integer execute(Connection connection) throws SQLException, AuditServiceException { int columnSize = -1; DatabaseMetaData metaData = connection.getMetaData(); ResultSet resultSet = metaData.getColumns(null, null, "events", "description"); setResultSet(resultSet); if (resultSet.next()) { columnSize = resultSet.getInt("COLUMN_SIZE"); if (resultSet.next()) { throw new AuditServiceException( "retrieved multiple column metadata entries for the description column in the events table"); } } else { throw new AuditServiceException( "could not retrieve the size of the description column in the events table"); } return columnSize; } }; return op.executeAuditOperation(); }
From source file:org.batoo.jpa.core.jdbc.adapter.JdbcTable.java
private void readColumns(DatabaseMetaData dbMetadata) throws SQLException { ResultSet rs = null;//from w ww .j a v a 2 s . co m try { rs = dbMetadata.getColumns(this.catalog, this.schema, this.name, "%"); while (rs.next()) { final JdbcColumn jdbcColumn = new JdbcColumn(rs); this.columns.put(jdbcColumn.getName().toUpperCase(), jdbcColumn); } } finally { DbUtils.closeQuietly(rs); } }
From source file:org.jtalks.poulpe.util.databasebackup.persistence.DbTableData.java
/** * Gets a default values for each of the columns if that values are defined for the columns. * // w ww . j a va 2 s.c o m * @param dbMetaData * a DatabaseMetaData instance to fetch the information from. * @return A map where key is a Column name and value is Column's default. * @throws SQLException * Is thrown in case any errors during work with database occur. */ private Map<String, String> getColumnDefaults(final DatabaseMetaData dbMetaData) throws SQLException { Map<String, String> columnDefaultValues = new HashMap<String, String>(); ResultSet tableMetaData = null; try { tableMetaData = dbMetaData.getColumns(null, null, tableName, "%"); while (tableMetaData.next()) { String defaultValue = tableMetaData.getString("COLUMN_DEF"); if (defaultValue != null && defaultValue.length() > 0) { columnDefaultValues.put(tableMetaData.getString("COLUMN_NAME"), defaultValue); } } } finally { if (tableMetaData != null) { tableMetaData.close(); } } return columnDefaultValues; }
From source file:org.openmrs.module.spreadsheetimport.DatabaseBackend.java
public static String importData(Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData, boolean rollbackTransaction) throws Exception { Connection conn = null;//w w w. j a v a2 s. c o m Statement s = null; Exception exception = null; String sql = null; String encounterId = null; try { // Connect to db Class.forName("com.mysql.jdbc.Driver").newInstance(); Properties p = Context.getRuntimeProperties(); String url = p.getProperty("connection.url"); conn = DriverManager.getConnection(url, p.getProperty("connection.username"), p.getProperty("connection.password")); conn.setAutoCommit(false); s = conn.createStatement(); List<String> importedTables = new ArrayList<String>(); // Import for (UniqueImport uniqueImport : rowData.keySet()) { String tableName = uniqueImport.getTableName(); boolean isEncounter = "encounter".equals(tableName); boolean isPerson = "person".equals(tableName); boolean isPatientIdentifier = "patient_identifier".equals(tableName); boolean isObservation = "obs".equals(tableName); boolean skip = false; // SPECIAL TREATMENT // for encounter, if the data is available in the row, it means we're UPDATING observations for an EXISTING encounter, so we don't have to create encounter // otherwise, we need to create a new encounter if (isEncounter) { Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { Object columnValue = column.getValue(); if (!columnValue.equals("")) { column.setGeneratedKey(columnValue.toString()); skip = true; importedTables.add("encounter"); // fake as just imported encounter break; } } if (skip) continue; } // SPECIAL TREATMENT // for observation, if the data to be inserted is empty, then simply skip if (isObservation) { Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { Object columnValue = column.getValue(); if (columnValue.equals("")) { skip = true; importedTables.add("observation"); // fake as just imported observation, not meaningful, just for consistency purpose break; } } if (skip) continue; } if (isPerson) { boolean isIdentifierExist = false; // SPECIAL TREATMENT 1 // if the patient_identifier.identifier is specified and it is linked to a person, then use that person instead // note: patient.patient_id == person.person_id (http://forum.openmrs.org/viewtopic.php?f=2&t=436) UniqueImport patientIdentifier = new UniqueImport("patient_identifier", null); if (rowData.containsKey(patientIdentifier)) { Set<SpreadsheetImportTemplateColumn> patientIdentifierColumns = rowData .get(patientIdentifier); for (SpreadsheetImportTemplateColumn patientIdentifierColumn : patientIdentifierColumns) { String columnName = patientIdentifierColumn.getColumnName(); if ("identifier".equals(columnName)) { isIdentifierExist = true; sql = "select patient_id from patient_identifier where identifier = " + patientIdentifierColumn.getValue(); System.out.println("Searching for existing patient of id " + patientIdentifierColumn.getValue()); ResultSet rs = s.executeQuery(sql); if (rs.next()) { String patientId = rs.getString(1); System.out.println("Found patient with patient_id = " + patientId); // no need to insert person, use the found patient_id as person_id Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { column.setGeneratedKey(patientId); } importedTables.add("person"); // fake as just imported person importedTables.add("patient"); // fake as just imported patient importedTables.add("patient_identifier"); // fake as just imported patient_identifier importedTables.add("person_name"); // fake as just imported person_name importedTables.add("person_address"); // fake as just imported person_address skip = true; } rs.close(); break; } } } if (skip) continue; // now, if we proceed to this point, it means patient identifier, if exists, does not match, and in that case, no point to match with person name // SPECIAL TREATMENT 2 // if first name, last name, middle name, gender, and birthdate match existing record, then use that record instead UniqueImport personName = new UniqueImport("person_name", null); if (rowData.containsKey(personName) && !isIdentifierExist) { Set<SpreadsheetImportTemplateColumn> personNameColumns = rowData.get(personName); // getting gender, birthdate from person Object gender = null; Object birthdate = null; for (SpreadsheetImportTemplateColumn personColumn : rowData.get(uniqueImport)) { String columnName = personColumn.getColumnName(); if ("birth_date".equals(columnName)) birthdate = personColumn.getValue(); if ("gender".equals(columnName)) gender = personColumn.getValue(); } // getting first name, last name, middle name from person Object givenName = null; Object familyName = null; Object middleName = null; for (SpreadsheetImportTemplateColumn personNameColumn : personNameColumns) { String columnName = personNameColumn.getColumnName(); if ("given_name".equals(columnName)) givenName = personNameColumn.getValue(); if ("family_name".equals(columnName)) familyName = personNameColumn.getValue(); if ("middle_name".equals(columnName)) middleName = personNameColumn.getValue(); } // find matching person name sql = "select person.person_id from person_name join person where gender " + (gender == null ? "is NULL" : "= " + gender) + " and birthdate " + (birthdate == null ? "is NULL" : "= " + birthdate) + " and given_name " + (givenName == null ? "is NULL" : "= " + givenName) + " and family_name " + (familyName == null ? "is NULL" : "= " + familyName) + " and middle_name " + (middleName == null ? "is NULL" : "= " + middleName); ResultSet rs = s.executeQuery(sql); String personId = null; if (rs.next()) { // matched => no need to insert person, use the found patient_id as person_id Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { column.setGeneratedKey(personId); } importedTables.add("person"); // fake as just imported person importedTables.add("patient"); // fake as just imported patient importedTables.add("person_name"); // fake as just imported person_name importedTables.add("person_address"); // fake as just imported person_address skip = true; } } if (skip) continue; } if (isPatientIdentifier && importedTables.contains("patient_identifier")) continue; // Data from columns Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); String columnNames = ""; String columnValues = ""; Set<SpreadsheetImportTemplateColumnPrespecifiedValue> columnPrespecifiedValueSet = null; Set<SpreadsheetImportTemplateColumnColumn> columnColumnsImportBefore = null; boolean isFirst = true; for (SpreadsheetImportTemplateColumn column : columnSet) { // special treatment for encounter: simply ignore this loop since we don't want to insert encounter_id if (isEncounter) { columnPrespecifiedValueSet = column.getColumnPrespecifiedValues(); columnColumnsImportBefore = column.getColumnColumnsImportBefore(); // inject date_created columnNames += "date_created"; columnValues += "now()"; // find encounter_datetime based on observation date time java.sql.Date encounterDatetime = new java.sql.Date(System.currentTimeMillis()); Set<UniqueImport> uniqueImports = rowData.keySet(); for (UniqueImport u : uniqueImports) { if ("obs".equals(u.getTableName())) { Set<SpreadsheetImportTemplateColumn> obsColumns = rowData.get(u); for (SpreadsheetImportTemplateColumn obsColumn : obsColumns) { if ("obs_datetime".equals(obsColumn.getColumnName())) { String obsColumnValue = obsColumn.getValue().toString(); obsColumnValue = obsColumnValue.substring(1, obsColumnValue.length() - 1); Date obsColumnValueDate = java.sql.Date.valueOf(obsColumnValue); if (obsColumnValueDate.before(encounterDatetime)) encounterDatetime = obsColumnValueDate; } } } } columnNames += ", encounter_datetime"; columnValues += ",'" + encounterDatetime.toString() + "'"; isFirst = false; break; } // Check for duplicates if (column.getDisallowDuplicateValue()) { sql = "select " + column.getColumnName() + " from " + column.getTableName() + " where " + column.getColumnName() + " = " + column.getValue(); if (log.isDebugEnabled()) { log.debug(sql); System.out.println(sql); } ResultSet rs = s.executeQuery(sql); boolean foundDuplicate = rs.next(); rs.close(); if (foundDuplicate) { throw new SpreadsheetImportDuplicateValueException(column); } } if (isFirst) { // Should be same for all columns in unique import columnPrespecifiedValueSet = column.getColumnPrespecifiedValues(); columnColumnsImportBefore = column.getColumnColumnsImportBefore(); isFirst = false; } else { columnNames += ","; columnValues += ","; } columnNames += column.getColumnName(); columnValues += column.getValue().toString(); } // Data from pre-specified values for (SpreadsheetImportTemplateColumnPrespecifiedValue columnPrespecifiedValue : columnPrespecifiedValueSet) { if (isFirst) isFirst = false; else { columnNames += ","; columnValues += ","; } columnNames += columnPrespecifiedValue.getColumnName(); columnValues += columnPrespecifiedValue.getPrespecifiedValue().getValue(); } // Data from columns import before if (!columnColumnsImportBefore.isEmpty()) { // Set up Map<String, String> mapPrimaryKeyColumnNameToGeneratedKey = new HashMap<String, String>(); for (SpreadsheetImportTemplateColumnColumn columnColumn : columnColumnsImportBefore) { String primaryKeyColumnName = columnColumn.getColumnName(); String columnGeneratedKey = columnColumn.getColumnImportFirst().getGeneratedKey(); if (mapPrimaryKeyColumnNameToGeneratedKey.containsKey(primaryKeyColumnName)) { String mapGeneratedKey = mapPrimaryKeyColumnNameToGeneratedKey .get(primaryKeyColumnName); if (!mapGeneratedKey.equals(columnGeneratedKey)) { throw new SpreadsheetImportUnhandledCaseException(); } } else { mapPrimaryKeyColumnNameToGeneratedKey.put(primaryKeyColumnName, columnGeneratedKey); } // TODO: I believe patient and person are only tables with this relationship, if not, then this // needs to be generalized if (primaryKeyColumnName.equals("patient_id") && importedTables.contains("person") && !importedTables.contains("patient")) { sql = "insert into patient (patient_id, creator) values (" + columnGeneratedKey + ", " + Context.getAuthenticatedUser().getId() + ")"; if (log.isDebugEnabled()) { log.debug(sql); } s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); // ResultSet rs = s.getGeneratedKeys(); // rs.next(); // if (!columnGeneratedKey.equals(rs.getString(1))) { // throw new SpreadsheetImportUnhandledCaseException(); // } importedTables.add("patient"); } } // Add columns for (String columnName : mapPrimaryKeyColumnNameToGeneratedKey.keySet()) { if (isFirst) isFirst = false; else { columnNames += ","; columnValues += ","; } columnNames += columnName; columnValues += mapPrimaryKeyColumnNameToGeneratedKey.get(columnName); } } // SPECIAL TREATMENT: if this is observation, then check for column obs_datetime. If not available, then use current time if (isObservation) { boolean hasDatetime = false; for (SpreadsheetImportTemplateColumn column : columnSet) { if ("obs_datetime".equals(column.getColumnName())) { hasDatetime = true; break; } } if (!hasDatetime) { columnNames += ",obs_datetime"; columnValues += ",now()"; } columnNames += ", date_created"; columnValues += ",now()"; } // SPECIAL TREATMENT: if this is patient identifier, then set location_id to NULL, to avoid CONSTRAINT `patient_identifier_ibfk_2` FOREIGN KEY (`location_id`) REFERENCES `location` (`location_id`)) if (isPatientIdentifier) { columnNames += ", location_id"; columnValues += ", NULL"; } // creator columnNames += ",creator"; columnValues += "," + Context.getAuthenticatedUser().getId(); // uuid DatabaseMetaData dmd = conn.getMetaData(); ResultSet rsColumns = dmd.getColumns(null, null, uniqueImport.getTableName(), "uuid"); if (rsColumns.next()) { columnNames += ",uuid"; columnValues += ",uuid()"; } rsColumns.close(); // Insert tableName sql = "insert into " + uniqueImport.getTableName() + " (" + columnNames + ")" + " values (" + columnValues + ")"; System.out.println(sql); if (log.isDebugEnabled()) { log.debug(sql); } s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); ResultSet rs = s.getGeneratedKeys(); rs.next(); for (SpreadsheetImportTemplateColumn column : columnSet) { column.setGeneratedKey(rs.getString(1)); } // SPECIAL TREATMENT: update Encounter ID back to the Excel file by returning it to the caller if (isEncounter) encounterId = rs.getString(1); rs.close(); importedTables.add(uniqueImport.getTableName()); } } catch (SQLSyntaxErrorException e) { throw new SpreadsheetImportSQLSyntaxException(sql, e.getMessage()); } catch (Exception e) { log.debug(e.toString()); exception = e; throw new SpreadsheetImportSQLSyntaxException(sql, e.getMessage()); // TODO: for web debug purpose only, should comment out later } finally { if (s != null) { try { s.close(); } catch (Exception e) { } } if (conn != null) { if (rollbackTransaction) { conn.rollback(); } else { conn.commit(); } try { conn.close(); } catch (Exception e) { } } } if (exception != null) { throw exception; } return encounterId; }
From source file:org.dbmaintain.database.impl.DerbyDatabase.java
/** * Returns the names of all columns that have a 'not-null' constraint on them. * <p/>/* ww w.j av a 2 s.c om*/ * This info is not available in the Derby sys tables. The database meta data is used instead to retrieve it. * * @param schemaName The schema, not null * @param tableName The table, not null * @return The set of column names, not null */ protected Set<String> getNotNullColummnNames(String schemaName, String tableName) { Connection connection = null; ResultSet resultSet = null; try { connection = getDataSource().getConnection(); DatabaseMetaData databaseMetaData = connection.getMetaData(); resultSet = databaseMetaData.getColumns(null, schemaName, tableName, "%"); Set<String> result = new HashSet<String>(); while (resultSet.next()) { if (resultSet.getInt(11) == DatabaseMetaData.columnNoNulls) { // NULLABLE result.add(resultSet.getString(4)); //COLUMN_NAME } } return result; } catch (SQLException e) { throw new DatabaseException("Unable to get not null column names for schema name: " + schemaName + ", table name: " + tableName, e); } finally { closeQuietly(connection, null, resultSet); } }
From source file:com.netflix.metacat.connector.jdbc.services.JdbcConnectorTableService.java
/** * Get the columns for a table. See//ww w. java 2 s . c o m * {@link java.sql.DatabaseMetaData#getColumns(String, String, String, String) getColumns} for format of the * ResultSet columns. * * @param connection The database connection to use * @param name The qualified name of the table to get the column descriptions for * @return The result set of information * @throws SQLException on query error */ protected ResultSet getColumns(@Nonnull @NonNull final Connection connection, @Nonnull @NonNull final QualifiedName name) throws SQLException { final String database = name.getDatabaseName(); final DatabaseMetaData metaData = connection.getMetaData(); return metaData.getColumns(database, database, name.getTableName(), JdbcConnectorUtils.MULTI_CHARACTER_SEARCH); }
From source file:com.qualogy.qafe.business.integration.rdb.SQLQueryDAO.java
/** * @param ds//from www . j a v a2 s . c o m * @param tableName * @throws SQLException */ private void populateTableColumnSet(DataSource ds, String tableName) throws SQLException { Connection conn = ds.getConnection(); DatabaseMetaData dbmd = conn.getMetaData(); ResultSet rsc = dbmd.getColumns(conn.getCatalog(), null, tableName, "%"); Set<String> foundColumnSet = new HashSet<String>(); while (rsc.next()) { String columnName = rsc.getString("COLUMN_NAME"); foundColumnSet.add(columnName); } tableColumnSet.put(tableName, foundColumnSet); DataSourceUtils.releaseConnection(conn, ds); }
From source file:com.uber.hoodie.hive.client.HoodieHiveClient.java
/** * Get the table schema//from www . j a va 2 s . co m * * @param datasetReference * @return */ public Map<String, String> getTableSchema(HoodieDatasetReference datasetReference) { if (!checkTableExists(datasetReference)) { throw new IllegalArgumentException( "Failed to get schema as table " + datasetReference.getDatabaseTableName() + " does not exist"); } Map<String, String> schema = Maps.newHashMap(); ResultSet result = null; try { Connection connection = getConnection(); DatabaseMetaData databaseMetaData = connection.getMetaData(); result = databaseMetaData.getColumns(null, datasetReference.getDatabaseName(), datasetReference.getTableName(), null); while (result.next()) { String columnName = result.getString(4); String columnType = result.getString(6); schema.put(columnName, columnType); } return schema; } catch (SQLException e) { throw new HoodieHiveDatasetException("Failed to get table schema for " + datasetReference, e); } finally { closeQuietly(result, null); } }
From source file:net.hydromatic.optiq.impl.jdbc.JdbcSchema.java
RelProtoDataType getRelDataType(DatabaseMetaData metaData, String catalogName, String schemaName, String tableName) throws SQLException { final ResultSet resultSet = metaData.getColumns(catalogName, schemaName, tableName, null); // Temporary type factory, just for the duration of this method. Allowable // because we're creating a proto-type, not a type; before being used, the // proto-type will be copied into a real type factory. final RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(); final RelDataTypeFactory.FieldInfoBuilder fieldInfo = typeFactory.builder(); while (resultSet.next()) { final String columnName = resultSet.getString(4); final int dataType = resultSet.getInt(5); final int size = resultSet.getInt(7); final int scale = resultSet.getInt(9); RelDataType sqlType = sqlType(typeFactory, dataType, size, scale); boolean nullable = resultSet.getBoolean(11); fieldInfo.add(columnName, sqlType).nullable(nullable); }//from w w w . j a v a 2s. co m resultSet.close(); return RelDataTypeImpl.proto(fieldInfo.build()); }
From source file:org.wso2.cep.broker.RDBMSBrokerType.java
private TableInfo initializeTableInfo(String databaseName, String tableName, Object message, BrokerConfiguration brokerConfiguration, Connection connection) throws SQLException { TableInfo tableInfo = new TableInfo(); tableInfo.setTableName(tableName);/*from w w w . j a v a 2 s. c om*/ // create the table. StringBuilder stringBuilder = new StringBuilder("CREATE TABLE IF NOT EXISTS "); stringBuilder.append(tableName); stringBuilder.append(" ("); boolean appendComma = false; for (Map.Entry<String, Object> entry : (((Map<String, Object>) message).entrySet())) { if (appendComma) { stringBuilder.append(","); } else { appendComma = true; } stringBuilder.append(entry.getKey()).append(" "); if (entry.getValue() instanceof Integer) { stringBuilder.append("INT"); } else if (entry.getValue() instanceof Long) { stringBuilder.append("BIGINT"); } else if (entry.getValue() instanceof Float) { stringBuilder.append("FLOAT"); } else if (entry.getValue() instanceof Double) { stringBuilder.append("DOUBLE"); } else if (entry.getValue() instanceof String) { stringBuilder.append("VARCHAR(255)"); } else if (entry.getValue() instanceof Boolean) { stringBuilder.append("BOOL"); } } stringBuilder.append(")"); Statement statement = connection.createStatement(); statement.executeUpdate(stringBuilder.toString()); statement.close(); ArrayList<Attribute> tableColumnList = new ArrayList<Attribute>(); stringBuilder = new StringBuilder("INSERT INTO "); stringBuilder.append(tableName); stringBuilder.append(" ( "); StringBuilder values = new StringBuilder(""); appendComma = false; DatabaseMetaData databaseMetaData = connection.getMetaData(); ResultSet rs = databaseMetaData.getColumns(null, null, databaseName + "." + 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.BOOLEAN: type = AttributeType.BOOL; break; } Attribute attribute = new Attribute(rs.getString("COLUMN_NAME"), type); tableColumnList.add(attribute); if (appendComma) { stringBuilder.append(","); values.append(","); } else { appendComma = true; } stringBuilder.append(attribute.getName()); values.append("?"); } stringBuilder.append(") VALUES ("); stringBuilder.append(values); stringBuilder.append(")"); tableInfo.setColumnOrder(tableColumnList); tableInfo.setPreparedStatement(connection.prepareStatement(stringBuilder.toString())); return tableInfo; }