Search in sources :

Example 1 with GeneratedKeys

use of org.h2.engine.GeneratedKeys in project h2database by h2database.

the class JdbcPreparedStatement method executeUpdateInternal.

private int executeUpdateInternal() throws SQLException {
    closeOldResultSet();
    synchronized (session) {
        try {
            setExecutingStatement(command);
            ResultWithGeneratedKeys result = command.executeUpdate(generatedKeysRequest);
            updateCount = result.getUpdateCount();
            ResultInterface gk = result.getGeneratedKeys();
            if (gk != null) {
                int id = getNextId(TraceObject.RESULT_SET);
                generatedKeys = new JdbcResultSet(conn, this, command, gk, id, false, true, false);
            }
        } finally {
            setExecutingStatement(null);
        }
    }
    return updateCount;
}
Also used : ResultInterface(org.h2.result.ResultInterface) ResultWithGeneratedKeys(org.h2.result.ResultWithGeneratedKeys)

Example 2 with GeneratedKeys

use of org.h2.engine.GeneratedKeys in project h2database by h2database.

the class JdbcStatement method executeUpdateInternal.

private int executeUpdateInternal(String sql, Object generatedKeysRequest) throws SQLException {
    checkClosedForWrite();
    try {
        closeOldResultSet();
        sql = JdbcConnection.translateSQL(sql, escapeProcessing);
        CommandInterface command = conn.prepareCommand(sql, fetchSize);
        synchronized (session) {
            setExecutingStatement(command);
            try {
                ResultWithGeneratedKeys result = command.executeUpdate(conn.scopeGeneratedKeys() ? false : generatedKeysRequest);
                updateCount = result.getUpdateCount();
                ResultInterface gk = result.getGeneratedKeys();
                if (gk != null) {
                    int id = getNextId(TraceObject.RESULT_SET);
                    generatedKeys = new JdbcResultSet(conn, this, command, gk, id, false, true, false);
                }
            } finally {
                setExecutingStatement(null);
            }
        }
        command.close();
        return updateCount;
    } finally {
        afterWriting();
    }
}
Also used : ResultInterface(org.h2.result.ResultInterface) CommandInterface(org.h2.command.CommandInterface) ResultWithGeneratedKeys(org.h2.result.ResultWithGeneratedKeys)

Example 3 with GeneratedKeys

use of org.h2.engine.GeneratedKeys 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 4 with GeneratedKeys

use of org.h2.engine.GeneratedKeys in project h2database by h2database.

the class Merge method update.

@Override
public int update() {
    int count;
    session.getUser().checkRight(targetTable, Right.INSERT);
    session.getUser().checkRight(targetTable, Right.UPDATE);
    setCurrentRowNumber(0);
    GeneratedKeys generatedKeys = session.getGeneratedKeys();
    if (!valuesExpressionList.isEmpty()) {
        // process values in list
        count = 0;
        generatedKeys.initialize(targetTable);
        for (int x = 0, size = valuesExpressionList.size(); x < size; x++) {
            setCurrentRowNumber(x + 1);
            generatedKeys.nextRow();
            Expression[] expr = valuesExpressionList.get(x);
            Row newRow = targetTable.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);
                        if (e instanceof SequenceValue) {
                            generatedKeys.add(c);
                        }
                    } catch (DbException ex) {
                        throw setRow(ex, count, getSQL(expr));
                    }
                }
            }
            merge(newRow);
            count++;
        }
    } else {
        // process select data for list
        query.setNeverLazy(true);
        ResultInterface rows = query.query(0);
        count = 0;
        targetTable.fire(session, Trigger.UPDATE | Trigger.INSERT, true);
        targetTable.lock(session, true, false);
        while (rows.next()) {
            count++;
            generatedKeys.nextRow();
            Value[] r = rows.currentRow();
            Row newRow = targetTable.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));
                }
            }
            merge(newRow);
        }
        rows.close();
        targetTable.fire(session, Trigger.UPDATE | Trigger.INSERT, false);
    }
    return count;
}
Also used : SequenceValue(org.h2.expression.SequenceValue) ResultInterface(org.h2.result.ResultInterface) Expression(org.h2.expression.Expression) Column(org.h2.table.Column) SequenceValue(org.h2.expression.SequenceValue) Value(org.h2.value.Value) GeneratedKeys(org.h2.engine.GeneratedKeys) Row(org.h2.result.Row) DbException(org.h2.message.DbException)

