Search in sources :

Example 71 with Set

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

the class Table method addDependencies.

/**
 * Add all objects that this table depends on to the hash set.
 *
 * @param dependencies the current set of dependencies
 */
public void addDependencies(HashSet<DbObject> dependencies) {
    if (dependencies.contains(this)) {
        // avoid endless recursion
        return;
    }
    if (sequences != null) {
        dependencies.addAll(sequences);
    }
    ExpressionVisitor visitor = ExpressionVisitor.getDependenciesVisitor(dependencies);
    for (Column col : columns) {
        col.isEverything(visitor);
    }
    if (constraints != null) {
        for (Constraint c : constraints) {
            c.isEverything(visitor);
        }
    }
    dependencies.add(this);
}
Also used : Constraint(org.h2.constraint.Constraint) ExpressionVisitor(org.h2.expression.ExpressionVisitor)

Example 72 with Set

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

the class Column method validateConvertUpdateSequence.

/**
 * Validate the value, convert it if required, and update the sequence value
 * if required. If the value is null, the default value (NULL if no default
 * is set) is returned. Check constraints are validated as well.
 *
 * @param session the session
 * @param value the value or null
 * @return the new or converted value
 */
public Value validateConvertUpdateSequence(Session session, Value value) {
    // take a local copy of defaultExpression to avoid holding the lock
    // while calling getValue
    final Expression localDefaultExpression;
    synchronized (this) {
        localDefaultExpression = defaultExpression;
    }
    Mode mode = session.getDatabase().getMode();
    if (value == null) {
        if (localDefaultExpression == null) {
            value = ValueNull.INSTANCE;
        } else {
            value = convert(localDefaultExpression.getValue(session), mode);
            if (!localDefaultExpression.isConstant()) {
                session.getGeneratedKeys().add(this);
            }
            if (primaryKey) {
                session.setLastIdentity(value);
            }
        }
    }
    if (value == ValueNull.INSTANCE) {
        if (convertNullToDefault) {
            value = convert(localDefaultExpression.getValue(session), mode);
            if (!localDefaultExpression.isConstant()) {
                session.getGeneratedKeys().add(this);
            }
        }
        if (value == ValueNull.INSTANCE && !nullable) {
            if (mode.convertInsertNullToZero) {
                DataType dt = DataType.getDataType(type);
                if (dt.decimal) {
                    value = ValueInt.get(0).convertTo(type);
                } else if (dt.type == Value.TIMESTAMP) {
                    value = ValueTimestamp.fromMillis(session.getTransactionStart());
                } else if (dt.type == Value.TIMESTAMP_TZ) {
                    long ms = session.getTransactionStart();
                    value = ValueTimestampTimeZone.fromDateValueAndNanos(DateTimeUtils.dateValueFromDate(ms), DateTimeUtils.nanosFromDate(ms), (short) 0);
                } else if (dt.type == Value.TIME) {
                    value = ValueTime.fromNanos(0);
                } else if (dt.type == Value.DATE) {
                    value = ValueDate.fromMillis(session.getTransactionStart());
                } else {
                    value = ValueString.get("").convertTo(type);
                }
            } else {
                throw DbException.get(ErrorCode.NULL_NOT_ALLOWED, name);
            }
        }
    }
    if (checkConstraint != null) {
        resolver.setValue(value);
        Value v;
        synchronized (this) {
            v = checkConstraint.getValue(session);
        }
        // Both TRUE and NULL are ok
        if (v != ValueNull.INSTANCE && !v.getBoolean()) {
            throw DbException.get(ErrorCode.CHECK_CONSTRAINT_VIOLATED_1, checkConstraint.getSQL());
        }
    }
    value = value.convertScale(mode.convertOnlyToSmallerScale, scale);
    if (precision > 0) {
        if (!value.checkPrecision(precision)) {
            String s = value.getTraceSQL();
            if (s.length() > 127) {
                s = s.substring(0, 128) + "...";
            }
            throw DbException.get(ErrorCode.VALUE_TOO_LONG_2, getCreateSQL(), s + " (" + value.getPrecision() + ")");
        }
    }
    if (isEnumerated() && value != ValueNull.INSTANCE) {
        if (!ValueEnum.isValid(enumerators, value)) {
            String s = value.getTraceSQL();
            if (s.length() > 127) {
                s = s.substring(0, 128) + "...";
            }
            throw DbException.get(ErrorCode.ENUM_VALUE_NOT_PERMITTED, getCreateSQL(), s);
        }
        value = ValueEnum.get(enumerators, value.getInt());
    }
    updateSequenceIfRequired(session, value);
    return value;
}
Also used : ValueExpression(org.h2.expression.ValueExpression) Expression(org.h2.expression.Expression) Mode(org.h2.engine.Mode) Value(org.h2.value.Value) SequenceValue(org.h2.expression.SequenceValue) DataType(org.h2.value.DataType) ValueString(org.h2.value.ValueString)

Example 73 with Set

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

the class JoinBatch method fetchCurrent.

