Search in sources :

Example 11 with Merge

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

the class Merge method merge.

/**
 * Merge the given row.
 *
 * @param row the row
 */
protected void merge(Row row) {
    ArrayList<Parameter> k = update.getParameters();
    for (int i = 0; i < columns.length; i++) {
        Column col = columns[i];
        Value v = row.getValue(col.getColumnId());
        Parameter p = k.get(i);
        p.setValue(v);
    }
    for (int i = 0; i < keys.length; i++) {
        Column col = keys[i];
        Value v = row.getValue(col.getColumnId());
        if (v == null) {
            throw DbException.get(ErrorCode.COLUMN_CONTAINS_NULL_VALUES_1, col.getSQL());
        }
        Parameter p = k.get(columns.length + i);
        p.setValue(v);
    }
    // try and update
    int count = update.update();
    // if update fails try an insert
    if (count == 0) {
        try {
            targetTable.validateConvertUpdateSequence(session, row);
            boolean done = targetTable.fireBeforeRow(session, null, row);
            if (!done) {
                targetTable.lock(session, true, false);
                targetTable.addRow(session, row);
                session.getGeneratedKeys().confirmRow(row);
                session.log(targetTable, UndoLogRecord.INSERT, row);
                targetTable.fireAfterRow(session, null, row, false);
            }
        } catch (DbException e) {
            if (e.getErrorCode() == ErrorCode.DUPLICATE_KEY_1) {
                // possibly a concurrent merge or insert
                Index index = (Index) e.getSource();
                if (index != null) {
                    // verify the index columns match the key
                    Column[] indexColumns = index.getColumns();
                    boolean indexMatchesKeys = true;
                    if (indexColumns.length <= keys.length) {
                        for (int i = 0; i < indexColumns.length; i++) {
                            if (indexColumns[i] != keys[i]) {
                                indexMatchesKeys = false;
                                break;
                            }
                        }
                    }
                    if (indexMatchesKeys) {
                        throw DbException.get(ErrorCode.CONCURRENT_UPDATE_1, targetTable.getName());
                    }
                }
            }
            throw e;
        }
    } else if (count != 1) {
        throw DbException.get(ErrorCode.DUPLICATE_KEY_1, targetTable.getSQL());
    }
}
Also used : Column(org.h2.table.Column) SequenceValue(org.h2.expression.SequenceValue) Value(org.h2.value.Value) Parameter(org.h2.expression.Parameter) Index(org.h2.index.Index) DbException(org.h2.message.DbException)

Example 12 with Merge

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

the class FullText method setWhitespaceChars.

/**
 * Change the whitespace characters. The whitespace characters are used to
 * separate words. If indexes already exist at the time this list is
 * changed, reindex must be called.
 *
 * @param conn the connection
 * @param whitespaceChars the list of characters
 */
public static void setWhitespaceChars(Connection conn, String whitespaceChars) throws SQLException {
    try {
        init(conn);
        FullTextSettings setting = FullTextSettings.getInstance(conn);
        setting.setWhitespaceChars(whitespaceChars);
        PreparedStatement prep = conn.prepareStatement("MERGE INTO " + SCHEMA + ".SETTINGS VALUES(?, ?)");
        prep.setString(1, "whitespaceChars");
        prep.setString(2, whitespaceChars);
        prep.execute();
    } catch (DbException e) {
        throw DbException.toSQLException(e);
    }
}
Also used : PreparedStatement(java.sql.PreparedStatement) DbException(org.h2.message.DbException)

Example 13 with Merge

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

the class PageBtreeNode method remove.

@Override
SearchRow remove(SearchRow row) {
    int at = find(row, false, false, true);
    // merge is not implemented to allow concurrent usage
    // TODO maybe implement merge
    PageBtree page = index.getPage(childPageIds[at]);
    SearchRow last = page.remove(row);
    index.getPageStore().logUndo(this, data);
    updateRowCount(-1);
    written = false;
    changeCount = index.getPageStore().getChangeCount();
    if (last == null) {
        // the last row didn't change - nothing to do
        return null;
    } else if (last == row) {
        // this child is now empty
        index.getPageStore().free(page.getPos());
        if (entryCount < 1) {
            // no more children - this page is empty as well
            return row;
        }
        if (at == entryCount) {
            // removing the last child
            last = getRow(at - 1);
        } else {
            last = null;
        }
        removeChild(at);
        index.getPageStore().update(this);
        return last;
    }
    // the last row is in the last child
    if (at == entryCount) {
        return last;
    }
    int child = childPageIds[at];
    removeChild(at);
    // TODO this can mean only the position is now stored
    // should split at the next possible moment
    addChild(at, child, last);
    // remove and add swapped two children, fix that
    int temp = childPageIds[at];
    childPageIds[at] = childPageIds[at + 1];
    childPageIds[at + 1] = temp;
    index.getPageStore().update(this);
    return null;
}
Also used : SearchRow(org.h2.result.SearchRow)

Example 14 with Merge

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

the class MVTable method rebuildIndexBlockMerge.

