Search in sources :

Example 1 with LocalResult

use of org.h2.result.LocalResult in project h2database by h2database.

the class ScriptCommand method query.

@Override
public ResultInterface query(int maxrows) {
    session.getUser().checkAdmin();
    reset();
    Database db = session.getDatabase();
    if (schemaNames != null) {
        for (String schemaName : schemaNames) {
            Schema schema = db.findSchema(schemaName);
            if (schema == null) {
                throw DbException.get(ErrorCode.SCHEMA_NOT_FOUND_1, schemaName);
            }
        }
    }
    try {
        result = createResult();
        deleteStore();
        openOutput();
        if (out != null) {
            buffer = new byte[Constants.IO_BUFFER_SIZE];
        }
        if (settings) {
            for (Setting setting : db.getAllSettings()) {
                if (setting.getName().equals(SetTypes.getTypeName(SetTypes.CREATE_BUILD))) {
                    // (it is only set when creating the database)
                    continue;
                }
                add(setting.getCreateSQL(), false);
            }
        }
        if (out != null) {
            add("", true);
        }
        for (User user : db.getAllUsers()) {
            add(user.getCreateSQL(passwords), false);
        }
        for (Role role : db.getAllRoles()) {
            add(role.getCreateSQL(true), false);
        }
        for (Schema schema : db.getAllSchemas()) {
            if (excludeSchema(schema)) {
                continue;
            }
            add(schema.getCreateSQL(), false);
        }
        for (UserDataType datatype : db.getAllUserDataTypes()) {
            if (drop) {
                add(datatype.getDropSQL(), false);
            }
            add(datatype.getCreateSQL(), false);
        }
        for (SchemaObject obj : db.getAllSchemaObjects(DbObject.CONSTANT)) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            Constant constant = (Constant) obj;
            add(constant.getCreateSQL(), false);
        }
        final ArrayList<Table> tables = db.getAllTablesAndViews(false);
        // sort by id, so that views are after tables and views on views
        // after the base views
        Collections.sort(tables, new Comparator<Table>() {

            @Override
            public int compare(Table t1, Table t2) {
                return t1.getId() - t2.getId();
            }
        });
        // Generate the DROP XXX  ... IF EXISTS
        for (Table table : tables) {
            if (excludeSchema(table.getSchema())) {
                continue;
            }
            if (excludeTable(table)) {
                continue;
            }
            if (table.isHidden()) {
                continue;
            }
            table.lock(session, false, false);
            String sql = table.getCreateSQL();
            if (sql == null) {
                // null for metadata tables
                continue;
            }
            if (drop) {
                add(table.getDropSQL(), false);
            }
        }
        for (SchemaObject obj : db.getAllSchemaObjects(DbObject.FUNCTION_ALIAS)) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            if (drop) {
                add(obj.getDropSQL(), false);
            }
            add(obj.getCreateSQL(), false);
        }
        for (UserAggregate agg : db.getAllAggregates()) {
            if (drop) {
                add(agg.getDropSQL(), false);
            }
            add(agg.getCreateSQL(), false);
        }
        for (SchemaObject obj : db.getAllSchemaObjects(DbObject.SEQUENCE)) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            Sequence sequence = (Sequence) obj;
            if (drop) {
                add(sequence.getDropSQL(), false);
            }
            add(sequence.getCreateSQL(), false);
        }
        // Generate CREATE TABLE and INSERT...VALUES
        int count = 0;
        for (Table table : tables) {
            if (excludeSchema(table.getSchema())) {
                continue;
            }
            if (excludeTable(table)) {
                continue;
            }
            if (table.isHidden()) {
                continue;
            }
            table.lock(session, false, false);
            String createTableSql = table.getCreateSQL();
            if (createTableSql == null) {
                // null for metadata tables
                continue;
            }
            final TableType tableType = table.getTableType();
            add(createTableSql, false);
            final ArrayList<Constraint> constraints = table.getConstraints();
            if (constraints != null) {
                for (Constraint constraint : constraints) {
                    if (Constraint.Type.PRIMARY_KEY == constraint.getConstraintType()) {
                        add(constraint.getCreateSQLWithoutIndexes(), false);
                    }
                }
            }
            if (TableType.TABLE == tableType) {
                if (table.canGetRowCount()) {
                    String rowcount = "-- " + table.getRowCountApproximation() + " +/- SELECT COUNT(*) FROM " + table.getSQL();
                    add(rowcount, false);
                }
                if (data) {
                    count = generateInsertValues(count, table);
                }
            }
            final ArrayList<Index> indexes = table.getIndexes();
            for (int j = 0; indexes != null && j < indexes.size(); j++) {
                Index index = indexes.get(j);
                if (!index.getIndexType().getBelongsToConstraint()) {
                    add(index.getCreateSQL(), false);
                }
            }
        }
        if (tempLobTableCreated) {
            add("DROP TABLE IF EXISTS SYSTEM_LOB_STREAM", true);
            add("CALL SYSTEM_COMBINE_BLOB(-1)", true);
            add("DROP ALIAS IF EXISTS SYSTEM_COMBINE_CLOB", true);
            add("DROP ALIAS IF EXISTS SYSTEM_COMBINE_BLOB", true);
            tempLobTableCreated = false;
        }
        // Generate CREATE CONSTRAINT ...
        final ArrayList<SchemaObject> constraints = db.getAllSchemaObjects(DbObject.CONSTRAINT);
        Collections.sort(constraints, new Comparator<SchemaObject>() {

            @Override
            public int compare(SchemaObject c1, SchemaObject c2) {
                return ((Constraint) c1).compareTo((Constraint) c2);
            }
        });
        for (SchemaObject obj : constraints) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            Constraint constraint = (Constraint) obj;
            if (excludeTable(constraint.getTable())) {
                continue;
            }
            if (constraint.getTable().isHidden()) {
                continue;
            }
            if (Constraint.Type.PRIMARY_KEY != constraint.getConstraintType()) {
                add(constraint.getCreateSQLWithoutIndexes(), false);
            }
        }
        // Generate CREATE TRIGGER ...
        for (SchemaObject obj : db.getAllSchemaObjects(DbObject.TRIGGER)) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            TriggerObject trigger = (TriggerObject) obj;
            if (excludeTable(trigger.getTable())) {
                continue;
            }
            add(trigger.getCreateSQL(), false);
        }
        // Generate GRANT ...
        for (Right right : db.getAllRights()) {
            DbObject object = right.getGrantedObject();
            if (object != null) {
                if (object instanceof Schema) {
                    if (excludeSchema((Schema) object)) {
                        continue;
                    }
                } else if (object instanceof Table) {
                    Table table = (Table) object;
                    if (excludeSchema(table.getSchema())) {
                        continue;
                    }
                    if (excludeTable(table)) {
                        continue;
                    }
                }
            }
            add(right.getCreateSQL(), false);
        }
        // Generate COMMENT ON ...
        for (Comment comment : db.getAllComments()) {
            add(comment.getCreateSQL(), false);
        }
        if (out != null) {
            out.close();
        }
    } catch (IOException e) {
        throw DbException.convertIOException(e, getFileName());
    } finally {
        closeIO();
    }
    result.done();
    LocalResult r = result;
    reset();
    return r;
}
Also used : SchemaObject(org.h2.schema.SchemaObject) User(org.h2.engine.User) Constraint(org.h2.constraint.Constraint) Constant(org.h2.schema.Constant) Schema(org.h2.schema.Schema) Right(org.h2.engine.Right) TriggerObject(org.h2.schema.TriggerObject) Index(org.h2.index.Index) ValueString(org.h2.value.ValueString) LocalResult(org.h2.result.LocalResult) Database(org.h2.engine.Database) Comment(org.h2.engine.Comment) Table(org.h2.table.Table) TableType(org.h2.table.TableType) DbObject(org.h2.engine.DbObject) Setting(org.h2.engine.Setting) UserDataType(org.h2.engine.UserDataType) Sequence(org.h2.schema.Sequence) IOException(java.io.IOException) Constraint(org.h2.constraint.Constraint) Role(org.h2.engine.Role) UserAggregate(org.h2.engine.UserAggregate)

