java.sql.DatabaseMetaData Java Examples

The following examples show how to use java.sql.DatabaseMetaData. 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: TajoTypeUtil.java    From tajo with Apache License 2.0 6 votes vote down vote up
public static short getSearchable(Type type) {
  /*
   * DatabaseMetaData.typePredNone - No support
   * DatabaseMetaData.typePredChar - Only support with WHERE .. LIKE
   * DatabaseMetaData.typePredBasic - Supported except for WHERE .. LIKE
   * DatabaseMetaData.typeSearchable - Supported for all WHERE ..
   */
  switch (type) {
    case INT1:
    case INT2:
    case INT4:
    case INT8:
    case FLOAT4:
    case FLOAT8:
    case DATE:
    case TIME:
    case TIMESTAMP:
    case NUMERIC: return DatabaseMetaData.typePredBasic;
    case VARCHAR:
    case TEXT: return DatabaseMetaData.typeSearchable;
    default: return DatabaseMetaData.typePredBasic;
  }
}
 
Example #2
Source File: MetaDataRegressionTest.java    From r-course with MIT License 6 votes vote down vote up
/**
 * Tests fix for BUG#21215151 - DATABASEMETADATA.GETCATALOGS() FAILS TO SORT RESULTS.
 * 
 * DatabaseMetaData.GetCatalogs() relies on the results of 'SHOW DATABASES' which deliver a sorted list of databases except for 'information_schema' which
 * is always returned in the first position.
 * This test creates set of databases around the relative position of 'information_schema' and checks the ordering of the final ResultSet.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug21215151() throws Exception {
    createDatabase("z_testBug21215151");
    createDatabase("j_testBug21215151");
    createDatabase("h_testBug21215151");
    createDatabase("i_testBug21215151");
    createDatabase("a_testBug21215151");

    DatabaseMetaData dbmd = this.conn.getMetaData();
    this.rs = dbmd.getCatalogs();

    System.out.println("Catalogs:");
    System.out.println("--------------------------------------------------");
    while (this.rs.next()) {
        System.out.println("\t" + this.rs.getString(1));
    }
    this.rs.beforeFirst();

    // check the relative position of each element in the result set compared to the previous element.
    String previousDb = "";
    while (this.rs.next()) {
        assertTrue("'" + this.rs.getString(1) + "' is lexicographically lower than the previous catalog. Check the system output to see the catalogs list.",
                previousDb.compareTo(this.rs.getString(1)) < 0);
        previousDb = this.rs.getString(1);
    }
}
 
Example #3
Source File: ConcurrentConnTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public static void getPrimaryKeys(DatabaseMetaData dmd, String tablePattern,PrintStream out)
throws SQLException
{
  ResultSet rs = dmd.getPrimaryKeys(null, null, tablePattern);
  while (rs.next())
  {
    // 1.TABLE_CAT String => table catalog (may be null)
    String tableCat = rs.getString(1);

    // 2.TABLE_SCHEM String => table schema (may be null)
    String tableSchem = rs.getString(2);

    // 3.TABLE_NAME String => table name
    String tableName = rs.getString(3);

    // 4.COLUMN_NAME String => column name
    String columnName = rs.getString(4);

    // 5.KEY_SEQ short => sequence number within primary key
    short keySeq = rs.getShort(5);

    // 6.PK_NAME String => primary key name (may be null)
    String pkName = rs.getString(6);
  }
  rs.close();
}
 
Example #4
Source File: SectDBSynchronizer.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
protected void addParentTables(DatabaseMetaData metaData, String schema,
    String tableName, String fullTableName) throws SQLException {
  HashSet<String> parents = this.parentTables.get(fullTableName);
  if (parents == null) {
    parents = new HashSet<String>(5);
    this.parentTables.put(fullTableName, parents);
  }
  ResultSet parentRS = metaData.getImportedKeys(null, schema, tableName);
  while (parentRS.next()) {
    String parentSchema = parentRS.getString("PKTABLE_SCHEM");
    String parentTableName = parentRS.getString("PKTABLE_NAME");
    parents = this.parentTables.get(fullTableName);
    if (parentSchema == null) {
      parentSchema = schema;
    }
    parents.add(parentSchema != null ? parentSchema + '.' + parentTableName
        : parentTableName);
  }
  parentRS.close();
}
 
Example #5
Source File: MySqlDefaultChanger.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @return list of {@link Columns} we can toggle with suffixes indicating their NOT NULL and default value status
 */
