Search in sources :

Example 31 with Set

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

the class Database method getDependentTable.

/**
 * Get the first table that depends on this object.
 *
 * @param obj the object to find
 * @param except the table to exclude (or null)
 * @return the first dependent table, or null
 */
public Table getDependentTable(SchemaObject obj, Table except) {
    switch(obj.getType()) {
        case DbObject.COMMENT:
        case DbObject.CONSTRAINT:
        case DbObject.INDEX:
        case DbObject.RIGHT:
        case DbObject.TRIGGER:
        case DbObject.USER:
            return null;
        default:
    }
    HashSet<DbObject> set = new HashSet<>();
    for (Table t : getAllTablesAndViews(false)) {
        if (except == t) {
            continue;
        } else if (TableType.VIEW == t.getTableType()) {
            continue;
        }
        set.clear();
        t.addDependencies(set);
        if (set.contains(obj)) {
            return t;
        }
    }
    return null;
}
Also used : MetaTable(org.h2.table.MetaTable) Table(org.h2.table.Table) HashSet(java.util.HashSet)

Example 32 with Set

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

the class CreateTable method update.

@Override
public int update() {
    if (!transactional) {
        session.commit(true);
    }
    Database db = session.getDatabase();
    if (!db.isPersistent()) {
        data.persistIndexes = false;
    }
    boolean isSessionTemporary = data.temporary && !data.globalTemporary;
    if (!isSessionTemporary) {
        db.lockMeta(session);
    }
    if (getSchema().resolveTableOrView(session, data.tableName) != null) {
        if (ifNotExists) {
            return 0;
        }
        throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, data.tableName);
    }
    if (asQuery != null) {
        asQuery.prepare();
        if (data.columns.isEmpty()) {
            generateColumnsFromQuery();
        } else if (data.columns.size() != asQuery.getColumnCount()) {
            throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
        }
    }
    changePrimaryKeysToNotNull(data.columns);
    data.id = getObjectId();
    data.create = create;
    data.session = session;
    Table table = getSchema().createTable(data);
    ArrayList<Sequence> sequences = generateSequences(data.columns, data.temporary);
    table.setComment(comment);
    if (isSessionTemporary) {
        if (onCommitDrop) {
            table.setOnCommitDrop(true);
        }
        if (onCommitTruncate) {
            table.setOnCommitTruncate(true);
        }
        session.addLocalTempTable(table);
    } else {
        db.lockMeta(session);
        db.addSchemaObject(session, table);
    }
    try {
        for (Column c : data.columns) {
            c.prepareExpression(session);
        }
        for (Sequence sequence : sequences) {
            table.addSequence(sequence);
        }
        createConstraints();
        if (asQuery != null) {
            boolean old = session.isUndoLogEnabled();
            try {
                session.setUndoLogEnabled(false);
                session.startStatementWithinTransaction();
                Insert insert = new Insert(session);
                insert.setSortedInsertMode(sortedInsertMode);
                insert.setQuery(asQuery);
                insert.setTable(table);
                insert.setInsertFromSelect(true);
                insert.prepare();
                insert.update();
            } finally {
                session.setUndoLogEnabled(old);
            }
        }
        HashSet<DbObject> set = new HashSet<>();
        set.clear();
        table.addDependencies(set);
        for (DbObject obj : set) {
            if (obj == table) {
                continue;
            }
            if (obj.getType() == DbObject.TABLE_OR_VIEW) {
                if (obj instanceof Table) {
                    Table t = (Table) obj;
                    if (t.getId() > table.getId()) {
                        throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED_1, "Table depends on another table " + "with a higher ID: " + t + ", this is currently not supported, " + "as it would prevent the database from " + "being re-opened");
                    }
                }
            }
        }
    } catch (DbException e) {
        db.checkPowerOff();
        db.removeSchemaObject(session, table);
        if (!transactional) {
            session.commit(true);
        }
        throw e;
    }
    return 0;
}
Also used : Table(org.h2.table.Table) ExpressionColumn(org.h2.expression.ExpressionColumn) Column(org.h2.table.Column) DbObject(org.h2.engine.DbObject) Database(org.h2.engine.Database) Sequence(org.h2.schema.Sequence) Insert(org.h2.command.dml.Insert) HashSet(java.util.HashSet) DbException(org.h2.message.DbException)

