Search in sources :

Example 6 with Backup

use of org.h2.tools.Backup in project h2database by h2database.

the class TestCrashAPI method getConnection.

private Connection getConnection(int seed, boolean delete) throws SQLException {
    openCount++;
    if (delete) {
        deleteDb();
    }
    // can not use FILE_LOCK=NO, otherwise something could be written into
    // the database in the finalize method
    String add = ";MAX_QUERY_TIMEOUT=10000";
    // int testing;
    // if(openCount >= 32) {
    // int test;
    // Runtime.getRuntime().halt(0);
    // System.exit(1);
    // }
    // System.out.println("now open " + openCount);
    // add += ";TRACE_LEVEL_FILE=3";
    // config.logMode = 2;
    // }
    String dbName = "crashApi" + seed;
    String url = getURL(DIR + "/" + dbName, true) + add;
    // int test;
    // url += ";DB_CLOSE_ON_EXIT=FALSE";
    // int test;
    // url += ";TRACE_LEVEL_FILE=3";
    Connection conn = null;
    String fileName = "temp/backup/db-" + uniqueId++ + ".zip";
    Backup.execute(fileName, getBaseDir() + "/" + DIR, dbName, true);
    // close databases earlier
    System.gc();
    try {
        conn = DriverManager.getConnection(url, "sa", getPassword(""));
        // delete the backup if opening was successful
        FileUtils.delete(fileName);
    } catch (SQLException e) {
        if (e.getErrorCode() == ErrorCode.WRONG_USER_OR_PASSWORD) {
            // delete if the password changed
            FileUtils.delete(fileName);
        }
        throw e;
    }
    int len = random.getInt(50);
    int first = random.getInt(statements.size() - len);
    int end = first + len;
    Statement stat = conn.createStatement();
    stat.execute("SET LOCK_TIMEOUT 10");
    stat.execute("SET WRITE_DELAY 0");
    if (random.nextBoolean()) {
        if (random.nextBoolean()) {
            double g = random.nextGaussian();
            int size = (int) Math.abs(10000 * g * g);
            stat.execute("SET CACHE_SIZE " + size);
        } else {
            stat.execute("SET CACHE_SIZE 0");
        }
    }
    stat.execute("SCRIPT NOPASSWORDS NOSETTINGS");
    for (int i = first; i < end && i < statements.size() && !stopped; i++) {
        try {
            stat.execute("SELECT * FROM TEST WHERE ID=1");
        } catch (Throwable t) {
            printIfBad(seed, -i, -1, t);
        }
        try {
            stat.execute("SELECT * FROM TEST WHERE ID=1 OR ID=1");
        } catch (Throwable t) {
            printIfBad(seed, -i, -1, t);
        }
        String sql = statements.get(i);
        try {
            // if(openCount == 32) {
            // int test;
            // System.out.println("stop!");
            // }
            stat.execute(sql);
        } catch (Throwable t) {
            printIfBad(seed, -i, -1, t);
        }
    }
    if (random.nextBoolean()) {
        try {
            conn.commit();
        } catch (Throwable t) {
            printIfBad(seed, 0, -1, t);
        }
    }
    return conn;
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) CallableStatement(java.sql.CallableStatement) Connection(java.sql.Connection) JdbcConnection(org.h2.jdbc.JdbcConnection) Savepoint(java.sql.Savepoint)

Example 7 with Backup

use of org.h2.tools.Backup in project h2database by h2database.

the class WebApp method tools.

