Search in sources :

Example 1 with TreeIndex

use of org.h2.index.TreeIndex in project h2database by h2database.

the class WebApp method addTablesAndViews.

private int addTablesAndViews(DbSchema schema, boolean mainSchema, StringBuilder buff, int treeIndex) throws SQLException {
    if (schema == null) {
        return treeIndex;
    }
    Connection conn = session.getConnection();
    DatabaseMetaData meta = session.getMetaData();
    int level = mainSchema ? 0 : 1;
    boolean showColumns = mainSchema || !schema.isSystem;
    String indentation = ", " + level + ", " + (showColumns ? "1" : "2") + ", ";
    String indentNode = ", " + (level + 1) + ", 2, ";
    DbTableOrView[] tables = schema.getTables();
    if (tables == null) {
        return treeIndex;
    }
    boolean isOracle = schema.getContents().isOracle();
    boolean notManyTables = tables.length < SysProperties.CONSOLE_MAX_TABLES_LIST_INDEXES;
    for (DbTableOrView table : tables) {
        if (table.isView()) {
            continue;
        }
        int tableId = treeIndex;
        String tab = table.getQuotedName();
        if (!mainSchema) {
            tab = schema.quotedName + "." + tab;
        }
        tab = escapeIdentifier(tab);
        buff.append("setNode(").append(treeIndex).append(indentation).append(" 'table', '").append(PageParser.escapeJavaScript(table.getName())).append("', 'javascript:ins(\\'").append(tab).append("\\',true)');\n");
        treeIndex++;
        if (mainSchema || showColumns) {
            StringBuilder columnsBuffer = new StringBuilder();
            treeIndex = addColumns(mainSchema, table, buff, treeIndex, notManyTables, columnsBuffer);
            if (!isOracle && notManyTables) {
                treeIndex = addIndexes(mainSchema, meta, table.getName(), schema.name, buff, treeIndex);
            }
            buff.append("addTable('").append(PageParser.escapeJavaScript(table.getName())).append("', '").append(PageParser.escapeJavaScript(columnsBuffer.toString())).append("', ").append(tableId).append(");\n");
        }
    }
    tables = schema.getTables();
    for (DbTableOrView view : tables) {
        if (!view.isView()) {
            continue;
        }
        int tableId = treeIndex;
        String tab = view.getQuotedName();
        if (!mainSchema) {
            tab = view.getSchema().quotedName + "." + tab;
        }
        tab = escapeIdentifier(tab);
        buff.append("setNode(").append(treeIndex).append(indentation).append(" 'view', '").append(PageParser.escapeJavaScript(view.getName())).append("', 'javascript:ins(\\'").append(tab).append("\\',true)');\n");
        treeIndex++;
        if (mainSchema) {
            StringBuilder columnsBuffer = new StringBuilder();
            treeIndex = addColumns(mainSchema, view, buff, treeIndex, notManyTables, columnsBuffer);
            if (schema.getContents().isH2()) {
                try (PreparedStatement prep = conn.prepareStatement("SELECT * FROM " + "INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=?")) {
                    prep.setString(1, view.getName());
                    ResultSet rs = prep.executeQuery();
                    if (rs.next()) {
                        String sql = rs.getString("SQL");
                        buff.append("setNode(").append(treeIndex).append(indentNode).append(" 'type', '").append(PageParser.escapeJavaScript(sql)).append("', null);\n");
                        treeIndex++;
                    }
                    rs.close();
                }
            }
            buff.append("addTable('").append(PageParser.escapeJavaScript(view.getName())).append("', '").append(PageParser.escapeJavaScript(columnsBuffer.toString())).append("', ").append(tableId).append(");\n");
        }
    }
    return treeIndex;
}
Also used : Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) SimpleResultSet(org.h2.tools.SimpleResultSet) DbTableOrView(org.h2.bnf.context.DbTableOrView) PreparedStatement(java.sql.PreparedStatement) DatabaseMetaData(java.sql.DatabaseMetaData)

Example 2 with TreeIndex

use of org.h2.index.TreeIndex in project h2database by h2database.

the class WebApp method tables.