Example 33 with Set

use of org.h2.command.dml.Set 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 34 with Set

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

the class Function method getSimpleValue.

private Value getSimpleValue(Session session, Value v0, Expression[] args, Value[] values) {
    Value result;
    switch(info.type) {
        case ABS:
            result = v0.getSignum() >= 0 ? v0 : v0.negate();
            break;
        case ACOS:
            result = ValueDouble.get(Math.acos(v0.getDouble()));
            break;
        case ASIN:
            result = ValueDouble.get(Math.asin(v0.getDouble()));
            break;
        case ATAN:
            result = ValueDouble.get(Math.atan(v0.getDouble()));
            break;
        case CEILING:
            result = ValueDouble.get(Math.ceil(v0.getDouble()));
            break;
        case COS:
            result = ValueDouble.get(Math.cos(v0.getDouble()));
            break;
        case COSH:
            result = ValueDouble.get(Math.cosh(v0.getDouble()));
            break;
        case COT:
            {
                double d = Math.tan(v0.getDouble());
                if (d == 0.0) {
                    throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
                }
                result = ValueDouble.get(1. / d);
                break;
            }
        case DEGREES:
            result = ValueDouble.get(Math.toDegrees(v0.getDouble()));
            break;
        case EXP:
            result = ValueDouble.get(Math.exp(v0.getDouble()));
            break;
        case FLOOR:
            result = ValueDouble.get(Math.floor(v0.getDouble()));
            break;
        case LN:
            result = ValueDouble.get(Math.log(v0.getDouble()));
            break;
        case LOG:
            if (database.getMode().logIsLogBase10) {
                result = ValueDouble.get(Math.log10(v0.getDouble()));
            } else {
                result = ValueDouble.get(Math.log(v0.getDouble()));
            }
            break;
        case LOG10:
            result = ValueDouble.get(Math.log10(v0.getDouble()));
            break;
        case PI:
            result = ValueDouble.get(Math.PI);
            break;
        case RADIANS:
            result = ValueDouble.get(Math.toRadians(v0.getDouble()));
            break;
        case RAND:
            {
                if (v0 != null) {
                    session.getRandom().setSeed(v0.getInt());
                }
                result = ValueDouble.get(session.getRandom().nextDouble());
                break;
            }
        case ROUNDMAGIC:
            result = ValueDouble.get(roundMagic(v0.getDouble()));
            break;
        case SIGN:
            result = ValueInt.get(v0.getSignum());
            break;
        case SIN:
            result = ValueDouble.get(Math.sin(v0.getDouble()));
            break;
        case SINH:
            result = ValueDouble.get(Math.sinh(v0.getDouble()));
            break;
        case SQRT:
            result = ValueDouble.get(Math.sqrt(v0.getDouble()));
            break;
        case TAN:
            result = ValueDouble.get(Math.tan(v0.getDouble()));
            break;
        case TANH:
            result = ValueDouble.get(Math.tanh(v0.getDouble()));
            break;
        case SECURE_RAND:
            result = ValueBytes.getNoCopy(MathUtils.secureRandomBytes(v0.getInt()));
            break;
        case EXPAND:
            result = ValueBytes.getNoCopy(CompressTool.getInstance().expand(v0.getBytesNoCopy()));
            break;
        case ZERO:
            result = ValueInt.get(0);
            break;
        case RANDOM_UUID:
            result = ValueUuid.getNewRandom();
            break;
        // string
        case ASCII:
            {
                String s = v0.getString();
                if (s.length() == 0) {
                    result = ValueNull.INSTANCE;
                } else {
                    result = ValueInt.get(s.charAt(0));
                }
                break;
            }
        case BIT_LENGTH:
            result = ValueLong.get(16 * length(v0));
            break;
        case CHAR:
            result = ValueString.get(String.valueOf((char) v0.getInt()), database.getMode().treatEmptyStringsAsNull);
            break;
        case CHAR_LENGTH:
        case LENGTH:
            result = ValueLong.get(length(v0));
            break;
        case OCTET_LENGTH:
            result = ValueLong.get(2 * length(v0));
            break;
        case CONCAT_WS:
        case CONCAT:
            {
                result = ValueNull.INSTANCE;
                int start = 0;
                String separator = "";
                if (info.type == CONCAT_WS) {
                    start = 1;
                    separator = getNullOrValue(session, args, values, 0).getString();
                }
                for (int i = start; i < args.length; i++) {
                    Value v = getNullOrValue(session, args, values, i);
                    if (v == ValueNull.INSTANCE) {
                        continue;
                    }
                    if (result == ValueNull.INSTANCE) {
                        result = v;
                    } else {
                        String tmp = v.getString();
                        if (!StringUtils.isNullOrEmpty(separator) && !StringUtils.isNullOrEmpty(tmp)) {
                            tmp = separator + tmp;
                        }
                        result = ValueString.get(result.getString() + tmp, database.getMode().treatEmptyStringsAsNull);
                    }
                }
                if (info.type == CONCAT_WS) {
                    if (separator != null && result == ValueNull.INSTANCE) {
                        result = ValueString.get("", database.getMode().treatEmptyStringsAsNull);
                    }
                }
                break;
            }
        case HEXTORAW:
            result = ValueString.get(hexToRaw(v0.getString()), database.getMode().treatEmptyStringsAsNull);
            break;
        case LOWER:
        case LCASE:
            // TODO this is locale specific, need to document or provide a way
            // to set the locale
            result = ValueString.get(v0.getString().toLowerCase(), database.getMode().treatEmptyStringsAsNull);
            break;
        case RAWTOHEX:
            result = ValueString.get(rawToHex(v0.getString()), database.getMode().treatEmptyStringsAsNull);
            break;
        case SOUNDEX:
            result = ValueString.get(getSoundex(v0.getString()), database.getMode().treatEmptyStringsAsNull);
            break;
        case SPACE:
            {
                int len = Math.max(0, v0.getInt());
                char[] chars = new char[len];
                for (int i = len - 1; i >= 0; i--) {
                    chars[i] = ' ';
                }
                result = ValueString.get(new String(chars), database.getMode().treatEmptyStringsAsNull);
                break;
            }
        case UPPER:
        case UCASE:
            // TODO this is locale specific, need to document or provide a way
            // to set the locale
            result = ValueString.get(v0.getString().toUpperCase(), database.getMode().treatEmptyStringsAsNull);
            break;
        case STRINGENCODE:
            result = ValueString.get(StringUtils.javaEncode(v0.getString()), database.getMode().treatEmptyStringsAsNull);
            break;
        case STRINGDECODE:
            result = ValueString.get(StringUtils.javaDecode(v0.getString()), database.getMode().treatEmptyStringsAsNull);
            break;
        case STRINGTOUTF8:
            result = ValueBytes.getNoCopy(v0.getString().getBytes(StandardCharsets.UTF_8));
            break;
        case UTF8TOSTRING:
            result = ValueString.get(new String(v0.getBytesNoCopy(), StandardCharsets.UTF_8), database.getMode().treatEmptyStringsAsNull);
            break;
        case XMLCOMMENT:
            result = ValueString.get(StringUtils.xmlComment(v0.getString()), database.getMode().treatEmptyStringsAsNull);
            break;
        case XMLCDATA:
            result = ValueString.get(StringUtils.xmlCData(v0.getString()), database.getMode().treatEmptyStringsAsNull);
            break;
        case XMLSTARTDOC:
            result = ValueString.get(StringUtils.xmlStartDoc(), database.getMode().treatEmptyStringsAsNull);
            break;
        case DAY_NAME:
            {
                int dayOfWeek = DateTimeUtils.getSundayDayOfWeek(DateTimeUtils.dateAndTimeFromValue(v0)[0]);
                result = ValueString.get(DateTimeFunctions.getMonthsAndWeeks(1)[dayOfWeek], database.getMode().treatEmptyStringsAsNull);
                break;
            }
        case DAY_OF_MONTH:
        case DAY_OF_WEEK:
        case DAY_OF_YEAR:
        case HOUR:
        case MINUTE:
        case MONTH:
        case QUARTER:
        case ISO_YEAR:
        case ISO_WEEK:
        case ISO_DAY_OF_WEEK:
        case SECOND:
        case WEEK:
        case YEAR:
            result = ValueInt.get(DateTimeFunctions.getIntDatePart(v0, info.type));
            break;
        case MONTH_NAME:
            {
                int month = DateTimeUtils.monthFromDateValue(DateTimeUtils.dateAndTimeFromValue(v0)[0]);
                result = ValueString.get(DateTimeFunctions.getMonthsAndWeeks(0)[month - 1], database.getMode().treatEmptyStringsAsNull);
                break;
            }
        case CURDATE:
        case CURRENT_DATE:
            {
                long now = session.getTransactionStart();
                // need to normalize
                result = ValueDate.fromMillis(now);
                break;
            }
        case CURTIME:
        case CURRENT_TIME:
            {
                long now = session.getTransactionStart();
                // need to normalize
                result = ValueTime.fromMillis(now);
                break;
            }
        case NOW:
        case CURRENT_TIMESTAMP:
            {
                long now = session.getTransactionStart();
                ValueTimestamp vt = ValueTimestamp.fromMillis(now);
                if (v0 != null) {
                    Mode mode = database.getMode();
                    vt = (ValueTimestamp) vt.convertScale(mode.convertOnlyToSmallerScale, v0.getInt());
                }
                result = vt;
                break;
            }
        case DATABASE:
            result = ValueString.get(database.getShortName(), database.getMode().treatEmptyStringsAsNull);
            break;
        case USER:
        case CURRENT_USER:
            result = ValueString.get(session.getUser().getName(), database.getMode().treatEmptyStringsAsNull);
            break;
        case IDENTITY:
            result = session.getLastIdentity();
            break;
        case SCOPE_IDENTITY:
            result = session.getLastScopeIdentity();
            break;
        case AUTOCOMMIT:
            result = ValueBoolean.get(session.getAutoCommit());
            break;
        case READONLY:
            result = ValueBoolean.get(database.isReadOnly());
            break;
        case DATABASE_PATH:
            {
                String path = database.getDatabasePath();
                result = path == null ? (Value) ValueNull.INSTANCE : ValueString.get(path, database.getMode().treatEmptyStringsAsNull);
                break;
            }
        case LOCK_TIMEOUT:
            result = ValueInt.get(session.getLockTimeout());
            break;
        case DISK_SPACE_USED:
            result = ValueLong.get(getDiskSpaceUsed(session, v0));
            break;
        case CAST:
        case CONVERT:
            {
                v0 = v0.convertTo(dataType);
                Mode mode = database.getMode();
                v0 = v0.convertScale(mode.convertOnlyToSmallerScale, scale);
                v0 = v0.convertPrecision(getPrecision(), false);
                result = v0;
                break;
            }
        case MEMORY_FREE:
            session.getUser().checkAdmin();
            result = ValueInt.get(Utils.getMemoryFree());
            break;
        case MEMORY_USED:
            session.getUser().checkAdmin();
            result = ValueInt.get(Utils.getMemoryUsed());
            break;
        case LOCK_MODE:
            result = ValueInt.get(database.getLockMode());
            break;
        case SCHEMA:
            result = ValueString.get(session.getCurrentSchemaName(), database.getMode().treatEmptyStringsAsNull);
            break;
        case SESSION_ID:
            result = ValueInt.get(session.getId());
            break;
        case IFNULL:
            {
                result = v0;
                if (v0 == ValueNull.INSTANCE) {
                    result = getNullOrValue(session, args, values, 1);
                }
                result = convertResult(result);
                break;
            }
        case CASEWHEN:
            {
                Value v;
                if (!v0.getBoolean()) {
                    v = getNullOrValue(session, args, values, 2);
                } else {
                    v = getNullOrValue(session, args, values, 1);
                }
                result = v.convertTo(dataType);
                break;
            }
        case DECODE:
            {
                int index = -1;
                for (int i = 1, len = args.length - 1; i < len; i += 2) {
                    if (database.areEqual(v0, getNullOrValue(session, args, values, i))) {
                        index = i + 1;
                        break;
                    }
                }
                if (index < 0 && args.length % 2 == 0) {
                    index = args.length - 1;
                }
                Value v = index < 0 ? ValueNull.INSTANCE : getNullOrValue(session, args, values, index);
                result = v.convertTo(dataType);
                break;
            }
        case NVL2:
            {
                Value v;
                if (v0 == ValueNull.INSTANCE) {
                    v = getNullOrValue(session, args, values, 2);
                } else {
                    v = getNullOrValue(session, args, values, 1);
                }
                result = v.convertTo(dataType);
                break;
            }
        case COALESCE:
            {
                result = v0;
                for (int i = 0; i < args.length; i++) {
                    Value v = getNullOrValue(session, args, values, i);
                    if (v != ValueNull.INSTANCE) {
                        result = v.convertTo(dataType);
                        break;
                    }
                }
                break;
            }
        case GREATEST:
        case LEAST:
            {
                result = ValueNull.INSTANCE;
                for (int i = 0; i < args.length; i++) {
                    Value v = getNullOrValue(session, args, values, i);
                    if (v != ValueNull.INSTANCE) {
                        v = v.convertTo(dataType);
                        if (result == ValueNull.INSTANCE) {
                            result = v;
                        } else {
                            int comp = database.compareTypeSafe(result, v);
                            if (info.type == GREATEST && comp < 0) {
                                result = v;
                            } else if (info.type == LEAST && comp > 0) {
                                result = v;
                            }
                        }
                    }
                }
                break;
            }
        case CASE:
            {
                Expression then = null;
                if (v0 == null) {
                    // (null, when, then, when, then, else)
                    for (int i = 1, len = args.length - 1; i < len; i += 2) {
                        Value when = args[i].getValue(session);
                        if (when.getBoolean()) {
                            then = args[i + 1];
                            break;
                        }
                    }
                } else {
                    // (expr, when, then, when, then, else)
                    if (v0 != ValueNull.INSTANCE) {
                        for (int i = 1, len = args.length - 1; i < len; i += 2) {
                            Value when = args[i].getValue(session);
                            if (database.areEqual(v0, when)) {
                                then = args[i + 1];
                                break;
                            }
                        }
                    }
                }
                if (then == null && args.length % 2 == 0) {
                    // then = elsePart
                    then = args[args.length - 1];
                }
                Value v = then == null ? ValueNull.INSTANCE : then.getValue(session);
                result = v.convertTo(dataType);
                break;
            }
        case ARRAY_GET:
            {
                if (v0.getType() == Value.ARRAY) {
                    Value v1 = getNullOrValue(session, args, values, 1);
                    int element = v1.getInt();
                    Value[] list = ((ValueArray) v0).getList();
                    if (element < 1 || element > list.length) {
                        result = ValueNull.INSTANCE;
                    } else {
                        result = list[element - 1];
                    }
                } else {
                    result = ValueNull.INSTANCE;
                }
                break;
            }
        case ARRAY_LENGTH:
            {
                if (v0.getType() == Value.ARRAY) {
                    Value[] list = ((ValueArray) v0).getList();
                    result = ValueInt.get(list.length);
                } else {
                    result = ValueNull.INSTANCE;
                }
                break;
            }
        case ARRAY_CONTAINS:
            {
                result = ValueBoolean.FALSE;
                if (v0.getType() == Value.ARRAY) {
                    Value v1 = getNullOrValue(session, args, values, 1);
                    Value[] list = ((ValueArray) v0).getList();
                    for (Value v : list) {
                        if (v.equals(v1)) {
                            result = ValueBoolean.TRUE;
                            break;
                        }
                    }
                }
                break;
            }
        case CANCEL_SESSION:
            {
                result = ValueBoolean.get(cancelStatement(session, v0.getInt()));
                break;
            }
        case TRANSACTION_ID:
            {
                result = session.getTransactionId();
                break;
            }
        default:
            result = null;
    }
    return result;
}
Also used : ValueTimestamp(org.h2.value.ValueTimestamp) Mode(org.h2.engine.Mode) Value(org.h2.value.Value) ValueString(org.h2.value.ValueString)