private String tools() {
    try {
        String toolName = (String) attributes.get("tool");
        session.put("tool", toolName);
        String args = (String) attributes.get("args");
        String[] argList = StringUtils.arraySplit(args, ',', false);
        Tool tool = null;
        if ("Backup".equals(toolName)) {
            tool = new Backup();
        } else if ("Restore".equals(toolName)) {
            tool = new Restore();
        } else if ("Recover".equals(toolName)) {
            tool = new Recover();
        } else if ("DeleteDbFiles".equals(toolName)) {
            tool = new DeleteDbFiles();
        } else if ("ChangeFileEncryption".equals(toolName)) {
            tool = new ChangeFileEncryption();
        } else if ("Script".equals(toolName)) {
            tool = new Script();
        } else if ("RunScript".equals(toolName)) {
            tool = new RunScript();
        } else if ("ConvertTraceFile".equals(toolName)) {
            tool = new ConvertTraceFile();
        } else if ("CreateCluster".equals(toolName)) {
            tool = new CreateCluster();
        } else {
            throw DbException.throwInternalError(toolName);
        }
        ByteArrayOutputStream outBuff = new ByteArrayOutputStream();
        PrintStream out = new PrintStream(outBuff, false, "UTF-8");
        tool.setOut(out);
        try {
            tool.runTool(argList);
            out.flush();
            String o = new String(outBuff.toByteArray(), StandardCharsets.UTF_8);
            String result = PageParser.escapeHtml(o);
            session.put("toolResult", result);
        } catch (Exception e) {
            session.put("toolResult", getStackTrace(0, e, true));
        }
    } catch (Exception e) {
        server.traceError(e);
    }
    return "tools.jsp";
}
Also used : ConvertTraceFile(org.h2.tools.ConvertTraceFile) RunScript(org.h2.tools.RunScript) Script(org.h2.tools.Script) PrintStream(java.io.PrintStream) Backup(org.h2.tools.Backup) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Restore(org.h2.tools.Restore) DeleteDbFiles(org.h2.tools.DeleteDbFiles) DbException(org.h2.message.DbException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLException(java.sql.SQLException) JdbcSQLException(org.h2.jdbc.JdbcSQLException) Recover(org.h2.tools.Recover) RunScript(org.h2.tools.RunScript) Tool(org.h2.util.Tool) ChangeFileEncryption(org.h2.tools.ChangeFileEncryption) CreateCluster(org.h2.tools.CreateCluster)

Example 8 with Backup

use of org.h2.tools.Backup in project h2database by h2database.

the class Parser method readCondition.

private Expression readCondition() {
    if (readIf("NOT")) {
        return new ConditionNot(readCondition());
    }
    if (readIf("EXISTS")) {
        read("(");
        Query query = parseSelect();
        // can not reduce expression because it might be a union except
        // query with distinct
        read(")");
        return new ConditionExists(query);
    }
    if (readIf("INTERSECTS")) {
        read("(");
        Expression r1 = readConcat();
        read(",");
        Expression r2 = readConcat();
        read(")");
        return new Comparison(session, Comparison.SPATIAL_INTERSECTS, r1, r2);
    }
    Expression r = readConcat();
    while (true) {
        // special case: NOT NULL is not part of an expression (as in CREATE
        // TABLE TEST(ID INT DEFAULT 0 NOT NULL))
        int backup = parseIndex;
        boolean not = false;
        if (readIf("NOT")) {
            not = true;
            if (isToken("NULL")) {
                // this really only works for NOT NULL!
                parseIndex = backup;
                currentToken = "NOT";
                break;
            }
        }
        if (readIf("LIKE")) {
            Expression b = readConcat();
            Expression esc = null;
            if (readIf("ESCAPE")) {
                esc = readConcat();
            }
            recompileAlways = true;
            r = new CompareLike(database, r, b, esc, false);
        } else if (readIf("ILIKE")) {
            Function function = Function.getFunction(database, "CAST");
            function.setDataType(new Column("X", Value.STRING_IGNORECASE));
            function.setParameter(0, r);
            r = function;
            Expression b = readConcat();
            Expression esc = null;
            if (readIf("ESCAPE")) {
                esc = readConcat();
            }
            recompileAlways = true;
            r = new CompareLike(database, r, b, esc, false);
        } else if (readIf("REGEXP")) {
            Expression b = readConcat();
            recompileAlways = true;
            r = new CompareLike(database, r, b, null, true);
        } else if (readIf("IS")) {
            if (readIf("NOT")) {
                if (readIf("NULL")) {
                    r = new Comparison(session, Comparison.IS_NOT_NULL, r, null);
                } else if (readIf("DISTINCT")) {
                    read("FROM");
                    r = new Comparison(session, Comparison.EQUAL_NULL_SAFE, r, readConcat());
                } else {
                    r = new Comparison(session, Comparison.NOT_EQUAL_NULL_SAFE, r, readConcat());
                }
            } else if (readIf("NULL")) {
                r = new Comparison(session, Comparison.IS_NULL, r, null);
            } else if (readIf("DISTINCT")) {
                read("FROM");
                r = new Comparison(session, Comparison.NOT_EQUAL_NULL_SAFE, r, readConcat());
            } else {
                r = new Comparison(session, Comparison.EQUAL_NULL_SAFE, r, readConcat());
            }
        } else if (readIf("IN")) {
            read("(");
            if (readIf(")")) {
                if (database.getMode().prohibitEmptyInPredicate) {
                    throw getSyntaxError();
                }
                r = ValueExpression.get(ValueBoolean.FALSE);
            } else {
                if (isSelect()) {
                    Query query = parseSelect();
                    // can not be lazy because we have to call
                    // method ResultInterface.containsDistinct
                    // which is not supported for lazy execution
                    query.setNeverLazy(true);
                    r = new ConditionInSelect(database, r, query, false, Comparison.EQUAL);
                } else {
                    ArrayList<Expression> v = New.arrayList();
                    Expression last;
                    do {
                        last = readExpression();
                        v.add(last);
                    } while (readIf(","));
                    if (v.size() == 1 && (last instanceof Subquery)) {
                        Subquery s = (Subquery) last;
                        Query q = s.getQuery();
                        r = new ConditionInSelect(database, r, q, false, Comparison.EQUAL);
                    } else {
                        r = new ConditionIn(database, r, v);
                    }
                }
                read(")");
            }
        } else if (readIf("BETWEEN")) {
            Expression low = readConcat();
            read("AND");
            Expression high = readConcat();
            Expression condLow = new Comparison(session, Comparison.SMALLER_EQUAL, low, r);
            Expression condHigh = new Comparison(session, Comparison.BIGGER_EQUAL, high, r);
            r = new ConditionAndOr(ConditionAndOr.AND, condLow, condHigh);
        } else {
            int compareType = getCompareType(currentTokenType);
            if (compareType < 0) {
                break;
            }
            read();
            if (readIf("ALL")) {
                read("(");
                Query query = parseSelect();
                r = new ConditionInSelect(database, r, query, true, compareType);
                read(")");
            } else if (readIf("ANY") || readIf("SOME")) {
                read("(");
                if (currentTokenType == PARAMETER && compareType == 0) {
                    Parameter p = readParameter();
                    r = new ConditionInParameter(database, r, p);
                } else {
                    Query query = parseSelect();
                    r = new ConditionInSelect(database, r, query, false, compareType);
                }
                read(")");
            } else {
                Expression right = readConcat();
                if (SysProperties.OLD_STYLE_OUTER_JOIN && readIf("(") && readIf("+") && readIf(")")) {
                    // join with (+)
                    if (r instanceof ExpressionColumn && right instanceof ExpressionColumn) {
                        ExpressionColumn leftCol = (ExpressionColumn) r;
                        ExpressionColumn rightCol = (ExpressionColumn) right;
                        ArrayList<TableFilter> filters = currentSelect.getTopFilters();
                        for (TableFilter f : filters) {
                            while (f != null) {
                                leftCol.mapColumns(f, 0);
                                rightCol.mapColumns(f, 0);
                                f = f.getJoin();
                            }
                        }
                        TableFilter leftFilter = leftCol.getTableFilter();
                        TableFilter rightFilter = rightCol.getTableFilter();
                        r = new Comparison(session, compareType, r, right);
                        if (leftFilter != null && rightFilter != null) {
                            int idx = filters.indexOf(rightFilter);
                            if (idx >= 0) {
                                filters.remove(idx);
                                leftFilter.addJoin(rightFilter, true, r);
                            } else {
                                rightFilter.mapAndAddFilter(r);
                            }
                            r = ValueExpression.get(ValueBoolean.TRUE);
                        }
                    }
                } else {
                    r = new Comparison(session, compareType, r, right);
                }
            }
        }
        if (not) {
            r = new ConditionNot(r);
        }
    }
    return r;
}
Also used : ConditionNot(org.h2.expression.ConditionNot) Query(org.h2.command.dml.Query) Subquery(org.h2.expression.Subquery) ConditionIn(org.h2.expression.ConditionIn) ConditionAndOr(org.h2.expression.ConditionAndOr) AlterTableRenameConstraint(org.h2.command.ddl.AlterTableRenameConstraint) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint) AlterTableDropConstraint(org.h2.command.ddl.AlterTableDropConstraint) CompareLike(org.h2.expression.CompareLike) ExpressionColumn(org.h2.expression.ExpressionColumn) Function(org.h2.expression.Function) TableFunction(org.h2.expression.TableFunction) JavaFunction(org.h2.expression.JavaFunction) ConditionInParameter(org.h2.expression.ConditionInParameter) ConditionInSelect(org.h2.expression.ConditionInSelect) Expression(org.h2.expression.Expression) ValueExpression(org.h2.expression.ValueExpression) Comparison(org.h2.expression.Comparison) AlterTableRenameColumn(org.h2.command.ddl.AlterTableRenameColumn) AlterTableAlterColumn(org.h2.command.ddl.AlterTableAlterColumn) Column(org.h2.table.Column) ExpressionColumn(org.h2.expression.ExpressionColumn) IndexColumn(org.h2.table.IndexColumn) TableFilter(org.h2.table.TableFilter) Parameter(org.h2.expression.Parameter) ConditionInParameter(org.h2.expression.ConditionInParameter) ConditionExists(org.h2.expression.ConditionExists)