Example 2 with LocalResult

use of org.h2.result.LocalResult in project h2database by h2database.

the class Select method queryWithoutCache.

@Override
protected ResultInterface queryWithoutCache(int maxRows, ResultTarget target) {
    int limitRows = maxRows == 0 ? -1 : maxRows;
    if (limitExpr != null) {
        Value v = limitExpr.getValue(session);
        int l = v == ValueNull.INSTANCE ? -1 : v.getInt();
        if (limitRows < 0) {
            limitRows = l;
        } else if (l >= 0) {
            limitRows = Math.min(l, limitRows);
        }
    }
    boolean lazy = session.isLazyQueryExecution() && target == null && !isForUpdate && !isQuickAggregateQuery && limitRows != 0 && offsetExpr == null && isReadOnly();
    int columnCount = expressions.size();
    LocalResult result = null;
    if (!lazy && (target == null || !session.getDatabase().getSettings().optimizeInsertFromSelect)) {
        result = createLocalResult(result);
    }
    if (sort != null && (!sortUsingIndex || distinct)) {
        result = createLocalResult(result);
        result.setSortOrder(sort);
    }
    if (distinct && !isDistinctQuery) {
        result = createLocalResult(result);
        result.setDistinct();
    }
    if (randomAccessResult) {
        result = createLocalResult(result);
    }
    if (isGroupQuery && !isGroupSortedQuery) {
        result = createLocalResult(result);
    }
    if (!lazy && (limitRows >= 0 || offsetExpr != null)) {
        result = createLocalResult(result);
    }
    topTableFilter.startQuery(session);
    topTableFilter.reset();
    boolean exclusive = isForUpdate && !isForUpdateMvcc;
    if (isForUpdateMvcc) {
        if (isGroupQuery) {
            throw DbException.getUnsupportedException("MVCC=TRUE && FOR UPDATE && GROUP");
        } else if (distinct) {
            throw DbException.getUnsupportedException("MVCC=TRUE && FOR UPDATE && DISTINCT");
        } else if (isQuickAggregateQuery) {
            throw DbException.getUnsupportedException("MVCC=TRUE && FOR UPDATE && AGGREGATE");
        } else if (topTableFilter.getJoin() != null) {
            throw DbException.getUnsupportedException("MVCC=TRUE && FOR UPDATE && JOIN");
        }
    }
    topTableFilter.lock(session, exclusive, exclusive);
    ResultTarget to = result != null ? result : target;
    lazy &= to == null;
    LazyResult lazyResult = null;
    if (limitRows != 0) {
        try {
            if (isQuickAggregateQuery) {
                queryQuick(columnCount, to);
            } else if (isGroupQuery) {
                if (isGroupSortedQuery) {
                    lazyResult = queryGroupSorted(columnCount, to);
                } else {
                    queryGroup(columnCount, result);
                }
            } else if (isDistinctQuery) {
                queryDistinct(to, limitRows);
            } else {
                lazyResult = queryFlat(columnCount, to, limitRows);
            }
        } finally {
            if (!lazy) {
                resetJoinBatchAfterQuery();
            }
        }
    }
    assert lazy == (lazyResult != null) : lazy;
    if (lazyResult != null) {
        if (limitRows > 0) {
            lazyResult.setLimit(limitRows);
        }
        return lazyResult;
    }
    if (offsetExpr != null) {
        result.setOffset(offsetExpr.getValue(session).getInt());
    }
    if (limitRows >= 0) {
        result.setLimit(limitRows);
    }
    if (result != null) {
        result.done();
        if (target != null) {
            while (result.next()) {
                target.addRow(result.currentRow());
            }
            result.close();
            return null;
        }
        return result;
    }
    return null;
}
Also used : Value(org.h2.value.Value)

