Search in sources :

Example 11 with RunScript

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

the class TestTools method testRecover.

private void testRecover() throws SQLException {
    if (config.memory) {
        return;
    }
    deleteDb("toolsRecover");
    org.h2.Driver.load();
    String url = getURL("toolsRecover", true);
    Connection conn = getConnection(url, "sa", "sa");
    Statement stat = conn.createStatement();
    stat.execute("create table test(id int primary key, " + "name varchar, b blob, c clob)");
    stat.execute("create table \"test 2\"(id int primary key, name varchar)");
    stat.execute("comment on table test is ';-)'");
    stat.execute("insert into test values" + "(1, 'Hello', SECURE_RAND(4100), '\u00e4' || space(4100))");
    ResultSet rs;
    rs = stat.executeQuery("select * from test");
    rs.next();
    byte[] b1 = rs.getBytes(3);
    String s1 = rs.getString(4);
    conn.close();
    Recover.main("-dir", getBaseDir(), "-db", "toolsRecover");
    // deleteDb would delete the .lob.db directory as well
    // deleteDb("toolsRecover");
    ArrayList<String> list = FileLister.getDatabaseFiles(getBaseDir(), "toolsRecover", true);
    for (String fileName : list) {
        if (!FileUtils.isDirectory(fileName)) {
            FileUtils.delete(fileName);
        }
    }
    conn = getConnection(url);
    stat = conn.createStatement();
    String suffix = ".h2.sql";
    stat.execute("runscript from '" + getBaseDir() + "/toolsRecover" + suffix + "'");
    rs = stat.executeQuery("select * from \"test 2\"");
    assertFalse(rs.next());
    rs = stat.executeQuery("select * from test");
    rs.next();
    assertEquals(1, rs.getInt(1));
    assertEquals("Hello", rs.getString(2));
    byte[] b2 = rs.getBytes(3);
    String s2 = rs.getString(4);
    assertEquals("\u00e4 ", s2.substring(0, 2));
    assertEquals(4100, b2.length);
    assertEquals(4101, s2.length());
    assertEquals(b1, b2);
    assertEquals(s1, s2);
    assertFalse(rs.next());
    conn.close();
    deleteDb("toolsRecover");
    FileUtils.delete(getBaseDir() + "/toolsRecover.h2.sql");
    String dir = getBaseDir() + "/toolsRecover.lobs.db";
    FileUtils.deleteRecursive(dir, false);
}
Also used : PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) SimpleResultSet(org.h2.tools.SimpleResultSet)

Example 12 with RunScript

use of org.h2.tools.RunScript in project ma-core-public by infiniteautomation.

the class H2InMemoryDatabaseProxy method initialize.

/* (non-Javadoc)
     * @see com.serotonin.m2m2.db.DatabaseProxy#initialize(java.lang.ClassLoader)
     */
@Override
public void initialize(ClassLoader classLoader) {
    JdbcDataSource jds = new JdbcDataSource();
    String url = "jdbc:h2:mem:" + databaseName + ";DB_CLOSE_DELAY=-1";
    jds.setUrl(url);
    dataSource = JdbcConnectionPool.create(jds);
    transactionManager = new DataSourceTransactionManager(dataSource);
    if (initWebConsole) {
        String[] webArgs = new String[4];
        webArgs[0] = "-webPort";
        webArgs[1] = webPort.toString();
        webArgs[2] = "-ifExists";
        webArgs[3] = "-webAllowOthers";
        try {
            this.web = Server.createWebServer(webArgs);
            this.web.start();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    ExtendedJdbcTemplate ejt = new ExtendedJdbcTemplate();
    ejt.setDataSource(getDataSource());
    // Create the empty database
    if (!tableExists(ejt, SchemaDefinition.USERS_TABLE)) {
        // The users table wasn't found, so assume that this is a new instance.
        // Create the tables
        runScript(this.getClass().getResourceAsStream("/createTables-" + getType().name() + ".sql"), null);
        for (DatabaseSchemaDefinition def : ModuleRegistry.getDefinitions(DatabaseSchemaDefinition.class)) def.newInstallationCheck(ejt);
        SystemSettingsDao.instance.setValue(SystemSettingsDao.DATABASE_SCHEMA_VERSION, Integer.toString(Common.getDatabaseSchemaVersion()));
        SystemSettingsDao.instance.setValue(SystemSettingsDao.BACKUP_ENABLED, "false");
        SystemSettingsDao.instance.setValue(SystemSettingsDao.DATABASE_BACKUP_ENABLED, "false");
        // Add the settings flag that this is a new instance. This flag is removed when an administrator
        // logs in.
        SystemSettingsDao.instance.setBooleanValue(SystemSettingsDao.NEW_INSTANCE, true);
        Providers.get(IMangoLifecycle.class).addStartupTask(new Runnable() {

            @Override
            public void run() {
                // New database. Create a default user.
                User user = new User();
                user.setId(Common.NEW_ID);
                user.setName("Administrator");
                user.setUsername("admin");
                user.setPassword(Common.encrypt("admin"));
                user.setEmail("admin@yourMangoDomain.com");
                user.setPhone("");
                user.setPermissions(SuperadminPermissionDefinition.GROUP_NAME);
                user.setDisabled(false);
                UserDao.instance.saveUser(user);
                DefaultDataPointPropertiesTemplateFactory factory = new DefaultDataPointPropertiesTemplateFactory();
                factory.saveDefaultTemplates();
            }
        });
    }
    // Check if we are using NoSQL
    if (NoSQLProxyFactory.instance.getProxy() != null) {
        noSQLProxy = NoSQLProxyFactory.instance.getProxy();
        noSQLProxy.initialize();
    }
    initialized = true;
}
Also used : User(com.serotonin.m2m2.vo.User) SQLException(java.sql.SQLException) DatabaseSchemaDefinition(com.serotonin.m2m2.module.DatabaseSchemaDefinition) JdbcDataSource(org.h2.jdbcx.JdbcDataSource) DefaultDataPointPropertiesTemplateFactory(com.serotonin.m2m2.vo.template.DefaultDataPointPropertiesTemplateFactory) ExtendedJdbcTemplate(com.serotonin.db.spring.ExtendedJdbcTemplate) DataSourceTransactionManager(org.springframework.jdbc.datasource.DataSourceTransactionManager)

Aggregations

Connection (java.sql.Connection)8 Statement (java.sql.Statement)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 PrintStream (java.io.PrintStream)4 PreparedStatement (java.sql.PreparedStatement)4 ResultSet (java.sql.ResultSet)4 SQLException (java.sql.SQLException)4 Recover (org.h2.tools.Recover)3 SimpleResultSet (org.h2.tools.SimpleResultSet)3 JdbcConnection (org.h2.jdbc.JdbcConnection)2 DbException (org.h2.message.DbException)2 RunScript (org.h2.tools.RunScript)2 ExtendedJdbcTemplate (com.serotonin.db.spring.ExtendedJdbcTemplate)1 DatabaseSchemaDefinition (com.serotonin.m2m2.module.DatabaseSchemaDefinition)1 User (com.serotonin.m2m2.vo.User)1 DefaultDataPointPropertiesTemplateFactory (com.serotonin.m2m2.vo.template.DefaultDataPointPropertiesTemplateFactory)1 File (java.io.File)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 DbContents (org.h2.bnf.context.DbContents)1 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)1