Search in sources :

Example 56 with Prepared

use of org.h2.test.db.Db.Prepared in project h2database by h2database.

the class Table method updateRows.

/**
 * Update a list of rows in this table.
 *
 * @param prepared the prepared statement
 * @param session the session
 * @param rows a list of row pairs of the form old row, new row, old row,
 *            new row,...
 */
public void updateRows(Prepared prepared, Session session, RowList rows) {
    // in case we need to undo the update
    Session.Savepoint rollback = session.setSavepoint();
    // remove the old rows
    int rowScanCount = 0;
    for (rows.reset(); rows.hasNext(); ) {
        if ((++rowScanCount & 127) == 0) {
            prepared.checkCanceled();
        }
        Row o = rows.next();
        rows.next();
        try {
            removeRow(session, o);
        } catch (DbException e) {
            if (e.getErrorCode() == ErrorCode.CONCURRENT_UPDATE_1) {
                session.rollbackTo(rollback, false);
                session.startStatementWithinTransaction();
                rollback = session.setSavepoint();
            }
            throw e;
        }
        session.log(this, UndoLogRecord.DELETE, o);
    }
    // add the new rows
    for (rows.reset(); rows.hasNext(); ) {
        if ((++rowScanCount & 127) == 0) {
            prepared.checkCanceled();
        }
        rows.next();
        Row n = rows.next();
        try {
            addRow(session, n);
        } catch (DbException e) {
            if (e.getErrorCode() == ErrorCode.CONCURRENT_UPDATE_1) {
                session.rollbackTo(rollback, false);
                session.startStatementWithinTransaction();
                rollback = session.setSavepoint();
            }
            throw e;
        }
        session.log(this, UndoLogRecord.INSERT, n);
    }
}
Also used : Row(org.h2.result.Row) SearchRow(org.h2.result.SearchRow) SimpleRow(org.h2.result.SimpleRow) Constraint(org.h2.constraint.Constraint) Session(org.h2.engine.Session) DbException(org.h2.message.DbException)

Example 57 with Prepared

use of org.h2.test.db.Db.Prepared in project h2database by h2database.

the class PgServerThread method process.

