Search in sources :

Example 6 with Replace

use of org.h2.command.dml.Replace in project h2database by h2database.

the class Parser method parsePrepared.

private Prepared parsePrepared() {
    int start = lastParseIndex;
    Prepared c = null;
    String token = currentToken;
    if (token.length() == 0) {
        c = new NoOperation(session);
    } else {
        char first = token.charAt(0);
        switch(first) {
            case '?':
                // read the ? as a parameter
                readTerm();
                // this is an 'out' parameter - set a dummy value
                parameters.get(0).setValue(ValueNull.INSTANCE);
                read("=");
                read("CALL");
                c = parseCall();
                break;
            case '(':
                c = parseSelect();
                break;
            case 'a':
            case 'A':
                if (readIf("ALTER")) {
                    c = parseAlter();
                } else if (readIf("ANALYZE")) {
                    c = parseAnalyze();
                }
                break;
            case 'b':
            case 'B':
                if (readIf("BACKUP")) {
                    c = parseBackup();
                } else if (readIf("BEGIN")) {
                    c = parseBegin();
                }
                break;
            case 'c':
            case 'C':
                if (readIf("COMMIT")) {
                    c = parseCommit();
                } else if (readIf("CREATE")) {
                    c = parseCreate();
                } else if (readIf("CALL")) {
                    c = parseCall();
                } else if (readIf("CHECKPOINT")) {
                    c = parseCheckpoint();
                } else if (readIf("COMMENT")) {
                    c = parseComment();
                }
                break;
            case 'd':
            case 'D':
                if (readIf("DELETE")) {
                    c = parseDelete();
                } else if (readIf("DROP")) {
                    c = parseDrop();
                } else if (readIf("DECLARE")) {
                    // support for DECLARE GLOBAL TEMPORARY TABLE...
                    c = parseCreate();
                } else if (readIf("DEALLOCATE")) {
                    c = parseDeallocate();
                }
                break;
            case 'e':
            case 'E':
                if (readIf("EXPLAIN")) {
                    c = parseExplain();
                } else if (readIf("EXECUTE")) {
                    c = parseExecute();
                }
                break;
            case 'f':
            case 'F':
                if (isToken("FROM")) {
                    c = parseSelect();
                }
                break;
            case 'g':
            case 'G':
                if (readIf("GRANT")) {
                    c = parseGrantRevoke(CommandInterface.GRANT);
                }
                break;
            case 'h':
            case 'H':
                if (readIf("HELP")) {
                    c = parseHelp();
                }
                break;
            case 'i':
            case 'I':
                if (readIf("INSERT")) {
                    c = parseInsert();
                }
                break;
            case 'm':
            case 'M':
                if (readIf("MERGE")) {
                    c = parseMerge();
                }
                break;
            case 'p':
            case 'P':
                if (readIf("PREPARE")) {
                    c = parsePrepare();
                }
                break;
            case 'r':
            case 'R':
                if (readIf("ROLLBACK")) {
                    c = parseRollback();
                } else if (readIf("REVOKE")) {
                    c = parseGrantRevoke(CommandInterface.REVOKE);
                } else if (readIf("RUNSCRIPT")) {
                    c = parseRunScript();
                } else if (readIf("RELEASE")) {
                    c = parseReleaseSavepoint();
                } else if (readIf("REPLACE")) {
                    c = parseReplace();
                }
                break;
            case 's':
            case 'S':
                if (isToken("SELECT")) {
                    c = parseSelect();
                } else if (readIf("SET")) {
                    c = parseSet();
                } else if (readIf("SAVEPOINT")) {
                    c = parseSavepoint();
                } else if (readIf("SCRIPT")) {
                    c = parseScript();
                } else if (readIf("SHUTDOWN")) {
                    c = parseShutdown();
                } else if (readIf("SHOW")) {
                    c = parseShow();
                }
                break;
            case 't':
            case 'T':
                if (readIf("TRUNCATE")) {
                    c = parseTruncate();
                }
                break;
            case 'u':
            case 'U':
                if (readIf("UPDATE")) {
                    c = parseUpdate();
                } else if (readIf("USE")) {
                    c = parseUse();
                }
                break;
            case 'v':
            case 'V':
                if (readIf("VALUES")) {
                    c = parseValues();
                }
                break;
            case 'w':
            case 'W':
                if (readIf("WITH")) {
                    c = parseWithStatementOrQuery();
                }
                break;
            case ';':
                c = new NoOperation(session);
                break;
            default:
                throw getSyntaxError();
        }
        if (indexedParameterList != null) {
            for (int i = 0, size = indexedParameterList.size(); i < size; i++) {
                if (indexedParameterList.get(i) == null) {
                    indexedParameterList.set(i, new Parameter(i));
                }
            }
            parameters = indexedParameterList;
        }
        if (readIf("{")) {
            do {
                int index = (int) readLong() - 1;
                if (index < 0 || index >= parameters.size()) {
                    throw getSyntaxError();
                }
                Parameter p = parameters.get(index);
                if (p == null) {
                    throw getSyntaxError();
                }
                read(":");
                Expression expr = readExpression();
                expr = expr.optimize(session);
                p.setValue(expr.getValue(session));
            } while (readIf(","));
            read("}");
            for (Parameter p : parameters) {
                p.checkSet();
            }
            parameters.clear();
        }
    }
    if (c == null) {
        throw getSyntaxError();
    }
    setSQL(c, null, start);
    return c;
}
Also used : NoOperation(org.h2.command.dml.NoOperation) Expression(org.h2.expression.Expression) ValueExpression(org.h2.expression.ValueExpression) Parameter(org.h2.expression.Parameter) ConditionInParameter(org.h2.expression.ConditionInParameter) ValueString(org.h2.value.ValueString) AlterTableRenameConstraint(org.h2.command.ddl.AlterTableRenameConstraint) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint) AlterTableDropConstraint(org.h2.command.ddl.AlterTableDropConstraint)