private String constructColumnListWithMetadata() {
    try (Connection con = getConnection(mySql)) {
        final DatabaseMetaData metaData = con.getMetaData();
        final String tableName = settings.getProperty(DatabaseSettings.MYSQL_TABLE);

        List<String> formattedColumns = new ArrayList<>(Columns.values().length);
        for (Columns col : Columns.values()) {
            formattedColumns.add(formatColumnWithMetadata(col, metaData, tableName));
        }
        return String.join(ChatColor.RESET + ", ", formattedColumns);
    } catch (SQLException e) {
        logger.logException("Failed to construct column list:", e);
        return ChatColor.RED + "An error occurred! Please see the console for details.";
    }
}
 
Example #6
Source File: LangProcedureTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
static String PARAMTYPE(short type) {
    switch (type) {
    case DatabaseMetaData.procedureColumnUnknown:
        return "procedureColumnUnknown";
    case DatabaseMetaData.procedureColumnIn:
        return "procedureColumnIn";
    case DatabaseMetaData.procedureColumnInOut:
        return "procedureColumnInOut";
    case DatabaseMetaData.procedureColumnOut:
        return "procedureColumnOut";
    case DatabaseMetaData.procedureColumnReturn:
        return "procedureColumnReturn";
    case DatabaseMetaData.procedureColumnResult:
        return "procedureColumnResult";
    default:
        return "???";
    }
}
 
Example #7
Source File: ImportFromDBManagerBase.java    From ermaster-b with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws InputException,
		InstantiationException, IllegalAccessException, SQLException {
	new Activator();

	DBSetting setting = new DBSetting("Oracle", "localhost", 1521, "XE",
			"nakajima", "nakajima", true, null, null);

	Connection con = null;
	try {
		con = setting.connect();
		DatabaseMetaData metaData = con.getMetaData();

		metaData.getIndexInfo(null, "SYS", "ALERT_QT", false, false);

	} finally {
		if (con != null) {
			con.close();
		}
	}
}
 
Example #8
Source File: MetaDataRegressionTest.java    From Komondor with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Tests fix for BUG#21978216, GETTYPEINFO REPORT MAXIMUM PRECISION OF 255 FOR VARBINARY
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug21978216() throws Exception {

    DatabaseMetaData meta = this.conn.getMetaData();
    this.rs = meta.getTypeInfo();
    while (this.rs.next()) {
        if (this.rs.getString("TYPE_NAME").equals("VARBINARY")) {
            if (versionMeetsMinimum(5, 0, 3)) {
                assertEquals(65535, this.rs.getInt("PRECISION"));
            } else {
                assertEquals(255, this.rs.getInt("PRECISION"));
            }
        }
    }

}
 
Example #9
Source File: JethroDataSqlDialect.java    From Bats with Apache License 2.0 6 votes vote down vote up
public JethroInfo get(final DatabaseMetaData metaData) {
  try {
    assert "JethroData".equals(metaData.getDatabaseProductName());
    String productVersion = metaData.getDatabaseProductVersion();
    synchronized (JethroInfoCacheImpl.this) {
      JethroInfo info = map.get(productVersion);
      if (info == null) {
        final Connection c = metaData.getConnection();
        info = makeInfo(c);
        map.put(productVersion, info);
      }
      return info;
    }
  } catch (Exception e) {
    LOGGER.error("Failed to create JethroDataDialect", e);
    throw new RuntimeException("Failed to create JethroDataDialect", e);
  }
}
 
Example #10
Source File: DatabaseRecordSink.java    From nifi with Apache License 2.0 6 votes vote down vote up
static TableSchema from(final Connection conn, final String catalog, final String schema, final String tableName,
                        final boolean translateColumnNames) throws SQLException {
    final DatabaseMetaData dmd = conn.getMetaData();
    if (!dmd.getTables(catalog, schema, tableName, null).next()) {
        throw new SQLException("Table " + tableName + " does not exist in the database");
    }

    try (final ResultSet colrs = dmd.getColumns(catalog, schema, tableName, "%")) {
        final List<ColumnDescription> cols = new ArrayList<>();
        while (colrs.next()) {
            final ColumnDescription col = ColumnDescription.from(colrs);
            cols.add(col);
        }

        return new TableSchema(cols, translateColumnNames, dmd.getIdentifierQuoteString());
    }
}
 
