Search in sources :

Example 26 with DatabaseMetaData

use of java.sql.DatabaseMetaData in project head by mifos.

the class SystemInformationServiceFacadeWebTier method getSystemInformation.

@Override
public SystemInformationDto getSystemInformation(ServletContext context, Locale locale) {
    try {
        DatabaseMetaData metaData = StaticHibernateUtil.getSessionTL().connection().getMetaData();
        final SystemInfo systemInfo = new SystemInfo(metaData, context, locale, true);
        systemInfo.setCustomReportsDir(BirtReportsUploadAction.getCustomReportStorageDirectory());
        return new SystemInformationDto(systemInfo.getApplicationServerInfo(), systemInfo.getApplicationVersion(), systemInfo.getBuildDate(), systemInfo.getBuildNumber(), systemInfo.getCommitIdentifier(), systemInfo.getCustomReportsDir(), systemInfo.getDatabaseName(), systemInfo.getDatabasePort(), systemInfo.getDatabaseServer(), systemInfo.getDatabaseUser(), systemInfo.getDatabaseVendor(), systemInfo.getDatabaseVersion(), systemInfo.getDriverName(), systemInfo.getDriverVersion(), systemInfo.getDateTimeString(), systemInfo.getDateTimeStringIso8601(), systemInfo.getInfoSource(), systemInfo.getInfoURL(), systemInfo.getJavaVendor(), systemInfo.getJavaVersion(), systemInfo.getOsArch(), systemInfo.getOsName(), systemInfo.getOsUser(), systemInfo.getOsVersion(), systemInfo.getReleaseName());
    } catch (HibernateException e) {
        throw new MifosRuntimeException(e);
    } catch (SQLException e) {
        throw new MifosRuntimeException(e);
    }
}
Also used : SystemInfo(org.mifos.application.admin.system.SystemInfo) HibernateException(org.hibernate.HibernateException) SQLException(java.sql.SQLException) DatabaseMetaData(java.sql.DatabaseMetaData) MifosRuntimeException(org.mifos.core.MifosRuntimeException)

Example 27 with DatabaseMetaData

use of java.sql.DatabaseMetaData in project henplus by neurolabs.

the class DescribeCommand method execute.

/**
     * execute the command given.
     */