Example 7 with Replace

use of org.h2.command.dml.Replace in project h2database by h2database.

the class Parser method parseReplace.

/**
 * MySQL compatibility. REPLACE is similar to MERGE.
 */
private Replace parseReplace() {
    Replace command = new Replace(session);
    currentPrepared = command;
    read("INTO");
    Table table = readTableOrView();
    command.setTable(table);
    if (readIf("(")) {
        if (isSelect()) {
            command.setQuery(parseSelect());
            read(")");
            return command;
        }
        Column[] columns = parseColumnList(table);
        command.setColumns(columns);
    }
    if (readIf("VALUES")) {
        do {
            ArrayList<Expression> values = New.arrayList();
            read("(");
            if (!readIf(")")) {
                do {
                    if (readIf("DEFAULT")) {
                        values.add(null);
                    } else {
                        values.add(readExpression());
                    }
                } while (readIfMore(false));
            }
            command.addRow(values.toArray(new Expression[0]));
        } while (readIf(","));
    } else {
        command.setQuery(parseSelect());
    }
    return command;
}
Also used : Replace(org.h2.command.dml.Replace) 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) 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) Expression(org.h2.expression.Expression) ValueExpression(org.h2.expression.ValueExpression)

Example 8 with Replace

use of org.h2.command.dml.Replace in project h2database by h2database.

the class Replace method update.

