Search in sources :

Example 1 with Alias

use of org.h2.expression.Alias in project ignite by apache.

the class DmlAstUtils method selectForUpdate.

/**
     * Generate SQL SELECT based on UPDATE's WHERE, LIMIT, etc.
     *
     * @param update Update statement.
     * @param keysParamIdx Index of new param for the array of keys.
     * @return SELECT statement.
     */
public static GridSqlSelect selectForUpdate(GridSqlUpdate update, @Nullable Integer keysParamIdx) {
    GridSqlSelect mapQry = new GridSqlSelect();
    mapQry.from(update.target());
    Set<GridSqlTable> tbls = new HashSet<>();
    collectAllGridTablesInTarget(update.target(), tbls);
    assert tbls.size() == 1 : "Failed to determine target table for UPDATE";
    GridSqlTable tbl = tbls.iterator().next();
    GridH2Table gridTbl = tbl.dataTable();
    assert gridTbl != null : "Failed to determine target grid table for UPDATE";
    Column h2KeyCol = gridTbl.getColumn(GridH2AbstractKeyValueRow.KEY_COL);
    Column h2ValCol = gridTbl.getColumn(GridH2AbstractKeyValueRow.VAL_COL);
    GridSqlColumn keyCol = new GridSqlColumn(h2KeyCol, tbl, h2KeyCol.getName());
    keyCol.resultType(GridSqlType.fromColumn(h2KeyCol));
    GridSqlColumn valCol = new GridSqlColumn(h2ValCol, tbl, h2ValCol.getName());
    valCol.resultType(GridSqlType.fromColumn(h2ValCol));
    mapQry.addColumn(keyCol, true);
    mapQry.addColumn(valCol, true);
    for (GridSqlColumn c : update.cols()) {
        String newColName = Parser.quoteIdentifier("_upd_" + c.columnName());
        // We have to use aliases to cover cases when the user
        // wants to update _val field directly (if it's a literal)
        GridSqlAlias alias = new GridSqlAlias(newColName, elementOrDefault(update.set().get(c.columnName()), c), true);
        alias.resultType(c.resultType());
        mapQry.addColumn(alias, true);
    }
    GridSqlElement where = update.where();
    if (keysParamIdx != null)
        where = injectKeysFilterParam(where, keyCol, keysParamIdx);
    mapQry.where(where);
    mapQry.limit(update.limit());
    return mapQry;
}
Also used : Column(org.h2.table.Column) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) ValueString(org.h2.value.ValueString) HashSet(java.util.HashSet)

Example 2 with Alias

use of org.h2.expression.Alias in project h2database by h2database.

the class Parser method parseCreate.