Example #11
Source File: DatabaseMetaDataIT.java    From snowflake-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void testFeatureNotSupportedException() throws Throwable
{
  try (Connection connection = getConnection())
  {
    DatabaseMetaData metaData = connection.getMetaData();
    expectFeatureNotSupportedException(() -> metaData.getBestRowIdentifier(
        null, null, null, 0, true));
    expectFeatureNotSupportedException(() -> metaData.getVersionColumns(null, null, null));
    expectFeatureNotSupportedException(() -> metaData.getSuperTypes(null, null, null));
    expectFeatureNotSupportedException(() -> metaData.getSuperTables(null, null, null));
    expectFeatureNotSupportedException(() -> metaData.getAttributes(null, null, null, null));
    expectFeatureNotSupportedException(metaData::getSQLStateType);
    expectFeatureNotSupportedException(metaData::locatorsUpdateCopy);
    expectFeatureNotSupportedException(metaData::getRowIdLifetime);
    expectFeatureNotSupportedException(metaData::autoCommitFailureClosesAllResultSets);
    expectFeatureNotSupportedException(metaData::getClientInfoProperties);
    expectFeatureNotSupportedException(() -> metaData.getPseudoColumns(null, null, null, null));
    expectFeatureNotSupportedException(metaData::generatedKeyAlwaysReturned);
    expectFeatureNotSupportedException(() -> metaData.unwrap(SnowflakeDatabaseMetaData.class));
    expectFeatureNotSupportedException(() -> metaData.isWrapperFor(SnowflakeDatabaseMetaData.class));
  }
}
 
Example #12
Source File: DbEngineManager.java    From aceql-http with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    * Returns true if Oracle Version is >= 12.1 (12.c)
    * 
    * @param connection
    * @return true if Oracle Version is >= 12.1 (12.c)
    * @throws SQLException
    */
   public static boolean isOracleVersionGtOrEq12c(Connection connection)
    throws SQLException {
DatabaseMetaData databaseMetaData = connection.getMetaData();
int versionMajor = databaseMetaData.getDatabaseMajorVersion();
int versionMinnor = databaseMetaData.getDatabaseMinorVersion();

if (versionMajor < 12) {
    return false;
} else if (versionMajor == 12) {
    if (versionMinnor >= 1) {
	return true;
    } else {
	return false;
    }
} else {
    return true;
}

   }
 
Example #13
Source File: NativeJdbcExtractorAdapter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Check for a ConnectionProxy chain, then delegate to doGetNativeConnection.
 * <p>ConnectionProxy is used by Spring's TransactionAwareDataSourceProxy
 * and LazyConnectionDataSourceProxy. The target connection behind it is
 * typically one from a local connection pool, to be unwrapped by the
 * doGetNativeConnection implementation of a concrete subclass.
 * @see #doGetNativeConnection
 * @see org.springframework.jdbc.datasource.ConnectionProxy
 * @see org.springframework.jdbc.datasource.DataSourceUtils#getTargetConnection
 * @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
 * @see org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy
 */
@Override
public Connection getNativeConnection(Connection con) throws SQLException {
	if (con == null) {
		return null;
	}
	Connection targetCon = DataSourceUtils.getTargetConnection(con);
	Connection nativeCon = doGetNativeConnection(targetCon);
	if (nativeCon == targetCon) {
		// We haven't received a different Connection, so we'll assume that there's
		// some additional proxying going on. Let's check whether we get something
		// different back from the DatabaseMetaData.getConnection() call.
		DatabaseMetaData metaData = targetCon.getMetaData();
		// The following check is only really there for mock Connections
		// which might not carry a DatabaseMetaData instance.
		if (metaData != null) {
			Connection metaCon = metaData.getConnection();
			if (metaCon != null && metaCon != targetCon) {
				// We've received a different Connection there:
				// Let's retry the native extraction process with it.
				nativeCon = doGetNativeConnection(metaCon);
			}
		}
	}
	return nativeCon;
}
 
Example #14
Source File: JdbcUtils.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
/**
 * Return whether the given JDBC driver supports JDBC 2.0 batch updates.
 * <p>Typically invoked right before execution of a given set of statements:
 * to decide whether the set of SQL statements should be executed through
 * the JDBC 2.0 batch mechanism or simply in a traditional one-by-one fashion.
 * <p>Logs a warning if the "supportsBatchUpdates" methods throws an exception
 * and simply returns {@code false} in that case.
 * @param con the Connection to check
 * @return whether JDBC 2.0 batch updates are supported
 * @see java.sql.DatabaseMetaData#supportsBatchUpdates()
 */