@Override
public int update() {
    int count;
    session.getUser().checkRight(table, Right.INSERT);
    session.getUser().checkRight(table, Right.UPDATE);
    setCurrentRowNumber(0);
    if (!list.isEmpty()) {
        count = 0;
        for (int x = 0, size = list.size(); x < size; x++) {
            setCurrentRowNumber(x + 1);
            Expression[] expr = list.get(x);
            Row newRow = table.getTemplateRow();
            for (int i = 0, len = columns.length; i < len; i++) {
                Column c = columns[i];
                int index = c.getColumnId();
                Expression e = expr[i];
                if (e != null) {
                    // e can be null (DEFAULT)
                    try {
                        Value v = c.convert(e.getValue(session));
                        newRow.setValue(index, v);
                    } catch (DbException ex) {
                        throw setRow(ex, count, getSQL(expr));
                    }
                }
            }
            replace(newRow);
            count++;
        }
    } else {
        ResultInterface rows = query.query(0);
        count = 0;
        table.fire(session, Trigger.UPDATE | Trigger.INSERT, true);
        table.lock(session, true, false);
        while (rows.next()) {
            count++;
            Value[] r = rows.currentRow();
            Row newRow = table.getTemplateRow();
            setCurrentRowNumber(count);
            for (int j = 0; j < columns.length; j++) {
                Column c = columns[j];
                int index = c.getColumnId();
                try {
                    Value v = c.convert(r[j]);
                    newRow.setValue(index, v);
                } catch (DbException ex) {
                    throw setRow(ex, count, getSQL(r));
                }
            }
            replace(newRow);
        }
        rows.close();
        table.fire(session, Trigger.UPDATE | Trigger.INSERT, false);
    }
    return count;
}
Also used : ResultInterface(org.h2.result.ResultInterface) Expression(org.h2.expression.Expression) Column(org.h2.table.Column) Value(org.h2.value.Value) Row(org.h2.result.Row) DbException(org.h2.message.DbException)

Example 9 with Replace

use of org.h2.command.dml.Replace in project h2database by h2database.

the class Function method getValueWithArgs.