Example 5 with GeneratedKeys

use of org.h2.engine.GeneratedKeys in project h2database by h2database.

the class WebApp method getResult.

private String getResult(Connection conn, int id, String sql, boolean allowEdit, boolean forceEdit) {
    try {
        sql = sql.trim();
        StringBuilder buff = new StringBuilder();
        String sqlUpper = StringUtils.toUpperEnglish(sql);
        if (sqlUpper.contains("CREATE") || sqlUpper.contains("DROP") || sqlUpper.contains("ALTER") || sqlUpper.contains("RUNSCRIPT")) {
            String sessionId = attributes.getProperty("jsessionid");
            buff.append("<script type=\"text/javascript\">parent['h2menu'].location='tables.do?jsessionid=").append(sessionId).append("';</script>");
        }
        Statement stat;
        DbContents contents = session.getContents();
        if (forceEdit || (allowEdit && contents.isH2())) {
            stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        } else {
            stat = conn.createStatement();
        }
        ResultSet rs;
        long time = System.currentTimeMillis();
        boolean metadata = false;
        int generatedKeys = Statement.NO_GENERATED_KEYS;
        boolean edit = false;
        boolean list = false;
        if (isBuiltIn(sql, "@autocommit_true")) {
            conn.setAutoCommit(true);
            return "${text.result.autoCommitOn}";
        } else if (isBuiltIn(sql, "@autocommit_false")) {
            conn.setAutoCommit(false);
            return "${text.result.autoCommitOff}";
        } else if (isBuiltIn(sql, "@cancel")) {
            stat = session.executingStatement;
            if (stat != null) {
                stat.cancel();
                buff.append("${text.result.statementWasCanceled}");
            } else {
                buff.append("${text.result.noRunningStatement}");
            }
            return buff.toString();
        } else if (isBuiltIn(sql, "@edit")) {
            edit = true;
            sql = sql.substring("@edit".length()).trim();
            session.put("resultSetSQL", sql);
        }
        if (isBuiltIn(sql, "@list")) {
            list = true;
            sql = sql.substring("@list".length()).trim();
        }
        if (isBuiltIn(sql, "@meta")) {
            metadata = true;
            sql = sql.substring("@meta".length()).trim();
        }
        if (isBuiltIn(sql, "@generated")) {
            generatedKeys = Statement.RETURN_GENERATED_KEYS;
            sql = sql.substring("@generated".length()).trim();
        } else if (isBuiltIn(sql, "@history")) {
            buff.append(getCommandHistoryString());
            return buff.toString();
        } else if (isBuiltIn(sql, "@loop")) {
            sql = sql.substring("@loop".length()).trim();
            int idx = sql.indexOf(' ');
            int count = Integer.decode(sql.substring(0, idx));
            sql = sql.substring(idx).trim();
            return executeLoop(conn, count, sql);
        } else if (isBuiltIn(sql, "@maxrows")) {
            int maxrows = (int) Double.parseDouble(sql.substring("@maxrows".length()).trim());
            session.put("maxrows", "" + maxrows);
            return "${text.result.maxrowsSet}";
        } else if (isBuiltIn(sql, "@parameter_meta")) {
            sql = sql.substring("@parameter_meta".length()).trim();
            PreparedStatement prep = conn.prepareStatement(sql);
            buff.append(getParameterResultSet(prep.getParameterMetaData()));
            return buff.toString();
        } else if (isBuiltIn(sql, "@password_hash")) {
            sql = sql.substring("@password_hash".length()).trim();
            String[] p = split(sql);
            return StringUtils.convertBytesToHex(SHA256.getKeyPasswordHash(p[0], p[1].toCharArray()));
        } else if (isBuiltIn(sql, "@prof_start")) {
            if (profiler != null) {
                profiler.stopCollecting();
            }
            profiler = new Profiler();
            profiler.startCollecting();
            return "Ok";
        } else if (isBuiltIn(sql, "@sleep")) {
            String s = sql.substring("@sleep".length()).trim();
            int sleep = 1;
            if (s.length() > 0) {
                sleep = Integer.parseInt(s);
            }
            Thread.sleep(sleep * 1000);
            return "Ok";
        } else if (isBuiltIn(sql, "@transaction_isolation")) {
            String s = sql.substring("@transaction_isolation".length()).trim();
            if (s.length() > 0) {
                int level = Integer.parseInt(s);
                conn.setTransactionIsolation(level);
            }
            buff.append("Transaction Isolation: ").append(conn.getTransactionIsolation()).append("<br />");
            buff.append(Connection.TRANSACTION_READ_UNCOMMITTED).append(": read_uncommitted<br />");
            buff.append(Connection.TRANSACTION_READ_COMMITTED).append(": read_committed<br />");
            buff.append(Connection.TRANSACTION_REPEATABLE_READ).append(": repeatable_read<br />");
            buff.append(Connection.TRANSACTION_SERIALIZABLE).append(": serializable");
        }
        if (sql.startsWith("@")) {
            rs = getMetaResultSet(conn, sql);
            if (rs == null) {
                buff.append("?: ").append(sql);
                return buff.toString();
            }
        } else {
            int maxrows = getMaxrows();
            stat.setMaxRows(maxrows);
            session.executingStatement = stat;
            boolean isResultSet = stat.execute(sql, generatedKeys);
            session.addCommand(sql);
            if (generatedKeys == Statement.RETURN_GENERATED_KEYS) {
                rs = null;
                rs = stat.getGeneratedKeys();
            } else {
                if (!isResultSet) {
                    buff.append("${text.result.updateCount}: ").append(stat.getUpdateCount());
                    time = System.currentTimeMillis() - time;
                    buff.append("<br />(").append(time).append(" ms)");
                    stat.close();
                    return buff.toString();
                }
                rs = stat.getResultSet();
            }
        }
        time = System.currentTimeMillis() - time;
        buff.append(getResultSet(sql, rs, metadata, list, edit, time, allowEdit));
        // }
        if (!edit) {
            stat.close();
        }
        return buff.toString();
    } catch (Throwable e) {
        // throwable: including OutOfMemoryError and so on
        return getStackTrace(id, e, session.getContents().isH2());
    } finally {
        session.executingStatement = null;
    }
}
Also used : Profiler(org.h2.util.Profiler) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) DbContents(org.h2.bnf.context.DbContents) ResultSet(java.sql.ResultSet) SimpleResultSet(org.h2.tools.SimpleResultSet) PreparedStatement(java.sql.PreparedStatement)

Aggregations

ResultInterface (org.h2.result.ResultInterface)6 ResultWithGeneratedKeys (org.h2.result.ResultWithGeneratedKeys)4 CommandInterface (org.h2.command.CommandInterface)2 GeneratedKeys (org.h2.engine.GeneratedKeys)2 Expression (org.h2.expression.Expression)2 SequenceValue (org.h2.expression.SequenceValue)2 DbException (org.h2.message.DbException)2 Row (org.h2.result.Row)2 Column (org.h2.table.Column)2 Value (org.h2.value.Value)2 IOException (java.io.IOException)1 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 Statement (java.sql.Statement)1 DbContents (org.h2.bnf.context.DbContents)1 ExpressionColumn (org.h2.expression.ExpressionColumn)1 ResultRemote (org.h2.result.ResultRemote)1 SimpleResultSet (org.h2.tools.SimpleResultSet)1 Profiler (org.h2.util.Profiler)1 Transfer (org.h2.value.Transfer)1