public static boolean supportsBatchUpdates(Connection con) {
	try {
		DatabaseMetaData dbmd = con.getMetaData();
		if (dbmd != null) {
			if (dbmd.supportsBatchUpdates()) {
				logger.debug("JDBC driver supports batch updates");
				return true;
			}
			else {
				logger.debug("JDBC driver does not support batch updates");
			}
		}
	}
	catch (SQLException ex) {
		logger.debug("JDBC driver 'supportsBatchUpdates' method threw exception", ex);
	}
	return false;
}
 
Example #15
Source File: UKTableMetaData.java    From youkefu with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param rs
 * @param meta
 * @param extras
 * @throws SQLException
 */
public UKTableMetaData(ResultSet rs, DatabaseMetaData meta, boolean extras, boolean upcase , boolean loadColumns , String dbtype)
		throws SQLException {
	if(dbtype!=null && dbtype.equals("hive")){
		catalog = null;
		schema = null;
		if(upcase){
			name =  rs.getObject("tab_name").toString() ;
		}else{
			name = rs.getObject("tab_name").toString();
		}
	}else{
		catalog = rs.getString("TABLE_CAT");
		schema = rs.getString("TABLE_SCHEM");
		if(upcase){
			name =  rs.getString("TABLE_NAME").toUpperCase() ;
		}else{
			name = rs.getString("TABLE_NAME");
		}
	}
	
	if(loadColumns){
		initColumns(meta , upcase);
	}
}
 
Example #16
Source File: Show.java    From jsqsh with Apache License 2.0 6 votes vote down vote up
private ResultSet doFunctions(Session session, Connection con, Options options)
    throws SQLException {
    
    if (options.arguments.size() > 2) {
        
        session.err.println("Use: \\show functions [[[catalog.]schema-pattern.]func-pattern]");
        return null;
    }
    
    if (options.essential) {
        
        options.columns = essentialFunctionCols;
    }
    
    SQLConnectionContext ctx = (SQLConnectionContext) session.getConnectionContext();
    SQLObjectName name =
        (options.arguments.size() == 2) ? new SQLObjectName(ctx, options.arguments.get(1))
            : new SQLObjectName(ctx, "%");
    
    DatabaseMetaData meta = con.getMetaData();
    return meta.getFunctions(
        (options.catalog != null ? options.catalog : name.getCatalog()),
        (options.schemaPattern != null ? options.schemaPattern : name.getSchema()),
        (options.tablePattern != null ? options.tablePattern : name.getName()));
}
 
Example #17
Source File: ConcurrentConnTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public static void getPrimaryKeys(DatabaseMetaData dmd, String tablePattern,PrintStream out)
throws SQLException
{
  ResultSet rs = dmd.getPrimaryKeys(null, null, tablePattern);
  while (rs.next())
  {
    // 1.TABLE_CAT String => table catalog (may be null)
    String tableCat = rs.getString(1);

    // 2.TABLE_SCHEM String => table schema (may be null)
    String tableSchem = rs.getString(2);

    // 3.TABLE_NAME String => table name
    String tableName = rs.getString(3);

    // 4.COLUMN_NAME String => column name
    String columnName = rs.getString(4);

    // 5.KEY_SEQ short => sequence number within primary key
    short keySeq = rs.getShort(5);

    // 6.PK_NAME String => primary key name (may be null)
    String pkName = rs.getString(6);
  }
  rs.close();
}
 
Example #18
Source File: JdbcUtils.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Return whether the given JDBC driver supports JDBC 2.0 batch updates.
 * <p>Typically invoked right before execution of a given set of statements:
 * to decide whether the set of SQL statements should be executed through
 * the JDBC 2.0 batch mechanism or simply in a traditional one-by-one fashion.
 * <p>Logs a warning if the "supportsBatchUpdates" methods throws an exception
 * and simply returns {@code false} in that case.
 * @param con the Connection to check
 * @return whether JDBC 2.0 batch updates are supported
 * @see java.sql.DatabaseMetaData#supportsBatchUpdates()
 */
