Search in sources :

Example 1 with Backup

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

the class Parser method parsePrepared.

private Prepared parsePrepared() {
    int start = lastParseIndex;
    Prepared c = null;
    String token = currentToken;
    if (token.length() == 0) {
        c = new NoOperation(session);
    } else {
        char first = token.charAt(0);
        switch(first) {
            case '?':
                // read the ? as a parameter
                readTerm();
                // this is an 'out' parameter - set a dummy value
                parameters.get(0).setValue(ValueNull.INSTANCE);
                read("=");
                read("CALL");
                c = parseCall();
                break;
            case '(':
                c = parseSelect();
                break;
            case 'a':
            case 'A':
                if (readIf("ALTER")) {
                    c = parseAlter();
                } else if (readIf("ANALYZE")) {
                    c = parseAnalyze();
                }
                break;
            case 'b':
            case 'B':
                if (readIf("BACKUP")) {
                    c = parseBackup();
                } else if (readIf("BEGIN")) {
                    c = parseBegin();
                }
                break;
            case 'c':
            case 'C':
                if (readIf("COMMIT")) {
                    c = parseCommit();
                } else if (readIf("CREATE")) {
                    c = parseCreate();
                } else if (readIf("CALL")) {
                    c = parseCall();
                } else if (readIf("CHECKPOINT")) {
                    c = parseCheckpoint();
                } else if (readIf("COMMENT")) {
                    c = parseComment();
                }
                break;
            case 'd':
            case 'D':
                if (readIf("DELETE")) {
                    c = parseDelete();
                } else if (readIf("DROP")) {
                    c = parseDrop();
                } else if (readIf("DECLARE")) {
                    // support for DECLARE GLOBAL TEMPORARY TABLE...
                    c = parseCreate();
                } else if (readIf("DEALLOCATE")) {
                    c = parseDeallocate();
                }
                break;
            case 'e':
            case 'E':
                if (readIf("EXPLAIN")) {
                    c = parseExplain();
                } else if (readIf("EXECUTE")) {
                    c = parseExecute();
                }
                break;
            case 'f':
            case 'F':
                if (isToken("FROM")) {
                    c = parseSelect();
                }
                break;
            case 'g':
            case 'G':
                if (readIf("GRANT")) {
                    c = parseGrantRevoke(CommandInterface.GRANT);
                }
                break;
            case 'h':
            case 'H':
                if (readIf("HELP")) {
                    c = parseHelp();
                }
                break;
            case 'i':
            case 'I':
                if (readIf("INSERT")) {
                    c = parseInsert();
                }
                break;
            case 'm':
            case 'M':
                if (readIf("MERGE")) {
                    c = parseMerge();
                }
                break;
            case 'p':
            case 'P':
                if (readIf("PREPARE")) {
                    c = parsePrepare();
                }
                break;
            case 'r':
            case 'R':
                if (readIf("ROLLBACK")) {
                    c = parseRollback();
                } else if (readIf("REVOKE")) {
                    c = parseGrantRevoke(CommandInterface.REVOKE);
                } else if (readIf("RUNSCRIPT")) {
                    c = parseRunScript();
                } else if (readIf("RELEASE")) {
                    c = parseReleaseSavepoint();
                } else if (readIf("REPLACE")) {
                    c = parseReplace();
                }
                break;
            case 's':
            case 'S':
                if (isToken("SELECT")) {
                    c = parseSelect();
                } else if (readIf("SET")) {
                    c = parseSet();
                } else if (readIf("SAVEPOINT")) {
                    c = parseSavepoint();
                } else if (readIf("SCRIPT")) {
                    c = parseScript();
                } else if (readIf("SHUTDOWN")) {
                    c = parseShutdown();
                } else if (readIf("SHOW")) {
                    c = parseShow();
                }
                break;
            case 't':
            case 'T':
                if (readIf("TRUNCATE")) {
                    c = parseTruncate();
                }
                break;
            case 'u':
            case 'U':
                if (readIf("UPDATE")) {
                    c = parseUpdate();
                } else if (readIf("USE")) {
                    c = parseUse();
                }
                break;
            case 'v':
            case 'V':
                if (readIf("VALUES")) {
                    c = parseValues();
                }
                break;
            case 'w':
            case 'W':
                if (readIf("WITH")) {
                    c = parseWithStatementOrQuery();
                }
                break;
            case ';':
                c = new NoOperation(session);
                break;
            default:
                throw getSyntaxError();
        }
        if (indexedParameterList != null) {
            for (int i = 0, size = indexedParameterList.size(); i < size; i++) {
                if (indexedParameterList.get(i) == null) {
                    indexedParameterList.set(i, new Parameter(i));
                }
            }
            parameters = indexedParameterList;
        }
        if (readIf("{")) {
            do {
                int index = (int) readLong() - 1;
                if (index < 0 || index >= parameters.size()) {
                    throw getSyntaxError();
                }
                Parameter p = parameters.get(index);
                if (p == null) {
                    throw getSyntaxError();
                }
                read(":");
                Expression expr = readExpression();
                expr = expr.optimize(session);
                p.setValue(expr.getValue(session));
            } while (readIf(","));
            read("}");
            for (Parameter p : parameters) {
                p.checkSet();
            }
            parameters.clear();
        }
    }
    if (c == null) {
        throw getSyntaxError();
    }
    setSQL(c, null, start);
    return c;
}
Also used : NoOperation(org.h2.command.dml.NoOperation) Expression(org.h2.expression.Expression) ValueExpression(org.h2.expression.ValueExpression) Parameter(org.h2.expression.Parameter) ConditionInParameter(org.h2.expression.ConditionInParameter) ValueString(org.h2.value.ValueString) AlterTableRenameConstraint(org.h2.command.ddl.AlterTableRenameConstraint) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint) AlterTableDropConstraint(org.h2.command.ddl.AlterTableDropConstraint)