private void process() throws IOException {
    int x;
    if (initDone) {
        x = dataInRaw.read();
        if (x < 0) {
            stop = true;
            return;
        }
    } else {
        x = 0;
    }
    int len = dataInRaw.readInt();
    len -= 4;
    byte[] data = Utils.newBytes(len);
    dataInRaw.readFully(data, 0, len);
    dataIn = new DataInputStream(new ByteArrayInputStream(data, 0, len));
    switch(x) {
        case 0:
            server.trace("Init");
            int version = readInt();
            if (version == 80877102) {
                server.trace("CancelRequest");
                int pid = readInt();
                int key = readInt();
                PgServerThread c = server.getThread(pid);
                if (c != null && key == c.secret) {
                    c.cancelRequest();
                } else {
                    // According to the PostgreSQL documentation, when canceling
                    // a request, if an invalid secret is provided then no
                    // exception should be sent back to the client.
                    server.trace("Invalid CancelRequest: pid=" + pid + ", key=" + key);
                }
                close();
            } else if (version == 80877103) {
                server.trace("SSLRequest");
                out.write('N');
            } else {
                server.trace("StartupMessage");
                server.trace(" version " + version + " (" + (version >> 16) + "." + (version & 0xff) + ")");
                while (true) {
                    String param = readString();
                    if (param.length() == 0) {
                        break;
                    }
                    String value = readString();
                    if ("user".equals(param)) {
                        this.userName = value;
                    } else if ("database".equals(param)) {
                        this.databaseName = server.checkKeyAndGetDatabaseName(value);
                    } else if ("client_encoding".equals(param)) {
                        // UTF8
                        clientEncoding = value;
                    } else if ("DateStyle".equals(param)) {
                        if (value.indexOf(',') < 0) {
                            value += ", MDY";
                        }
                        dateStyle = value;
                    }
                    // extra_float_digits 2
                    // geqo on (Genetic Query Optimization)
                    server.trace(" param " + param + "=" + value);
                }
                sendAuthenticationCleartextPassword();
                initDone = true;
            }
            break;
        case 'p':
            {
                server.trace("PasswordMessage");
                String password = readString();
                try {
                    Properties info = new Properties();
                    info.put("MODE", "PostgreSQL");
                    info.put("USER", userName);
                    info.put("PASSWORD", password);
                    String url = "jdbc:h2:" + databaseName;
                    ConnectionInfo ci = new ConnectionInfo(url, info);
                    String baseDir = server.getBaseDir();
                    if (baseDir == null) {
                        baseDir = SysProperties.getBaseDir();
                    }
                    if (baseDir != null) {
                        ci.setBaseDir(baseDir);
                    }
                    if (server.getIfExists()) {
                        ci.setProperty("IFEXISTS", "TRUE");
                    }
                    conn = new JdbcConnection(ci, false);
                    // can not do this because when called inside
                    // DriverManager.getConnection, a deadlock occurs
                    // conn = DriverManager.getConnection(url, userName, password);
                    initDb();
                    sendAuthenticationOk();
                } catch (Exception e) {
                    e.printStackTrace();
                    stop = true;
                }
                break;
            }
        case 'P':
            {
                server.trace("Parse");
                Prepared p = new Prepared();
                p.name = readString();
                p.sql = getSQL(readString());
                int paramTypesCount = readShort();
                int[] paramTypes = null;
                if (paramTypesCount > 0) {
                    paramTypes = new int[paramTypesCount];
                    for (int i = 0; i < paramTypesCount; i++) {
                        paramTypes[i] = readInt();
                    }
                }
                try {
                    p.prep = (JdbcPreparedStatement) conn.prepareStatement(p.sql);
                    ParameterMetaData meta = p.prep.getParameterMetaData();
                    p.paramType = new int[meta.getParameterCount()];
                    for (int i = 0; i < p.paramType.length; i++) {
                        int type;
                        if (i < paramTypesCount && paramTypes[i] != 0) {
                            type = paramTypes[i];
                            server.checkType(type);
                        } else {
                            type = PgServer.convertType(meta.getParameterType(i + 1));
                        }
                        p.paramType[i] = type;
                    }
                    prepared.put(p.name, p);
                    sendParseComplete();
                } catch (Exception e) {
                    sendErrorResponse(e);
                }
                break;
            }
        case 'B':
            {
                server.trace("Bind");
                Portal portal = new Portal();
                portal.name = readString();
                String prepName = readString();
                Prepared prep = prepared.get(prepName);
                if (prep == null) {
                    sendErrorResponse("Prepared not found");
                    break;
                }
                portal.prep = prep;
                portals.put(portal.name, portal);
                int formatCodeCount = readShort();
                int[] formatCodes = new int[formatCodeCount];
                for (int i = 0; i < formatCodeCount; i++) {
                    formatCodes[i] = readShort();
                }
                int paramCount = readShort();
                try {
                    for (int i = 0; i < paramCount; i++) {
                        setParameter(prep.prep, prep.paramType[i], i, formatCodes);
                    }
                } catch (Exception e) {
                    sendErrorResponse(e);
                    break;
                }
                int resultCodeCount = readShort();
                portal.resultColumnFormat = new int[resultCodeCount];
                for (int i = 0; i < resultCodeCount; i++) {
                    portal.resultColumnFormat[i] = readShort();
                }
                sendBindComplete();
                break;
            }
        case 'C':
            {
                char type = (char) readByte();
                String name = readString();
                server.trace("Close");
                if (type == 'S') {
                    Prepared p = prepared.remove(name);
                    if (p != null) {
                        JdbcUtils.closeSilently(p.prep);
                    }
                } else if (type == 'P') {
                    portals.remove(name);
                } else {
                    server.trace("expected S or P, got " + type);
                    sendErrorResponse("expected S or P");
                    break;
                }
                sendCloseComplete();
                break;
            }
        case 'D':
            {
                char type = (char) readByte();
                String name = readString();
                server.trace("Describe");
                if (type == 'S') {
                    Prepared p = prepared.get(name);
                    if (p == null) {
                        sendErrorResponse("Prepared not found: " + name);
                    } else {
                        try {
                            sendParameterDescription(p.prep.getParameterMetaData(), p.paramType);
                            sendRowDescription(p.prep.getMetaData());
                        } catch (Exception e) {
                            sendErrorResponse(e);
                        }
                    }
                } else if (type == 'P') {
                    Portal p = portals.get(name);
                    if (p == null) {
                        sendErrorResponse("Portal not found: " + name);
                    } else {
                        PreparedStatement prep = p.prep.prep;
                        try {
                            ResultSetMetaData meta = prep.getMetaData();
                            sendRowDescription(meta);
                        } catch (Exception e) {
                            sendErrorResponse(e);
                        }
                    }
                } else {
                    server.trace("expected S or P, got " + type);
                    sendErrorResponse("expected S or P");
                }
                break;
            }
        case 'E':
            {
                String name = readString();
                server.trace("Execute");
                Portal p = portals.get(name);
                if (p == null) {
                    sendErrorResponse("Portal not found: " + name);
                    break;
                }
                int maxRows = readShort();
                Prepared prepared = p.prep;
                JdbcPreparedStatement prep = prepared.prep;
                server.trace(prepared.sql);
                try {
                    prep.setMaxRows(maxRows);
                    setActiveRequest(prep);
                    boolean result = prep.execute();
                    if (result) {
                        try {
                            ResultSet rs = prep.getResultSet();
                            // the meta-data is sent in the prior 'Describe'
                            while (rs.next()) {
                                sendDataRow(rs, p.resultColumnFormat);
                            }
                            sendCommandComplete(prep, 0);
                        } catch (Exception e) {
                            sendErrorResponse(e);
                        }
                    } else {
                        sendCommandComplete(prep, prep.getUpdateCount());
                    }
                } catch (Exception e) {
                    if (prep.isCancelled()) {
                        sendCancelQueryResponse();
                    } else {
                        sendErrorResponse(e);
                    }
                } finally {
                    setActiveRequest(null);
                }
                break;
            }
        case 'S':
            {
                server.trace("Sync");
                sendReadyForQuery();
                break;
            }
        case 'Q':
            {
                server.trace("Query");
                String query = readString();
                ScriptReader reader = new ScriptReader(new StringReader(query));
                while (true) {
                    JdbcStatement stat = null;
                    try {
                        String s = reader.readStatement();
                        if (s == null) {
                            break;
                        }
                        s = getSQL(s);
                        stat = (JdbcStatement) conn.createStatement();
                        setActiveRequest(stat);
                        boolean result = stat.execute(s);
                        if (result) {
                            ResultSet rs = stat.getResultSet();
                            ResultSetMetaData meta = rs.getMetaData();
                            try {
                                sendRowDescription(meta);
                                while (rs.next()) {
                                    sendDataRow(rs, null);
                                }
                                sendCommandComplete(stat, 0);
                            } catch (Exception e) {
                                sendErrorResponse(e);
                                break;
                            }
                        } else {
                            sendCommandComplete(stat, stat.getUpdateCount());
                        }
                    } catch (SQLException e) {
                        if (stat != null && stat.isCancelled()) {
                            sendCancelQueryResponse();
                        } else {
                            sendErrorResponse(e);
                        }
                        break;
                    } finally {
                        JdbcUtils.closeSilently(stat);
                        setActiveRequest(null);
                    }
                }
                sendReadyForQuery();
                break;
            }
        case 'X':
            {
                server.trace("Terminate");
                close();
                break;
            }
        default:
            server.trace("Unsupported: " + x + " (" + (char) x + ")");
            break;
    }
}
Also used : SQLException(java.sql.SQLException) JdbcConnection(org.h2.jdbc.JdbcConnection) PreparedStatement(java.sql.PreparedStatement) JdbcPreparedStatement(org.h2.jdbc.JdbcPreparedStatement) DataInputStream(java.io.DataInputStream) SysProperties(org.h2.engine.SysProperties) Properties(java.util.Properties) DbException(org.h2.message.DbException) SQLException(java.sql.SQLException) IOException(java.io.IOException) EOFException(java.io.EOFException) ResultSetMetaData(java.sql.ResultSetMetaData) JdbcStatement(org.h2.jdbc.JdbcStatement) ByteArrayInputStream(java.io.ByteArrayInputStream) ResultSet(java.sql.ResultSet) JdbcResultSet(org.h2.jdbc.JdbcResultSet) StringReader(java.io.StringReader) ConnectionInfo(org.h2.engine.ConnectionInfo) JdbcPreparedStatement(org.h2.jdbc.JdbcPreparedStatement) ParameterMetaData(java.sql.ParameterMetaData) ScriptReader(org.h2.util.ScriptReader)