@Override
public int execute(final SQLSession session, final String cmd, final String param) {
    // make use of properties for these properties?
    // (since the options just toggle, this may be convenient)
    boolean showDescriptions = true;
    boolean showIndex = "idescribe".equals(cmd);
    boolean showTime = true;
    final StringTokenizer st = new StringTokenizer(param);
    if (st.countTokens() < 1) {
        return SYNTAX_ERROR;
    }
    // this was a flag to ensure that all options come before the tablenames
    // can probably be removed...
    final boolean moreOptions = true;
    while (st.hasMoreTokens()) {
        String tabName = st.nextToken();
        if (moreOptions && tabName.startsWith("-")) {
            if (tabName.indexOf('i') > -1) {
                showIndex = !showIndex;
            }
            if (tabName.indexOf('v') > -1) {
                showDescriptions = !showDescriptions;
            }
            if (tabName.indexOf('t') > -1) {
                showTime = !showTime;
            }
        } else {
            // more_options = false; // options can stand at every position
            // --> toggle
            boolean correctName = true;
            if (tabName.startsWith("\"")) {
                tabName = stripQuotes(tabName);
                correctName = false;
            }
            // separate schama and table.
            String schema = null;
            final int schemaDelim = tabName.indexOf('.');
            if (schemaDelim > 0) {
                schema = tabName.substring(0, schemaDelim);
                tabName = tabName.substring(schemaDelim + 1);
            }
            // FIXME: provide correct name as well for schema!
            if (correctName) {
                final String alternative = _tableCompleter.correctTableName(tabName);
                if (alternative != null && !alternative.equals(tabName)) {
                    tabName = alternative;
                    HenPlus.out().println("describing table: '" + tabName + "' (corrected name)");
                }
            }
            ResultSet rset = null;
            final Set<String> doubleCheck = new HashSet<String>();
            try {
                _interrupted = false;
                SigIntHandler.getInstance().pushInterruptable(this);
                boolean anyLeftArrow = false;
                boolean anyRightArrow = false;
                final long startTime = System.currentTimeMillis();
                final String catalog = session.getConnection().getCatalog();
                String description = null;
                String tableType = null;
                if (_interrupted) {
                    return SUCCESS;
                }
                final DatabaseMetaData meta = session.getConnection().getMetaData();
                for (int i = 0; i < DESC_META.length; ++i) {
                    DESC_META[i].resetWidth();
                }
                rset = meta.getTables(catalog, schema, tabName, LIST_TABLES);
                if (rset != null && rset.next()) {
                    tableType = rset.getString(4);
                    // remark
                    description = rset.getString(5);
                }
                rset.close();
                /*
                     * get primary keys.
                     */
                if (_interrupted) {
                    return SUCCESS;
                }
                final Map<String, String> pks = new HashMap<String, String>();
                rset = meta.getPrimaryKeys(null, schema, tabName);
                if (rset != null) {
                    while (!_interrupted && rset.next()) {
                        final String col = rset.getString(4);
                        final int pkseq = rset.getInt(5);
                        final String pkname = rset.getString(6);
                        String desc = pkname != null ? pkname : "*";
                        if (pkseq > 1) {
                            desc = new StringBuilder().append(desc).append("{").append(pkseq).append("}").toString();
                        }
                        pks.put(col, desc);
                    }
                    rset.close();
                }
                /*
                     * get referenced primary keys.
                     */
                if (_interrupted) {
                    return SUCCESS;
                }
                rset = meta.getExportedKeys(null, schema, tabName);
                if (rset != null) {
                    while (!_interrupted && rset.next()) {
                        final String col = rset.getString(4);
                        String fktable = rset.getString(7);
                        final String fkcolumn = rset.getString(8);
                        fktable = new StringBuilder().append(fktable).append("(").append(fkcolumn).append(")").toString();
                        String desc = pks.get(col);
                        desc = desc == null ? new StringBuilder().append(" <- ").append(fktable).toString() : new StringBuilder().append(desc).append("\n <- ").append(fktable).toString();
                        anyLeftArrow = true;
                        pks.put(col, desc);
                    }
                    rset.close();
                }
                /*
                     * get foreign keys.
                     */
                if (_interrupted) {
                    return SUCCESS;
                }
                final Map<String, String> fks = new HashMap<String, String>();
                // with foreign keys...
                try {
                    rset = meta.getImportedKeys(null, schema, tabName);
                } catch (final NoSuchElementException e) {
                    Logger.debug("Database problem reading meta data: ", e);
                }
                if (rset != null) {
                    while (!_interrupted && rset.next()) {
                        String table = rset.getString(3);
                        final String pkcolumn = rset.getString(4);
                        table = table + "(" + pkcolumn + ")";
                        final String col = rset.getString(8);
                        final String fkname = rset.getString(12);
                        String desc = fkname != null ? new StringBuilder().append(fkname).append("\n -> ").toString() : " -> ";
                        desc += table;
                        anyRightArrow = true;
                        fks.put(col, desc);
                    }
                    rset.close();
                }
                HenPlus.out().println(("VIEW".equals(tableType) ? "View: " : "Table: ") + tabName);
                if (description != null) {
                    HenPlus.out().println(description);
                }
                if (catalog != null) {
                    HenPlus.msg().println("catalog: " + catalog);
                }
                if (anyLeftArrow) {
                    HenPlus.msg().println(" '<-' : referenced by");
                }
                if (anyRightArrow) {
                    HenPlus.msg().println(" '->' : referencing");
                }
                /*
                     * if all columns belong to the same table name, then don't
                     * report it. A different table name may only occur in rare
                     * circumstance like object oriented databases.
                     */
                boolean allSameTableName = true;
                /*
                     * build up actual describe table.
                     */
                if (_interrupted) {
                    return SUCCESS;
                }
                rset = meta.getColumns(catalog, schema, tabName, null);
                final List<Column[]> rows = new ArrayList<Column[]>();
                int colNum = 0;
                boolean anyDescription = false;
                if (rset != null) {
                    while (!_interrupted && rset.next()) {
                        final Column[] row = new Column[9];
                        row[0] = new Column(++colNum);
                        final String thisTabName = rset.getString(3);
                        row[1] = new Column(thisTabName);
                        allSameTableName &= tabName.equals(thisTabName);
                        final String colname = rset.getString(4);
                        if (doubleCheck.contains(colname)) {
                            continue;
                        }
                        doubleCheck.add(colname);
                        row[2] = new Column(colname);
                        String type = rset.getString(6);
                        final int colSize = rset.getInt(7);
                        final int colDp = rset.getInt(9);
                        if (colSize > 0) {
                            if (colDp == 0) {
                                type = type + "(" + colSize + ")";
                            } else {
                                type = type + "(" + colSize + "," + colDp + ")";
                            }
                        }
                        row[3] = new Column(type);
                        final String defaultVal = rset.getString(13);
                        row[4] = new Column(rset.getString(18));
                        // oracle appends newline to default values for some
                        // reason.
                        row[5] = new Column((defaultVal != null ? defaultVal.trim() : null));
                        final String pkdesc = pks.get(colname);
                        row[6] = new Column(pkdesc != null ? pkdesc : "");
                        final String fkdesc = fks.get(colname);
                        row[7] = new Column(fkdesc != null ? fkdesc : "");
                        final String colDesc = showDescriptions ? rset.getString(12) : null;
                        row[8] = new Column(colDesc);
                        anyDescription |= colDesc != null;
                        rows.add(row);
                    }
                }
                rset.close();
                /*
                     * we render the table now, since we only know now, whether
                     * we will show the first column and the description column
                     * or not.
                     */
                DESC_META[1].setDisplay(!allSameTableName);
                DESC_META[8].setDisplay(anyDescription);
                final TableRenderer table = new TableRenderer(DESC_META, HenPlus.out());
                final Iterator<Column[]> it = rows.iterator();
                while (it.hasNext()) {
                    table.addRow(it.next());
                }
                table.closeTable();
                if (_interrupted) {
                    return SUCCESS;
                }
                if (showIndex) {
                    showIndexInformation(tabName, schema, meta);
                }
                if (showTime) {
                    TimeRenderer.printTime(System.currentTimeMillis() - startTime, HenPlus.out());
                    HenPlus.out().println();
                }
            } catch (final Exception e) {
                final String ex = e.getMessage() != null ? e.getMessage().trim() : e.toString();
                Logger.error("Database problem reading meta data: ", ex);
                return EXEC_FAILED;
            } finally {
                if (rset != null) {
                    try {
                        rset.close();
                    } catch (final Exception e) {
                    }
                }
            }
        }
    }
    return SUCCESS;
}
Also used : TableRenderer(henplus.view.TableRenderer) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) DatabaseMetaData(java.sql.DatabaseMetaData) SQLException(java.sql.SQLException) NoSuchElementException(java.util.NoSuchElementException) StringTokenizer(java.util.StringTokenizer) Column(henplus.view.Column) ResultSet(java.sql.ResultSet) NoSuchElementException(java.util.NoSuchElementException) HashSet(java.util.HashSet)