Example 2 with Backup

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

the class Engine method createSessionAndValidate.

private Session createSessionAndValidate(ConnectionInfo ci) {
    try {
        ConnectionInfo backup = null;
        String lockMethodName = ci.getProperty("FILE_LOCK", null);
        FileLockMethod fileLockMethod = FileLock.getFileLockMethod(lockMethodName);
        if (fileLockMethod == FileLockMethod.SERIALIZED) {
            // In serialized mode, database instance sharing is not possible
            ci.setProperty("OPEN_NEW", "TRUE");
            try {
                backup = ci.clone();
            } catch (CloneNotSupportedException e) {
                throw DbException.convert(e);
            }
        }
        Session session = openSession(ci);
        validateUserAndPassword(true);
        if (backup != null) {
            session.setConnectionInfo(backup);
        }
        return session;
    } catch (DbException e) {
        if (e.getErrorCode() == ErrorCode.WRONG_USER_OR_PASSWORD) {
            validateUserAndPassword(false);
        }
        throw e;
    }
}
Also used : FileLockMethod(org.h2.store.FileLockMethod) DbException(org.h2.message.DbException)

Example 3 with Backup

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

the class BackupCommand method backupTo.

private void backupTo(String fileName) {
    Database db = session.getDatabase();
    if (!db.isPersistent()) {
        throw DbException.get(ErrorCode.DATABASE_IS_NOT_PERSISTENT);
    }
    try {
        Store mvStore = db.getMvStore();
        if (mvStore != null) {
            mvStore.flush();
        }
        String name = db.getName();
        name = FileUtils.getName(name);
        try (OutputStream zip = FileUtils.newOutputStream(fileName, false)) {
            ZipOutputStream out = new ZipOutputStream(zip);
            db.flush();
            if (db.getPageStore() != null) {
                String fn = db.getName() + Constants.SUFFIX_PAGE_FILE;
                backupPageStore(out, fn, db.getPageStore());
            }
            // synchronize on the database, to avoid concurrent temp file
            // creation / deletion / backup
            String base = FileUtils.getParent(db.getName());
            synchronized (db.getLobSyncObject()) {
                String prefix = db.getDatabasePath();
                String dir = FileUtils.getParent(prefix);
                dir = FileLister.getDir(dir);
                ArrayList<String> fileList = FileLister.getDatabaseFiles(dir, name, true);
                for (String n : fileList) {
                    if (n.endsWith(Constants.SUFFIX_LOB_FILE)) {
                        backupFile(out, base, n);
                    }
                    if (n.endsWith(Constants.SUFFIX_MV_FILE) && mvStore != null) {
                        MVStore s = mvStore.getStore();
                        boolean before = s.getReuseSpace();
                        s.setReuseSpace(false);
                        try {
                            InputStream in = mvStore.getInputStream();
                            backupFile(out, base, n, in);
                        } finally {
                            s.setReuseSpace(before);
                        }
                    }
                }
            }
            out.close();
        }
    } catch (IOException e) {
        throw DbException.convertIOException(e, fileName);
    }
}
Also used : MVStore(org.h2.mvstore.MVStore) ZipOutputStream(java.util.zip.ZipOutputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) ZipOutputStream(java.util.zip.ZipOutputStream) Database(org.h2.engine.Database) Store(org.h2.mvstore.db.MVTableEngine.Store) PageStore(org.h2.store.PageStore) MVStore(org.h2.mvstore.MVStore) IOException(java.io.IOException)