private Value getValueWithArgs(Session session, Expression[] args) {
    Value[] values = new Value[args.length];
    if (info.nullIfParameterIsNull) {
        for (int i = 0; i < args.length; i++) {
            Expression e = args[i];
            Value v = e.getValue(session);
            if (v == ValueNull.INSTANCE) {
                return ValueNull.INSTANCE;
            }
            values[i] = v;
        }
    }
    Value v0 = getNullOrValue(session, args, values, 0);
    Value resultSimple = getSimpleValue(session, v0, args, values);
    if (resultSimple != null) {
        return resultSimple;
    }
    Value v1 = getNullOrValue(session, args, values, 1);
    Value v2 = getNullOrValue(session, args, values, 2);
    Value v3 = getNullOrValue(session, args, values, 3);
    Value v4 = getNullOrValue(session, args, values, 4);
    Value v5 = getNullOrValue(session, args, values, 5);
    Value result;
    switch(info.type) {
        case ATAN2:
            result = ValueDouble.get(Math.atan2(v0.getDouble(), v1.getDouble()));
            break;
        case BITAND:
            result = ValueLong.get(v0.getLong() & v1.getLong());
            break;
        case BITGET:
            result = ValueBoolean.get((v0.getLong() & (1L << v1.getInt())) != 0);
            break;
        case BITOR:
            result = ValueLong.get(v0.getLong() | v1.getLong());
            break;
        case BITXOR:
            result = ValueLong.get(v0.getLong() ^ v1.getLong());
            break;
        case MOD:
            {
                long x = v1.getLong();
                if (x == 0) {
                    throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
                }
                result = ValueLong.get(v0.getLong() % x);
                break;
            }
        case POWER:
            result = ValueDouble.get(Math.pow(v0.getDouble(), v1.getDouble()));
            break;
        case ROUND:
            {
                double f = v1 == null ? 1. : Math.pow(10., v1.getDouble());
                double middleResult = v0.getDouble() * f;
                int oneWithSymbol = middleResult > 0 ? 1 : -1;
                result = ValueDouble.get(Math.round(Math.abs(middleResult)) / f * oneWithSymbol);
                break;
            }
        case TRUNCATE:
            {
                if (v0.getType() == Value.TIMESTAMP) {
                    result = ValueTimestamp.fromDateValueAndNanos(((ValueTimestamp) v0).getDateValue(), 0);
                } else if (v0.getType() == Value.DATE) {
                    result = ValueTimestamp.fromDateValueAndNanos(((ValueDate) v0).getDateValue(), 0);
                } else if (v0.getType() == Value.TIMESTAMP_TZ) {
                    ValueTimestampTimeZone ts = (ValueTimestampTimeZone) v0;
                    result = ValueTimestampTimeZone.fromDateValueAndNanos(ts.getDateValue(), 0, ts.getTimeZoneOffsetMins());
                } else if (v0.getType() == Value.STRING) {
                    ValueTimestamp ts = ValueTimestamp.parse(v0.getString(), session.getDatabase().getMode());
                    result = ValueTimestamp.fromDateValueAndNanos(ts.getDateValue(), 0);
                } else {
                    double d = v0.getDouble();
                    int p = v1 == null ? 0 : v1.getInt();
                    double f = Math.pow(10., p);
                    double g = d * f;
                    result = ValueDouble.get(((d < 0) ? Math.ceil(g) : Math.floor(g)) / f);
                }
                break;
            }
        case HASH:
            result = ValueBytes.getNoCopy(getHash(v0.getString(), v1.getBytesNoCopy(), v2.getInt()));
            break;
        case ENCRYPT:
            result = ValueBytes.getNoCopy(encrypt(v0.getString(), v1.getBytesNoCopy(), v2.getBytesNoCopy()));
            break;
        case DECRYPT:
            result = ValueBytes.getNoCopy(decrypt(v0.getString(), v1.getBytesNoCopy(), v2.getBytesNoCopy()));
            break;
        case COMPRESS:
            {
                String algorithm = null;
                if (v1 != null) {
                    algorithm = v1.getString();
                }
                result = ValueBytes.getNoCopy(CompressTool.getInstance().compress(v0.getBytesNoCopy(), algorithm));
                break;
            }
        case DIFFERENCE:
            result = ValueInt.get(getDifference(v0.getString(), v1.getString()));
            break;
        case INSERT:
            {
                if (v1 == ValueNull.INSTANCE || v2 == ValueNull.INSTANCE) {
                    result = v1;
                } else {
                    result = ValueString.get(insert(v0.getString(), v1.getInt(), v2.getInt(), v3.getString()), database.getMode().treatEmptyStringsAsNull);
                }
                break;
            }
        case LEFT:
            result = ValueString.get(left(v0.getString(), v1.getInt()), database.getMode().treatEmptyStringsAsNull);
            break;
        case LOCATE:
            {
                int start = v2 == null ? 0 : v2.getInt();
                result = ValueInt.get(locate(v0.getString(), v1.getString(), start));
                break;
            }
        case INSTR:
            {
                int start = v2 == null ? 0 : v2.getInt();
                result = ValueInt.get(locate(v1.getString(), v0.getString(), start));
                break;
            }
        case REPEAT:
            {
                int count = Math.max(0, v1.getInt());
                result = ValueString.get(repeat(v0.getString(), count), database.getMode().treatEmptyStringsAsNull);
                break;
            }
        case REPLACE:
            {
                if (v0 == ValueNull.INSTANCE || v1 == ValueNull.INSTANCE || v2 == ValueNull.INSTANCE && database.getMode().getEnum() != Mode.ModeEnum.Oracle) {
                    result = ValueNull.INSTANCE;
                } else {
                    String s0 = v0.getString();
                    String s1 = v1.getString();
                    String s2 = (v2 == null) ? "" : v2.getString();
                    if (s2 == null) {
                        s2 = "";
                    }
                    result = ValueString.get(StringUtils.replaceAll(s0, s1, s2), database.getMode().treatEmptyStringsAsNull);
                }
                break;
            }
        case RIGHT:
            result = ValueString.get(right(v0.getString(), v1.getInt()), database.getMode().treatEmptyStringsAsNull);
            break;
        case LTRIM:
            result = ValueString.get(StringUtils.trim(v0.getString(), true, false, v1 == null ? " " : v1.getString()), database.getMode().treatEmptyStringsAsNull);
            break;
        case TRIM:
            result = ValueString.get(StringUtils.trim(v0.getString(), true, true, v1 == null ? " " : v1.getString()), database.getMode().treatEmptyStringsAsNull);
            break;
        case RTRIM:
            result = ValueString.get(StringUtils.trim(v0.getString(), false, true, v1 == null ? " " : v1.getString()), database.getMode().treatEmptyStringsAsNull);
            break;
        case SUBSTR:
        case SUBSTRING:
            {
                String s = v0.getString();
                int offset = v1.getInt();
                if (offset < 0) {
                    offset = s.length() + offset + 1;
                }
                int length = v2 == null ? s.length() : v2.getInt();
                result = ValueString.get(substring(s, offset, length), database.getMode().treatEmptyStringsAsNull);
                break;
            }
        case POSITION:
            result = ValueInt.get(locate(v0.getString(), v1.getString(), 0));
            break;
        case XMLATTR:
            result = ValueString.get(StringUtils.xmlAttr(v0.getString(), v1.getString()), database.getMode().treatEmptyStringsAsNull);
            break;
        case XMLNODE:
            {
                String attr = v1 == null ? null : v1 == ValueNull.INSTANCE ? null : v1.getString();
                String content = v2 == null ? null : v2 == ValueNull.INSTANCE ? null : v2.getString();
                boolean indent = v3 == null ? true : v3.getBoolean();
                result = ValueString.get(StringUtils.xmlNode(v0.getString(), attr, content, indent), database.getMode().treatEmptyStringsAsNull);
                break;
            }
        case REGEXP_REPLACE:
            {
                String regexp = v1.getString();
                String replacement = v2.getString();
                if (database.getMode().regexpReplaceBackslashReferences) {
                    if ((replacement.indexOf('\\') >= 0) || (replacement.indexOf('$') >= 0)) {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < replacement.length(); i++) {
                            char c = replacement.charAt(i);
                            if (c == '$') {
                                sb.append('\\');
                            } else if (c == '\\' && ++i < replacement.length()) {
                                c = replacement.charAt(i);
                                sb.append(c >= '0' && c <= '9' ? '$' : '\\');
                            }
                            sb.append(c);
                        }
                        replacement = sb.toString();
                    }
                }
                String regexpMode = v3 == null || v3.getString() == null ? "" : v3.getString();
                int flags = makeRegexpFlags(regexpMode);
                try {
                    result = ValueString.get(Pattern.compile(regexp, flags).matcher(v0.getString()).replaceAll(replacement), database.getMode().treatEmptyStringsAsNull);
                } catch (StringIndexOutOfBoundsException e) {
                    throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, replacement);
                } catch (PatternSyntaxException e) {
                    throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, regexp);
                } catch (IllegalArgumentException e) {
                    throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, replacement);
                }
                break;
            }
        case RPAD:
            result = ValueString.get(StringUtils.pad(v0.getString(), v1.getInt(), v2 == null ? null : v2.getString(), true), database.getMode().treatEmptyStringsAsNull);
            break;
        case LPAD:
            result = ValueString.get(StringUtils.pad(v0.getString(), v1.getInt(), v2 == null ? null : v2.getString(), false), database.getMode().treatEmptyStringsAsNull);
            break;
        case ORA_HASH:
            result = ValueLong.get(oraHash(v0.getString(), v1 == null ? null : v1.getInt(), v2 == null ? null : v2.getInt()));
            break;
        case TO_CHAR:
            switch(v0.getType()) {
                case Value.TIME:
                case Value.DATE:
                case Value.TIMESTAMP:
                case Value.TIMESTAMP_TZ:
                    result = ValueString.get(ToChar.toCharDateTime(v0, v1 == null ? null : v1.getString(), v2 == null ? null : v2.getString()), database.getMode().treatEmptyStringsAsNull);
                    break;
                case Value.SHORT:
                case Value.INT:
                case Value.LONG:
                case Value.DECIMAL:
                case Value.DOUBLE:
                case Value.FLOAT:
                    result = ValueString.get(ToChar.toChar(v0.getBigDecimal(), v1 == null ? null : v1.getString(), v2 == null ? null : v2.getString()), database.getMode().treatEmptyStringsAsNull);
                    break;
                default:
                    result = ValueString.get(v0.getString(), database.getMode().treatEmptyStringsAsNull);
            }
            break;
        case TO_DATE:
            result = ToDateParser.toDate(v0.getString(), v1 == null ? null : v1.getString());
            break;
        case TO_TIMESTAMP:
            result = ToDateParser.toTimestamp(v0.getString(), v1 == null ? null : v1.getString());
            break;
        case ADD_MONTHS:
            result = DateTimeFunctions.dateadd("MONTH", v1.getInt(), v0);
            break;
        case TO_TIMESTAMP_TZ:
            result = ToDateParser.toTimestampTz(v0.getString(), v1 == null ? null : v1.getString());
            break;
        case TRANSLATE:
            {
                String matching = v1.getString();
                String replacement = v2.getString();
                result = ValueString.get(translate(v0.getString(), matching, replacement), database.getMode().treatEmptyStringsAsNull);
                break;
            }
        case H2VERSION:
            result = ValueString.get(Constants.getVersion(), database.getMode().treatEmptyStringsAsNull);
            break;
        case DATE_ADD:
            result = DateTimeFunctions.dateadd(v0.getString(), v1.getLong(), v2);
            break;
        case DATE_DIFF:
            result = ValueLong.get(DateTimeFunctions.datediff(v0.getString(), v1, v2));
            break;
        case DATE_TRUNC:
            result = DateTimeFunctions.truncateDate(v0.getString(), v1);
            break;
        case EXTRACT:
            result = DateTimeFunctions.extract(v0.getString(), v1);
            break;
        case FORMATDATETIME:
            {
                if (v0 == ValueNull.INSTANCE || v1 == ValueNull.INSTANCE) {
                    result = ValueNull.INSTANCE;
                } else {
                    String locale = v2 == null ? null : v2 == ValueNull.INSTANCE ? null : v2.getString();
                    String tz = v3 == null ? null : v3 == ValueNull.INSTANCE ? null : v3.getString();
                    if (v0 instanceof ValueTimestampTimeZone) {
                        tz = DateTimeUtils.timeZoneNameFromOffsetMins(((ValueTimestampTimeZone) v0).getTimeZoneOffsetMins());
                    }
                    result = ValueString.get(DateTimeFunctions.formatDateTime(v0.getTimestamp(), v1.getString(), locale, tz), database.getMode().treatEmptyStringsAsNull);
                }
                break;
            }
        case PARSEDATETIME:
            {
                if (v0 == ValueNull.INSTANCE || v1 == ValueNull.INSTANCE) {
                    result = ValueNull.INSTANCE;
                } else {
                    String locale = v2 == null ? null : v2 == ValueNull.INSTANCE ? null : v2.getString();
                    String tz = v3 == null ? null : v3 == ValueNull.INSTANCE ? null : v3.getString();
                    java.util.Date d = DateTimeFunctions.parseDateTime(v0.getString(), v1.getString(), locale, tz);
                    result = ValueTimestamp.fromMillis(d.getTime());
                }
                break;
            }
        case NULLIF:
            result = database.areEqual(v0, v1) ? ValueNull.INSTANCE : v0;
            break;
        // system
        case NEXTVAL:
            {
                Sequence sequence = getSequence(session, v0, v1);
                SequenceValue value = new SequenceValue(sequence);
                result = value.getValue(session);
                break;
            }
        case CURRVAL:
            {
                Sequence sequence = getSequence(session, v0, v1);
                result = ValueLong.get(sequence.getCurrentValue());
                break;
            }
        case CSVREAD:
            {
                String fileName = v0.getString();
                String columnList = v1 == null ? null : v1.getString();
                Csv csv = new Csv();
                String options = v2 == null ? null : v2.getString();
                String charset = null;
                if (options != null && options.indexOf('=') >= 0) {
                    charset = csv.setOptions(options);
                } else {
                    charset = options;
                    String fieldSeparatorRead = v3 == null ? null : v3.getString();
                    String fieldDelimiter = v4 == null ? null : v4.getString();
                    String escapeCharacter = v5 == null ? null : v5.getString();
                    Value v6 = getNullOrValue(session, args, values, 6);
                    String nullString = v6 == null ? null : v6.getString();
                    setCsvDelimiterEscape(csv, fieldSeparatorRead, fieldDelimiter, escapeCharacter);
                    csv.setNullString(nullString);
                }
                char fieldSeparator = csv.getFieldSeparatorRead();
                String[] columns = StringUtils.arraySplit(columnList, fieldSeparator, true);
                try {
                    result = ValueResultSet.get(csv.read(fileName, columns, charset));
                } catch (SQLException e) {
                    throw DbException.convert(e);
                }
                break;
            }
        case LINK_SCHEMA:
            {
                session.getUser().checkAdmin();
                Connection conn = session.createConnection(false);
                ResultSet rs = LinkSchema.linkSchema(conn, v0.getString(), v1.getString(), v2.getString(), v3.getString(), v4.getString(), v5.getString());
                result = ValueResultSet.get(rs);
                break;
            }
        case CSVWRITE:
            {
                session.getUser().checkAdmin();
                Connection conn = session.createConnection(false);
                Csv csv = new Csv();
                String options = v2 == null ? null : v2.getString();
                String charset = null;
                if (options != null && options.indexOf('=') >= 0) {
                    charset = csv.setOptions(options);
                } else {
                    charset = options;
                    String fieldSeparatorWrite = v3 == null ? null : v3.getString();
                    String fieldDelimiter = v4 == null ? null : v4.getString();
                    String escapeCharacter = v5 == null ? null : v5.getString();
                    Value v6 = getNullOrValue(session, args, values, 6);
                    String nullString = v6 == null ? null : v6.getString();
                    Value v7 = getNullOrValue(session, args, values, 7);
                    String lineSeparator = v7 == null ? null : v7.getString();
                    setCsvDelimiterEscape(csv, fieldSeparatorWrite, fieldDelimiter, escapeCharacter);
                    csv.setNullString(nullString);
                    if (lineSeparator != null) {
                        csv.setLineSeparator(lineSeparator);
                    }
                }
                try {
                    int rows = csv.write(conn, v0.getString(), v1.getString(), charset);
                    result = ValueInt.get(rows);
                } catch (SQLException e) {
                    throw DbException.convert(e);
                }
                break;
            }
        case SET:
            {
                Variable var = (Variable) args[0];
                session.setVariable(var.getName(), v1);
                result = v1;
                break;
            }
        case FILE_READ:
            {
                session.getUser().checkAdmin();
                String fileName = v0.getString();
                boolean blob = args.length == 1;
                try {
                    long fileLength = FileUtils.size(fileName);
                    final InputStream in = FileUtils.newInputStream(fileName);
                    try {
                        if (blob) {
                            result = database.getLobStorage().createBlob(in, fileLength);
                        } else {
                            Reader reader;
                            if (v1 == ValueNull.INSTANCE) {
                                reader = new InputStreamReader(in);
                            } else {
                                reader = new InputStreamReader(in, v1.getString());
                            }
                            result = database.getLobStorage().createClob(reader, fileLength);
                        }
                    } finally {
                        IOUtils.closeSilently(in);
                    }
                    session.addTemporaryLob(result);
                } catch (IOException e) {
                    throw DbException.convertIOException(e, fileName);
                }
                break;
            }
        case FILE_WRITE:
            {
                session.getUser().checkAdmin();
                result = ValueNull.INSTANCE;
                String fileName = v1.getString();
                try {
                    FileOutputStream fileOutputStream = new FileOutputStream(fileName);
                    try (InputStream in = v0.getInputStream()) {
                        result = ValueLong.get(IOUtils.copyAndClose(in, fileOutputStream));
                    }
                } catch (IOException e) {
                    throw DbException.convertIOException(e, fileName);
                }
                break;
            }
        case TRUNCATE_VALUE:
            {
                result = v0.convertPrecision(v1.getLong(), v2.getBoolean());
                break;
            }
        case XMLTEXT:
            if (v1 == null) {
                result = ValueString.get(StringUtils.xmlText(v0.getString()), database.getMode().treatEmptyStringsAsNull);
            } else {
                result = ValueString.get(StringUtils.xmlText(v0.getString(), v1.getBoolean()), database.getMode().treatEmptyStringsAsNull);
            }
            break;
        case REGEXP_LIKE:
            {
                String regexp = v1.getString();
                String regexpMode = v2 == null || v2.getString() == null ? "" : v2.getString();
                int flags = makeRegexpFlags(regexpMode);
                try {
                    result = ValueBoolean.get(Pattern.compile(regexp, flags).matcher(v0.getString()).find());
                } catch (PatternSyntaxException e) {
                    throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, regexp);
                }
                break;
            }
        case VALUES:
            result = session.getVariable(args[0].getSchemaName() + "." + args[0].getTableName() + "." + args[0].getColumnName());
            break;
        case SIGNAL:
            {
                String sqlState = v0.getString();
                if (sqlState.startsWith("00") || !SIGNAL_PATTERN.matcher(sqlState).matches()) {
                    throw DbException.getInvalidValueException("SQLSTATE", sqlState);
                }
                String msgText = v1.getString();
                throw DbException.fromUser(sqlState, msgText);
            }
        default:
            throw DbException.throwInternalError("type=" + info.type);
    }
    return result;
}
Also used : SQLException(java.sql.SQLException) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) ValueString(org.h2.value.ValueString) ValueTimestamp(org.h2.value.ValueTimestamp) ResultSet(java.sql.ResultSet) ValueResultSet(org.h2.value.ValueResultSet) ValueDate(org.h2.value.ValueDate) PatternSyntaxException(java.util.regex.PatternSyntaxException) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Csv(org.h2.tools.Csv) ValueTimestampTimeZone(org.h2.value.ValueTimestampTimeZone) Connection(java.sql.Connection) Sequence(org.h2.schema.Sequence) IOException(java.io.IOException) ValueDate(org.h2.value.ValueDate) FileOutputStream(java.io.FileOutputStream) Value(org.h2.value.Value)