public static boolean supportsBatchUpdates(Connection con) {
	try {
		DatabaseMetaData dbmd = con.getMetaData();
		if (dbmd != null) {
			if (dbmd.supportsBatchUpdates()) {
				logger.debug("JDBC driver supports batch updates");
				return true;
			}
			else {
				logger.debug("JDBC driver does not support batch updates");
			}
		}
	}
	catch (SQLException ex) {
		logger.debug("JDBC driver 'supportsBatchUpdates' method threw exception", ex);
	}
	return false;
}
 
Example #19
Source File: JDBCAvroRegistryString.java    From components with Apache License 2.0 5 votes vote down vote up
protected Schema inferSchemaResultSet(JDBCTableMetadata tableMetadata) throws SQLException {
    DatabaseMetaData databaseMetdata = tableMetadata.getDatabaseMetaData();

    Set<String> keys = getPrimaryKeys(databaseMetdata, tableMetadata.getCatalog(), tableMetadata.getDbSchema(),
            tableMetadata.getTablename());

    Set<String> existNames = new HashSet<String>();
    int index = 0;
    
    try (ResultSet metadata = databaseMetdata.getColumns(tableMetadata.getCatalog(), tableMetadata.getDbSchema(),
            tableMetadata.getTablename(), null)) {
        if (!metadata.next()) {
            return null;
        }

        List<Field> fields = new ArrayList<>();
        String tablename = metadata.getString("TABLE_NAME");

        do {
            int size = metadata.getInt("COLUMN_SIZE");
            int scale = metadata.getInt("DECIMAL_DIGITS");
            int dbtype = metadata.getInt("DATA_TYPE");
            boolean nullable = DatabaseMetaData.columnNullable == metadata.getInt("NULLABLE");

            String columnName = metadata.getString("COLUMN_NAME");
            boolean isKey = keys.contains(columnName);

            String defaultValue = metadata.getString("COLUMN_DEF");

            String validName = NameUtil.correct(columnName, index++, existNames);
            existNames.add(validName);
            
            Field field = sqlType2Avro(size, scale, dbtype, nullable, validName, columnName, defaultValue, isKey);

            fields.add(field);
        } while (metadata.next());

        return Schema.createRecord(NameUtil.correct(tablename, 0, new HashSet<String>()), null, null, false, fields);
    }
}
 
Example #20
Source File: MetadataUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Call {@link DatabaseMetaData#getIndexInfo(String, String, String,
 * boolean, boolean)}, wrapping any internal runtime exception into an
 * {@link SQLException}.
 */
public static ResultSet getIndexInfo(DatabaseMetaData dmd,
        String catalog, String schema, String table,
        boolean unique, boolean approximate) throws SQLException {
    try {
        return dmd.getIndexInfo(catalog, schema, table, unique,
                approximate);
    } catch (SQLException e) {
        throw e;
    } catch (Throwable t) {
        throw new SQLException(t);
    }
}
 
Example #21
Source File: SQLQueryBuilderTest.java    From pxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testIdMixedCaseWithFilterAndPartition() throws Exception {
    context.setDataSource("sales");
    List<ColumnDescriptor> columns = new ArrayList<>();
    columns.add(new ColumnDescriptor("id", DataType.INTEGER.getOID(), 0, "int4", null));
    columns.add(new ColumnDescriptor("cDate", DataType.DATE.getOID(), 1, "date", null));
    context.setTupleDescription(columns);

    DatabaseMetaData localDatabaseMetaData = mock(DatabaseMetaData.class);
    when(localDatabaseMetaData.supportsMixedCaseIdentifiers()).thenReturn(false);
    when(localDatabaseMetaData.getExtraNameCharacters()).thenReturn("");
    when(localDatabaseMetaData.getDatabaseProductName()).thenReturn("mysql");
    when(localDatabaseMetaData.getIdentifierQuoteString()).thenReturn("\"");

    // id > 5
    context.setFilterString("a0c20s1d5o2");

    context.addOption("PARTITION_BY", "cDate:date");
    context.addOption("RANGE", "2008-01-01:2009-01-01");
    context.addOption("INTERVAL", "2:month");
    JdbcPartitionFragmenter fragmenter = new JdbcPartitionFragmenter();
    fragmenter.initialize(context);
    List<Fragment> fragments = fragmenter.getFragments();
    assertEquals(9, fragments.size());
    // Partition: cdate >= 2008-01-01 and cdate < 2008-03-01
    context.setFragmentMetadata(fragments.get(2).getMetadata());

    String expected = "SELECT \"id\", \"cDate\" FROM sales WHERE \"id\" > 5 AND \"cDate\" >= DATE('2008-01-01') AND \"cDate\" < DATE('2008-03-01')";

    SQLQueryBuilder builder = new SQLQueryBuilder(context, localDatabaseMetaData);
    builder.autoSetQuoteString();
    String query = builder.buildSelectQuery();
    assertEquals(expected, query);
}
 