Example 58 with Prepared

use of org.h2.test.db.Db.Prepared in project h2database by h2database.

the class Parser method parseTruncate.

private Prepared parseTruncate() {
    read("TABLE");
    Table table = readTableOrView();
    TruncateTable command = new TruncateTable(session);
    command.setTable(table);
    return command;
}
Also used : RangeTable(org.h2.table.RangeTable) TruncateTable(org.h2.command.ddl.TruncateTable) CreateTable(org.h2.command.ddl.CreateTable) FunctionTable(org.h2.table.FunctionTable) CreateLinkedTable(org.h2.command.ddl.CreateLinkedTable) Table(org.h2.table.Table) DropTable(org.h2.command.ddl.DropTable) TruncateTable(org.h2.command.ddl.TruncateTable)

Example 59 with Prepared

use of org.h2.test.db.Db.Prepared in project h2database by h2database.

the class Parser method parseComment.

private Prepared parseComment() {
    int type = 0;
    read("ON");
    boolean column = false;
    if (readIf("TABLE") || readIf("VIEW")) {
        type = DbObject.TABLE_OR_VIEW;
    } else if (readIf("COLUMN")) {
        column = true;
        type = DbObject.TABLE_OR_VIEW;
    } else if (readIf("CONSTANT")) {
        type = DbObject.CONSTANT;
    } else if (readIf("CONSTRAINT")) {
        type = DbObject.CONSTRAINT;
    } else if (readIf("ALIAS")) {
        type = DbObject.FUNCTION_ALIAS;
    } else if (readIf("INDEX")) {
        type = DbObject.INDEX;
    } else if (readIf("ROLE")) {
        type = DbObject.ROLE;
    } else if (readIf("SCHEMA")) {
        type = DbObject.SCHEMA;
    } else if (readIf("SEQUENCE")) {
        type = DbObject.SEQUENCE;
    } else if (readIf("TRIGGER")) {
        type = DbObject.TRIGGER;
    } else if (readIf("USER")) {
        type = DbObject.USER;
    } else if (readIf("DOMAIN")) {
        type = DbObject.USER_DATATYPE;
    } else {
        throw getSyntaxError();
    }
    SetComment command = new SetComment(session);
    String objectName;
    if (column) {
        // can't use readIdentifierWithSchema() because
        // it would not read schema.table.column correctly
        // if the db name is equal to the schema name
        ArrayList<String> list = New.arrayList();
        do {
            list.add(readUniqueIdentifier());
        } while (readIf("."));
        schemaName = session.getCurrentSchemaName();
        if (list.size() == 4) {
            if (!equalsToken(database.getShortName(), list.remove(0))) {
                throw DbException.getSyntaxError(sqlCommand, parseIndex, "database name");
            }
        }
        if (list.size() == 3) {
            schemaName = list.remove(0);
        }
        if (list.size() != 2) {
            throw DbException.getSyntaxError(sqlCommand, parseIndex, "table.column");
        }
        objectName = list.get(0);
        command.setColumn(true);
        command.setColumnName(list.get(1));
    } else {
        objectName = readIdentifierWithSchema();
    }
    command.setSchemaName(schemaName);
    command.setObjectName(objectName);
    command.setObjectType(type);
    read("IS");
    command.setCommentExpression(readExpression());
    return command;
}
Also used : SetComment(org.h2.command.ddl.SetComment) ValueString(org.h2.value.ValueString) AlterTableRenameConstraint(org.h2.command.ddl.AlterTableRenameConstraint) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint) AlterTableDropConstraint(org.h2.command.ddl.AlterTableDropConstraint)

