Search in sources :

Example 96 with Database

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

the class TcpServer method shutdown.

/**
 * Stop the TCP server with the given URL.
 *
 * @param url the database URL
 * @param password the password
 * @param force if the server should be stopped immediately
 * @param all whether all TCP servers that are running in the JVM should be
 *            stopped
 */
public static synchronized void shutdown(String url, String password, boolean force, boolean all) throws SQLException {
    try {
        int port = Constants.DEFAULT_TCP_PORT;
        int idx = url.lastIndexOf(':');
        if (idx >= 0) {
            String p = url.substring(idx + 1);
            if (StringUtils.isNumber(p)) {
                port = Integer.decode(p);
            }
        }
        String db = getManagementDbName(port);
        try {
            org.h2.Driver.load();
        } catch (Throwable e) {
            throw DbException.convert(e);
        }
        for (int i = 0; i < 2; i++) {
            Connection conn = null;
            PreparedStatement prep = null;
            try {
                conn = DriverManager.getConnection("jdbc:h2:" + url + "/" + db, "", password);
                prep = conn.prepareStatement("CALL STOP_SERVER(?, ?, ?)");
                prep.setInt(1, all ? 0 : port);
                prep.setString(2, password);
                prep.setInt(3, force ? SHUTDOWN_FORCE : SHUTDOWN_NORMAL);
                try {
                    prep.execute();
                } catch (SQLException e) {
                    if (force) {
                    // ignore
                    } else {
                        if (e.getErrorCode() != ErrorCode.CONNECTION_BROKEN_1) {
                            throw e;
                        }
                    }
                }
                break;
            } catch (SQLException e) {
                if (i == 1) {
                    throw e;
                }
            } finally {
                JdbcUtils.closeSilently(prep);
                JdbcUtils.closeSilently(conn);
            }
        }
    } catch (Exception e) {
        throw DbException.toSQLException(e);
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) DbException(org.h2.message.DbException) UnknownHostException(java.net.UnknownHostException) SQLException(java.sql.SQLException)

Example 97 with Database

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

the class TestTools method testBackupRestore.

private void testBackupRestore() throws SQLException {
    org.h2.Driver.load();
    String url = "jdbc:h2:" + getBaseDir() + "/testBackupRestore";
    String user = "sa", password = "abc";
    final String fileName = getBaseDir() + "/b2.zip";
    DeleteDbFiles.main("-dir", getBaseDir(), "-db", "testBackupRestore", "-quiet");
    Connection conn = getConnection(url, user, password);
    conn.createStatement().execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
    conn.createStatement().execute("INSERT INTO TEST VALUES(1, 'Hello')");
    conn.close();
    Backup.main("-file", fileName, "-dir", getBaseDir(), "-db", "testBackupRestore", "-quiet");
    DeleteDbFiles.main("-dir", getBaseDir(), "-db", "testBackupRestore", "-quiet");
    Restore.main("-file", fileName, "-dir", getBaseDir(), "-db", "testBackupRestore", "-quiet");
    conn = getConnection("jdbc:h2:" + getBaseDir() + "/testBackupRestore", "sa", "abc");
    ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM TEST");
    assertTrue(rs.next());
    assertFalse(rs.next());
    new AssertThrows(ErrorCode.CANNOT_CHANGE_SETTING_WHEN_OPEN_1) {

        @Override
        public void test() throws SQLException {
            // must fail when the database is in use
            Backup.main("-file", fileName, "-dir", getBaseDir(), "-db", "testBackupRestore");
        }
    };
    conn.close();
    DeleteDbFiles.main("-dir", getBaseDir(), "-db", "testBackupRestore", "-quiet");
}
Also used : AssertThrows(org.h2.test.utils.AssertThrows) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) SimpleResultSet(org.h2.tools.SimpleResultSet)

Example 98 with Database

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

the class TestReopen method logDb.