Example #22
Source File: ConsumerSchemaMeta.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static TableMeta tableMeta(MysqlConnection connection, String schema, String table) throws SQLException {
  String jdbcUrl = connection.toConnectionUrl(schema);
  DataSource dataSource = new DriverDataSource(jdbcUrl, Driver.class.getName(), new Properties(),
      connection.getUser(), connection.getPassword());
  Consumer single = Consumer.singleTable(schema, table);
  HashMap<Consumer, List<SchemaMeta>> res;
  try (Connection dataSourceConnection = dataSource.getConnection()) {
    DatabaseMetaData metaData = dataSourceConnection.getMetaData();
    try (ResultSet tableResultSet = metaData
        .getTables(schema, null, table, new String[]{"TABLE"})) {
      res = getSchemaMeta(metaData, tableResultSet, Sets.newHashSet(single));
    }
  }
  return res.get(single).get(0).findTable(schema, table);
}
 
Example #23
Source File: DerbyTableMetaDataProvider.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@Override
public void initializeWithMetaData(DatabaseMetaData databaseMetaData) throws SQLException {
	super.initializeWithMetaData(databaseMetaData);
	if (!databaseMetaData.supportsGetGeneratedKeys()) {
		logger.warn("Overriding supportsGetGeneratedKeys from DatabaseMetaData to 'true'; it was reported as " +
				"'false' by " + databaseMetaData.getDriverName() + " " + databaseMetaData.getDriverVersion());
		supportsGeneratedKeysOverride = true;
	}
}
 
Example #24
Source File: JdbcExplorer.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<TableDesc, TableExtDesc> loadTableMetadata(String database, String table, String prj)
        throws SQLException {
    TableDesc tableDesc = new TableDesc();
    tableDesc.setDatabase(database.toUpperCase(Locale.ROOT));
    tableDesc.setName(table.toUpperCase(Locale.ROOT));
    tableDesc.setUuid(RandomUtil.randomUUID().toString());
    tableDesc.setLastModified(0);
    tableDesc.setSourceType(ISourceAware.ID_JDBC);

    Connection con = SqlUtil.getConnection(dbconf);
    DatabaseMetaData dbmd = con.getMetaData();

    try (ResultSet rs = jdbcMetadataDialect.getTable(dbmd, database, table)) {
        String tableType = null;
        while (rs.next()) {
            tableType = rs.getString("TABLE_TYPE");
        }
        if (tableType != null) {
            tableDesc.setTableType(tableType);
        } else {
            throw new RuntimeException(
                    String.format(Locale.ROOT, "table %s not found in schema:%s", table, database));
        }
    }

    try (ResultSet rs = jdbcMetadataDialect.listColumns(dbmd, database, table)) {
        tableDesc.setColumns(extractColumnFromMeta(rs));
    } finally {
        DBUtils.closeQuietly(con);
    }

    TableExtDesc tableExtDesc = new TableExtDesc();
    tableExtDesc.setIdentity(tableDesc.getIdentity());
    tableExtDesc.setUuid(RandomUtil.randomUUID().toString());
    tableExtDesc.setLastModified(0);
    tableExtDesc.init(prj);

    return Pair.newPair(tableDesc, tableExtDesc);
}
 
Example #25
Source File: PrimaveraDatabaseReader.java    From mpxj with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Populate data for analytics.
 */
private void processAnalytics() throws SQLException
{
   allocateConnection();

   try
   {
      DatabaseMetaData meta = m_connection.getMetaData();
      String productName = meta.getDatabaseProductName();
      if (productName == null || productName.isEmpty())
      {
         productName = "DATABASE";
      }
      else
      {
         productName = productName.toUpperCase();
      }

      ProjectProperties properties = m_reader.getProject().getProjectProperties();
      properties.setFileApplication("Primavera");
      properties.setFileType(productName);
   }

   finally
   {
      releaseConnection();
   }
}
 