Example 28 with DatabaseMetaData

use of java.sql.DatabaseMetaData in project henplus by neurolabs.

the class SQLMetaDataBuilder method getMetaData.

public SQLMetaData getMetaData(final SQLSession session, final Iterator<String> tableNamesIter) {
    final SQLMetaData result = new SQLMetaData();
    ResultSet rset = null;
    try {
        _interrupted = false;
        final String catalog = session.getConnection().getCatalog();
        if (_interrupted) {
            return null;
        }
        final DatabaseMetaData meta = session.getConnection().getMetaData();
        while (tableNamesIter.hasNext() && !_interrupted) {
            final String tableName = tableNamesIter.next();
            rset = meta.getColumns(catalog, null, tableName, null);
            final Table table = buildTable(catalog, meta, tableName, rset);
            result.addTable(table);
        }
    } catch (final Exception e) {
        if (VERBOSE) {
            e.printStackTrace();
        }
        HenPlus.msg().println("Database problem reading meta data: " + e.getMessage().trim());
    } finally {
        if (rset != null) {
            try {
                rset.close();
            } catch (final Exception e) {
            }
        }
    }
    return result;
}
Also used : Table(henplus.sqlmodel.Table) ResultSet(java.sql.ResultSet) DatabaseMetaData(java.sql.DatabaseMetaData) SQLException(java.sql.SQLException) NoSuchElementException(java.util.NoSuchElementException)

Example 29 with DatabaseMetaData

use of java.sql.DatabaseMetaData in project henplus by neurolabs.

the class SQLSession method connect.