Example 4 with Backup

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

the class TestWeb method testTools.

private void testTools() throws Exception {
    if (config.memory || config.cipher != null) {
        return;
    }
    deleteDb(getTestName());
    Connection conn = getConnection(getTestName());
    conn.createStatement().execute("create table test(id int) as select 1");
    conn.close();
    Server server = new Server();
    server.setOut(new PrintStream(new ByteArrayOutputStream()));
    server.runTool("-web", "-webPort", "8182", "-properties", "null", "-tcp", "-tcpPort", "9101");
    try {
        String url = "http://localhost:8182";
        WebClient client;
        String result;
        client = new WebClient();
        result = client.get(url);
        client.readSessionId(result);
        result = client.get(url, "tools.jsp");
        FileUtils.delete(getBaseDir() + "/backup.zip");
        result = client.get(url, "tools.do?tool=Backup&args=-dir," + getBaseDir() + ",-db," + getTestName() + ",-file," + getBaseDir() + "/backup.zip");
        deleteDb(getTestName());
        assertTrue(FileUtils.exists(getBaseDir() + "/backup.zip"));
        result = client.get(url, "tools.do?tool=DeleteDbFiles&args=-dir," + getBaseDir() + ",-db," + getTestName());
        String fn = getBaseDir() + "/" + getTestName();
        if (config.mvStore) {
            fn += Constants.SUFFIX_MV_FILE;
        } else {
            fn += Constants.SUFFIX_PAGE_FILE;
        }
        assertFalse(FileUtils.exists(fn));
        result = client.get(url, "tools.do?tool=Restore&args=-dir," + getBaseDir() + ",-db," + getTestName() + ",-file," + getBaseDir() + "/backup.zip");
        assertTrue(FileUtils.exists(fn));
        FileUtils.delete(getBaseDir() + "/web.h2.sql");
        FileUtils.delete(getBaseDir() + "/backup.zip");
        result = client.get(url, "tools.do?tool=Recover&args=-dir," + getBaseDir() + ",-db," + getTestName());
        assertTrue(FileUtils.exists(getBaseDir() + "/" + getTestName() + ".h2.sql"));
        FileUtils.delete(getBaseDir() + "/web.h2.sql");
        result = client.get(url, "tools.do?tool=RunScript&args=-script," + getBaseDir() + "/" + getTestName() + ".h2.sql,-url," + getURL(getTestName(), true) + ",-user," + getUser() + ",-password," + getPassword());
        FileUtils.delete(getBaseDir() + "/" + getTestName() + ".h2.sql");
        assertTrue(FileUtils.exists(fn));
        deleteDb(getTestName());
    } finally {
        server.shutdown();
    }
}
Also used : PrintStream(java.io.PrintStream) Server(org.h2.tools.Server) Connection(java.sql.Connection) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 5 with Backup

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

the class BnfRandom method getRandomSQL.

public String getRandomSQL() {
    int sid = random.nextInt(statements.size());
    RuleHead r = statements.get(sid);
    level = 0;
    r.getRule().accept(this);
    sql = sql.trim();
    if (sql.length() > 0) {
        if (sql.indexOf("TRACE_LEVEL_") < 0 && sql.indexOf("COLLATION") < 0 && sql.indexOf("SCRIPT ") < 0 && sql.indexOf("CSVWRITE") < 0 && sql.indexOf("BACKUP") < 0 && sql.indexOf("DB_CLOSE_DELAY") < 0) {
            if (SHOW_SYNTAX) {
                System.out.println("  " + sql);
            }
            return sql;
        }
    }
    return null;
}
Also used : RuleHead(org.h2.bnf.RuleHead)

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