private String tables() {
    DbContents contents = session.getContents();
    boolean isH2 = false;
    try {
        String url = (String) session.get("url");
        Connection conn = session.getConnection();
        contents.readContents(url, conn);
        session.loadBnf();
        isH2 = contents.isH2();
        StringBuilder buff = new StringBuilder().append("setNode(0, 0, 0, 'database', '").append(PageParser.escapeJavaScript(url)).append("', null);\n");
        int treeIndex = 1;
        DbSchema defaultSchema = contents.getDefaultSchema();
        treeIndex = addTablesAndViews(defaultSchema, true, buff, treeIndex);
        DbSchema[] schemas = contents.getSchemas();
        for (DbSchema schema : schemas) {
            if (schema == defaultSchema || schema == null) {
                continue;
            }
            buff.append("setNode(").append(treeIndex).append(", 0, 1, 'folder', '").append(PageParser.escapeJavaScript(schema.name)).append("', null);\n");
            treeIndex++;
            treeIndex = addTablesAndViews(schema, false, buff, treeIndex);
        }
        if (isH2) {
            try (Statement stat = conn.createStatement()) {
                ResultSet rs = stat.executeQuery("SELECT * FROM " + "INFORMATION_SCHEMA.SEQUENCES ORDER BY SEQUENCE_NAME");
                for (int i = 0; rs.next(); i++) {
                    if (i == 0) {
                        buff.append("setNode(").append(treeIndex).append(", 0, 1, 'sequences', '${text.tree.sequences}', null);\n");
                        treeIndex++;
                    }
                    String name = rs.getString("SEQUENCE_NAME");
                    String current = rs.getString("CURRENT_VALUE");
                    String increment = rs.getString("INCREMENT");
                    buff.append("setNode(").append(treeIndex).append(", 1, 1, 'sequence', '").append(PageParser.escapeJavaScript(name)).append("', null);\n");
                    treeIndex++;
                    buff.append("setNode(").append(treeIndex).append(", 2, 2, 'type', '${text.tree.current}: ").append(PageParser.escapeJavaScript(current)).append("', null);\n");
                    treeIndex++;
                    if (!"1".equals(increment)) {
                        buff.append("setNode(").append(treeIndex).append(", 2, 2, 'type', '${text.tree.increment}: ").append(PageParser.escapeJavaScript(increment)).append("', null);\n");
                        treeIndex++;
                    }
                }
                rs.close();
                rs = stat.executeQuery("SELECT * FROM " + "INFORMATION_SCHEMA.USERS ORDER BY NAME");
                for (int i = 0; rs.next(); i++) {
                    if (i == 0) {
                        buff.append("setNode(").append(treeIndex).append(", 0, 1, 'users', '${text.tree.users}', null);\n");
                        treeIndex++;
                    }
                    String name = rs.getString("NAME");
                    String admin = rs.getString("ADMIN");
                    buff.append("setNode(").append(treeIndex).append(", 1, 1, 'user', '").append(PageParser.escapeJavaScript(name)).append("', null);\n");
                    treeIndex++;
                    if (admin.equalsIgnoreCase("TRUE")) {
                        buff.append("setNode(").append(treeIndex).append(", 2, 2, 'type', '${text.tree.admin}', null);\n");
                        treeIndex++;
                    }
                }
                rs.close();
            }
        }
        DatabaseMetaData meta = session.getMetaData();
        String version = meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion();
        buff.append("setNode(").append(treeIndex).append(", 0, 0, 'info', '").append(PageParser.escapeJavaScript(version)).append("', null);\n").append("refreshQueryTables();");
        session.put("tree", buff.toString());
    } catch (Exception e) {
        session.put("tree", "");
        session.put("error", getStackTrace(0, e, isH2));
    }
    return "tables.jsp";
}
Also used : DbContents(org.h2.bnf.context.DbContents) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) DbSchema(org.h2.bnf.context.DbSchema) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) SimpleResultSet(org.h2.tools.SimpleResultSet) DatabaseMetaData(java.sql.DatabaseMetaData) DbException(org.h2.message.DbException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLException(java.sql.SQLException) JdbcSQLException(org.h2.jdbc.JdbcSQLException)

Example 3 with TreeIndex

use of org.h2.index.TreeIndex in project h2database by h2database.

the class RegularTable method addIndex.

@Override
public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType, boolean create, String indexComment) {
    if (indexType.isPrimaryKey()) {
        for (IndexColumn c : cols) {
            Column column = c.column;
            if (column.isNullable()) {
                throw DbException.get(ErrorCode.COLUMN_MUST_NOT_BE_NULLABLE_1, column.getName());
            }
            column.setPrimaryKey(true);
        }
    }
    boolean isSessionTemporary = isTemporary() && !isGlobalTemporary();
    if (!isSessionTemporary) {
        database.lockMeta(session);
    }
    Index index;
    if (isPersistIndexes() && indexType.isPersistent()) {
        int mainIndexColumn;
        if (database.isStarting() && database.getPageStore().getRootPageId(indexId) != 0) {
            mainIndexColumn = -1;
        } else if (!database.isStarting() && mainIndex.getRowCount(session) != 0) {
            mainIndexColumn = -1;
        } else {
            mainIndexColumn = getMainIndexColumn(indexType, cols);
        }
        if (mainIndexColumn != -1) {
            mainIndex.setMainIndexColumn(mainIndexColumn);
            index = new PageDelegateIndex(this, indexId, indexName, indexType, mainIndex, create, session);
        } else if (indexType.isSpatial()) {
            index = new SpatialTreeIndex(this, indexId, indexName, cols, indexType, true, create, session);
        } else {
            index = new PageBtreeIndex(this, indexId, indexName, cols, indexType, create, session);
        }
    } else {
        if (indexType.isHash()) {
            if (cols.length != 1) {
                throw DbException.getUnsupportedException("hash indexes may index only one column");
            }
            if (indexType.isUnique()) {
                index = new HashIndex(this, indexId, indexName, cols, indexType);
            } else {
                index = new NonUniqueHashIndex(this, indexId, indexName, cols, indexType);
            }
        } else if (indexType.isSpatial()) {
            index = new SpatialTreeIndex(this, indexId, indexName, cols, indexType, false, true, session);
        } else {
            index = new TreeIndex(this, indexId, indexName, cols, indexType);
        }
    }
    if (database.isMultiVersion()) {
        index = new MultiVersionIndex(index, this);
    }
    if (index.needRebuild() && rowCount > 0) {
        try {
            Index scan = getScanIndex(session);
            long remaining = scan.getRowCount(session);
            long total = remaining;
            Cursor cursor = scan.find(session, null, null);
            long i = 0;
            int bufferSize = (int) Math.min(rowCount, database.getMaxMemoryRows());
            ArrayList<Row> buffer = new ArrayList<>(bufferSize);
            String n = getName() + ":" + index.getName();
            int t = MathUtils.convertLongToInt(total);
            while (cursor.next()) {
                database.setProgress(DatabaseEventListener.STATE_CREATE_INDEX, n, MathUtils.convertLongToInt(i++), t);
                Row row = cursor.get();
                buffer.add(row);
                if (buffer.size() >= bufferSize) {
                    addRowsToIndex(session, buffer, index);
                }
                remaining--;
            }
            addRowsToIndex(session, buffer, index);
            if (SysProperties.CHECK && remaining != 0) {
                DbException.throwInternalError("rowcount remaining=" + remaining + " " + getName());
            }
        } catch (DbException e) {
            getSchema().freeUniqueName(indexName);
            try {
                index.remove(session);
            } catch (DbException e2) {
                // this could happen, for example on failure in the storage
                // but if that is not the case it means
                // there is something wrong with the database
                trace.error(e2, "could not remove index");
                throw e2;
            }
            throw e;
        }
    }
    index.setTemporary(isTemporary());
    if (index.getCreateSQL() != null) {
        index.setComment(indexComment);
        if (isSessionTemporary) {
            session.addLocalTempTableIndex(index);
        } else {
            database.addSchemaObject(session, index);
        }
    }
    indexes.add(index);
    setModified();
    return index;
}
Also used : SpatialTreeIndex(org.h2.index.SpatialTreeIndex) PageDelegateIndex(org.h2.index.PageDelegateIndex) NonUniqueHashIndex(org.h2.index.NonUniqueHashIndex) PageBtreeIndex(org.h2.index.PageBtreeIndex) ArrayList(java.util.ArrayList) NonUniqueHashIndex(org.h2.index.NonUniqueHashIndex) Index(org.h2.index.Index) HashIndex(org.h2.index.HashIndex) ScanIndex(org.h2.index.ScanIndex) PageBtreeIndex(org.h2.index.PageBtreeIndex) TreeIndex(org.h2.index.TreeIndex) PageDataIndex(org.h2.index.PageDataIndex) PageDelegateIndex(org.h2.index.PageDelegateIndex) MultiVersionIndex(org.h2.index.MultiVersionIndex) SpatialTreeIndex(org.h2.index.SpatialTreeIndex) NonUniqueHashIndex(org.h2.index.NonUniqueHashIndex) HashIndex(org.h2.index.HashIndex) Cursor(org.h2.index.Cursor) Constraint(org.h2.constraint.Constraint) DbException(org.h2.message.DbException) TreeIndex(org.h2.index.TreeIndex) SpatialTreeIndex(org.h2.index.SpatialTreeIndex) MultiVersionIndex(org.h2.index.MultiVersionIndex) Row(org.h2.result.Row)

