Search in sources :

Example 81 with User

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

the class TestPgServer method testCancelQuery.

private void testCancelQuery() throws Exception {
    if (!getPgJdbcDriver()) {
        return;
    }
    Server server = createPgServer("-pgPort", "5535", "-pgDaemon", "-key", "pgserver", "mem:pgserver");
    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5535/pgserver", "sa", "sa");
        final Statement stat = conn.createStatement();
        stat.execute("create alias sleep for \"java.lang.Thread.sleep\"");
        // create a table with 200 rows (cancel interval is 127)
        stat.execute("create table test(id int)");
        for (int i = 0; i < 200; i++) {
            stat.execute("insert into test (id) values (rand())");
        }
        Future<Boolean> future = executor.submit(new Callable<Boolean>() {

            @Override
            public Boolean call() throws SQLException {
                return stat.execute("select id, sleep(5) from test");
            }
        });
        // give it a little time to start and then cancel it
        Thread.sleep(100);
        stat.cancel();
        try {
            future.get();
            throw new IllegalStateException();
        } catch (ExecutionException e) {
            assertStartsWith(e.getCause().getMessage(), "ERROR: canceling statement due to user request");
        } finally {
            conn.close();
        }
    } finally {
        server.stop();
        executor.shutdown();
    }
    deleteDb("pgserver");
}
Also used : Server(org.h2.tools.Server) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ExecutorService(java.util.concurrent.ExecutorService) Connection(java.sql.Connection) ExecutionException(java.util.concurrent.ExecutionException)

Example 82 with User

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

the class TestPgServer method testBinaryTypes.

private void testBinaryTypes() throws SQLException {
    if (!getPgJdbcDriver()) {
        return;
    }
    Server server = createPgServer("-pgPort", "5535", "-pgDaemon", "-key", "pgserver", "mem:pgserver");
    try {
        Properties props = new Properties();
        props.setProperty("user", "sa");
        props.setProperty("password", "sa");
        // force binary
        props.setProperty("prepareThreshold", "-1");
        Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5535/pgserver", props);
        Statement stat = conn.createStatement();
        stat.execute("create table test(x1 varchar, x2 int, " + "x3 smallint, x4 bigint, x5 double, x6 float, " + "x7 real, x8 boolean, x9 char, x10 bytea, " + "x11 date, x12 time, x13 timestamp, x14 numeric)");
        PreparedStatement ps = conn.prepareStatement("insert into test values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        ps.setString(1, "test");
        ps.setInt(2, 12345678);
        ps.setShort(3, (short) 12345);
        ps.setLong(4, 1234567890123L);
        ps.setDouble(5, 123.456);
        ps.setFloat(6, 123.456f);
        ps.setFloat(7, 123.456f);
        ps.setBoolean(8, true);
        ps.setByte(9, (byte) 0xfe);
        ps.setBytes(10, new byte[] { 'a', (byte) 0xfe, '\127' });
        ps.setDate(11, Date.valueOf("2015-01-31"));
        ps.setTime(12, Time.valueOf("20:11:15"));
        ps.setTimestamp(13, Timestamp.valueOf("2001-10-30 14:16:10.111"));
        ps.setBigDecimal(14, new BigDecimal("12345678901234567890.12345"));
        ps.execute();
        for (int i = 1; i <= 14; i++) {
            ps.setNull(i, Types.NULL);
        }
        ps.execute();
        ResultSet rs = stat.executeQuery("select * from test");
        assertTrue(rs.next());
        assertEquals("test", rs.getString(1));
        assertEquals(12345678, rs.getInt(2));
        assertEquals((short) 12345, rs.getShort(3));
        assertEquals(1234567890123L, rs.getLong(4));
        assertEquals(123.456, rs.getDouble(5));
        assertEquals(123.456f, rs.getFloat(6));
        assertEquals(123.456f, rs.getFloat(7));
        assertEquals(true, rs.getBoolean(8));
        assertEquals((byte) 0xfe, rs.getByte(9));
        assertEquals(new byte[] { 'a', (byte) 0xfe, '\127' }, rs.getBytes(10));
        assertEquals(Date.valueOf("2015-01-31"), rs.getDate(11));
        assertEquals(Time.valueOf("20:11:15"), rs.getTime(12));
        assertEquals(Timestamp.valueOf("2001-10-30 14:16:10.111"), rs.getTimestamp(13));
        assertEquals(new BigDecimal("12345678901234567890.12345"), rs.getBigDecimal(14));
        assertTrue(rs.next());
        for (int i = 1; i <= 14; i++) {
            assertNull(rs.getObject(i));
        }
        assertFalse(rs.next());
        conn.close();
    } finally {
        server.stop();
    }
}
Also used : Server(org.h2.tools.Server) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Properties(java.util.Properties) BigDecimal(java.math.BigDecimal)

Example 83 with User

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

the class GenerateModels method execute.

/**
 * Generates models from the database.
 *
 * @param url the database URL
 * @param user the user name
 * @param password the password
 * @param schema the schema to read from. null for all schemas.
 * @param table the table to model. null for all tables within schema.
 * @param packageName the package name of the model classes.
 * @param folder destination folder for model classes (package path not
 *            included)
 * @param annotateSchema includes the schema in the table model annotations
 * @param trimStrings automatically trim strings that exceed maxLength
 */
public static void execute(String url, String user, String password, String schema, String table, String packageName, String folder, boolean annotateSchema, boolean trimStrings) throws SQLException {
    Connection conn = null;
    try {
        org.h2.Driver.load();
        conn = DriverManager.getConnection(url, user, password);
        Db db = Db.open(url, user, password.toCharArray());
        DbInspector inspector = new DbInspector(db);
        List<String> models = inspector.generateModel(schema, table, packageName, annotateSchema, trimStrings);
        File parentFile;
        if (StringUtils.isNullOrEmpty(folder)) {
            parentFile = new File(System.getProperty("user.dir"));
        } else {
            parentFile = new File(folder);
        }
        parentFile.mkdirs();
        Pattern p = Pattern.compile("class ([a-zA-Z0-9]+)");
        for (String model : models) {
            Matcher m = p.matcher(model);
            if (m.find()) {
                String className = m.group().substring("class".length()).trim();
                File classFile = new File(parentFile, className + ".java");
                Writer o = new FileWriter(classFile, false);
                PrintWriter writer = new PrintWriter(new BufferedWriter(o));
                writer.write(model);
                writer.close();
                System.out.println("Generated " + classFile.getAbsolutePath());
            }
        }
    } catch (IOException io) {
        throw DbException.convertIOException(io, "could not generate model").getSQLException();
    } finally {
        JdbcUtils.closeSilently(conn);
    }
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) FileWriter(java.io.FileWriter) Connection(java.sql.Connection) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) DbInspector(org.h2.jaqu.DbInspector) File(java.io.File) Db(org.h2.jaqu.Db) PrintWriter(java.io.PrintWriter) BufferedWriter(java.io.BufferedWriter) FileWriter(java.io.FileWriter) Writer(java.io.Writer) PrintWriter(java.io.PrintWriter)