Example 9 with Backup

use of org.h2.tools.Backup in project h2database by h2database.

the class DbUpgrade method upgrade.

private static void upgrade(ConnectionInfo ci, Properties info) throws SQLException {
    String name = ci.getName();
    String data = name + Constants.SUFFIX_OLD_DATABASE_FILE;
    String index = name + ".index.db";
    String lobs = name + ".lobs.db";
    String backupData = data + ".backup";
    String backupIndex = index + ".backup";
    String backupLobs = lobs + ".backup";
    String script = null;
    try {
        if (scriptInTempDir) {
            new File(Utils.getProperty("java.io.tmpdir", ".")).mkdirs();
            script = File.createTempFile("h2dbmigration", "backup.sql").getAbsolutePath();
        } else {
            script = name + ".script.sql";
        }
        String oldUrl = "jdbc:h2v1_1:" + name + ";UNDO_LOG=0;LOG=0;LOCK_MODE=0";
        String cipher = ci.getProperty("CIPHER", null);
        if (cipher != null) {
            oldUrl += ";CIPHER=" + cipher;
        }
        Connection conn = DriverManager.getConnection(oldUrl, info);
        Statement stat = conn.createStatement();
        String uuid = UUID.randomUUID().toString();
        if (cipher != null) {
            stat.execute("script to '" + script + "' cipher aes password '" + uuid + "' --hide--");
        } else {
            stat.execute("script to '" + script + "'");
        }
        conn.close();
        FileUtils.move(data, backupData);
        FileUtils.move(index, backupIndex);
        if (FileUtils.exists(lobs)) {
            FileUtils.move(lobs, backupLobs);
        }
        ci.removeProperty("IFEXISTS", false);
        conn = new JdbcConnection(ci, true);
        stat = conn.createStatement();
        if (cipher != null) {
            stat.execute("runscript from '" + script + "' cipher aes password '" + uuid + "' --hide--");
        } else {
            stat.execute("runscript from '" + script + "'");
        }
        stat.execute("analyze");
        stat.execute("shutdown compact");
        stat.close();
        conn.close();
        if (deleteOldDb) {
            FileUtils.delete(backupData);
            FileUtils.delete(backupIndex);
            FileUtils.deleteRecursive(backupLobs, false);
        }
    } catch (Exception e) {
        if (FileUtils.exists(backupData)) {
            FileUtils.move(backupData, data);
        }
        if (FileUtils.exists(backupIndex)) {
            FileUtils.move(backupIndex, index);
        }
        if (FileUtils.exists(backupLobs)) {
            FileUtils.move(backupLobs, lobs);
        }
        FileUtils.delete(name + ".h2.db");
        throw DbException.toSQLException(e);
    } finally {
        if (script != null) {
            FileUtils.delete(script);
        }
    }
}
Also used : Statement(java.sql.Statement) Connection(java.sql.Connection) JdbcConnection(org.h2.jdbc.JdbcConnection) JdbcConnection(org.h2.jdbc.JdbcConnection) File(java.io.File) DbException(org.h2.message.DbException) SQLException(java.sql.SQLException)

