Search in sources :

Example 56 with Expression

use of de.neemann.digital.hdl.model2.expression.Expression in project ignite by apache.

the class GridH2CollocationModel method joinedWithCollocated.

/**
 * @param f Filter.
 * @return Affinity join type.
 */
@SuppressWarnings("ForLoopReplaceableByForEach")
private Affinity joinedWithCollocated(int f) {
    TableFilter tf = childFilters[f];
    GridH2Table tbl = (GridH2Table) tf.getTable();
    if (validate) {
        if (tbl.rowDescriptor().context().customAffinityMapper())
            throw customAffinityError(tbl.cacheName());
        if (F.isEmpty(tf.getIndexConditions())) {
            throw new CacheException("Failed to prepare distributed join query: " + "join condition does not use index [joinedCache=" + tbl.cacheName() + ", plan=" + tf.getSelect().getPlanSQL() + ']');
        }
    }
    IndexColumn affCol = tbl.getAffinityKeyColumn();
    boolean affKeyCondFound = false;
    if (affCol != null) {
        ArrayList<IndexCondition> idxConditions = tf.getIndexConditions();
        int affColId = affCol.column.getColumnId();
        for (int i = 0; i < idxConditions.size(); i++) {
            IndexCondition c = idxConditions.get(i);
            int colId = c.getColumn().getColumnId();
            int cmpType = c.getCompareType();
            if ((cmpType == Comparison.EQUAL || cmpType == Comparison.EQUAL_NULL_SAFE) && (colId == affColId || tbl.rowDescriptor().isKeyColumn(colId)) && c.isEvaluatable()) {
                affKeyCondFound = true;
                Expression exp = c.getExpression();
                exp = exp.getNonAliasExpression();
                if (exp instanceof ExpressionColumn) {
                    ExpressionColumn expCol = (ExpressionColumn) exp;
                    // This is one of our previous joins.
                    TableFilter prevJoin = expCol.getTableFilter();
                    if (prevJoin != null) {
                        GridH2CollocationModel cm = child(indexOf(prevJoin), true);
                        // different affinity columns from different tables.
                        if (cm != null && !cm.view) {
                            Type t = cm.type(true);
                            if (t.isPartitioned() && t.isCollocated() && isAffinityColumn(prevJoin, expCol, validate))
                                return Affinity.COLLOCATED_JOIN;
                        }
                    }
                }
            }
        }
    }
    return affKeyCondFound ? Affinity.HAS_AFFINITY_CONDITION : Affinity.NONE;
}
Also used : TableFilter(org.h2.table.TableFilter) CacheException(javax.cache.CacheException) Expression(org.h2.expression.Expression) IndexCondition(org.h2.index.IndexCondition) IndexColumn(org.h2.table.IndexColumn) ExpressionColumn(org.h2.expression.ExpressionColumn)

Example 57 with Expression

use of de.neemann.digital.hdl.model2.expression.Expression in project h2database by h2database.

the class ExecuteProcedure method setParameters.

private void setParameters() {
    Prepared prepared = procedure.getPrepared();
    ArrayList<Parameter> params = prepared.getParameters();
    for (int i = 0; params != null && i < params.size() && i < expressions.size(); i++) {
        Expression expr = expressions.get(i);
        Parameter p = params.get(i);
        p.setValue(expr.getValue(session));
    }
}
Also used : Expression(org.h2.expression.Expression) Prepared(org.h2.command.Prepared) Parameter(org.h2.expression.Parameter)

Example 58 with Expression

use of de.neemann.digital.hdl.model2.expression.Expression in project h2database by h2database.

the class Insert method handleOnDuplicate.

/**
 * @param de duplicate key exception
 * @return {@code true} if row was updated, {@code false} if row was ignored
 */
private boolean handleOnDuplicate(DbException de) {
    if (de.getErrorCode() != ErrorCode.DUPLICATE_KEY_1) {
        throw de;
    }
    if (duplicateKeyAssignmentMap == null || duplicateKeyAssignmentMap.isEmpty()) {
        if (ignore) {
            return false;
        }
        throw de;
    }
    ArrayList<String> variableNames = new ArrayList<>(duplicateKeyAssignmentMap.size());
    Expression[] row = list.get(getCurrentRowNumber() - 1);
    for (int i = 0; i < columns.length; i++) {
        String key = table.getSchema().getName() + "." + table.getName() + "." + columns[i].getName();
        variableNames.add(key);
        session.setVariable(key, row[i].getValue(session));
    }
    StatementBuilder buff = new StatementBuilder("UPDATE ");
    buff.append(table.getSQL()).append(" SET ");
    for (Column column : duplicateKeyAssignmentMap.keySet()) {
        buff.appendExceptFirst(", ");
        Expression ex = duplicateKeyAssignmentMap.get(column);
        buff.append(column.getSQL()).append("=").append(ex.getSQL());
    }
    buff.append(" WHERE ");
    Index foundIndex = (Index) de.getSource();
    if (foundIndex == null) {
        throw DbException.getUnsupportedException("Unable to apply ON DUPLICATE KEY UPDATE, no index found!");
    }
    buff.append(prepareUpdateCondition(foundIndex).getSQL());
    String sql = buff.toString();
    Update command = (Update) session.prepare(sql);
    command.setUpdateToCurrentValuesReturnsZero(true);
    for (Parameter param : command.getParameters()) {
        Parameter insertParam = parameters.get(param.getIndex());
        param.setValue(insertParam.getValue(session));
    }
    boolean result = command.update() > 0;
    for (String variableName : variableNames) {
        session.setVariable(variableName, ValueNull.INSTANCE);
    }
    return result;
}
Also used : Expression(org.h2.expression.Expression) Column(org.h2.table.Column) ExpressionColumn(org.h2.expression.ExpressionColumn) StatementBuilder(org.h2.util.StatementBuilder) ArrayList(java.util.ArrayList) Parameter(org.h2.expression.Parameter) MVPrimaryIndex(org.h2.mvstore.db.MVPrimaryIndex) Index(org.h2.index.Index)