Example 4 with TreeIndex

use of org.h2.index.TreeIndex in project h2database by h2database.

the class WebApp method addColumns.

private static int addColumns(boolean mainSchema, DbTableOrView table, StringBuilder buff, int treeIndex, boolean showColumnTypes, StringBuilder columnsBuffer) {
    DbColumn[] columns = table.getColumns();
    for (int i = 0; columns != null && i < columns.length; i++) {
        DbColumn column = columns[i];
        if (columnsBuffer.length() > 0) {
            columnsBuffer.append(' ');
        }
        columnsBuffer.append(column.getName());
        String col = escapeIdentifier(column.getName());
        String level = mainSchema ? ", 1, 1" : ", 2, 2";
        buff.append("setNode(").append(treeIndex).append(level).append(", 'column', '").append(PageParser.escapeJavaScript(column.getName())).append("', 'javascript:ins(\\'").append(col).append("\\')');\n");
        treeIndex++;
        if (mainSchema && showColumnTypes) {
            buff.append("setNode(").append(treeIndex).append(", 2, 2, 'type', '").append(PageParser.escapeJavaScript(column.getDataType())).append("', null);\n");
            treeIndex++;
        }
    }
    return treeIndex;
}
Also used : DbColumn(org.h2.bnf.context.DbColumn)

