Example usage for java.sql Connection getMetaData

List of usage examples for java.sql Connection getMetaData

Introduction

In this page you can find the example usage for java.sql Connection getMetaData.

Prototype

DatabaseMetaData getMetaData() throws SQLException;

Source Link

Document

Retrieves a DatabaseMetaData object that contains metadata about the database to which this Connection object represents a connection.

Usage

From source file:gridool.db.helpers.GridDbUtils.java

/**
 * @return column position is not provided in the returning foreign keys
 *///from  ww w  .j  a va  2s. co  m
@Nonnull
public static Collection<ForeignKey> getExportedKeys(@Nonnull final Connection conn,
        @Nullable final String pkTableName, final boolean setColumnPositions) throws SQLException {
    DatabaseMetaData metadata = conn.getMetaData();
    String catalog = conn.getCatalog();
    final Map<String, ForeignKey> mapping = new HashMap<String, ForeignKey>(4);
    final ResultSet rs = metadata.getExportedKeys(catalog, null, pkTableName);
    try {
        while (rs.next()) {
            final String fkName = rs.getString("FK_NAME");
            ForeignKey fk = mapping.get(fkName);
            if (fk == null) {
                String fkTableName = rs.getString("FKTABLE_NAME");
                fk = new ForeignKey(fkName, fkTableName, pkTableName);
                mapping.put(fkName, fk);
            }
            fk.addColumn(rs, metadata);
        }
    } finally {
        rs.close();
    }
    final Collection<ForeignKey> fkeys = mapping.values();
    if (setColumnPositions) {
        for (ForeignKey fk : fkeys) {
            fk.setColumnPositions(metadata);
        }
    }
    return fkeys;
}

From source file:gridool.db.helpers.GridDbUtils.java

/**
 * @return column position is provided in the returning foreign keys
 *//*from  ww w.  ja  v  a  2 s  .c  o m*/
@Nonnull
public static Collection<ForeignKey> getForeignKeys(@Nonnull final Connection conn,
        @Nullable final String fkTableName, final boolean setColumnPositions) throws SQLException {
    DatabaseMetaData metadata = conn.getMetaData();
    String catalog = conn.getCatalog();
    final Map<String, ForeignKey> mapping = new HashMap<String, ForeignKey>(4);
    final ResultSet rs = metadata.getImportedKeys(catalog, null, fkTableName);
    try {
        while (rs.next()) {
            final String fkName = rs.getString("FK_NAME");
            ForeignKey fk = mapping.get(fkName);
            if (fk == null) {
                //String fkTableName = rs.getString("FKTABLE_NAME");
                String pkTableName = rs.getString("PKTABLE_NAME");
                fk = new ForeignKey(fkName, fkTableName, pkTableName);
                mapping.put(fkName, fk);
            }
            fk.addColumn(rs, metadata);
        }
    } finally {
        rs.close();
    }
    final Collection<ForeignKey> fkeys = mapping.values();
    if (setColumnPositions) {
        for (ForeignKey fk : fkeys) {
            fk.setColumnPositions(metadata);
        }
    }
    return fkeys;
}

From source file:scott.barleydb.test.TestBase.java