Example 10 with Replace

use of org.h2.command.dml.Replace in project h2database by h2database.

the class Page method setValue.

/**
 * Replace the value at an index in this page.
 *
 * @param index the index
 * @param value the new value
 * @return the old value
 */
public Object setValue(int index, Object value) {
    Object old = values[index];
    // this is slightly slower:
    // values = Arrays.copyOf(values, values.length);
    values = values.clone();
    DataType valueType = map.getValueType();
    if (isPersistent()) {
        addMemory(valueType.getMemory(value) - valueType.getMemory(old));
    }
    values[index] = value;
    return old;
}
Also used : DataType(org.h2.mvstore.type.DataType)

Aggregations

Connection (java.sql.Connection)7 ResultSet (java.sql.ResultSet)7 PreparedStatement (java.sql.PreparedStatement)6 Statement (java.sql.Statement)6 Expression (org.h2.expression.Expression)4 JdbcConnection (org.h2.jdbc.JdbcConnection)4 MVStore (org.h2.mvstore.MVStore)4 Column (org.h2.table.Column)4 Value (org.h2.value.Value)4 ValueString (org.h2.value.ValueString)4 BigDecimal (java.math.BigDecimal)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 ExpressionColumn (org.h2.expression.ExpressionColumn)3 SQLException (java.sql.SQLException)2 LinkedHashMap (java.util.LinkedHashMap)2 RuleFixed (org.h2.bnf.RuleFixed)2 RuleHead (org.h2.bnf.RuleHead)2 ValueExpression (org.h2.expression.ValueExpression)2 JdbcSQLException (org.h2.jdbc.JdbcSQLException)2 DbException (org.h2.message.DbException)2