Example 5 with TreeIndex

use of org.h2.index.TreeIndex in project h2database by h2database.

the class WebApp method addIndexes.

private static int addIndexes(boolean mainSchema, DatabaseMetaData meta, String table, String schema, StringBuilder buff, int treeIndex) throws SQLException {
    ResultSet rs;
    try {
        rs = meta.getIndexInfo(null, schema, table, false, true);
    } catch (SQLException e) {
        // SQLite
        return treeIndex;
    }
    HashMap<String, IndexInfo> indexMap = new HashMap<>();
    while (rs.next()) {
        String name = rs.getString("INDEX_NAME");
        IndexInfo info = indexMap.get(name);
        if (info == null) {
            int t = rs.getInt("TYPE");
            String type;
            if (t == DatabaseMetaData.tableIndexClustered) {
                type = "";
            } else if (t == DatabaseMetaData.tableIndexHashed) {
                type = " (${text.tree.hashed})";
            } else if (t == DatabaseMetaData.tableIndexOther) {
                type = "";
            } else {
                type = null;
            }
            if (name != null && type != null) {
                info = new IndexInfo();
                info.name = name;
                type = (rs.getBoolean("NON_UNIQUE") ? "${text.tree.nonUnique}" : "${text.tree.unique}") + type;
                info.type = type;
                info.columns = rs.getString("COLUMN_NAME");
                indexMap.put(name, info);
            }
        } else {
            info.columns += ", " + rs.getString("COLUMN_NAME");
        }
    }
    rs.close();
    if (indexMap.size() > 0) {
        String level = mainSchema ? ", 1, 1" : ", 2, 1";
        String levelIndex = mainSchema ? ", 2, 1" : ", 3, 1";
        String levelColumnType = mainSchema ? ", 3, 2" : ", 4, 2";
        buff.append("setNode(").append(treeIndex).append(level).append(", 'index_az', '${text.tree.indexes}', null);\n");
        treeIndex++;
        for (IndexInfo info : indexMap.values()) {
            buff.append("setNode(").append(treeIndex).append(levelIndex).append(", 'index', '").append(PageParser.escapeJavaScript(info.name)).append("', null);\n");
            treeIndex++;
            buff.append("setNode(").append(treeIndex).append(levelColumnType).append(", 'type', '").append(info.type).append("', null);\n");
            treeIndex++;
            buff.append("setNode(").append(treeIndex).append(levelColumnType).append(", 'type', '").append(PageParser.escapeJavaScript(info.columns)).append("', null);\n");
            treeIndex++;
        }
    }
    return treeIndex;
}
Also used : SQLException(java.sql.SQLException) JdbcSQLException(org.h2.jdbc.JdbcSQLException) HashMap(java.util.HashMap) ResultSet(java.sql.ResultSet) SimpleResultSet(org.h2.tools.SimpleResultSet)

Aggregations

ResultSet (java.sql.ResultSet)3 SimpleResultSet (org.h2.tools.SimpleResultSet)3 Connection (java.sql.Connection)2 DatabaseMetaData (java.sql.DatabaseMetaData)2 PreparedStatement (java.sql.PreparedStatement)2 SQLException (java.sql.SQLException)2 JdbcSQLException (org.h2.jdbc.JdbcSQLException)2 DbException (org.h2.message.DbException)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Statement (java.sql.Statement)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 DbColumn (org.h2.bnf.context.DbColumn)1 DbContents (org.h2.bnf.context.DbContents)1 DbSchema (org.h2.bnf.context.DbSchema)1 DbTableOrView (org.h2.bnf.context.DbTableOrView)1 Constraint (org.h2.constraint.Constraint)1 Cursor (org.h2.index.Cursor)1 HashIndex (org.h2.index.HashIndex)1 Index (org.h2.index.Index)1