public void connect() throws SQLException, IOException {
    /*
         * close old connection ..
         */
    if (_conn != null) {
        try {
            _conn.close();
        } catch (final Throwable t) {
        /* ignore */
        }
        _conn = null;
    }
    final Properties props = new Properties();
    /*
         * FIXME make generic plugin for specific database drivers that handle
         * the specific stuff. For now this is a quick hack.
         */
    if (_url.startsWith("jdbc:oracle:")) {
        /*
             * this is needed to make comment in oracle show up in the remarks
             * http://forums.oracle.com/forums/thread.jsp?forum=99&thread=225790
             */
        props.setProperty("remarksReporting", "true");
    }
    /*
         * try to connect directly with the url. Several JDBC-Drivers allow to
         * embed the username and password directly in the URL.
         */
    if (_username == null || _password == null) {
        try {
            _conn = DriverManager.getConnection(_url, props);
        } catch (final SQLException e) {
            HenPlus.msg().println(e.getMessage());
            // only query terminals.
            if (HenPlus.msg().isTerminal()) {
                promptUserPassword();
            }
        }
    }
    if (_conn == null) {
        _conn = DriverManager.getConnection(_url, _username, _password);
    }
    if (_conn != null && _username == null) {
        try {
            final DatabaseMetaData meta = _conn.getMetaData();
            if (meta != null) {
                _username = meta.getUserName();
            }
        } catch (final Exception e) {
        /* ok .. at least I tried */
        }
    }
    _connectTime = System.currentTimeMillis();
}
Also used : SQLException(java.sql.SQLException) Properties(java.util.Properties) DatabaseMetaData(java.sql.DatabaseMetaData) IOException(java.io.IOException) SQLException(java.sql.SQLException)

Example 30 with DatabaseMetaData

use of java.sql.DatabaseMetaData in project henplus by neurolabs.

the class TreeCommand method execute.

/**
     * execute the command given.
     */
@Override
public int execute(final SQLSession session, final String cmd, final String param) {
    final StringTokenizer st = new StringTokenizer(param);
    final int argc = st.countTokens();
    if (argc != 1) {
        return SYNTAX_ERROR;
    }
    boolean correctName = true;
    String tabName = (String) st.nextElement();
    if (tabName.startsWith("\"")) {
        tabName = stripQuotes(tabName);
        correctName = false;
    }
    if (correctName) {
        final String alternative = _tableCompleter.correctTableName(tabName);
        if (alternative != null && !alternative.equals(tabName)) {
            tabName = alternative;
        }
    }
    // fixme: determine
    final String schema = null;
    try {
        final long startTime = System.currentTimeMillis();
        final DatabaseMetaData dbMeta = session.getConnection().getMetaData();
        _interrupted = false;
        SigIntHandler.getInstance().pushInterruptable(this);
        // build a tree of all tables I depend on..
        final Node myParents = buildTree(new ReferenceMetaDataSource() {

            @Override
            public ResultSet getReferenceMetaData(final String schema, final String table) throws SQLException {
                return dbMeta.getImportedKeys(null, schema, table);
            }
        }, IMP_PRIMARY_KEY_TABLE, new TreeMap<String, Node>(), schema, tabName);
        if (_interrupted) {
            return SUCCESS;
        }
        myParents.markDepths();
        // build a tree of all tables that depend on me ...
        final Node myChilds = buildTree(new ReferenceMetaDataSource() {

            @Override
            public ResultSet getReferenceMetaData(final String schema, final String table) throws SQLException {
                return dbMeta.getExportedKeys(null, schema, table);
            }
        }, EXP_FOREIGN_KEY_TABLE, new TreeMap<String, Node>(), schema, tabName);
        if (_interrupted) {
            return SUCCESS;
        }
        myChilds.markDepths();
        final int reversIndent = myParents.printReverse(HenPlus.out());
        final int tabLen = tabName.length();
        int startPos = reversIndent - tabLen / 2;
        if (startPos < 0) {
            startPos = 0;
        }
        for (int i = 0; i < startPos; ++i) {
            HenPlus.out().print(" ");
        }
        HenPlus.out().attributeBold();
        HenPlus.out().println(tabName);
        HenPlus.out().attributeReset();
        myChilds.print(HenPlus.out(), startPos + tabLen / 2);
        TimeRenderer.printTime(System.currentTimeMillis() - startTime, HenPlus.msg());
        HenPlus.msg().println();
    } catch (final Exception e) {
        HenPlus.msg().println("problem getting database meta data: " + e.getMessage());
        return EXEC_FAILED;
    }
    return SUCCESS;
}
Also used : SQLException(java.sql.SQLException) DatabaseMetaData(java.sql.DatabaseMetaData) SQLException(java.sql.SQLException) StringTokenizer(java.util.StringTokenizer) ResultSet(java.sql.ResultSet)

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