@SuppressWarnings("unchecked")
private void fetchCurrent(final int jfId) {
    assert current.prev == null || current.prev.isRow(jfId) : "prev must be already fetched";
    assert jfId == 0 || current.isRow(jfId - 1) : "left must be already fetched";
    assert !current.isRow(jfId) : "double fetching";
    Object x = current.row(jfId);
    assert x != null : "x null";
    // in case of outer join we don't have any future around empty cursor
    boolean newCursor = x == EMPTY_CURSOR;
    if (newCursor) {
        if (jfId == 0) {
            // the top cursor is new and empty, then the whole select will
            // not produce any rows
            current.drop();
            return;
        }
    } else if (current.isFuture(jfId)) {
        // get cursor from a future
        x = get((Future<Cursor>) x);
        current.updateRow(jfId, x, JoinRow.S_FUTURE, JoinRow.S_CURSOR);
        newCursor = true;
    }
    final JoinFilter jf = filters[jfId];
    Cursor c = (Cursor) x;
    assert c != null;
    JoinFilter join = jf.join;
    while (true) {
        if (c == null || !c.next()) {
            if (newCursor && jf.isOuterJoin()) {
                // replace cursor with null-row
                current.updateRow(jfId, jf.getNullRow(), JoinRow.S_CURSOR, JoinRow.S_ROW);
                c = null;
                newCursor = false;
            } else {
                // cursor is done, drop it
                current.drop();
                return;
            }
        }
        if (!jf.isOk(c == null)) {
            // try another row from the cursor
            continue;
        }
        boolean joinEmpty = false;
        if (join != null && !join.collectSearchRows()) {
            if (join.isOuterJoin()) {
                joinEmpty = true;
            } else {
                // join will fail, try next row in the cursor
                continue;
            }
        }
        if (c != null) {
            current = current.copyBehind(jfId);
            // update jf, set current row from cursor
            current.updateRow(jfId, c.get(), JoinRow.S_CURSOR, JoinRow.S_ROW);
        }
        if (joinEmpty) {
            // update jf.join, set an empty cursor
            current.updateRow(join.id, EMPTY_CURSOR, JoinRow.S_NULL, JoinRow.S_CURSOR);
        }
        return;
    }
}
Also used : Cursor(org.h2.index.Cursor) IndexCursor(org.h2.index.IndexCursor) ViewCursor(org.h2.index.ViewCursor)

Example 74 with Set

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

the class JdbcUtils method loadUserClass.

/**
 * Load a class, but check if it is allowed to load this class first. To
 * perform access rights checking, the system property h2.allowedClasses
 * needs to be set to a list of class file name prefixes.
 *
 * @param className the name of the class
 * @return the class object
 */
@SuppressWarnings("unchecked")
public static <Z> Class<Z> loadUserClass(String className) {
    if (allowedClassNames == null) {
        // initialize the static fields
        String s = SysProperties.ALLOWED_CLASSES;
        ArrayList<String> prefixes = New.arrayList();
        boolean allowAll = false;
        HashSet<String> classNames = new HashSet<>();
        for (String p : StringUtils.arraySplit(s, ',', true)) {
            if (p.equals("*")) {
                allowAll = true;
            } else if (p.endsWith("*")) {
                prefixes.add(p.substring(0, p.length() - 1));
            } else {
                classNames.add(p);
            }
        }
        allowedClassNamePrefixes = prefixes.toArray(new String[0]);
        allowAllClasses = allowAll;
        allowedClassNames = classNames;
    }
    if (!allowAllClasses && !allowedClassNames.contains(className)) {
        boolean allowed = false;
        for (String s : allowedClassNamePrefixes) {
            if (className.startsWith(s)) {
                allowed = true;
            }
        }
        if (!allowed) {
            throw DbException.get(ErrorCode.ACCESS_DENIED_TO_CLASS_1, className);
        }
    }
    // Use provided class factory first.
    for (ClassFactory classFactory : getUserClassFactories()) {
        if (classFactory.match(className)) {
            try {
                Class<?> userClass = classFactory.loadClass(className);
                if (userClass != null) {
                    return (Class<Z>) userClass;
                }
            } catch (Exception e) {
                throw DbException.get(ErrorCode.CLASS_NOT_FOUND_1, e, className);
            }
        }
    }
    // Use local ClassLoader
    try {
        return (Class<Z>) Class.forName(className);
    } catch (ClassNotFoundException e) {
        try {
            return (Class<Z>) Class.forName(className, true, Thread.currentThread().getContextClassLoader());
        } catch (Exception e2) {
            throw DbException.get(ErrorCode.CLASS_NOT_FOUND_1, e, className);
        }
    } catch (NoClassDefFoundError e) {
        throw DbException.get(ErrorCode.CLASS_NOT_FOUND_1, e, className);
    } catch (Error e) {
        // UnsupportedClassVersionError
        throw DbException.get(ErrorCode.GENERAL_ERROR_1, e, className);
    }
}
Also used : ClassFactory(org.h2.util.Utils.ClassFactory) IOException(java.io.IOException) DbException(org.h2.message.DbException) ObjectStreamClass(java.io.ObjectStreamClass) HashSet(java.util.HashSet)

Example 75 with Set

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

the class MergedResultSet method getResult.

/**
 * Returns merged results set.
 *
 * @return result set with rows from all appended result sets
 */
public SimpleResultSet getResult() {
    SimpleResultSet rs = new SimpleResultSet();
    for (SimpleColumnInfo ci : columns) {
        rs.addColumn(ci.name, ci.type, ci.typeName, ci.precision, ci.scale);
    }
    for (Map<SimpleColumnInfo, Object> map : data) {
        Object[] row = new Object[columns.size()];
        for (Map.Entry<SimpleColumnInfo, Object> entry : map.entrySet()) {
            row[columns.indexOf(entry.getKey())] = entry.getValue();
        }
        rs.addRow(row);
    }
    return rs;
}
Also used : SimpleResultSet(org.h2.tools.SimpleResultSet) Map(java.util.Map) HashMap(java.util.HashMap)

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