Search in sources :

Example 1 with User

use of org.h2.engine.User 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 User

use of org.h2.engine.User in project h2database by h2database.

the class Parser method parseAlterUser.

private AlterUser parseAlterUser() {
    String userName = readUniqueIdentifier();
    if (readIf("SET")) {
        AlterUser command = new AlterUser(session);
        command.setType(CommandInterface.ALTER_USER_SET_PASSWORD);
        command.setUser(database.getUser(userName));
        if (readIf("PASSWORD")) {
            command.setPassword(readExpression());
        } else if (readIf("SALT")) {
            command.setSalt(readExpression());
            read("HASH");
            command.setHash(readExpression());
        } else {
            throw getSyntaxError();
        }
        return command;
    } else if (readIf("RENAME")) {
        read("TO");
        AlterUser command = new AlterUser(session);
        command.setType(CommandInterface.ALTER_USER_RENAME);
        command.setUser(database.getUser(userName));
        String newName = readUniqueIdentifier();
        command.setNewName(newName);
        return command;
    } else if (readIf("ADMIN")) {
        AlterUser command = new AlterUser(session);
        command.setType(CommandInterface.ALTER_USER_ADMIN);
        User user = database.getUser(userName);
        command.setUser(user);
        if (readIf("TRUE")) {
            command.setAdmin(true);
        } else if (readIf("FALSE")) {
            command.setAdmin(false);
        } else {
            throw getSyntaxError();
        }
        return command;
    }
    throw getSyntaxError();
}
Also used : AlterUser(org.h2.command.ddl.AlterUser) User(org.h2.engine.User) DropUser(org.h2.command.ddl.DropUser) CreateUser(org.h2.command.ddl.CreateUser) ValueString(org.h2.value.ValueString) AlterUser(org.h2.command.ddl.AlterUser)

Example 3 with User

use of org.h2.engine.User 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 4 with User

use of org.h2.engine.User in project h2database by h2database.

the class Parser method readTerm.