Example #26
Source File: ExportDb.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void execute(Connection con, int schemaVersion) throws Exception
{
    final DatabaseMetaData dbmd = con.getMetaData();

    String schemaName = databaseMetaDataHelper.getSchema(con);

    schema = new Schema(schemaName, namePrefix, schemaVersion, true);
    String[] prefixFilters = namePrefixFilters(dbmd);
    
    for (String filter : prefixFilters)
    {
        extractSchema(dbmd, schemaName, filter);
    }
}
 
Example #27
Source File: JavaInformations.java    From javamelody with Apache License 2.0 5 votes vote down vote up
private static void appendDataBaseVersion(StringBuilder result, Connection connection)
		throws SQLException {
	final DatabaseMetaData metaData = connection.getMetaData();
	// Sécurité: pour l'instant on n'indique pas metaData.getUserName()
	result.append(metaData.getURL()).append('\n');
	result.append(metaData.getDatabaseProductName()).append(", ")
			.append(metaData.getDatabaseProductVersion()).append('\n');
	result.append("Driver JDBC:\n").append(metaData.getDriverName()).append(", ")
			.append(metaData.getDriverVersion());
}
 
Example #28
Source File: ConcurrentConnTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static void metadataCalls(Connection conn)
throws Exception
{
  System.out.println("A new connection is doing metadata calls, but never commit...");

  DatabaseMetaData dmd = conn.getMetaData();
  getTypeInfo(dmd,System.out);
  getTables(dmd,System.out);
  getColumnInfo(dmd, "%",System.out);
  getPrimaryKeys(dmd, "%",System.out);
  getExportedKeys(dmd, "%",System.out);

}
 
Example #29
Source File: MetadataTest.java    From Komondor with GNU General Public License v3.0 5 votes vote down vote up
public void testGetPrimaryKeys() throws SQLException {
    try {
        createTable("multikey", "(d INT NOT NULL, b INT NOT NULL, a INT NOT NULL, c INT NOT NULL, PRIMARY KEY (d, b, a, c))");
        DatabaseMetaData dbmd = this.conn.getMetaData();
        this.rs = dbmd.getPrimaryKeys(this.conn.getCatalog(), "", "multikey");

        short[] keySeqs = new short[4];
        String[] columnNames = new String[4];
        int i = 0;

        while (this.rs.next()) {
            this.rs.getString("TABLE_NAME");
            columnNames[i] = this.rs.getString("COLUMN_NAME");

            this.rs.getString("PK_NAME");
            keySeqs[i] = this.rs.getShort("KEY_SEQ");
            i++;
        }

        if ((keySeqs[0] != 3) && (keySeqs[1] != 2) && (keySeqs[2] != 4) && (keySeqs[3] != 1)) {
            fail("Keys returned in wrong order");
        }
    } finally {
        if (this.rs != null) {
            try {
                this.rs.close();
            } catch (SQLException sqlEx) {
                /* ignore */
            }
        }
    }
}
 
Example #30
Source File: SqlStoredConnectorMetaDataExtensionTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFetchStoredProcedureMetadataWithSingleParameter() throws SQLException {
    final Connection connection = mock(Connection.class);

    final DatabaseMetaData databaseMetaData = mock(DatabaseMetaData.class);
    when(connection.getMetaData()).thenReturn(databaseMetaData);

    when(databaseMetaData.getDatabaseProductName()).thenReturn("POSTGRESQL");

    final ResultSet result = mock(ResultSet.class);
    when(databaseMetaData.getProcedureColumns("catalog", "schema", "procedureName", null)).thenReturn(result);

    when(result.next()).thenReturn(true, false);
    when(result.getString("COLUMN_NAME")).thenReturn("A");
    when(result.getInt("COLUMN_TYPE")).thenReturn(ColumnMode.IN.ordinal());
    when(result.getInt("DATA_TYPE")).thenReturn(JDBCType.INTEGER.getVendorTypeNumber());

    final StoredProcedureMetadata metadata = SqlSupport.getStoredProcedureMetadata(connection, "catalog", "schema",
        "procedureName");

    final StoredProcedureColumn columnA = new StoredProcedureColumn();
    columnA.setJdbcType(JDBCType.INTEGER);
    columnA.setName("A");
    columnA.setOrdinal(0);
    columnA.setMode(ColumnMode.IN);

    assertThat(metadata.getName()).isEqualTo("procedureName");
    assertThat(metadata.getTemplate()).isEqualTo("procedureName(INTEGER ${body[A]})");
    final List<StoredProcedureColumn> columnList = metadata.getColumnList();
    assertThat(columnList.get(0)).isEqualToComparingFieldByField(columnA);
}