Example 3 with LocalResult

use of org.h2.result.LocalResult in project h2database by h2database.

the class Explain method query.

@Override
public ResultInterface query(int maxrows) {
    Column column = new Column("PLAN", Value.STRING);
    Database db = session.getDatabase();
    ExpressionColumn expr = new ExpressionColumn(db, column);
    Expression[] expressions = { expr };
    result = new LocalResult(session, expressions, 1);
    if (maxrows >= 0) {
        String plan;
        if (executeCommand) {
            PageStore store = null;
            Store mvStore = null;
            if (db.isPersistent()) {
                store = db.getPageStore();
                if (store != null) {
                    store.statisticsStart();
                }
                mvStore = db.getMvStore();
                if (mvStore != null) {
                    mvStore.statisticsStart();
                }
            }
            if (command.isQuery()) {
                command.query(maxrows);
            } else {
                command.update();
            }
            plan = command.getPlanSQL();
            Map<String, Integer> statistics = null;
            if (store != null) {
                statistics = store.statisticsEnd();
            } else if (mvStore != null) {
                statistics = mvStore.statisticsEnd();
            }
            if (statistics != null) {
                int total = 0;
                for (Entry<String, Integer> e : statistics.entrySet()) {
                    total += e.getValue();
                }
                if (total > 0) {
                    statistics = new TreeMap<>(statistics);
                    StringBuilder buff = new StringBuilder();
                    if (statistics.size() > 1) {
                        buff.append("total: ").append(total).append('\n');
                    }
                    for (Entry<String, Integer> e : statistics.entrySet()) {
                        int value = e.getValue();
                        int percent = (int) (100L * value / total);
                        buff.append(e.getKey()).append(": ").append(value);
                        if (statistics.size() > 1) {
                            buff.append(" (").append(percent).append("%)");
                        }
                        buff.append('\n');
                    }
                    plan += "\n/*\n" + buff.toString() + "*/";
                }
            }
        } else {
            plan = command.getPlanSQL();
        }
        add(plan);
    }
    result.done();
    return result;
}
Also used : Store(org.h2.mvstore.db.MVTableEngine.Store) PageStore(org.h2.store.PageStore) PageStore(org.h2.store.PageStore) ValueString(org.h2.value.ValueString) ExpressionColumn(org.h2.expression.ExpressionColumn) LocalResult(org.h2.result.LocalResult) ExpressionColumn(org.h2.expression.ExpressionColumn) Column(org.h2.table.Column) Expression(org.h2.expression.Expression) Database(org.h2.engine.Database)