Example 59 with Expression

use of de.neemann.digital.hdl.model2.expression.Expression in project h2database by h2database.

the class Insert method insertRows.

private int insertRows() {
    session.getUser().checkRight(table, Right.INSERT);
    setCurrentRowNumber(0);
    table.fire(session, Trigger.INSERT, true);
    rowNumber = 0;
    GeneratedKeys generatedKeys = session.getGeneratedKeys();
    generatedKeys.initialize(table);
    int listSize = list.size();
    if (listSize > 0) {
        int columnLen = columns.length;
        for (int x = 0; x < listSize; x++) {
            session.startStatementWithinTransaction();
            generatedKeys.nextRow();
            Row newRow = table.getTemplateRow();
            Expression[] expr = list.get(x);
            setCurrentRowNumber(x + 1);
            for (int i = 0; i < columnLen; i++) {
                Column c = columns[i];
                int index = c.getColumnId();
                Expression e = expr[i];
                if (e != null) {
                    // e can be null (DEFAULT)
                    e = e.optimize(session);
                    try {
                        Value v = c.convert(e.getValue(session), session.getDatabase().getMode());
                        newRow.setValue(index, v);
                        if (e instanceof SequenceValue) {
                            generatedKeys.add(c);
                        }
                    } catch (DbException ex) {
                        throw setRow(ex, x, getSQL(expr));
                    }
                }
            }
            rowNumber++;
            table.validateConvertUpdateSequence(session, newRow);
            boolean done = table.fireBeforeRow(session, null, newRow);
            if (!done) {
                table.lock(session, true, false);
                try {
                    table.addRow(session, newRow);
                } catch (DbException de) {
                    if (handleOnDuplicate(de)) {
                        // MySQL returns 2 for updated row
                        // TODO: detect no-op change
                        rowNumber++;
                    } else {
                        // INSERT IGNORE case
                        rowNumber--;
                    }
                    continue;
                }
                generatedKeys.confirmRow(newRow);
                session.log(table, UndoLogRecord.INSERT, newRow);
                table.fireAfterRow(session, null, newRow, false);
            }
        }
    } else {
        table.lock(session, true, false);
        if (insertFromSelect) {
            query.query(0, this);
        } else {
            ResultInterface rows = query.query(0);
            while (rows.next()) {
                generatedKeys.nextRow();
                Value[] r = rows.currentRow();
                Row newRow = addRowImpl(r);
                if (newRow != null) {
                    generatedKeys.confirmRow(newRow);
                }
            }
            rows.close();
        }
    }
    table.fire(session, Trigger.INSERT, false);
    return rowNumber;
}
Also used : SequenceValue(org.h2.expression.SequenceValue) ResultInterface(org.h2.result.ResultInterface) Expression(org.h2.expression.Expression) Column(org.h2.table.Column) ExpressionColumn(org.h2.expression.ExpressionColumn) Value(org.h2.value.Value) SequenceValue(org.h2.expression.SequenceValue) GeneratedKeys(org.h2.engine.GeneratedKeys) Row(org.h2.result.Row) DbException(org.h2.message.DbException)

Example 60 with Expression

use of de.neemann.digital.hdl.model2.expression.Expression in project h2database by h2database.

the class Insert method prepare.

@Override
public void prepare() {
    if (columns == null) {
        if (!list.isEmpty() && list.get(0).length == 0) {
            // special case where table is used as a sequence
            columns = new Column[0];
        } else {
            columns = table.getColumns();
        }
    }
    if (!list.isEmpty()) {
        for (Expression[] expr : list) {
            if (expr.length != columns.length) {
                throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
            }
            for (int i = 0, len = expr.length; i < len; i++) {
                Expression e = expr[i];
                if (e != null) {
                    if (sourceTableFilter != null) {
                        e.mapColumns(sourceTableFilter, 0);
                    }
                    e = e.optimize(session);
                    if (e instanceof Parameter) {
                        Parameter p = (Parameter) e;
                        p.setColumn(columns[i]);
                    }
                    expr[i] = e;
                }
            }
        }
    } else {
        query.prepare();
        if (query.getColumnCount() != columns.length) {
            throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
        }
    }
}
Also used : Expression(org.h2.expression.Expression) Parameter(org.h2.expression.Parameter)

Aggregations

Expression (org.h2.expression.Expression)84 ValueExpression (org.h2.expression.ValueExpression)53 Column (org.h2.table.Column)45 ExpressionColumn (org.h2.expression.ExpressionColumn)38 IndexColumn (org.h2.table.IndexColumn)24 AlterTableAlterColumn (org.h2.command.ddl.AlterTableAlterColumn)21 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)18 ValueString (org.h2.value.ValueString)18 AlterTableRenameColumn (org.h2.command.ddl.AlterTableRenameColumn)17 TableFilter (org.h2.table.TableFilter)15 AlterTableDropConstraint (org.h2.command.ddl.AlterTableDropConstraint)14 AlterTableRenameConstraint (org.h2.command.ddl.AlterTableRenameConstraint)14 Expression (expression.Expression)13 Table (org.h2.table.Table)13 Value (org.h2.value.Value)12 ArrayList (java.util.ArrayList)11 Node (expression.Node)10 RangeTable (org.h2.table.RangeTable)10 Number (expression.Number)9 CreateTable (org.h2.command.ddl.CreateTable)9