public static void setupDefs() throws Exception {
    if (env != null) {
        return;//from   ww w .j  av a  2  s .  c o m
    }

    entityContextServices = new TestEntityContextServices(dataSource);
    env = new Environment(entityContextServices);
    /*
     * The server executes by default in the same context
     * and provides reasonable values for result-set scrolling and fetching
     */
    env.setDefaultRuntimeProperties(new RuntimeProperties().concurrency(Concurrency.READ_ONLY).fetchSize(100)
            .executeInSameContext(true).scrollType(ScrollType.FORWARD_ONLY));
    env.setQueryPreProcessor(new QueryPreProcessor());

    entityContextServices.setEnvironment(env);
    env.loadDefinitions();

    Connection connection = dataSource.getConnection();
    DatabaseMetaData metadata = connection.getMetaData();
    entityContextServices.addDatabases(new HsqlDatabase(metadata), new OracleDatabase(metadata),
            new SqlServerDatabase(metadata), new MySqlDatabase(metadata));

    connection.close();

    class TestSequenceGenerator implements SequenceGenerator {
        Long key = 1l;

        @Override
        public Object getNextKey(EntityType entityType) {
            return key++;
        }
    }
    ;

    entityContextServices.setSequenceGenerator(new TestSequenceGenerator());
    entityContextServices.register(new LongToStringTimestampConverter());

    env.addDefinitions(Definitions
            .create(loadDefinitions("src/test/java/org/example/acl/aclspec.xml", "org.example.acl")));
    env.addDefinitions(Definitions
            .create(loadDefinitions("src/test/java/org/example/etl/etlspec.xml", "org.example.etl")));

    env.getDefinitions("org.example.acl").registerQueries(new QUser(), new QAccessArea());

    env.getDefinitions("org.example.acl").registerProxyFactory(new MacProxyFactory());

    env.getDefinitions("org.example.etl").registerQueries(new QXmlSyntaxModel(), new QXmlStructure(),
            new QXmlMapping(), new QCsvSyntaxModel(), new QCsvStructure(), new QCsvStructureField(),
            new QCsvMapping(), new QTemplate(), new QTemplateContent(), new QTemplateBusinessType(),
            new QBusinessType(), new QRawData());

    env.getDefinitions("org.example.etl").registerProxyFactory(new MiProxyFactory());

    transformXml = "<?xml version=\"1.0\"?>" + "<xsl:stylesheet version=\"1.0\" "
            + "xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" + "<xsl:strip-space elements=\"*\" />"
            + "<xsl:output method=\"xml\" indent=\"yes\" />" + "" + "<xsl:template match=\"node() | @*\">"
            + "<xsl:copy>" + "<xsl:apply-templates select=\"node() | @*\" />" + "</xsl:copy>"
            + "</xsl:template>" + "</xsl:stylesheet>";
}

From source file:net.bull.javamelody.internal.model.JavaInformations.java

private static void appendDataBaseVersion(StringBuilder result, Connection connection) throws SQLException {
    final DatabaseMetaData metaData = connection.getMetaData();
    // Scurit: 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());
}

From source file:gridool.db.helpers.GridDbUtils.java

@Nullable
public static PrimaryKey getPrimaryKey(@Nonnull final Connection conn, @CheckForNull final String pkTableName,
        final boolean reserveAdditionalInfo) throws SQLException {
    if (pkTableName == null) {
        throw new IllegalArgumentException();
    }//from  ww  w .  j a v  a  2s  .c o  m
    DatabaseMetaData metadata = conn.getMetaData();
    String catalog = conn.getCatalog();
    final ResultSet rs = metadata.getPrimaryKeys(catalog, null, pkTableName);
    final PrimaryKey pkey;
    try {
        if (!rs.next()) {
            return null;
        }
        String pkName = rs.getString("PK_NAME");
        pkey = new PrimaryKey(pkName, pkTableName);
        do {
            pkey.addColumn(rs);
        } while (rs.next());
    } finally {
        rs.close();
    }

    if (reserveAdditionalInfo) {
        // set foreign key column positions
        pkey.setColumnPositions(metadata);
        // set exported keys
        final Collection<ForeignKey> exportedKeys = getExportedKeys(conn, pkTableName, false);
        if (!exportedKeys.isEmpty()) {
            final List<String> pkColumnsProbe = pkey.getColumnNames();
            final int numPkColumnsProbe = pkColumnsProbe.size();
            final List<ForeignKey> exportedKeyList = new ArrayList<ForeignKey>(4);
            outer: for (ForeignKey fk : exportedKeys) {
                List<String> names = fk.getPkColumnNames();
                if (names.size() != numPkColumnsProbe) {
                    continue;
                }
                for (String name : names) {
                    if (!pkColumnsProbe.contains(name)) {
                        continue outer;
                    }
                }
                exportedKeyList.add(fk);
            }
            if (!exportedKeyList.isEmpty()) {
                pkey.setExportedKeys(exportedKeyList);
            }
        }
    }
    return pkey;
}