Example 60 with Prepared

use of org.h2.test.db.Db.Prepared in project h2database by h2database.

the class Parser method parseAnalyze.

private Prepared parseAnalyze() {
    Analyze command = new Analyze(session);
    if (readIf("TABLE")) {
        Table table = readTableOrView();
        command.setTable(table);
    }
    if (readIf("SAMPLE_SIZE")) {
        command.setTop(readPositiveInt());
    }
    return command;
}
Also used : RangeTable(org.h2.table.RangeTable) TruncateTable(org.h2.command.ddl.TruncateTable) CreateTable(org.h2.command.ddl.CreateTable) FunctionTable(org.h2.table.FunctionTable) CreateLinkedTable(org.h2.command.ddl.CreateLinkedTable) Table(org.h2.table.Table) DropTable(org.h2.command.ddl.DropTable) Analyze(org.h2.command.ddl.Analyze)

Aggregations

Prepared (org.h2.command.Prepared)32 ValueString (org.h2.value.ValueString)16 SQLException (java.sql.SQLException)11 ArrayList (java.util.ArrayList)11 AlterTableDropConstraint (org.h2.command.ddl.AlterTableDropConstraint)11 AlterTableRenameConstraint (org.h2.command.ddl.AlterTableRenameConstraint)11 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)10 Parameter (org.h2.expression.Parameter)10 DbException (org.h2.message.DbException)10 PreparedStatement (java.sql.PreparedStatement)9 Value (org.h2.value.Value)8 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)7 Query (org.h2.command.dml.Query)7 Expression (org.h2.expression.Expression)7 Column (org.h2.table.Column)7 Connection (java.sql.Connection)6 IndexColumn (org.h2.table.IndexColumn)6 ResultSet (java.sql.ResultSet)5 SQLClientInfoException (java.sql.SQLClientInfoException)5 Savepoint (java.sql.Savepoint)5