private synchronized void logDb(String fileName) {
    writeCount++;
    if ((writeCount & (testEvery - 1)) != 0) {
        return;
    }
    if (FileUtils.size(fileName) > maxFileSize) {
        // System.out.println(fileName + " " + IOUtils.length(fileName));
        return;
    }
    System.out.println("+ write #" + writeCount + " verify #" + verifyCount);
    try {
        if (fileName.endsWith(Constants.SUFFIX_PAGE_FILE)) {
            IOUtils.copyFiles(fileName, testDatabase + Constants.SUFFIX_PAGE_FILE);
        } else {
            IOUtils.copyFiles(fileName, testDatabase + Constants.SUFFIX_MV_FILE);
        }
        verifyCount++;
        // avoid using the Engine class to avoid deadlocks
        Properties p = new Properties();
        String userName = getUser();
        p.setProperty("user", userName);
        p.setProperty("password", getPassword());
        String url = "jdbc:h2:" + testDatabase + ";FILE_LOCK=NO;TRACE_LEVEL_FILE=0";
        ConnectionInfo ci = new ConnectionInfo(url, p);
        Database database = new Database(ci, null);
        // close the database
        Session session = database.getSystemSession();
        session.prepare("script to '" + testDatabase + ".sql'").query(0);
        session.prepare("shutdown immediately").update();
        database.removeSession(null);
        // everything OK - return
        return;
    } catch (DbException e) {
        SQLException e2 = DbException.toSQLException(e);
        int errorCode = e2.getErrorCode();
        if (errorCode == ErrorCode.WRONG_USER_OR_PASSWORD) {
            return;
        } else if (errorCode == ErrorCode.FILE_ENCRYPTION_ERROR_1) {
            return;
        }
        e.printStackTrace(System.out);
        throw e;
    } catch (Exception e) {
        // failed
        int errorCode = 0;
        if (e instanceof SQLException) {
            errorCode = ((SQLException) e).getErrorCode();
        }
        if (errorCode == ErrorCode.WRONG_USER_OR_PASSWORD) {
            return;
        } else if (errorCode == ErrorCode.FILE_ENCRYPTION_ERROR_1) {
            return;
        }
        e.printStackTrace(System.out);
    }
    System.out.println("begin ------------------------------ " + writeCount);
    try {
        Recover.execute(fileName.substring(0, fileName.lastIndexOf('/')), null);
    } catch (SQLException e) {
    // ignore
    }
    testDatabase += "X";
    try {
        if (fileName.endsWith(Constants.SUFFIX_PAGE_FILE)) {
            IOUtils.copyFiles(fileName, testDatabase + Constants.SUFFIX_PAGE_FILE);
        } else {
            IOUtils.copyFiles(fileName, testDatabase + Constants.SUFFIX_MV_FILE);
        }
        // avoid using the Engine class to avoid deadlocks
        Properties p = new Properties();
        String url = "jdbc:h2:" + testDatabase + ";FILE_LOCK=NO";
        ConnectionInfo ci = new ConnectionInfo(url, p);
        Database database = new Database(ci, null);
        // close the database
        database.removeSession(null);
    } catch (Exception e) {
        int errorCode = 0;
        if (e instanceof DbException) {
            e = ((DbException) e).getSQLException();
            errorCode = ((SQLException) e).getErrorCode();
        }
        if (errorCode == ErrorCode.WRONG_USER_OR_PASSWORD) {
            return;
        } else if (errorCode == ErrorCode.FILE_ENCRYPTION_ERROR_1) {
            return;
        }
        StringBuilder buff = new StringBuilder();
        StackTraceElement[] list = e.getStackTrace();
        for (int i = 0; i < 10 && i < list.length; i++) {
            buff.append(list[i].toString()).append('\n');
        }
        String s = buff.toString();
        if (!knownErrors.contains(s)) {
            System.out.println(writeCount + " code: " + errorCode + " " + e.toString());
            e.printStackTrace(System.out);
            knownErrors.add(s);
        } else {
            System.out.println(writeCount + " code: " + errorCode);
        }
    }
}
Also used : SQLException(java.sql.SQLException) Database(org.h2.engine.Database) ConnectionInfo(org.h2.engine.ConnectionInfo) Properties(java.util.Properties) DbException(org.h2.message.DbException) SQLException(java.sql.SQLException) Session(org.h2.engine.Session) DbException(org.h2.message.DbException)