From source file:com.digitalgeneralists.assurance.Application.java

static void installDb(InputStream propertiesFileStream, InputStream dbScriptStream)
        throws IOException, SQLException {
    Logger logger = Logger.getLogger(Application.class);

    Connection dbConnection = null;
    ResultSet rs = null;//from   ww  w .j a  va  2s .  c  o m
    try {
        Properties properties = new Properties();

        if (propertiesFileStream != null) {
            properties.load(propertiesFileStream);
        } else {
            throw new FileNotFoundException("The database properties file could not be loaded.");
        }
        String dbUrl = (String) properties.get("jdbc.url");
        String dbUser = (String) properties.get("jdbc.username");
        String dbPassword = (String) properties.get("jdbc.password");

        dbConnection = DriverManager.getConnection(dbUrl, dbUser, dbPassword);

        ArrayList<String> listOfDatabases = new ArrayList<String>();
        DatabaseMetaData meta = dbConnection.getMetaData();
        String[] tableTypes = { "TABLE" };
        rs = meta.getTables(null, null, Application.verificationTableName, tableTypes);
        while (rs.next()) {
            String databaseName = rs.getString("TABLE_NAME");
            listOfDatabases.add(databaseName.toUpperCase());
        }
        if (listOfDatabases.contains(Application.verificationTableName)) {
            logger.info("Database already exists");
        } else {
            ScriptRunner runner = new ScriptRunner(dbConnection, true, true);

            Reader dbScript = new InputStreamReader(dbScriptStream);
            runner.runScript(dbScript);

            logger.info("Database is created");
        }
    } finally {
        if (rs != null) {
            try {
                rs.close();
                rs = null;
            } catch (SQLException e) {
                // The ship is going down. Not much we can do.
                logger.fatal(e);
            }
        }
        if (dbConnection != null) {
            dbConnection.close();
            dbConnection = null;
        }
    }

    logger = null;
}

From source file:com.alibaba.otter.shared.common.utils.meta.DdlUtils.java