Example 84 with User

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

the class TestMVTableEngine method testEncryption.

private void testEncryption() throws Exception {
    if (config.memory) {
        return;
    }
    deleteDb(getTestName());
    String dbName = getTestName() + ";MV_STORE=TRUE";
    Connection conn;
    Statement stat;
    String url = getURL(dbName + ";CIPHER=AES", true);
    String user = "sa";
    String password = "123 123";
    conn = DriverManager.getConnection(url, user, password);
    stat = conn.createStatement();
    stat.execute("create table test(id int primary key)");
    conn.close();
    conn = DriverManager.getConnection(url, user, password);
    stat = conn.createStatement();
    stat.execute("select * from test");
    stat.execute("drop table test");
    conn.close();
}
Also used : PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) JdbcConnection(org.h2.jdbc.JdbcConnection)

Example 85 with User

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

the class TestConnectionPool method testTimeout.

private void testTimeout() throws Exception {
    String url = getURL("connectionPool", true), user = getUser();
    String password = getPassword();
    final JdbcConnectionPool man = JdbcConnectionPool.create(url, user, password);
    man.setLoginTimeout(1);
    createClassProxy(man.getClass());
    assertThrows(IllegalArgumentException.class, man).setMaxConnections(-1);
    man.setMaxConnections(2);
    // connection 1 (of 2)
    Connection conn = man.getConnection();
    Task t = new Task() {

        @Override
        public void call() {
            while (!stop) {
                // this calls notifyAll
                man.setMaxConnections(1);
                man.setMaxConnections(2);
            }
        }
    };
    t.execute();
    long time = System.nanoTime();
    Connection conn2 = null;
    try {
        // connection 2 (of 1 or 2) may fail
        conn2 = man.getConnection();
        // connection 3 (of 1 or 2) must fail
        man.getConnection();
        fail();
    } catch (SQLException e) {
        if (conn2 != null) {
            conn2.close();
        }
        assertContains(e.toString().toLowerCase(), "timeout");
        time = System.nanoTime() - time;
        assertTrue("timeout after " + TimeUnit.NANOSECONDS.toMillis(time) + " ms", time > TimeUnit.SECONDS.toNanos(1));
    } finally {
        conn.close();
        t.get();
    }
    man.dispose();
}
Also used : Task(org.h2.util.Task) JdbcConnectionPool(org.h2.jdbcx.JdbcConnectionPool) SQLException(java.sql.SQLException) Connection(java.sql.Connection)

Aggregations

Connection (java.sql.Connection)36 SQLException (java.sql.SQLException)21 PreparedStatement (java.sql.PreparedStatement)17 Statement (java.sql.Statement)17 ResultSet (java.sql.ResultSet)16 Server (org.h2.tools.Server)15 DbException (org.h2.message.DbException)14 Column (org.h2.table.Column)12 ValueString (org.h2.value.ValueString)12 Properties (java.util.Properties)10 Database (org.h2.engine.Database)10 Schema (org.h2.schema.Schema)8 IOException (java.io.IOException)7 User (org.h2.engine.User)7 JdbcDataSource (org.h2.jdbcx.JdbcDataSource)7 SimpleResultSet (org.h2.tools.SimpleResultSet)7 Value (org.h2.value.Value)7 PrintStream (java.io.PrintStream)6 Timestamp (java.sql.Timestamp)6 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)6