private Expression readTerm() {
    Expression r;
    switch(currentTokenType) {
        case AT:
            read();
            r = new Variable(session, readAliasIdentifier());
            if (readIf(":=")) {
                Expression value = readExpression();
                Function function = Function.getFunction(database, "SET");
                function.setParameter(0, r);
                function.setParameter(1, value);
                r = function;
            }
            break;
        case PARAMETER:
            r = readParameter();
            break;
        case KEYWORD:
            if (isToken("SELECT") || isToken("FROM") || isToken("WITH")) {
                Query query = parseSelect();
                r = new Subquery(query);
            } else {
                throw getSyntaxError();
            }
            break;
        case IDENTIFIER:
            String name = currentToken;
            if (currentTokenQuoted) {
                read();
                if (readIf("(")) {
                    r = readFunction(null, name);
                } else if (readIf(".")) {
                    r = readTermObjectDot(name);
                } else {
                    r = new ExpressionColumn(database, null, null, name);
                }
            } else {
                read();
                if (readIf(".")) {
                    r = readTermObjectDot(name);
                } else if (equalsToken("CASE", name)) {
                    // CASE must be processed before (,
                    // otherwise CASE(3) would be a function call, which it is
                    // not
                    r = readCase();
                } else if (readIf("(")) {
                    r = readFunction(null, name);
                } else if (equalsToken("CURRENT_USER", name)) {
                    r = readFunctionWithoutParameters("USER");
                } else if (equalsToken("CURRENT_TIMESTAMP", name)) {
                    r = readFunctionWithoutParameters("CURRENT_TIMESTAMP");
                } else if (equalsToken("SYSDATE", name)) {
                    r = readFunctionWithoutParameters("CURRENT_TIMESTAMP");
                } else if (equalsToken("SYSTIMESTAMP", name)) {
                    r = readFunctionWithoutParameters("CURRENT_TIMESTAMP");
                } else if (equalsToken("CURRENT_DATE", name)) {
                    r = readFunctionWithoutParameters("CURRENT_DATE");
                } else if (equalsToken("TODAY", name)) {
                    r = readFunctionWithoutParameters("CURRENT_DATE");
                } else if (equalsToken("CURRENT_TIME", name)) {
                    r = readFunctionWithoutParameters("CURRENT_TIME");
                } else if (equalsToken("SYSTIME", name)) {
                    r = readFunctionWithoutParameters("CURRENT_TIME");
                } else if (equalsToken("CURRENT", name)) {
                    if (readIf("TIMESTAMP")) {
                        r = readFunctionWithoutParameters("CURRENT_TIMESTAMP");
                    } else if (readIf("TIME")) {
                        r = readFunctionWithoutParameters("CURRENT_TIME");
                    } else if (readIf("DATE")) {
                        r = readFunctionWithoutParameters("CURRENT_DATE");
                    } else {
                        r = new ExpressionColumn(database, null, null, name);
                    }
                } else if (equalsToken("NEXT", name) && readIf("VALUE")) {
                    read("FOR");
                    Sequence sequence = readSequence();
                    r = new SequenceValue(sequence);
                } else if (equalsToken("TIME", name)) {
                    boolean without = readIf("WITHOUT");
                    if (without) {
                        read("TIME");
                        read("ZONE");
                    }
                    if (currentTokenType != VALUE || currentValue.getType() != Value.STRING) {
                        if (without) {
                            throw getSyntaxError();
                        }
                        r = new ExpressionColumn(database, null, null, name);
                    } else {
                        String time = currentValue.getString();
                        read();
                        r = ValueExpression.get(ValueTime.parse(time));
                    }
                } else if (equalsToken("TIMESTAMP", name)) {
                    if (readIf("WITH")) {
                        read("TIME");
                        read("ZONE");
                        if (currentTokenType != VALUE || currentValue.getType() != Value.STRING) {
                            throw getSyntaxError();
                        }
                        String timestamp = currentValue.getString();
                        read();
                        r = ValueExpression.get(ValueTimestampTimeZone.parse(timestamp));
                    } else {
                        boolean without = readIf("WITHOUT");
                        if (without) {
                            read("TIME");
                            read("ZONE");
                        }
                        if (currentTokenType != VALUE || currentValue.getType() != Value.STRING) {
                            if (without) {
                                throw getSyntaxError();
                            }
                            r = new ExpressionColumn(database, null, null, name);
                        } else {
                            String timestamp = currentValue.getString();
                            read();
                            r = ValueExpression.get(ValueTimestamp.parse(timestamp, database.getMode()));
                        }
                    }
                } else if (currentTokenType == VALUE && currentValue.getType() == Value.STRING) {
                    if (equalsToken("DATE", name) || equalsToken("D", name)) {
                        String date = currentValue.getString();
                        read();
                        r = ValueExpression.get(ValueDate.parse(date));
                    } else if (equalsToken("T", name)) {
                        String time = currentValue.getString();
                        read();
                        r = ValueExpression.get(ValueTime.parse(time));
                    } else if (equalsToken("TS", name)) {
                        String timestamp = currentValue.getString();
                        read();
                        r = ValueExpression.get(ValueTimestamp.parse(timestamp, database.getMode()));
                    } else if (equalsToken("X", name)) {
                        read();
                        byte[] buffer = StringUtils.convertHexToBytes(currentValue.getString());
                        r = ValueExpression.get(ValueBytes.getNoCopy(buffer));
                    } else if (equalsToken("E", name)) {
                        String text = currentValue.getString();
                        // the PostgreSQL ODBC driver uses
                        // LIKE E'PROJECT\\_DATA' instead of LIKE
                        // 'PROJECT\_DATA'
                        // N: SQL-92 "National Language" strings
                        text = StringUtils.replaceAll(text, "\\\\", "\\");
                        read();
                        r = ValueExpression.get(ValueString.get(text));
                    } else if (equalsToken("N", name)) {
                        // SQL-92 "National Language" strings
                        String text = currentValue.getString();
                        read();
                        r = ValueExpression.get(ValueString.get(text));
                    } else {
                        r = new ExpressionColumn(database, null, null, name);
                    }
                } else {
                    r = new ExpressionColumn(database, null, null, name);
                }
            }
            break;
        case MINUS:
            read();
            if (currentTokenType == VALUE) {
                r = ValueExpression.get(currentValue.negate());
                if (r.getType() == Value.LONG && r.getValue(session).getLong() == Integer.MIN_VALUE) {
                    // convert Integer.MIN_VALUE to type 'int'
                    // (Integer.MAX_VALUE+1 is of type 'long')
                    r = ValueExpression.get(ValueInt.get(Integer.MIN_VALUE));
                } else if (r.getType() == Value.DECIMAL && r.getValue(session).getBigDecimal().compareTo(ValueLong.MIN_BD) == 0) {
                    // convert Long.MIN_VALUE to type 'long'
                    // (Long.MAX_VALUE+1 is of type 'decimal')
                    r = ValueExpression.get(ValueLong.MIN);
                }
                read();
            } else {
                r = new Operation(OpType.NEGATE, readTerm(), null);
            }
            break;
        case PLUS:
            read();
            r = readTerm();
            break;
        case OPEN:
            read();
            if (readIf(")")) {
                r = new ExpressionList(new Expression[0]);
            } else {
                r = readExpression();
                if (readIf(",")) {
                    ArrayList<Expression> list = New.arrayList();
                    list.add(r);
                    while (!readIf(")")) {
                        r = readExpression();
                        list.add(r);
                        if (!readIf(",")) {
                            read(")");
                            break;
                        }
                    }
                    r = new ExpressionList(list.toArray(new Expression[0]));
                } else {
                    read(")");
                }
            }
            break;
        case TRUE:
            read();
            r = ValueExpression.get(ValueBoolean.TRUE);
            break;
        case FALSE:
            read();
            r = ValueExpression.get(ValueBoolean.FALSE);
            break;
        case ROWNUM:
            read();
            if (readIf("(")) {
                read(")");
            }
            if (currentSelect == null && currentPrepared == null) {
                throw getSyntaxError();
            }
            r = new Rownum(currentSelect == null ? currentPrepared : currentSelect);
            break;
        case NULL:
            read();
            r = ValueExpression.getNull();
            break;
        case VALUE:
            r = ValueExpression.get(currentValue);
            read();
            break;
        default:
            throw getSyntaxError();
    }
    if (readIf("[")) {
        Function function = Function.getFunction(database, "ARRAY_GET");
        function.setParameter(0, r);
        r = readExpression();
        r = new Operation(OpType.PLUS, r, ValueExpression.get(ValueInt.get(1)));
        function.setParameter(1, r);
        r = function;
        read("]");
    }
    if (readIf("::")) {
        // PostgreSQL compatibility
        if (isToken("PG_CATALOG")) {
            read("PG_CATALOG");
            read(".");
        }
        if (readIf("REGCLASS")) {
            FunctionAlias f = findFunctionAlias(Constants.SCHEMA_MAIN, "PG_GET_OID");
            if (f == null) {
                throw getSyntaxError();
            }
            Expression[] args = { r };
            r = new JavaFunction(f, args);
        } else {
            Column col = parseColumnWithType(null);
            Function function = Function.getFunction(database, "CAST");
            function.setDataType(col);
            function.setParameter(0, r);
            r = function;
        }
    }
    return r;
}
Also used : Variable(org.h2.expression.Variable) Query(org.h2.command.dml.Query) CreateFunctionAlias(org.h2.command.ddl.CreateFunctionAlias) FunctionAlias(org.h2.engine.FunctionAlias) DropFunctionAlias(org.h2.command.ddl.DropFunctionAlias) JavaFunction(org.h2.expression.JavaFunction) ValueString(org.h2.value.ValueString) DropSequence(org.h2.command.ddl.DropSequence) CreateSequence(org.h2.command.ddl.CreateSequence) Sequence(org.h2.schema.Sequence) AlterSequence(org.h2.command.dml.AlterSequence) Operation(org.h2.expression.Operation) NoOperation(org.h2.command.dml.NoOperation) Subquery(org.h2.expression.Subquery) Rownum(org.h2.expression.Rownum) ExpressionColumn(org.h2.expression.ExpressionColumn) Function(org.h2.expression.Function) TableFunction(org.h2.expression.TableFunction) JavaFunction(org.h2.expression.JavaFunction) SequenceValue(org.h2.expression.SequenceValue) Expression(org.h2.expression.Expression) ValueExpression(org.h2.expression.ValueExpression) AlterTableRenameColumn(org.h2.command.ddl.AlterTableRenameColumn) AlterTableAlterColumn(org.h2.command.ddl.AlterTableAlterColumn) Column(org.h2.table.Column) ExpressionColumn(org.h2.expression.ExpressionColumn) IndexColumn(org.h2.table.IndexColumn) ExpressionList(org.h2.expression.ExpressionList)