private Prepared parseCreate() {
    boolean orReplace = false;
    if (readIf("OR")) {
        read("REPLACE");
        orReplace = true;
    }
    boolean force = readIf("FORCE");
    if (readIf("VIEW")) {
        return parseCreateView(force, orReplace);
    } else if (readIf("ALIAS")) {
        return parseCreateFunctionAlias(force);
    } else if (readIf("SEQUENCE")) {
        return parseCreateSequence();
    } else if (readIf("USER")) {
        return parseCreateUser();
    } else if (readIf("TRIGGER")) {
        return parseCreateTrigger(force);
    } else if (readIf("ROLE")) {
        return parseCreateRole();
    } else if (readIf("SCHEMA")) {
        return parseCreateSchema();
    } else if (readIf("CONSTANT")) {
        return parseCreateConstant();
    } else if (readIf("DOMAIN")) {
        return parseCreateUserDataType();
    } else if (readIf("TYPE")) {
        return parseCreateUserDataType();
    } else if (readIf("DATATYPE")) {
        return parseCreateUserDataType();
    } else if (readIf("AGGREGATE")) {
        return parseCreateAggregate(force);
    } else if (readIf("LINKED")) {
        return parseCreateLinkedTable(false, false, force);
    }
    // tables or linked tables
    boolean memory = false, cached = false;
    if (readIf("MEMORY")) {
        memory = true;
    } else if (readIf("CACHED")) {
        cached = true;
    }
    if (readIf("LOCAL")) {
        read("TEMPORARY");
        if (readIf("LINKED")) {
            return parseCreateLinkedTable(true, false, force);
        }
        read("TABLE");
        return parseCreateTable(true, false, cached);
    } else if (readIf("GLOBAL")) {
        read("TEMPORARY");
        if (readIf("LINKED")) {
            return parseCreateLinkedTable(true, true, force);
        }
        read("TABLE");
        return parseCreateTable(true, true, cached);
    } else if (readIf("TEMP") || readIf("TEMPORARY")) {
        if (readIf("LINKED")) {
            return parseCreateLinkedTable(true, true, force);
        }
        read("TABLE");
        return parseCreateTable(true, true, cached);
    } else if (readIf("TABLE")) {
        if (!cached && !memory) {
            cached = database.getDefaultTableType() == Table.TYPE_CACHED;
        }
        return parseCreateTable(false, false, cached);
    } else if (readIf("SYNONYM")) {
        return parseCreateSynonym(orReplace);
    } else {
        boolean hash = false, primaryKey = false;
        boolean unique = false, spatial = false;
        String indexName = null;
        Schema oldSchema = null;
        boolean ifNotExists = false;
        if (readIf("PRIMARY")) {
            read("KEY");
            if (readIf("HASH")) {
                hash = true;
            }
            primaryKey = true;
            if (!isToken("ON")) {
                ifNotExists = readIfNotExists();
                indexName = readIdentifierWithSchema(null);
                oldSchema = getSchema();
            }
        } else {
            if (readIf("UNIQUE")) {
                unique = true;
            }
            if (readIf("HASH")) {
                hash = true;
            }
            if (readIf("SPATIAL")) {
                spatial = true;
            }
            if (readIf("INDEX")) {
                if (!isToken("ON")) {
                    ifNotExists = readIfNotExists();
                    indexName = readIdentifierWithSchema(null);
                    oldSchema = getSchema();
                }
            } else {
                throw getSyntaxError();
            }
        }
        read("ON");
        String tableName = readIdentifierWithSchema();
        checkSchema(oldSchema);
        CreateIndex command = new CreateIndex(session, getSchema());
        command.setIfNotExists(ifNotExists);
        command.setPrimaryKey(primaryKey);
        command.setTableName(tableName);
        command.setUnique(unique);
        command.setIndexName(indexName);
        command.setComment(readCommentIf());
        read("(");
        command.setIndexColumns(parseIndexColumnList());
        if (readIf("USING")) {
            if (hash) {
                throw getSyntaxError();
            }
            if (spatial) {
                throw getSyntaxError();
            }
            if (readIf("BTREE")) {
            // default
            } else if (readIf("RTREE")) {
                spatial = true;
            } else if (readIf("HASH")) {
                hash = true;
            } else {
                throw getSyntaxError();
            }
        }
        command.setHash(hash);
        command.setSpatial(spatial);
        return command;
    }
}
Also used : CreateIndex(org.h2.command.ddl.CreateIndex) DropSchema(org.h2.command.ddl.DropSchema) CreateSchema(org.h2.command.ddl.CreateSchema) Schema(org.h2.schema.Schema) ValueString(org.h2.value.ValueString)

Example 3 with Alias

use of org.h2.expression.Alias 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 4 with Alias

use of org.h2.expression.Alias in project h2database by h2database.

the class ScriptCommand method writeLobStream.