Example 35 with Set

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

the class FullText method init.

/**
 * Initializes full text search functionality for this database. This adds
 * the following Java functions to the database:
 * <ul>
 * <li>FT_CREATE_INDEX(schemaNameString, tableNameString,
 * columnListString)</li>
 * <li>FT_SEARCH(queryString, limitInt, offsetInt): result set</li>
 * <li>FT_REINDEX()</li>
 * <li>FT_DROP_ALL()</li>
 * </ul>
 * It also adds a schema FT to the database where bookkeeping information
 * is stored. This function may be called from a Java application, or by
 * using the SQL statements:
 *
 * <pre>
 * CREATE ALIAS IF NOT EXISTS FT_INIT FOR
 *      &quot;org.h2.fulltext.FullText.init&quot;;
 * CALL FT_INIT();
 * </pre>
 *
 * @param conn the connection
 */
public static void init(Connection conn) throws SQLException {
    Statement stat = conn.createStatement();
    stat.execute("CREATE SCHEMA IF NOT EXISTS " + SCHEMA);
    stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA + ".INDEXES(ID INT AUTO_INCREMENT PRIMARY KEY, " + "SCHEMA VARCHAR, TABLE VARCHAR, COLUMNS VARCHAR, " + "UNIQUE(SCHEMA, TABLE))");
    stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA + ".WORDS(ID INT AUTO_INCREMENT PRIMARY KEY, " + "NAME VARCHAR, UNIQUE(NAME))");
    stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA + ".ROWS(ID IDENTITY, HASH INT, INDEXID INT, " + "KEY VARCHAR, UNIQUE(HASH, INDEXID, KEY))");
    stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA + ".MAP(ROWID INT, WORDID INT, PRIMARY KEY(WORDID, ROWID))");
    stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA + ".IGNORELIST(LIST VARCHAR)");
    stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA + ".SETTINGS(KEY VARCHAR PRIMARY KEY, VALUE VARCHAR)");
    stat.execute("CREATE ALIAS IF NOT EXISTS FT_CREATE_INDEX FOR \"" + FullText.class.getName() + ".createIndex\"");
    stat.execute("CREATE ALIAS IF NOT EXISTS FT_DROP_INDEX FOR \"" + FullText.class.getName() + ".dropIndex\"");
    stat.execute("CREATE ALIAS IF NOT EXISTS FT_SEARCH FOR \"" + FullText.class.getName() + ".search\"");
    stat.execute("CREATE ALIAS IF NOT EXISTS FT_SEARCH_DATA FOR \"" + FullText.class.getName() + ".searchData\"");
    stat.execute("CREATE ALIAS IF NOT EXISTS FT_REINDEX FOR \"" + FullText.class.getName() + ".reindex\"");
    stat.execute("CREATE ALIAS IF NOT EXISTS FT_DROP_ALL FOR \"" + FullText.class.getName() + ".dropAll\"");
    FullTextSettings setting = FullTextSettings.getInstance(conn);
    ResultSet rs = stat.executeQuery("SELECT * FROM " + SCHEMA + ".IGNORELIST");
    while (rs.next()) {
        String commaSeparatedList = rs.getString(1);
        setIgnoreList(setting, commaSeparatedList);
    }
    rs = stat.executeQuery("SELECT * FROM " + SCHEMA + ".SETTINGS");
    while (rs.next()) {
        String key = rs.getString(1);
        if ("whitespaceChars".equals(key)) {
            String value = rs.getString(2);
            setting.setWhitespaceChars(value);
        }
    }
    rs = stat.executeQuery("SELECT * FROM " + SCHEMA + ".WORDS");
    while (rs.next()) {
        String word = rs.getString("NAME");
        int id = rs.getInt("ID");
        word = setting.convertWord(word);
        if (word != null) {
            setting.addWord(word, id);
        }
    }
    setting.setInitialized(true);
}
Also used : PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) SimpleResultSet(org.h2.tools.SimpleResultSet) ResultSet(java.sql.ResultSet)

Aggregations

SQLException (java.sql.SQLException)107 DbException (org.h2.message.DbException)80 PreparedStatement (java.sql.PreparedStatement)78 Connection (java.sql.Connection)70 Statement (java.sql.Statement)63 ResultSet (java.sql.ResultSet)62 Value (org.h2.value.Value)51 JdbcConnection (org.h2.jdbc.JdbcConnection)48 SimpleResultSet (org.h2.tools.SimpleResultSet)36 HashSet (java.util.HashSet)28 Column (org.h2.table.Column)24 Savepoint (java.sql.Savepoint)23 ValueString (org.h2.value.ValueString)21 IOException (java.io.IOException)20 Random (java.util.Random)17 Expression (org.h2.expression.Expression)16 Task (org.h2.util.Task)16 ExpressionColumn (org.h2.expression.ExpressionColumn)14 ValueExpression (org.h2.expression.ValueExpression)13 IndexColumn (org.h2.table.IndexColumn)13