Example 5 with User

use of org.h2.engine.User in project h2database by h2database.

the class Parser method parseSingleCommonTableExpression.

private TableView parseSingleCommonTableExpression(boolean isPersistent) {
    String cteViewName = readIdentifierWithSchema();
    Schema schema = getSchema();
    Table recursiveTable = null;
    ArrayList<Column> columns = New.arrayList();
    String[] cols = null;
    // query, if not supplied by user
    if (readIf("(")) {
        cols = parseColumnList();
        for (String c : cols) {
            // we don't really know the type of the column, so STRING will
            // have to do, UNKNOWN does not work here
            columns.add(new Column(c, Value.STRING));
        }
    }
    Table oldViewFound = null;
    if (isPersistent) {
        oldViewFound = getSchema().findTableOrView(session, cteViewName);
    } else {
        oldViewFound = session.findLocalTempTable(cteViewName);
    }
    // this persistent check conflicts with check 10 lines down
    if (oldViewFound != null) {
        if (!(oldViewFound instanceof TableView)) {
            throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, cteViewName);
        }
        TableView tv = (TableView) oldViewFound;
        if (!tv.isTableExpression()) {
            throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, cteViewName);
        }
        if (isPersistent) {
            oldViewFound.lock(session, true, true);
            database.removeSchemaObject(session, oldViewFound);
        } else {
            session.removeLocalTempTable(oldViewFound);
        }
        oldViewFound = null;
    }
    /*
         * This table is created as a workaround because recursive table
         * expressions need to reference something that look like themselves to
         * work (its removed after creation in this method). Only create table
         * data and table if we don't have a working CTE already.
         */
    recursiveTable = TableView.createShadowTableForRecursiveTableExpression(isPersistent, session, cteViewName, schema, columns, database);
    List<Column> columnTemplateList;
    String[] querySQLOutput = { null };
    try {
        read("AS");
        read("(");
        Query withQuery = parseSelect();
        if (isPersistent) {
            withQuery.session = session;
        }
        read(")");
        columnTemplateList = TableView.createQueryColumnTemplateList(cols, withQuery, querySQLOutput);
    } finally {
        TableView.destroyShadowTableForRecursiveExpression(isPersistent, session, recursiveTable);
    }
    return createCTEView(cteViewName, querySQLOutput[0], columnTemplateList, true, /* allowRecursiveQueryDetection */
    true, /* add to session */
    isPersistent, session);
}
Also used : RangeTable(org.h2.table.RangeTable) TruncateTable(org.h2.command.ddl.TruncateTable) CreateTable(org.h2.command.ddl.CreateTable) FunctionTable(org.h2.table.FunctionTable) CreateLinkedTable(org.h2.command.ddl.CreateLinkedTable) Table(org.h2.table.Table) DropTable(org.h2.command.ddl.DropTable) Query(org.h2.command.dml.Query) AlterTableRenameColumn(org.h2.command.ddl.AlterTableRenameColumn) AlterTableAlterColumn(org.h2.command.ddl.AlterTableAlterColumn) Column(org.h2.table.Column) ExpressionColumn(org.h2.expression.ExpressionColumn) IndexColumn(org.h2.table.IndexColumn) DropSchema(org.h2.command.ddl.DropSchema) CreateSchema(org.h2.command.ddl.CreateSchema) Schema(org.h2.schema.Schema) ValueString(org.h2.value.ValueString) TableView(org.h2.table.TableView)

Aggregations

Connection (java.sql.Connection)36 SQLException (java.sql.SQLException)21 PreparedStatement (java.sql.PreparedStatement)17 Statement (java.sql.Statement)17 ResultSet (java.sql.ResultSet)16 Server (org.h2.tools.Server)15 DbException (org.h2.message.DbException)14 Column (org.h2.table.Column)12 ValueString (org.h2.value.ValueString)12 Properties (java.util.Properties)10 Database (org.h2.engine.Database)10 Schema (org.h2.schema.Schema)8 IOException (java.io.IOException)7 User (org.h2.engine.User)7 JdbcDataSource (org.h2.jdbcx.JdbcDataSource)7 SimpleResultSet (org.h2.tools.SimpleResultSet)7 Value (org.h2.value.Value)7 PrintStream (java.io.PrintStream)6 Timestamp (java.sql.Timestamp)6 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)6