private void rebuildIndexBlockMerge(Session session, MVIndex index) {
    if (index instanceof MVSpatialIndex) {
        // the spatial index doesn't support multi-way merge sort
        rebuildIndexBuffered(session, index);
    }
    // Read entries in memory, sort them, write to a new map (in sorted
    // order); repeat (using a new map for every block of 1 MB) until all
    // record are read. Merge all maps to the target (using merge sort;
    // duplicates are detected in the target). For randomly ordered data,
    // this should use relatively few write operations.
    // A possible optimization is: change the buffer size from "row count"
    // to "amount of memory", and buffer index keys instead of rows.
    Index scan = getScanIndex(session);
    long remaining = scan.getRowCount(session);
    long total = remaining;
    Cursor cursor = scan.find(session, null, null);
    long i = 0;
    Store store = session.getDatabase().getMvStore();
    int bufferSize = database.getMaxMemoryRows() / 2;
    ArrayList<Row> buffer = new ArrayList<>(bufferSize);
    String n = getName() + ":" + index.getName();
    int t = MathUtils.convertLongToInt(total);
    ArrayList<String> bufferNames = New.arrayList();
    while (cursor.next()) {
        Row row = cursor.get();
        buffer.add(row);
        database.setProgress(DatabaseEventListener.STATE_CREATE_INDEX, n, MathUtils.convertLongToInt(i++), t);
        if (buffer.size() >= bufferSize) {
            sortRows(buffer, index);
            String mapName = store.nextTemporaryMapName();
            index.addRowsToBuffer(buffer, mapName);
            bufferNames.add(mapName);
            buffer.clear();
        }
        remaining--;
    }
    sortRows(buffer, index);
    if (!bufferNames.isEmpty()) {
        String mapName = store.nextTemporaryMapName();
        index.addRowsToBuffer(buffer, mapName);
        bufferNames.add(mapName);
        buffer.clear();
        index.addBufferedRows(bufferNames);
    } else {
        addRowsToIndex(session, buffer, index);
    }
    if (SysProperties.CHECK && remaining != 0) {
        DbException.throwInternalError("rowcount remaining=" + remaining + " " + getName());
    }
}
Also used : ArrayList(java.util.ArrayList) Store(org.h2.mvstore.db.MVTableEngine.Store) Index(org.h2.index.Index) MultiVersionIndex(org.h2.index.MultiVersionIndex) Row(org.h2.result.Row) Cursor(org.h2.index.Cursor) Constraint(org.h2.constraint.Constraint)

Example 15 with Merge

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

the class TableDefinition method merge.

void merge(Db db, Object obj) {
    if (primaryKeyColumnNames == null || primaryKeyColumnNames.size() == 0) {
        throw new IllegalStateException("No primary key columns defined " + "for table " + obj.getClass() + " - no update possible");
    }
    SQLStatement stat = new SQLStatement(db);
    StatementBuilder buff = new StatementBuilder("MERGE INTO ");
    buff.append(db.getDialect().getTableName(schemaName, tableName)).append(" (");
    buff.resetCount();
    for (FieldDefinition field : fields) {
        buff.appendExceptFirst(", ");
        buff.append(field.columnName);
    }
    buff.append(") KEY(");
    buff.resetCount();
    for (FieldDefinition field : fields) {
        if (field.isPrimaryKey) {
            buff.appendExceptFirst(", ");
            buff.append(field.columnName);
        }
    }
    buff.append(") ");
    buff.resetCount();
    buff.append("VALUES (");
    for (FieldDefinition field : fields) {
        buff.appendExceptFirst(", ");
        buff.append('?');
        Object value = getValue(obj, field);
        stat.addParameter(value);
    }
    buff.append(')');
    stat.setSQL(buff.toString());
    StatementLogger.merge(stat.getSQL());
    stat.executeUpdate();
}
Also used : StatementBuilder(org.h2.util.StatementBuilder)

Aggregations

Column (org.h2.table.Column)10 Expression (org.h2.expression.Expression)8 PreparedStatement (java.sql.PreparedStatement)7 Statement (java.sql.Statement)6 ArrayList (java.util.ArrayList)6 Connection (java.sql.Connection)5 ResultSet (java.sql.ResultSet)5 SQLException (java.sql.SQLException)4 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)4 ValueExpression (org.h2.expression.ValueExpression)4 ValueString (org.h2.value.ValueString)4 BinaryObject (org.apache.ignite.binary.BinaryObject)3 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)3 AlterTableAlterColumn (org.h2.command.ddl.AlterTableAlterColumn)3 AlterTableDropConstraint (org.h2.command.ddl.AlterTableDropConstraint)3 AlterTableRenameColumn (org.h2.command.ddl.AlterTableRenameColumn)3 AlterTableRenameConstraint (org.h2.command.ddl.AlterTableRenameConstraint)3 ExpressionColumn (org.h2.expression.ExpressionColumn)3 ResultInterface (org.h2.result.ResultInterface)3 IndexColumn (org.h2.table.IndexColumn)3