public static Table findTable(final JdbcTemplate jdbcTemplate, final String catalogName,
        final String schemaName, final String tableName, final DdlUtilsFilter filter) throws Exception {
    return (Table) jdbcTemplate.execute(new ConnectionCallback() {

        public Object doInConnection(Connection con) throws SQLException, DataAccessException {
            Table table = null;/* ww  w  .  ja  v  a 2s.  co  m*/
            DatabaseMetaDataWrapper metaData = new DatabaseMetaDataWrapper();

            try {
                if (filter != null) {
                    con = filter.filterConnection(con);
                    Assert.notNull(con);
                }
                DatabaseMetaData databaseMetaData = con.getMetaData();
                if (filter != null) {
                    databaseMetaData = filter.filterDataBaseMetaData(jdbcTemplate, con, databaseMetaData);
                    Assert.notNull(databaseMetaData);
                }

                metaData.setMetaData(databaseMetaData);
                metaData.setTableTypes(TableType.toStrings(SUPPORTED_TABLE_TYPES));
                metaData.setCatalog(catalogName);
                metaData.setSchemaPattern(schemaName);

                String convertTableName = tableName;
                if (databaseMetaData.storesUpperCaseIdentifiers()) {
                    metaData.setCatalog(catalogName.toUpperCase());
                    metaData.setSchemaPattern(schemaName.toUpperCase());
                    convertTableName = tableName.toUpperCase();
                }
                if (databaseMetaData.storesLowerCaseIdentifiers()) {
                    metaData.setCatalog(catalogName.toLowerCase());
                    metaData.setSchemaPattern(schemaName.toLowerCase());
                    convertTableName = tableName.toLowerCase();
                }

                ResultSet tableData = null;
                try {
                    tableData = metaData.getTables(convertTableName);

                    while ((tableData != null) && tableData.next()) {
                        Map<String, Object> values = readColumns(tableData, initColumnsForTable());

                        table = readTable(metaData, values);
                        if (table.getName().equalsIgnoreCase(tableName)) {
                            break;
                        }
                    }
                } finally {
                    JdbcUtils.closeResultSet(tableData);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }

            makeAllColumnsPrimaryKeysIfNoPrimaryKeysFound(table);

            return table;
        }
    });
}

From source file:com.alibaba.otter.shared.common.utils.meta.DdlUtils.java

@SuppressWarnings("unchecked")
public static List<Table> findTables(final JdbcTemplate jdbcTemplate, final String catalogName,
        final String schemaName, final String tableNamePattern, final DdlUtilsFilter filter,
        final DdlTableNameFilter tableNameFilter) throws Exception {
    return (List<Table>) jdbcTemplate.execute(new ConnectionCallback() {

        public Object doInConnection(Connection con) throws SQLException, DataAccessException {
            List<Table> tables = new ArrayList<Table>();
            DatabaseMetaDataWrapper metaData = new DatabaseMetaDataWrapper();

            try {
                if (filter != null) {
                    con = filter.filterConnection(con);
                    Assert.notNull(con);
                }// ww w  .  j  av  a 2 s  .c  o m
                DatabaseMetaData databaseMetaData = con.getMetaData();
                if (filter != null) {
                    databaseMetaData = filter.filterDataBaseMetaData(jdbcTemplate, con, databaseMetaData);
                    Assert.notNull(databaseMetaData);
                }

                metaData.setMetaData(databaseMetaData);
                metaData.setTableTypes(TableType.toStrings(SUPPORTED_TABLE_TYPES));
                metaData.setCatalog(catalogName);
                metaData.setSchemaPattern(schemaName);

                String convertTableName = tableNamePattern;
                if (databaseMetaData.storesUpperCaseIdentifiers()) {
                    metaData.setCatalog(catalogName.toUpperCase());
                    metaData.setSchemaPattern(schemaName.toUpperCase());
                    convertTableName = tableNamePattern.toUpperCase();
                }
                if (databaseMetaData.storesLowerCaseIdentifiers()) {
                    metaData.setCatalog(catalogName.toLowerCase());
                    metaData.setSchemaPattern(schemaName.toLowerCase());
                    convertTableName = tableNamePattern.toLowerCase();
                }

                ResultSet tableData = null;
                try {
                    tableData = metaData.getTables(convertTableName);

                    while ((tableData != null) && tableData.next()) {
                        Map<String, Object> values = readColumns(tableData, initColumnsForTable());

                        Table table = readTable(metaData, values);
                        if ((tableNameFilter == null)
                                || tableNameFilter.accept(catalogName, schemaName, table.getName())) {
                            tables.add(table);
                        }
                    }
                } finally {
                    JdbcUtils.closeResultSet(tableData);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }

            for (Table table : tables) {
                makeAllColumnsPrimaryKeysIfNoPrimaryKeysFound(table);
            }

            return tables;
        }
    });
}

From source file:jp.co.golorp.emarf.sql.MetaData.java

/**
 * @param cn/*from  w  ww  .  j  ava  2s  .  c  om*/
 *            ?
 * @param tableName
 *            ??
 * @return ???Set
 */
private static Set<String> getPrimaryKeys(final Connection cn, final String tableName) {

    List<String> pkList = null;

    ResultSet rs = null;
    try {

        // ??
        DatabaseMetaData dmd = cn.getMetaData();
        rs = dmd.getPrimaryKeys(null, null, tableName);
        while (rs.next()) {

            if (pkList == null) {
                pkList = new ArrayList<String>();
            }

            String columnName = rs.getString("COLUMN_NAME");

            // rdbms? 1,2,3,
            // sqlite?0,1,2, ??
            int keySeq = rs.getShort("KEY_SEQ");

            while (pkList.size() <= keySeq) {
                pkList.add(null);
            }
            pkList.set(keySeq, columnName);
        }

    } catch (SQLException e) {
        throw new SystemError(e);
    } finally {
        DbUtils.closeQuietly(rs);
    }

    List<String> primaryKeys = null;

    if (pkList != null) {
        for (String pk : pkList) {
            if (StringUtil.isNotBlank(pk)) {
                if (primaryKeys == null) {
                    primaryKeys = new ArrayList<String>();
                }
                primaryKeys.add(pk);
            }
        }
    }

    if (primaryKeys == null) {
        return null;
    }

    return new LinkedHashSet<String>(primaryKeys);
}

From source file:jp.co.golorp.emarf.sql.MetaData.java

/**
 * @return ?//ww  w  .  jav  a 2s  .  c  o  m
 */
private static List<TableInfo> prepareTableInfos() {

    String catalog = BUNDLE.getString("catalog");

    String schemaPattern = BUNDLE.getString("schemaPattern");

    String tableNamePattern = BUNDLE.getString("tableNamePattern");

    String typesText = BUNDLE.getString("types");

    String[] types = null;
    if (StringUtil.isNotBlank(typesText)) {
        types = StringUtil.split(typesText);
    }

    // oracle
    if (catalog.equals("")) {
        catalog = null;
    }
    if (schemaPattern.equals("")) {
        schemaPattern = null;
    }
    if (tableNamePattern.equals("")) {
        tableNamePattern = null;
    }
    if (StringUtil.isBlank(types)) {
        types = null;
    }

    List<TableInfo> tableInfos = new ArrayList<TableInfo>();

    Connection cn = Connections.get();
    try {
        ResultSet rs = null;
        try {

            // ?
            rs = cn.getMetaData().getTables(catalog, schemaPattern, tableNamePattern, types);
            while (rs.next()) {

                // ??
                String tableName = rs.getString("TABLE_NAME");

                // 
                String tableType = rs.getString("TABLE_TYPE");

                // 
                String remarks = rs.getString("REMARKS");
                if (StringUtil.isBlank(remarks)) {
                    if (commentSource == TableCommentSources.showTableStatus) {
                        // MySQL???showTableStatus?????
                        remarks = getTableCommentByShowTableStatus(cn, tableName);
                    } else if (commentSource == TableCommentSources.userTabComments) {
                        // Oracle???userTabComments?????
                        remarks = getTableCommentByUserTabComments(cn, tableName);
                    } else {
                        // ??
                        remarks = getTableComment(cn, tableName);
                    }
                }

                // view??
                Map<String, ViewInfo> viewInfos = null;
                Set<String> primaryKeys = null;
                if (tableType.equals("VIEW")) {
                    viewInfos = getViewInfos(cn, tableName);
                } else {
                    primaryKeys = MetaData.getPrimaryKeys(cn, tableName);
                }

                // ?????
                String tableMei = null;
                if (StringUtil.isNotBlank(remarks)) {
                    tableMei = remarks.split("\t")[0];
                }

                // ?
                List<ColumnInfo> columnInfos = MetaData.getColumnInfos(cn, tableName);

                // ??
                String modelName = StringUtil.toUpperCamelCase(tableName);

                // 
                tableInfos.add(new TableInfo(modelName, tableName, tableType, tableMei, primaryKeys,
                        columnInfos, viewInfos));
            }

        } catch (SQLException e) {
            throw new SystemError(e);
        } finally {
            DbUtils.closeQuietly(rs);
        }
    } catch (Exception e) {
        throw new SystemError(e);
    } finally {
        Connections.close();
    }

    for (String columnInfoName : NOT_EXIST_COLUMN_INFO_NAMES) {
        LOG.trace("Column MetaData [" + columnInfoName + "] is not exists.");
    }

    return tableInfos;
}