Example 10 with Backup

use of org.h2.tools.Backup in project h2database by h2database.

the class TestBackup method testConcurrentBackup.

private void testConcurrentBackup() throws SQLException {
    if (config.networked || !config.big) {
        return;
    }
    deleteDb("backup");
    String url = getURL("backup;multi_threaded=true", true);
    Connection conn = getConnection(url);
    final Statement stat = conn.createStatement();
    stat.execute("create table test(id int primary key, name varchar)");
    stat.execute("insert into test select x, 'Hello' from system_range(1, 2)");
    conn.setAutoCommit(false);
    Connection conn1;
    conn1 = getConnection(url);
    final AtomicLong updateEnd = new AtomicLong();
    final Statement stat1 = conn.createStatement();
    Task task = new Task() {

        @Override
        public void call() throws Exception {
            while (!stop) {
                if (System.nanoTime() < updateEnd.get()) {
                    stat.execute("update test set name = 'Hallo'");
                    stat1.execute("checkpoint");
                    stat.execute("update test set name = 'Hello'");
                    stat.execute("commit");
                    stat.execute("checkpoint");
                } else {
                    Thread.sleep(10);
                }
            }
        }
    };
    Connection conn2;
    conn2 = getConnection(url + ";database_event_listener='" + BackupListener.class.getName() + "'");
    Statement stat2 = conn2.createStatement();
    task.execute();
    for (int i = 0; i < 10; i++) {
        updateEnd.set(System.nanoTime() + TimeUnit.SECONDS.toNanos(2));
        stat2.execute("backup to '" + getBaseDir() + "/backup.zip'");
        stat2.execute("checkpoint");
        Restore.execute(getBaseDir() + "/backup.zip", getBaseDir() + "/t" + i, "backup");
        Connection conn3 = getConnection("t" + i + "/backup");
        Statement stat3 = conn3.createStatement();
        stat3.execute("script");
        ResultSet rs = stat3.executeQuery("select * from test where name='Hallo'");
        while (rs.next()) {
            fail();
        }
        conn3.close();
    }
    task.get();
    conn2.close();
    conn.close();
    conn1.close();
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) Task(org.h2.util.Task) Statement(java.sql.Statement) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet)

Aggregations

Connection (java.sql.Connection)5 Statement (java.sql.Statement)4 SQLException (java.sql.SQLException)3 JdbcConnection (org.h2.jdbc.JdbcConnection)3 DbException (org.h2.message.DbException)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 PrintStream (java.io.PrintStream)2 PreparedStatement (java.sql.PreparedStatement)2 ResultSet (java.sql.ResultSet)2 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)2 AlterTableDropConstraint (org.h2.command.ddl.AlterTableDropConstraint)2 AlterTableRenameConstraint (org.h2.command.ddl.AlterTableRenameConstraint)2 ConditionInParameter (org.h2.expression.ConditionInParameter)2 Expression (org.h2.expression.Expression)2 Parameter (org.h2.expression.Parameter)2 ValueExpression (org.h2.expression.ValueExpression)2 File (java.io.File)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1