Example 99 with Database

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

the class TestShell method test.

@Override
public void test() throws Exception {
    Shell shell = new Shell();
    ByteArrayOutputStream buff = new ByteArrayOutputStream();
    shell.setOut(new PrintStream(buff));
    shell.runTool("-url", "jdbc:h2:mem:", "-driver", "org.h2.Driver", "-user", "sa", "-password", "sa", "-properties", "null", "-sql", "select 'Hello ' || 'World' as hi");
    String s = new String(buff.toByteArray());
    assertContains(s, "HI");
    assertContains(s, "Hello World");
    assertContains(s, "(1 row, ");
    shell = new Shell();
    buff = new ByteArrayOutputStream();
    shell.setOut(new PrintStream(buff));
    shell.runTool("-help");
    s = new String(buff.toByteArray());
    assertContains(s, "Interactive command line tool to access a database using JDBC.");
    test(true);
    test(false);
}
Also used : PrintStream(java.io.PrintStream) Shell(org.h2.tools.Shell) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 100 with Database

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

the class TestFileLockSerialized method testConcurrentReadWrite.

private void testConcurrentReadWrite() throws Exception {
    deleteDb("fileLockSerialized");
    String url = "jdbc:h2:" + getBaseDir() + "/fileLockSerialized";
    String writeUrl = url + ";FILE_LOCK=SERIALIZED;OPEN_NEW=TRUE";
    // ;TRACE_LEVEL_SYSTEM_OUT=3
    // String readUrl = writeUrl + ";ACCESS_MODE_DATA=R";
    trace(" create database");
    Class.forName("org.h2.Driver");
    Connection conn = getConnection(writeUrl, "sa", "sa");
    Statement stat = conn.createStatement();
    stat.execute("create table test(id int primary key)");
    Connection conn3 = getConnection(writeUrl, "sa", "sa");
    PreparedStatement prep3 = conn3.prepareStatement("insert into test values(?)");
    Connection conn2 = getConnection(writeUrl, "sa", "sa");
    Statement stat2 = conn2.createStatement();
    printResult(stat2, "select * from test");
    stat2.execute("create local temporary table temp(name varchar) not persistent");
    printResult(stat2, "select * from temp");
    trace(" insert row 1");
    stat.execute("insert into test values(1)");
    trace(" insert row 2");
    prep3.setInt(1, 2);
    prep3.execute();
    printResult(stat2, "select * from test");
    printResult(stat2, "select * from temp");
    conn.close();
    conn2.close();
    conn3.close();
}
Also used : PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) JdbcConnection(org.h2.jdbc.JdbcConnection) PreparedStatement(java.sql.PreparedStatement)

Aggregations

Database (org.h2.engine.Database)79 SQLException (java.sql.SQLException)45 PreparedStatement (java.sql.PreparedStatement)38 DbException (org.h2.message.DbException)37 ResultSet (java.sql.ResultSet)34 Statement (java.sql.Statement)32 SimpleResultSet (org.h2.tools.SimpleResultSet)32 Connection (java.sql.Connection)27 Table (org.h2.table.Table)25 Value (org.h2.value.Value)25 Column (org.h2.table.Column)22 IOException (java.io.IOException)19 Constraint (org.h2.constraint.Constraint)18 Expression (org.h2.expression.Expression)17 ExpressionColumn (org.h2.expression.ExpressionColumn)17 ValueString (org.h2.value.ValueString)15 ValueExpression (org.h2.expression.ValueExpression)14 Session (org.h2.engine.Session)13 JdbcConnection (org.h2.jdbc.JdbcConnection)13 Schema (org.h2.schema.Schema)13