Example 4 with LocalResult

use of org.h2.result.LocalResult in project h2database by h2database.

the class Call method queryMeta.

@Override
public ResultInterface queryMeta() {
    LocalResult result;
    if (isResultSet) {
        Expression[] expr = expression.getExpressionColumns(session);
        result = new LocalResult(session, expr, expr.length);
    } else {
        result = new LocalResult(session, expressions, 1);
    }
    result.done();
    return result;
}
Also used : LocalResult(org.h2.result.LocalResult) Expression(org.h2.expression.Expression)

Example 5 with LocalResult

use of org.h2.result.LocalResult in project h2database by h2database.

the class GeneratedKeys method getKeys.

/**
 * Returns generated keys.
 *
 * @param session
 *            session
 * @return local result with generated keys
 */
public LocalResult getKeys(Session session) {
    Database db = session == null ? null : session.getDatabase();
    if (Boolean.FALSE.equals(generatedKeysRequest)) {
        clear(null);
        return new LocalResult();
    }
    ArrayList<ExpressionColumn> expressionColumns;
    if (Boolean.TRUE.equals(generatedKeysRequest)) {
        expressionColumns = new ArrayList<>(allColumns.size());
        for (Column column : allColumns) {
            expressionColumns.add(new ExpressionColumn(db, column));
        }
    } else if (generatedKeysRequest instanceof int[]) {
        if (table != null) {
            int[] indices = (int[]) generatedKeysRequest;
            Column[] columns = table.getColumns();
            int cnt = columns.length;
            allColumns.clear();
            expressionColumns = new ArrayList<>(indices.length);
            for (int idx : indices) {
                if (idx >= 1 && idx <= cnt) {
                    Column column = columns[idx - 1];
                    expressionColumns.add(new ExpressionColumn(db, column));
                    allColumns.add(column);
                }
            }
        } else {
            clear(null);
            return new LocalResult();
        }
    } else if (generatedKeysRequest instanceof String[]) {
        if (table != null) {
            String[] names = (String[]) generatedKeysRequest;
            allColumns.clear();
            expressionColumns = new ArrayList<>(names.length);
            for (String name : names) {
                Column column;
                search: if (table.doesColumnExist(name)) {
                    column = table.getColumn(name);
                } else {
                    name = StringUtils.toUpperEnglish(name);
                    if (table.doesColumnExist(name)) {
                        column = table.getColumn(name);
                    } else {
                        for (Column c : table.getColumns()) {
                            if (c.getName().equalsIgnoreCase(name)) {
                                column = c;
                                break search;
                            }
                        }
                        continue;
                    }
                }
                expressionColumns.add(new ExpressionColumn(db, column));
                allColumns.add(column);
            }
        } else {
            clear(null);
            return new LocalResult();
        }
    } else {
        clear(null);
        return new LocalResult();
    }
    int columnCount = expressionColumns.size();
    if (columnCount == 0) {
        clear(null);
        return new LocalResult();
    }
    LocalResult result = new LocalResult(session, expressionColumns.toArray(new Expression[0]), columnCount);
    for (Map<Column, Value> map : data) {
        Value[] row = new Value[columnCount];
        for (Map.Entry<Column, Value> entry : map.entrySet()) {
            int idx = allColumns.indexOf(entry.getKey());
            if (idx >= 0) {
                row[idx] = entry.getValue();
            }
        }
        for (int i = 0; i < columnCount; i++) {
            if (row[i] == null) {
                row[i] = ValueNull.INSTANCE;
            }
        }
        result.addRow(row);
    }
    clear(null);
    return result;
}
Also used : ArrayList(java.util.ArrayList) ExpressionColumn(org.h2.expression.ExpressionColumn) LocalResult(org.h2.result.LocalResult) ExpressionColumn(org.h2.expression.ExpressionColumn) Column(org.h2.table.Column) Expression(org.h2.expression.Expression) Value(org.h2.value.Value) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

LocalResult (org.h2.result.LocalResult)11 Value (org.h2.value.Value)7 Database (org.h2.engine.Database)3 Expression (org.h2.expression.Expression)3 Column (org.h2.table.Column)3 HashMap (java.util.HashMap)2 ExpressionColumn (org.h2.expression.ExpressionColumn)2 ResultInterface (org.h2.result.ResultInterface)2 ValueArray (org.h2.value.ValueArray)2 ValueString (org.h2.value.ValueString)2 IOException (java.io.IOException)1 ResultSet (java.sql.ResultSet)1 ArrayList (java.util.ArrayList)1 Map (java.util.Map)1 Parser (org.h2.command.Parser)1 Query (org.h2.command.dml.Query)1 SelectUnion (org.h2.command.dml.SelectUnion)1 Constraint (org.h2.constraint.Constraint)1 Comment (org.h2.engine.Comment)1 DbObject (org.h2.engine.DbObject)1