jdbcschema.java

来自「数据仓库展示程序」· Java 代码 · 共 1,385 行 · 第 1/3 页

JAVA
1,385
字号
         *
         * @return
         */
        public Iterator getColumns() {
            return getColumnMap().values().iterator();
        }

        /**
         * Iterate over all all column usages of a give column type.
         *
         * @param columnType
         * @return
         */
        public Iterator getColumnUsages(final int columnType) {

            class CTIterator implements Iterator {
                private final Iterator columns;
                private final int columnType;
                private Iterator it;
                private Object nextObject;

                CTIterator(final Iterator columns, final int columnType) {
                    this.columns = columns;
                    this.columnType = columnType;
                }
                public boolean hasNext() {
                    while (true) {
                        while ((it == null) || ! it.hasNext()) {
                            if (! columns.hasNext()) {
                                nextObject = null;
                                return false;
                            }
                            Column c = (Column) columns.next();
                            it = c.getUsages();
                        }
                        JdbcSchema.Table.Column.Usage usage =
                            (JdbcSchema.Table.Column.Usage) it.next();
                        if (usage.isColumnType(columnType)) {
                            nextObject = usage;
                            return true;
                        }
                    }
                }
                public Object next() {
                    return nextObject;
                }
                public void remove() {
                    it.remove();
                }
            }
            return new CTIterator(getColumns(), columnType);
        }

        /**
         * Get a column by its name.
         *
         * @param columnName
         * @return
         */
        public Column getColumn(final String columnName) {
            return (Column) getColumnMap().get(columnName);
        }

        /**
         * Return true if this table contains a column with the given name.
         *
         * @param columnName
         * @return
         */
        public boolean constainsColumn(final String columnName) {
            return getColumnMap().containsKey(columnName);
        }

        /**
         * Set the table usage (fact, aggregate or other).
         *
         * @param tableUsage
         */
        public void setTableUsage(final int tableUsage) {
            // if it has already been set, then it can NOT be reset
            if ((this.tableUsage != UNKNOWN_TABLE_USAGE) &&
                    (this.tableUsage != tableUsage)) {

                throw mres.AttemptToChangeTableUsage.ex(
                    getName(),
                    convertTableUsageToName(this.tableUsage),
                    convertTableUsageToName(tableUsage));
            }
            this.tableUsage = tableUsage;
        }

        /**
         * Get the table's usage.
         *
         * @return
         */
        public int getTableUsage() {
            return tableUsage;
        }

        /**
         * Set the table type
         *
         * @param tableType
         */
        public void setTableType(final String tableType) {
            // if it has already been set, then it can NOT be reset
            if ((this.tableType != UNKNOWN_TABLE_TYPE) &&
                    (! this.tableType.equals(tableType))) {

                throw mres.AttemptToChangeTableType.ex(
                    getName(),
                    this.tableType,
                    tableType);
            }
            this.tableType = tableType;
        }
        /**
         * Get the table's type.
         *
         * @return
         */
        public String getTableType() {
            return tableType;
        }

        public String toString() {
            StringWriter sw = new StringWriter(256);
            PrintWriter pw = new PrintWriter(sw);
            print(pw, "");
            pw.flush();
            return sw.toString();
        }
        public void print(final PrintWriter pw, final String prefix) {
            pw.print(prefix);
            pw.println("Table:");
            String subprefix = prefix + "  ";
            String subsubprefix = subprefix + "  ";

            pw.print(subprefix);
            pw.print("name=");
            pw.print(getName());
            pw.print(", type=");
            pw.print(getTableType());
            pw.print(", usage=");
            pw.println(convertTableUsageToName(getTableUsage()));

            pw.print(subprefix);
            pw.print("totalColumnSize=");
            pw.println(getTotalColumnSize());

            pw.print(subprefix);
            pw.println("Columns: [");
            Iterator it = getColumnMap().values().iterator();
            while (it.hasNext()) {
                Column column = (Column) it.next();
                column.print(pw, subsubprefix);
                pw.println();
            }
            pw.print(subprefix);
            pw.println("]");
        }

        /**
         * Get all of the columns associated with a table and create Column
         * objects with the column's name, type, type name and column size.
         *
         * @throws SQLException
         */
        private void loadColumns() throws SQLException {
            if (! allColumnsLoaded) {
                Connection conn = JdbcSchema.this.getConnection();
                try {
                    DatabaseMetaData dmd = conn.getMetaData();

                    String schema = JdbcSchema.this.getSchemaName();
                    String catalog = JdbcSchema.this.getCatalogName();
                    String tableName = getName();
                    String columnNamePattern = "%";

                    ResultSet rs = null;
                    try {
                        Map map = getColumnMap();
                        rs = dmd.getColumns(catalog,
                                            schema,
                                            tableName,
                                            columnNamePattern);
                        while (rs.next()) {
                            String name = rs.getString(4);
                            int type = rs.getInt(5);
                            String typeName = rs.getString(6);
                            int columnSize = rs.getInt(7);
                            int decimalDigits = rs.getInt(9);
                            int numPrecRadix = rs.getInt(10);
                            int charOctetLength = rs.getInt(16);
                            String isNullable = rs.getString(18);

                            Column column = new Column(name);
                            column.setType(type);
                            column.setTypeName(typeName);
                            column.setColumnSize(columnSize);
                            column.setDecimalDigits(decimalDigits);
                            column.setNumPrecRadix(numPrecRadix);
                            column.setCharOctetLength(charOctetLength);
                            column.setIsNullable(! isNullable.equals("NO"));

                            map.put(name, column);
                            totalColumnSize += column.getColumnSize();
                        }
                    } finally {
                        if (rs != null) {
                            rs.close();
                        }
                    }
                } finally {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        //ignore
                    }
                }

                allColumnsLoaded = true;
            }
        }
        private Map getColumnMap() {
            if (columnMap == null) {
                columnMap = new HashMap();
            }
            return columnMap;
        }
    }

    private DataSource dataSource;
    private String schema;
    private String catalog;
    private boolean allTablesLoaded;
    private Map tables;

    JdbcSchema(final DataSource dataSource) {
        this.dataSource = dataSource;
        this.tables = new HashMap();
    }

    /**
     * This forces the tables to be loaded.
     *
     * @throws SQLException
     */
    public void load() throws SQLException {
        loadTables();
    }

    /**
     * For testing ONLY
     *
     * @return
    JdbcSchema copy() {
        JdbcSchema jdbcSchema = new JdbcSchema(dataSource);
        jdbcSchema.setSchemaName(getSchemaName());
        jdbcSchema.setCatalogName(getCatalogName());

        Map m = jdbcSchema.getTablesMap();
        for (Iterator it = getTables(); it.hasNext(); ) {
            Table table = (Table) it.next();
            m.put(table.getName(), table.copy());
        }

        return jdbcSchema;
    }
     */

    /**
     * For testing ONLY
    void clearUsages() {
        for (Iterator it = getTables(); it.hasNext(); ) {
            Table table = (Table) it.next();
            table.clearUsages();
        }
    }
     */

    protected void clear() {
        // keep the DataSource, clear/reset everything else
        allTablesLoaded = false;
        schema = null;
        catalog = null;
        tables.clear();
    }

    /**
     * This is used for testing allowing one to load tables and their columns
     * from more than one datasource
     */
    void resetAllTablesLoaded() {
        allTablesLoaded = false;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    protected void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    /**
     * Get the java.sql.Connection associated with this database.
     *
     * @return
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }

    /**
     * Set the database's schema name.
     *
     * @param schema
     */
    public void setSchemaName(final String schema) {
        this.schema = schema;
    }

    /**
     * Get the database's schema name.
     *
     * @return
     */
    public String getSchemaName() {
        return schema;
    }
    /**
     * Set the database's catalog name.
     *
     * @param catalog
     */
    public void setCatalogName(final String catalog) {
        this.catalog = catalog;
    }
    /**
     * Get the database's catalog name.
     *
     * @return
     */
    public String getCatalogName() {
        return catalog;
    }

    /**
     * Get iterator over the database's tables.
     *
     * @return
     * @throws SQLException
     */
    public synchronized Iterator getTables() {
        return getTablesMap().values().iterator();
    }

    /**
     * Get a table by name.
     *
     * @param tableName
     * @return
     */
    public synchronized Table getTable(final String tableName) {
        Map tables = getTablesMap();
        Table table = (Table) tables.get(tableName);
        return table;
    }
    public String toString() {
        StringWriter sw = new StringWriter(256);
        PrintWriter pw = new PrintWriter(sw);
        print(pw, "");
        pw.flush();
        return sw.toString();
    }
    public void print(final PrintWriter pw, final String prefix) {
        pw.print(prefix);
        pw.println("JdbcSchema:");
        String subprefix = prefix + "  ";
        String subsubprefix = subprefix + "  ";

        pw.print(subprefix);
        pw.println("Tables: [");
        Iterator it = getTablesMap().values().iterator();
        while (it.hasNext()) {
            Table table = (Table) it.next();
            table.print(pw, subsubprefix);
        }
        pw.print(subprefix);
        pw.println("]");
    }

    /**
     * This method gets all of the tables (and views) in the database.
     * If called a second time, this method is a no-op.
     *
     * @throws SQLException
     */
    private void loadTables() throws SQLException {
        if (! allTablesLoaded) {
            Map tables = getTablesMap();
            Connection conn = getConnection();
            DatabaseMetaData dmd = conn.getMetaData();

            String schema = getSchemaName();
            String catalog = getCatalogName();
            String[] tableTypes = { "TABLE", "VIEW" };
            String tableName = "%";

            ResultSet rs = null;
            try {
                rs = dmd.getTables(catalog,
                                   schema,
                                   tableName,
                                   tableTypes);
                if (rs != null) {
                    while (rs.next()) {
                        addTable(rs);
                    }
                } else {
                    getLogger().debug("ERROR: rs == null");
                }
            } finally {
                if (rs != null) {
                    rs.close();
                }
            }
            try {
                conn.close();
            } catch (SQLException e) {
                //ignore
            }

            allTablesLoaded = true;
        }
    }

    /**
     * Make a Table from an ResultSet - the table's name is the ResultSet third
     * entry.
     *
     * @param rs
     * @throws SQLException
     */
    protected void addTable(final ResultSet rs) throws SQLException {
        String name = rs.getString(3);
        String tableType = rs.getString(4);
        Table table = new Table(name);
        table.setTableType(tableType);

        tables.put(table.getName(), table);
    }
    private Map getTablesMap() {
        return tables;
    }
}

// End JdbcSchema.java

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?