private int writeLobStream(Value v) throws IOException {
    if (!tempLobTableCreated) {
        add("CREATE TABLE IF NOT EXISTS SYSTEM_LOB_STREAM" + "(ID INT NOT NULL, PART INT NOT NULL, " + "CDATA VARCHAR, BDATA BINARY)", true);
        add("CREATE PRIMARY KEY SYSTEM_LOB_STREAM_PRIMARY_KEY " + "ON SYSTEM_LOB_STREAM(ID, PART)", true);
        add("CREATE ALIAS IF NOT EXISTS " + "SYSTEM_COMBINE_CLOB FOR \"" + this.getClass().getName() + ".combineClob\"", true);
        add("CREATE ALIAS IF NOT EXISTS " + "SYSTEM_COMBINE_BLOB FOR \"" + this.getClass().getName() + ".combineBlob\"", true);
        tempLobTableCreated = true;
    }
    int id = nextLobId++;
    switch(v.getType()) {
        case Value.BLOB:
            {
                byte[] bytes = new byte[lobBlockSize];
                try (InputStream input = v.getInputStream()) {
                    for (int i = 0; ; i++) {
                        StringBuilder buff = new StringBuilder(lobBlockSize * 2);
                        buff.append("INSERT INTO SYSTEM_LOB_STREAM VALUES(").append(id).append(", ").append(i).append(", NULL, '");
                        int len = IOUtils.readFully(input, bytes, lobBlockSize);
                        if (len <= 0) {
                            break;
                        }
                        buff.append(StringUtils.convertBytesToHex(bytes, len)).append("')");
                        String sql = buff.toString();
                        add(sql, true);
                    }
                }
                break;
            }
        case Value.CLOB:
            {
                char[] chars = new char[lobBlockSize];
                try (Reader reader = v.getReader()) {
                    for (int i = 0; ; i++) {
                        StringBuilder buff = new StringBuilder(lobBlockSize * 2);
                        buff.append("INSERT INTO SYSTEM_LOB_STREAM VALUES(").append(id).append(", ").append(i).append(", ");
                        int len = IOUtils.readFully(reader, chars, lobBlockSize);
                        if (len == 0) {
                            break;
                        }
                        buff.append(StringUtils.quoteStringSQL(new String(chars, 0, len))).append(", NULL)");
                        String sql = buff.toString();
                        add(sql, true);
                    }
                }
                break;
            }
        default:
            DbException.throwInternalError("type:" + v.getType());
    }
    return id;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) Reader(java.io.Reader) BufferedReader(java.io.BufferedReader) ValueString(org.h2.value.ValueString) Constraint(org.h2.constraint.Constraint)

Example 5 with Alias

use of org.h2.expression.Alias in project h2database by h2database.

the class Select method prepare.

