Search in sources :

Example 16 with DatabaseMetaData

use of java.sql.DatabaseMetaData in project jetty.project by eclipse.

the class DataSourceLoginService method prepareTables.

/* ------------------------------------------------------------ */
/**
     * @throws NamingException
     * @throws SQLException
     */
private void prepareTables() throws NamingException, SQLException {
    if (_createTables) {
        boolean autocommit = true;
        Connection connection = getConnection();
        try (Statement stmt = connection.createStatement()) {
            autocommit = connection.getAutoCommit();
            connection.setAutoCommit(false);
            DatabaseMetaData metaData = connection.getMetaData();
            //check if tables exist
            String tableName = (metaData.storesLowerCaseIdentifiers() ? _userTableName.toLowerCase(Locale.ENGLISH) : (metaData.storesUpperCaseIdentifiers() ? _userTableName.toUpperCase(Locale.ENGLISH) : _userTableName));
            try (ResultSet result = metaData.getTables(null, null, tableName, null)) {
                if (!result.next()) {
                    //user table default
                    /*
                         * create table _userTableName (_userTableKey integer,
                         * _userTableUserField varchar(100) not null unique,
                         * _userTablePasswordField varchar(20) not null, primary key(_userTableKey));
                         */
                    stmt.executeUpdate("create table " + _userTableName + "(" + _userTableKey + " integer," + _userTableUserField + " varchar(100) not null unique," + _userTablePasswordField + " varchar(20) not null, primary key(" + _userTableKey + "))");
                    if (LOG.isDebugEnabled())
                        LOG.debug("Created table " + _userTableName);
                }
            }
            tableName = (metaData.storesLowerCaseIdentifiers() ? _roleTableName.toLowerCase(Locale.ENGLISH) : (metaData.storesUpperCaseIdentifiers() ? _roleTableName.toUpperCase(Locale.ENGLISH) : _roleTableName));
            try (ResultSet result = metaData.getTables(null, null, tableName, null)) {
                if (!result.next()) {
                    //role table default
                    /*
                         * create table _roleTableName (_roleTableKey integer,
                         * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey));
                         */
                    String str = "create table " + _roleTableName + " (" + _roleTableKey + " integer, " + _roleTableRoleField + " varchar(100) not null unique, primary key(" + _roleTableKey + "))";
                    stmt.executeUpdate(str);
                    if (LOG.isDebugEnabled())
                        LOG.debug("Created table " + _roleTableName);
                }
            }
            tableName = (metaData.storesLowerCaseIdentifiers() ? _userRoleTableName.toLowerCase(Locale.ENGLISH) : (metaData.storesUpperCaseIdentifiers() ? _userRoleTableName.toUpperCase(Locale.ENGLISH) : _userRoleTableName));
            try (ResultSet result = metaData.getTables(null, null, tableName, null)) {
                if (!result.next()) {
                    //user-role table
                    /*
                         * create table _userRoleTableName (_userRoleTableUserKey integer,
                         * _userRoleTableRoleKey integer,
                         * primary key (_userRoleTableUserKey, _userRoleTableRoleKey));
                         *
                         * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey);
                         */
                    stmt.executeUpdate("create table " + _userRoleTableName + " (" + _userRoleTableUserKey + " integer, " + _userRoleTableRoleKey + " integer, " + "primary key (" + _userRoleTableUserKey + ", " + _userRoleTableRoleKey + "))");
                    stmt.executeUpdate("create index indx_user_role on " + _userRoleTableName + "(" + _userRoleTableUserKey + ")");
                    if (LOG.isDebugEnabled())
                        LOG.debug("Created table " + _userRoleTableName + " and index");
                }
            }
            connection.commit();
        } finally {
            try {
                connection.setAutoCommit(autocommit);
            } catch (SQLException e) {
                if (LOG.isDebugEnabled())
                    LOG.debug("Prepare tables", e);
            } finally {
                try {
                    connection.close();
                } catch (SQLException e) {
                    if (LOG.isDebugEnabled())
                        LOG.debug("Prepare tables", e);
                }
            }
        }
    } else if (LOG.isDebugEnabled()) {
        LOG.debug("createTables false");
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) DatabaseMetaData(java.sql.DatabaseMetaData)

Example 17 with DatabaseMetaData

use of java.sql.DatabaseMetaData in project qi4j-sdk by Qi4j.

the class GenericDatabaseExplorer method visitDatabaseTables.

public static void visitDatabaseTables(Connection connection, String catalogName, String schemaNamePattern, String tableNamePattern, DatabaseProcessor processor, SQLVendor sqlSyntaxVendor) throws SQLException {
    DatabaseMetaData metaData = connection.getMetaData();
    connection.setReadOnly(true);
    ResultSet rs = metaData.getTables(catalogName, schemaNamePattern, tableNamePattern, new String[] { "TABLE" });
    try {
        while (rs.next()) {
            String schemaName = rs.getString(2);
            try {
                processor.beginProcessSchemaInfo(schemaName);
                String tableName = rs.getString(3);
                String tableRemarks = rs.getString(5);
                try {
                    processor.beginProcessTableInfo(schemaName, tableName, tableRemarks);
                    List<ColumnInfo> colInfos = new ArrayList<>();
                    ResultSet rsCols = metaData.getColumns(null, schemaName, tableName, null);
                    try {
                        while (rsCols.next()) {
                            String nullable = rsCols.getString(18);
                            colInfos.add(new ColumnInfo(rsCols.getString(4), rsCols.getInt(5), rsCols.getString(6), rsCols.getInt(7), rsCols.getInt(9), nullable.length() > 0 ? Boolean.toString(nullable.equals("YES")) : "unknown", rsCols.getString(13), rsCols.getString(12)));
                        }
                    } finally {
                        rsCols.close();
                    }
                    rsCols = metaData.getImportedKeys(null, schemaName, tableName);
                    Map<String, ForeignKeyInfo> fkInfos = new HashMap<>();
                    try {
                        while (rsCols.next()) {
                            fkInfos.put(//
                            rsCols.getString(8), new ForeignKeyInfo(rsCols.getString(2), rsCols.getString(3), rsCols.getString(4), rsCols.getShort(10), rsCols.getShort(11), rsCols.getShort(14)));
                        }
                    } finally {
                        rsCols.close();
                    }
                    try {
                        processor.beginProcessColumns(schemaName, tableName, tableRemarks);
                        for (ColumnInfo colInfo : colInfos) {
                            try {
                                processor.beginProcessColumnInfo(schemaName, tableName, colInfo, fkInfos.get(colInfo._name));
                            } finally {
                                processor.endProcessColumnInfo(schemaName, tableName, colInfo, fkInfos.get(colInfo._name));
                            }
                        }
                    } finally {
                        processor.endProcessColumns(schemaName, tableName, tableRemarks);
                    }
                    QueryFactory q = sqlSyntaxVendor.getQueryFactory();
                    TableReferenceFactory t = sqlSyntaxVendor.getTableReferenceFactory();
                    QuerySpecificationBuilder builda = q.querySpecificationBuilder();
                    builda.getSelect().selectAll();
                    builda.getFrom().addTableReferences(t.tableBuilder(t.table(t.tableName(schemaName, tableName))));
                    String sql = sqlSyntaxVendor.toString(q.createQuery(builda.createExpression()));
                    Statement stmt = connection.createStatement();
                    ResultSet rowsRs = null;
                    try {
                        rowsRs = stmt.executeQuery(sql);
                        processor.beginProcessRows(schemaName, tableName, tableRemarks);
                        while (rowsRs.next()) {
                            Object[] rowContents = new Object[colInfos.size()];
                            for (Integer x = 0; x < rowContents.length; ++x) {
                                rowContents[x] = rowsRs.getObject(x + 1);
                            }
                            try {
                                processor.beginProcessRowInfo(schemaName, tableName, rowContents);
                            } finally {
                                processor.endProcessRowInfo(schemaName, tableName, rowContents);
                            }
                        }
                    } finally {
                        processor.endProcessRows(schemaName, tableName, tableRemarks);
                        if (rowsRs != null) {
                            rowsRs.close();
                        }
                        stmt.close();
                    }
                } finally {
                    processor.endProcessTableInfo(schemaName, tableName, tableRemarks);
                }
            } finally {
                processor.endProcessSchemaInfo(schemaName);
            }
        }
    } finally {
        SQLUtil.closeQuietly(rs);
    }
}
Also used : QueryFactory(org.sql.generation.api.grammar.factories.QueryFactory) HashMap(java.util.HashMap) Statement(java.sql.Statement) ArrayList(java.util.ArrayList) QuerySpecificationBuilder(org.sql.generation.api.grammar.builders.query.QuerySpecificationBuilder) DatabaseMetaData(java.sql.DatabaseMetaData) TableReferenceFactory(org.sql.generation.api.grammar.factories.TableReferenceFactory) ResultSet(java.sql.ResultSet)

Example 18 with DatabaseMetaData

use of java.sql.DatabaseMetaData in project OpenAttestation by OpenAttestation.

the class Derby method listTablesAndViews.

public static Set<String> listTablesAndViews(Connection targetDBConn) throws SQLException {
    HashSet<String> set = new HashSet<String>();
    DatabaseMetaData dbmeta = targetDBConn.getMetaData();
    readDBTable(set, dbmeta, "TABLE", null);
    readDBTable(set, dbmeta, "VIEW", null);
    return set;
}
Also used : DatabaseMetaData(java.sql.DatabaseMetaData) HashSet(java.util.HashSet)

Example 19 with DatabaseMetaData

use of java.sql.DatabaseMetaData in project druid by alibaba.

the class ConnectionProxyImpl method getMetaData.

@Override
public DatabaseMetaData getMetaData() throws SQLException {
    FilterChainImpl chain = createChain();
    DatabaseMetaData value = chain.connection_getMetaData(this);
    recycleFilterChain(chain);
    return value;
}
Also used : FilterChainImpl(com.alibaba.druid.filter.FilterChainImpl) DatabaseMetaData(java.sql.DatabaseMetaData)

Example 20 with DatabaseMetaData

use of java.sql.DatabaseMetaData in project dubbo by alibaba.

the class DatabaseStatusChecker method check.

public Status check() {
    boolean ok;
    try {
        Connection connection = dataSource.getConnection();
        try {
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet resultSet = metaData.getTypeInfo();
            try {
                ok = resultSet.next();
            } finally {
                resultSet.close();
            }
            if (message == null) {
                message = metaData.getURL() + " (" + metaData.getDatabaseProductName() + " " + metaData.getDatabaseProductVersion() + ", " + getIsolation(metaData.getDefaultTransactionIsolation()) + ")";
            }
            if (version == 0) {
                version = metaData.getDatabaseMajorVersion();
            }
        } finally {
            connection.close();
        }
    } catch (Throwable e) {
        logger.error(e.getMessage(), e);
        ok = false;
    }
    return new Status(!ok ? Status.Level.ERROR : (version < 5 ? Status.Level.WARN : Status.Level.OK), message);
}
Also used : Status(com.alibaba.dubbo.common.status.Status) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) DatabaseMetaData(java.sql.DatabaseMetaData)

Aggregations

DatabaseMetaData (java.sql.DatabaseMetaData)299 ResultSet (java.sql.ResultSet)176 Connection (java.sql.Connection)139 SQLException (java.sql.SQLException)116 Test (org.junit.Test)81 ResultSetMetaData (java.sql.ResultSetMetaData)41 Statement (java.sql.Statement)36 ArrayList (java.util.ArrayList)33 PreparedStatement (java.sql.PreparedStatement)29 Properties (java.util.Properties)24 PhoenixDatabaseMetaData (org.apache.phoenix.jdbc.PhoenixDatabaseMetaData)16 PhoenixConnection (org.apache.phoenix.jdbc.PhoenixConnection)15 IOException (java.io.IOException)14 HashMap (java.util.HashMap)11 DataSource (javax.sql.DataSource)9 HashSet (java.util.HashSet)8 List (java.util.List)8 Savepoint (java.sql.Savepoint)6 GargoyleException (com.kyj.fx.voeditor.visual.exceptions.GargoyleException)5 TreeSet (java.util.TreeSet)5