@Override
public void prepare() {
    if (isPrepared) {
        // sometimes a subquery is prepared twice (CREATE TABLE AS SELECT)
        return;
    }
    if (SysProperties.CHECK && !checkInit) {
        DbException.throwInternalError("not initialized");
    }
    if (orderList != null) {
        sort = prepareOrder(orderList, expressions.size());
        orderList = null;
    }
    ColumnNamer columnNamer = new ColumnNamer(session);
    for (int i = 0; i < expressions.size(); i++) {
        Expression e = expressions.get(i);
        String proposedColumnName = e.getAlias();
        String columnName = columnNamer.getColumnName(e, i, proposedColumnName);
        // if the name changed, create an alias
        if (!columnName.equals(proposedColumnName)) {
            e = new Alias(e, columnName, true);
        }
        expressions.set(i, e.optimize(session));
    }
    if (condition != null) {
        condition = condition.optimize(session);
        for (TableFilter f : filters) {
            // left outer join child on p = pc where c is null;
            if (!f.isJoinOuter() && !f.isJoinOuterIndirect()) {
                condition.createIndexConditions(session, f);
            }
        }
    }
    if (isGroupQuery && groupIndex == null && havingIndex < 0 && filters.size() == 1) {
        if (condition == null) {
            Table t = filters.get(0).getTable();
            ExpressionVisitor optimizable = ExpressionVisitor.getOptimizableVisitor(t);
            isQuickAggregateQuery = isEverything(optimizable);
        }
    }
    cost = preparePlan(session.isParsingCreateView());
    if (distinct && session.getDatabase().getSettings().optimizeDistinct && !isGroupQuery && filters.size() == 1 && expressions.size() == 1 && condition == null) {
        Expression expr = expressions.get(0);
        expr = expr.getNonAliasExpression();
        if (expr instanceof ExpressionColumn) {
            Column column = ((ExpressionColumn) expr).getColumn();
            int selectivity = column.getSelectivity();
            Index columnIndex = topTableFilter.getTable().getIndexForColumn(column, false, true);
            if (columnIndex != null && selectivity != Constants.SELECTIVITY_DEFAULT && selectivity < 20) {
                // the first column must be ascending
                boolean ascending = columnIndex.getIndexColumns()[0].sortType == SortOrder.ASCENDING;
                Index current = topTableFilter.getIndex();
                // if another index is faster
                if (columnIndex.canFindNext() && ascending && (current == null || current.getIndexType().isScan() || columnIndex == current)) {
                    IndexType type = columnIndex.getIndexType();
                    // indexes don't work
                    if (!type.isHash() && (!type.isUnique() || columnIndex.getColumns().length > 1)) {
                        topTableFilter.setIndex(columnIndex);
                        isDistinctQuery = true;
                    }
                }
            }
        }
    }
    if (sort != null && !isQuickAggregateQuery && !isGroupQuery) {
        Index index = getSortIndex();
        Index current = topTableFilter.getIndex();
        if (index != null && current != null) {
            if (current.getIndexType().isScan() || current == index) {
                topTableFilter.setIndex(index);
                if (!topTableFilter.hasInComparisons()) {
                    // in(select ...) and in(1,2,3) may return the key in
                    // another order
                    sortUsingIndex = true;
                }
            } else if (index.getIndexColumns() != null && index.getIndexColumns().length >= current.getIndexColumns().length) {
                IndexColumn[] sortColumns = index.getIndexColumns();
                IndexColumn[] currentColumns = current.getIndexColumns();
                boolean swapIndex = false;
                for (int i = 0; i < currentColumns.length; i++) {
                    if (sortColumns[i].column != currentColumns[i].column) {
                        swapIndex = false;
                        break;
                    }
                    if (sortColumns[i].sortType != currentColumns[i].sortType) {
                        swapIndex = true;
                    }
                }
                if (swapIndex) {
                    topTableFilter.setIndex(index);
                    sortUsingIndex = true;
                }
            }
        }
    }
    if (!isQuickAggregateQuery && isGroupQuery && getGroupByExpressionCount() > 0) {
        Index index = getGroupSortedIndex();
        Index current = topTableFilter.getIndex();
        if (index != null && current != null && (current.getIndexType().isScan() || current == index)) {
            topTableFilter.setIndex(index);
            isGroupSortedQuery = true;
        }
    }
    expressionArray = expressions.toArray(new Expression[0]);
    isPrepared = true;
}
Also used : Index(org.h2.index.Index) IndexType(org.h2.index.IndexType)

Aggregations

ResultSet (java.sql.ResultSet)38 Statement (java.sql.Statement)38 Connection (java.sql.Connection)31 SimpleResultSet (org.h2.tools.SimpleResultSet)31 PreparedStatement (java.sql.PreparedStatement)28 CallableStatement (java.sql.CallableStatement)18 ValueString (org.h2.value.ValueString)17 SQLException (java.sql.SQLException)11 Column (org.h2.table.Column)10 GridSqlColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn)6 Expression (org.h2.expression.Expression)6 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 GridSqlAlias (org.apache.ignite.internal.processors.query.h2.sql.GridSqlAlias)5 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)4 GridSqlElement (org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement)4 GridSqlSelect (org.apache.ignite.internal.processors.query.h2.sql.GridSqlSelect)4 GridSqlTable (org.apache.ignite.internal.processors.query.h2.sql.GridSqlTable)4 Session (org.h2.engine.Session)4 ValueExpression (org.h2.expression.ValueExpression)4