java.sql.Connection

Here are the examples of the java api class java.sql.Connection taken from open source projects.

1. TestJDBC40Exception#testTimeout()

Project: derby
Source File: TestJDBC40Exception.java
View license
public void testTimeout() throws SQLException {
    Connection con1 = openDefaultConnection();
    Connection con2 = openDefaultConnection();
    con1.setAutoCommit(false);
    con2.setAutoCommit(false);
    con1.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
    con2.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
    con1.createStatement().execute("select * from EXCEPTION_TABLE1 for update");
    try {
        con2.createStatement().execute("select * from EXCEPTION_TABLE1 for update");
        fail("Statement didn't fail.");
    } catch (SQLTransactionRollbackException e) {
        assertTrue("Unexpected SQL State: " + e.getSQLState(), e.getSQLState().startsWith("40"));
    }
    con1.rollback();
    con1.close();
    con2.rollback();
    con2.close();
}

2. TestConnectionPool#testAutoCommitBehavior()

View license
@Test
public void testAutoCommitBehavior() throws Exception {
    final Connection conn0 = newConnection();
    assertNotNull("connection should not be null", conn0);
    assertTrue("autocommit should be true for conn0", conn0.getAutoCommit());
    final Connection conn1 = newConnection();
    assertTrue("autocommit should be true for conn1", conn1.getAutoCommit());
    conn1.close();
    assertTrue("autocommit should be true for conn0", conn0.getAutoCommit());
    conn0.setAutoCommit(false);
    assertFalse("autocommit should be false for conn0", conn0.getAutoCommit());
    conn0.close();
    final Connection conn2 = newConnection();
    assertTrue("autocommit should be true for conn2", conn2.getAutoCommit());
    final Connection conn3 = newConnection();
    assertTrue("autocommit should be true for conn3", conn3.getAutoCommit());
    conn2.close();
    conn3.close();
}

3. DataSourceConnectionSourceTest#testDscsSetUrl()

View license
@Test
public void testDscsSetUrl() throws Exception {
    DataSource dataSource = createMock(DataSource.class);
    Connection conn = createMock(Connection.class);
    conn.setAutoCommit(true);
    conn.setAutoCommit(true);
    conn.setAutoCommit(false);
    expect(conn.getAutoCommit()).andReturn(false);
    conn.setAutoCommit(true);
    conn.close();
    conn.close();
    conn.close();
    expect(dataSource.getConnection()).andReturn(conn);
    expect(dataSource.getConnection()).andReturn(conn);
    expect(dataSource.getConnection()).andReturn(conn);
    replay(dataSource, conn);
    DataSourceConnectionSource dcs = new DataSourceConnectionSource();
    dcs.setDataSource(dataSource);
    dcs.setDatabaseUrl(DEFAULT_DATABASE_URL);
    dcs.initialize();
    DatabaseConnection jdbcConn = dcs.getReadOnlyConnection(TABLE_NAME);
    jdbcConn.close();
    dcs.close();
    verify(dataSource, conn);
}

4. TestTransaction#testForUpdate()

Project: ThriftyPaxos
Source File: TestTransaction.java
View license
private void testForUpdate() throws SQLException {
    deleteDb("transaction");
    Connection conn = getConnection("transaction");
    conn.setAutoCommit(false);
    Statement stat = conn.createStatement();
    stat.execute("create table test(id int primary key, name varchar)");
    stat.execute("insert into test values(1, 'Hello'), (2, 'World')");
    conn.commit();
    PreparedStatement prep = conn.prepareStatement("select * from test where id = 1 for update");
    prep.execute();
    // releases the lock
    conn.commit();
    prep.execute();
    Connection conn2 = getConnection("transaction");
    conn2.setAutoCommit(false);
    Statement stat2 = conn2.createStatement();
    if (config.mvcc) {
        stat2.execute("update test set name = 'Welt' where id = 2");
    }
    assertThrows(ErrorCode.LOCK_TIMEOUT_1, stat2).execute("update test set name = 'Hallo' where id = 1");
    conn2.close();
    conn.close();
}

5. TestTransaction#testConcurrentSelectForUpdate()

Project: ThriftyPaxos
Source File: TestTransaction.java
View license
private void testConcurrentSelectForUpdate() throws SQLException {
    deleteDb("transaction");
    Connection conn = getConnection("transaction");
    conn.setAutoCommit(false);
    Statement stat = conn.createStatement();
    stat.execute("create table test(id int primary key, name varchar)");
    stat.execute("insert into test values(1, 'Hello'), (2, 'World')");
    conn.commit();
    PreparedStatement prep = conn.prepareStatement("select * from test for update");
    prep.execute();
    Connection conn2 = getConnection("transaction");
    conn2.setAutoCommit(false);
    assertThrows(ErrorCode.LOCK_TIMEOUT_1, conn2.createStatement()).execute("select * from test for update");
    conn2.close();
    conn.close();
}

6. TestPerUserPoolDataSource#testTransactionIsolationBehavior()

View license
@Test
public void testTransactionIsolationBehavior() throws Exception {
    final Connection conn = getConnection();
    assertNotNull(conn);
    assertEquals(Connection.TRANSACTION_READ_COMMITTED, conn.getTransactionIsolation());
    conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    conn.close();
    final Connection conn2 = getConnection();
    assertEquals(Connection.TRANSACTION_READ_COMMITTED, conn2.getTransactionIsolation());
    final Connection conn3 = getConnection();
    assertEquals(Connection.TRANSACTION_READ_COMMITTED, conn3.getTransactionIsolation());
    conn2.close();
    conn3.close();
}

7. TestSharedPoolDataSource#testTransactionIsolationBehavior()

View license
@Test
public void testTransactionIsolationBehavior() throws Exception {
    final Connection conn = getConnection();
    assertNotNull(conn);
    assertEquals(Connection.TRANSACTION_READ_COMMITTED, conn.getTransactionIsolation());
    conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    conn.close();
    final Connection conn2 = getConnection();
    assertEquals(Connection.TRANSACTION_READ_COMMITTED, conn2.getTransactionIsolation());
    final Connection conn3 = getConnection();
    assertEquals(Connection.TRANSACTION_READ_COMMITTED, conn3.getTransactionIsolation());
    conn2.close();
    conn3.close();
}

8. TestBasicDataSource#testTransactionIsolationBehavior()

View license
@Test
public void testTransactionIsolationBehavior() throws Exception {
    final Connection conn = getConnection();
    assertNotNull(conn);
    assertEquals(Connection.TRANSACTION_READ_COMMITTED, conn.getTransactionIsolation());
    conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    conn.close();
    final Connection conn2 = getConnection();
    assertEquals(Connection.TRANSACTION_READ_COMMITTED, conn2.getTransactionIsolation());
    final Connection conn3 = getConnection();
    assertEquals(Connection.TRANSACTION_READ_COMMITTED, conn3.getTransactionIsolation());
    conn2.close();
    conn3.close();
}

9. SetTransactionIsolationTest#testSetTransactionIsolationCommitRollback()

View license
/**
     * setTransactionIsolation commits?
     */
public void testSetTransactionIsolationCommitRollback() throws SQLException {
    Connection conn = getConnection();
    conn.rollback();
    conn.setAutoCommit(false);
    conn.setTransactionIsolation(java.sql.Connection.TRANSACTION_SERIALIZABLE);
    Statement s = conn.createStatement();
    s.executeUpdate("delete from t3");
    s.executeUpdate("insert into t3 values(1)");
    conn.commit();
    s.executeUpdate("insert into t3 values(2)");
    conn.setTransactionIsolation(java.sql.Connection.TRANSACTION_SERIALIZABLE);
    conn.rollback();
    ResultSet rs = s.executeQuery("select count(*) from t3");
    rs.next();
    int count = rs.getInt(1);
    assertEquals(1, count);
    rs.close();
    s.close();
}

10. TestCPDSConnectionFactory#testSharedPoolDSDestroyOnReturn()

View license
/**
     * JIRA DBCP-216
     *
     * Check PoolableConnection close triggered by destroy is handled
     * properly. PooledConnectionProxy (dubiously) fires connectionClosed
     * when PooledConnection itself is closed.
     */
@Test
public void testSharedPoolDSDestroyOnReturn() throws Exception {
    final PerUserPoolDataSource ds = new PerUserPoolDataSource();
    ds.setConnectionPoolDataSource(cpds);
    ds.setPerUserMaxTotal("username", Integer.valueOf(10));
    ds.setPerUserMaxWaitMillis("username", Long.valueOf(50));
    ds.setPerUserMaxIdle("username", Integer.valueOf(2));
    final Connection conn1 = ds.getConnection("username", "password");
    final Connection conn2 = ds.getConnection("username", "password");
    final Connection conn3 = ds.getConnection("username", "password");
    assertEquals(3, ds.getNumActive("username"));
    conn1.close();
    assertEquals(1, ds.getNumIdle("username"));
    conn2.close();
    assertEquals(2, ds.getNumIdle("username"));
    // Return to pool will trigger destroy -> close sequence
    conn3.close();
    assertEquals(2, ds.getNumIdle("username"));
    ds.close();
}

11. TestKeyedCPDSConnectionFactory#testSharedPoolDSDestroyOnReturn()

View license
/**
     * JIRA DBCP-216
     *
     * Check PoolableConnection close triggered by destroy is handled
     * properly. PooledConnectionProxy (dubiously) fires connectionClosed
     * when PooledConnection itself is closed.
     */
@Test
public void testSharedPoolDSDestroyOnReturn() throws Exception {
    final SharedPoolDataSource ds = new SharedPoolDataSource();
    ds.setConnectionPoolDataSource(cpds);
    ds.setMaxTotal(10);
    ds.setDefaultMaxWaitMillis(50);
    ds.setDefaultMaxIdle(2);
    final Connection conn1 = ds.getConnection("username", "password");
    final Connection conn2 = ds.getConnection("username", "password");
    final Connection conn3 = ds.getConnection("username", "password");
    assertEquals(3, ds.getNumActive());
    conn1.close();
    assertEquals(1, ds.getNumIdle());
    conn2.close();
    assertEquals(2, ds.getNumIdle());
    // Return to pool will trigger destroy -> close sequence
    conn3.close();
    assertEquals(2, ds.getNumIdle());
    ds.close();
}

12. J2EEDataSourceTest#doTestSchemaIsReset()

Project: derby
Source File: J2EEDataSourceTest.java
View license
/**
     * Executes a test sequence to make sure the schema (and with DERBY-4551,
     * current user) is correctly reset between logical connections.
     *
     * @param pc pooled connection to get logical connections from
     * @param userSchema name of the default schema for the connection (user)
     * @throws SQLException if something goes wrong...
     */
private void doTestSchemaIsReset(PooledConnection pc, String userSchema) throws SQLException {
    Connection con1 = pc.getConnection();
    JDBC.assertCurrentSchema(con1, userSchema);
    JDBC.assertCurrentUser(con1, userSchema);
    Statement stmt1 = con1.createStatement();
    // Change the schema.
    stmt1.execute("set schema APP");
    stmt1.close();
    JDBC.assertCurrentSchema(con1, "APP");
    JDBC.assertCurrentUser(con1, userSchema);
    // Close the logical connection and get a new one.
    con1.close();
    Connection con2 = pc.getConnection();
    // Make sure the schema has been reset from APP to the user name.
    JDBC.assertCurrentSchema(con2, userSchema);
    JDBC.assertCurrentUser(con2, userSchema);
    con2.close();
    // Try a third time, but don't change the schema now.
    Connection con3 = pc.getConnection();
    JDBC.assertCurrentSchema(con3, userSchema);
    JDBC.assertCurrentUser(con3, userSchema);
    con3.close();
    pc.close();
}

13. SavepointJdbc30Test#testSwapSavepointsAcrossConnectionAndRelease()

Project: derby
Source File: SavepointJdbc30Test.java
View license
/**
     * Test 7a: BUG 4468 - should not be able to pass a savepoint from a
     * different transaction for release/rollback
     */
public void testSwapSavepointsAcrossConnectionAndRelease() throws SQLException {
    Connection con = getConnection();
    Connection con2 = openDefaultConnection();
    con2.setAutoCommit(false);
    Savepoint savepoint1 = con2.setSavepoint("s1");
    Statement s = createStatement();
    s.executeUpdate("INSERT INTO T1 VALUES(2,1)");
    con.setSavepoint("s1");
    try {
        con.releaseSavepoint(savepoint1);
        fail("FAIL 7a - releasing a another transaction's savepoint did " + "not raise error");
    } catch (SQLException se) {
        if (usingEmbedded()) {
            assertSQLState("3B502", se);
        } else if (usingDerbyNetClient()) {
            assertSQLState("XJ097", se);
        }
    }
    con.commit();
    con2.commit();
}

14. SavepointJdbc30Test#testSwapSavepointsAcrossConnectionsAndRollback()

Project: derby
Source File: SavepointJdbc30Test.java
View license
/**
     * Test 7b - swap savepoints across connections
     */
public void testSwapSavepointsAcrossConnectionsAndRollback() throws SQLException {
    Connection con = getConnection();
    Connection con2 = openDefaultConnection();
    con2.setAutoCommit(false);
    Savepoint savepoint1 = con2.setSavepoint("s1");
    Statement s = createStatement();
    s.executeUpdate("INSERT INTO T1 VALUES(2,1)");
    con.setSavepoint("s1");
    try {
        con.rollback(savepoint1);
        fail("FAIL 7b - rolling back a another transaction's savepoint " + "did not raise error");
    } catch (SQLException se) {
        if (usingEmbedded()) {
            assertSQLState("3B502", se);
        } else if (usingDerbyNetClient()) {
            assertSQLState("XJ097", se);
        }
    }
    con.commit();
    con2.commit();
}

15. SequenceTest#test_08_DropOtherSchemaSequence()

Project: derby
Source File: SequenceTest.java
View license
/**
     * Test trying to drop a sequence in a schema that doesn't belong to one
     */
public void test_08_DropOtherSchemaSequence() throws SQLException {
    Connection adminCon = openUserConnection(TEST_DBO);
    Connection alphaCon = openUserConnection(ALPHA);
    Statement stmtAlpha = alphaCon.createStatement();
    stmtAlpha.executeUpdate("CREATE SEQUENCE alpha_seq");
    Connection betaCon = openUserConnection(BETA);
    Statement stmtBeta = betaCon.createStatement();
    // should implicitly create schema ALPHA
    assertStatementError("42507", stmtBeta, "DROP SEQUENCE alpha.alpha_seq restrict");
    // Cleanup:
    stmtAlpha.executeUpdate("DROP SEQUENCE alpha_seq restrict");
    stmtAlpha.close();
    stmtBeta.close();
    alphaCon.close();
    betaCon.close();
    adminCon.close();
}

16. SequenceTest#test_09_CreateOtherSchemaSequence()

Project: derby
Source File: SequenceTest.java
View license
/**
     * Test trying to create a sequence in a schema that doesn't belong to one
     */
public void test_09_CreateOtherSchemaSequence() throws SQLException {
    // create DB
    Connection adminCon = openUserConnection(TEST_DBO);
    Connection alphaCon = openUserConnection(ALPHA);
    Statement stmtAlpha = alphaCon.createStatement();
    stmtAlpha.executeUpdate("CREATE SEQUENCE alpha_seq");
    Connection betaCon = openUserConnection(BETA);
    Statement stmtBeta = betaCon.createStatement();
    // should implicitly create schema ALPHA
    assertStatementError("42507", stmtBeta, "CREATE SEQUENCE alpha.alpha_seq3");
    // Cleanup:
    stmtAlpha.executeUpdate("DROP SEQUENCE alpha_seq restrict");
    stmtAlpha.close();
    stmtBeta.close();
    alphaCon.close();
    betaCon.close();
    adminCon.close();
}

17. FlywayMediumTest#connectionCount()

Project: flyway
Source File: FlywayMediumTest.java
View license
/**
     * Tests the functionality of the OpenConnectionCountDriverDataSource.
     */
@Test
public void connectionCount() throws Exception {
    OpenConnectionCountDriverDataSource dataSource = new OpenConnectionCountDriverDataSource();
    assertEquals(0, dataSource.getOpenConnectionCount());
    Connection connection = dataSource.getConnection();
    assertEquals(1, dataSource.getOpenConnectionCount());
    connection.close();
    assertEquals(0, dataSource.getOpenConnectionCount());
    Connection connection2 = dataSource.getConnection();
    assertEquals(1, dataSource.getOpenConnectionCount());
    Connection connection3 = dataSource.getConnection();
    assertEquals(2, dataSource.getOpenConnectionCount());
    connection2.close();
    assertEquals(1, dataSource.getOpenConnectionCount());
    connection3.close();
    assertEquals(0, dataSource.getOpenConnectionCount());
}

18. MiscTest#xtestLocking()

Project: pgjdbc
Source File: MiscTest.java
View license
public void xtestLocking() throws Exception {
    Connection con = TestUtil.openDB();
    Connection con2 = TestUtil.openDB();
    TestUtil.createTable(con, "test_lock", "name text");
    Statement st = con.createStatement();
    Statement st2 = con2.createStatement();
    con.setAutoCommit(false);
    st.execute("lock table test_lock");
    st2.executeUpdate("insert into test_lock ( name ) values ('hello')");
    con.commit();
    TestUtil.dropTable(con, "test_lock");
    con.close();
    con2.close();
}

19. TestCases#testSelectForUpdate()

Project: ThriftyPaxos
Source File: TestCases.java
View license
private void testSelectForUpdate() throws SQLException {
    trace("testSelectForUpdate");
    deleteDb("cases");
    Connection conn1 = getConnection("cases");
    Statement stat1 = conn1.createStatement();
    stat1.execute("CREATE TABLE TEST(ID INT)");
    stat1.execute("INSERT INTO TEST VALUES(1)");
    conn1.setAutoCommit(false);
    stat1.execute("SELECT * FROM TEST FOR UPDATE");
    Connection conn2 = getConnection("cases");
    Statement stat2 = conn2.createStatement();
    assertThrows(ErrorCode.LOCK_TIMEOUT_1, stat2).execute("UPDATE TEST SET ID=2");
    conn1.commit();
    stat2.execute("UPDATE TEST SET ID=2");
    conn1.close();
    conn2.close();
}

20. TestMvcc2#testSelectForUpdate()

Project: ThriftyPaxos
Source File: TestMvcc2.java
View license
private void testSelectForUpdate() throws SQLException {
    Connection conn = getConnection("mvcc2;SELECT_FOR_UPDATE_MVCC=true");
    Connection conn2 = getConnection("mvcc2;SELECT_FOR_UPDATE_MVCC=true");
    Statement stat = conn.createStatement();
    stat.execute("create table test(id int primary key, name varchar)");
    conn.setAutoCommit(false);
    stat.execute("insert into test select x, 'Hello' from system_range(1, 10)");
    stat.execute("select * from test where id = 3 for update");
    conn.commit();
    assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, stat).execute("select sum(id) from test for update");
    assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, stat).execute("select distinct id from test for update");
    assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, stat).execute("select id from test group by id for update");
    assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, stat).execute("select t1.id from test t1, test t2 for update");
    stat.execute("select * from test where id = 3 for update");
    conn2.setAutoCommit(false);
    conn2.createStatement().execute("select * from test where id = 4 for update");
    assertThrows(ErrorCode.LOCK_TIMEOUT_1, conn2.createStatement()).execute("select * from test where id = 3 for update");
    conn.close();
}

21. TestMVTableEngine#testTimeout()

Project: ThriftyPaxos
Source File: TestMVTableEngine.java
View license
private void testTimeout() throws Exception {
    FileUtils.deleteRecursive(getBaseDir(), true);
    Connection conn;
    Connection conn2;
    Statement stat;
    Statement stat2;
    String url = "mvstore;MV_STORE=TRUE;MVCC=TRUE";
    url = getURL(url, true);
    conn = getConnection(url);
    stat = conn.createStatement();
    stat.execute("create table test(id identity, name varchar)");
    conn2 = getConnection(url);
    stat2 = conn2.createStatement();
    conn.setAutoCommit(false);
    conn2.setAutoCommit(false);
    stat.execute("insert into test values(1, 'Hello')");
    assertThrows(ErrorCode.LOCK_TIMEOUT_1, stat2).execute("insert into test values(1, 'Hello')");
    conn2.close();
    conn.close();
}

22. TestFileLockSerialized#testWrongDatabaseInstanceOnReconnect()

View license
private void testWrongDatabaseInstanceOnReconnect() throws Exception {
    deleteDb("fileLockSerialized");
    String urlShared = "jdbc:h2:" + getBaseDir() + "/fileLockSerialized;FILE_LOCK=SERIALIZED";
    String urlForNew = urlShared + ";OPEN_NEW=TRUE";
    Connection connShared1 = getConnection(urlShared);
    Statement statement1 = connShared1.createStatement();
    Connection connShared2 = getConnection(urlShared);
    Connection connNew = getConnection(urlForNew);
    statement1.execute("create table test1(id int)");
    connShared1.close();
    connShared2.close();
    connNew.close();
    deleteDb("fileLockSerialized");
}

23. TestLinkedTable#testLinkDrop()

Project: ThriftyPaxos
Source File: TestLinkedTable.java
View license
private static void testLinkDrop() throws SQLException {
    org.h2.Driver.load();
    Connection connA = DriverManager.getConnection("jdbc:h2:mem:a");
    Statement statA = connA.createStatement();
    statA.execute("CREATE TABLE TEST(ID INT)");
    Connection connB = DriverManager.getConnection("jdbc:h2:mem:b");
    Statement statB = connB.createStatement();
    statB.execute("CREATE LINKED TABLE " + "TEST_LINK('', 'jdbc:h2:mem:a', '', '', 'TEST')");
    connA.close();
    // the connection should be closed now
    // (and the table should disappear because the last connection was
    // closed)
    statB.execute("DROP TABLE TEST_LINK");
    connA = DriverManager.getConnection("jdbc:h2:mem:a");
    statA = connA.createStatement();
    // table should not exist now
    statA.execute("CREATE TABLE TEST(ID INT)");
    connA.close();
    connB.close();
}

24. TestTransaction#testSetTransaction()

Project: ThriftyPaxos
Source File: TestTransaction.java
View license
private void testSetTransaction() throws SQLException {
    deleteDb("transaction");
    Connection conn = getConnection("transaction");
    conn.setAutoCommit(false);
    Statement stat = conn.createStatement();
    stat.execute("create table test(id int)");
    stat.execute("insert into test values(1)");
    stat.execute("set @x = 1");
    conn.commit();
    assertSingleValue(stat, "select id from test", 1);
    assertSingleValue(stat, "call @x", 1);
    stat.execute("update test set id=2");
    stat.execute("set @x = 2");
    conn.rollback();
    assertSingleValue(stat, "select id from test", 1);
    assertSingleValue(stat, "call @x", 2);
    conn.close();
}

25. TestCancel#testQueryTimeoutInTransaction()

Project: ThriftyPaxos
Source File: TestCancel.java
View license
private void testQueryTimeoutInTransaction() throws SQLException {
    deleteDb("cancel");
    Connection conn = getConnection("cancel");
    Statement stat = conn.createStatement();
    stat.execute("CREATE TABLE TEST(ID INT)");
    conn.setAutoCommit(false);
    stat.execute("INSERT INTO TEST VALUES(1)");
    Savepoint sp = conn.setSavepoint();
    stat.execute("INSERT INTO TEST VALUES(2)");
    stat.setQueryTimeout(1);
    conn.rollback(sp);
    conn.commit();
    conn.close();
}

26. TestMvcc2#testInsertUpdateRollback()

Project: ThriftyPaxos
Source File: TestMvcc2.java
View license
private void testInsertUpdateRollback() throws SQLException {
    Connection conn = getConnection();
    conn.setAutoCommit(false);
    Statement stmt = conn.createStatement();
    stmt.execute(DROP_TABLE);
    stmt.execute(CREATE_TABLE);
    conn.commit();
    stmt.execute(INSERT);
    stmt.execute(UPDATE);
    conn.rollback();
    conn.close();
}

27. TestMVTableEngine#testManyTransactions()

Project: ThriftyPaxos
Source File: TestMVTableEngine.java
View license
private void testManyTransactions() throws Exception {
    deleteDb("testManyTransactions");
    Connection conn = getConnection("testManyTransactions");
    Statement stat = conn.createStatement();
    stat.execute("create table test()");
    conn.setAutoCommit(false);
    stat.execute("insert into test values()");
    Connection conn2 = getConnection("testManyTransactions");
    Statement stat2 = conn2.createStatement();
    for (long i = 0; i < 100000; i++) {
        stat2.execute("insert into test values()");
    }
    conn2.close();
    conn.close();
}

28. TestPageStoreCoverage#testLongTransaction()

View license
private void testLongTransaction() throws SQLException {
    Connection conn;
    conn = getConnection(URL);
    Statement stat = conn.createStatement();
    stat.execute("create table test(id identity, name varchar)");
    conn.setAutoCommit(false);
    stat.execute("insert into test " + "select null, space(10) from system_range(1, 10)");
    Connection conn2;
    conn2 = getConnection(URL);
    Statement stat2 = conn2.createStatement();
    stat2.execute("checkpoint");
    // large transaction
    stat2.execute("create table test2(id identity, name varchar)");
    stat2.execute("create index idx_test2_name on test2(name)");
    stat2.execute("insert into test2 " + "select null, x || space(10000) from system_range(1, 100)");
    stat2.execute("drop table test2");
    conn2.close();
    stat.execute("drop table test");
    conn.close();
}

29. JdbcSharedConnectionTest#testSharedConnectionInLocalTransaction()

Project: btm
Source File: JdbcSharedConnectionTest.java
View license
public void testSharedConnectionInLocalTransaction() throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("*** Starting testSharedConnectionInLocalTransaction: getting connection from DS1");
    }
    Connection connection1 = poolingDataSource1.getConnection();
    // createStatement causes enlistment
    connection1.createStatement();
    if (log.isDebugEnabled()) {
        log.debug("*** getting second connection from DS1");
    }
    Connection connection2 = poolingDataSource1.getConnection();
    PooledConnectionProxy handle1 = (PooledConnectionProxy) connection1;
    PooledConnectionProxy handle2 = (PooledConnectionProxy) connection2;
    assertNotSame(handle1.getProxiedDelegate(), handle2.getProxiedDelegate());
    connection1.close();
    connection2.close();
}

30. JdbcSharedConnectionTest#testUnSharedConnectionInLocalTransaction()

Project: btm
Source File: JdbcSharedConnectionTest.java
View license
public void testUnSharedConnectionInLocalTransaction() throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("*** Starting testUnSharedConnectionInLocalTransaction: getting connection from DS2");
    }
    Connection connection1 = poolingDataSource2.getConnection();
    // createStatement causes enlistment
    connection1.createStatement();
    if (log.isDebugEnabled()) {
        log.debug("*** getting second connection from DS2");
    }
    Connection connection2 = poolingDataSource2.getConnection();
    PooledConnectionProxy handle1 = (PooledConnectionProxy) connection1;
    PooledConnectionProxy handle2 = (PooledConnectionProxy) connection2;
    assertNotSame(handle1.getProxiedDelegate(), handle2.getProxiedDelegate());
    connection1.close();
    connection2.close();
}

31. TestBasicDataSource#testInvalidateConnection()

View license
@Test
public void testInvalidateConnection() throws Exception {
    ds.setMaxTotal(2);
    final Connection conn1 = ds.getConnection();
    final Connection conn2 = ds.getConnection();
    ds.invalidateConnection(conn1);
    assertTrue(conn1.isClosed());
    assertEquals(1, ds.getNumActive());
    assertEquals(0, ds.getNumIdle());
    final Connection conn3 = ds.getConnection();
    conn2.close();
    conn3.close();
}

32. metadataMultiConnTest#testMetadataMultiConn()

Project: derby
Source File: metadataMultiConnTest.java
View license
public void testMetadataMultiConn() throws SQLException {
    Connection conn1 = openDefaultConnection();
    metadataCalls(conn1);
    Connection conn2 = openDefaultConnection();
    metadataCalls(conn2);
    Connection conn3 = openDefaultConnection();
    metadataCalls(conn3);
    conn1.commit();
    conn2.commit();
    checkConsistencyOfAllTables(conn3);
}

33. ResultSetMiscTest#testBug4810()

Project: derby
Source File: ResultSetMiscTest.java
View license
/**
     * Test fix for Bug4810 -Connection.commit() & rollback() do not
     * commit/rollback in auto-commit mode.
     */
public void testBug4810() throws SQLException {
    Connection con = getConnection();
    Statement stmt = con.createStatement();
    stmt.executeUpdate("create table bug4810(i int, b int)");
    stmt.executeUpdate("insert into bug4810 values (1,1), (1,2), (1,3), (1,4)");
    stmt.executeUpdate("insert into bug4810 values (1,1), (1,2), (1,3), (1,4)");
    con.commit();
    con.setAutoCommit(true);
    con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
    // Just autocommit
    checkLocksForAutoCommitSelect(con, stmt, 0);
    // commit with autocommit
    checkLocksForAutoCommitSelect(con, stmt, 1);
    // rollback with autocommit
    checkLocksForAutoCommitSelect(con, stmt, 2);
    stmt.execute("drop table bug4810");
    con.commit();
    stmt.close();
}

34. SavepointJdbc30Test#testSavepointFromEarlierTransactionAfterToggleAutocommit()

Project: derby
Source File: SavepointJdbc30Test.java
View license
/**
     * Test 13 shouldn't be able to use a savepoint from earlier transaction
     * after setting autocommit on and off
     */
public void testSavepointFromEarlierTransactionAfterToggleAutocommit() throws SQLException {
    Connection con = getConnection();
    Savepoint savepoint1 = con.setSavepoint("MyName");
    con.setAutoCommit(true);
    con.setAutoCommit(false);
    Savepoint savepoint2 = con.setSavepoint("MyName1");
    try {
        // shouldn't be able to use savepoint from earlier tranasaction
        // after setting autocommit on and off
        con.releaseSavepoint(savepoint1);
        fail("FAIL 13 shouldn't be able to use a savepoint from earlier " + "transaction after setting autocommit on and off");
    } catch (SQLException se) {
        assertSQLState("3B001", se);
    }
    con.releaseSavepoint(savepoint2);
    con.rollback();
}

35. SavepointJdbc30Test#xtestGetSavepoint()

Project: derby
Source File: SavepointJdbc30Test.java
View license
/**
     * Test 47 multiple tests for getSavepointId()
     */
public void xtestGetSavepoint() throws SQLException {
    Connection con = getConnection();
    Savepoint savepoint1 = con.setSavepoint();
    Savepoint savepoint2 = con.setSavepoint();
    savepoint1.getSavepointId();
    savepoint2.getSavepointId();
    con.releaseSavepoint(savepoint2);
    savepoint2 = con.setSavepoint();
    savepoint2.getSavepointId();
    con.commit();
    savepoint2 = con.setSavepoint();
    savepoint2.getSavepointId();
    con.rollback();
    savepoint2 = con.setSavepoint();
    savepoint2.getSavepointId();
    con.rollback();
}

36. SequenceGeneratorTest#test_14_6553()

Project: derby
Source File: SequenceGeneratorTest.java
View license
/**
     * <p>
     * Verify that we don't get an internal error when creating a sequence-invoking trigger.
     * See DERBY-6553.
     * </p>
     */
public void test_14_6553() throws Exception {
    Connection dboConn = openUserConnection(TEST_DBO);
    //
    // The original DERBY-6553 test case.
    //
    goodStatement(dboConn, "create table t1_6553_1(x int, y int, z int)");
    goodStatement(dboConn, "create table t2_6553_1(x int, y int, z int)");
    goodStatement(dboConn, "create sequence seq_6553_1");
    goodStatement(dboConn, "values next value for seq_6553_1");
    goodStatement(dboConn, "create trigger tr1 after insert on t1_6553_1 insert into t2_6553_1(x) values (next value for seq_6553_1)");
    //
    // The abbreviated test case.
    //
    dboConn.setAutoCommit(false);
    goodStatement(dboConn, "create sequence seq_6553");
    dboConn.commit();
    goodStatement(dboConn, "values next value for seq_6553");
    expectExecutionError(dboConn, DUPLICATE_SEQUENCE, "create sequence seq_6553");
    dboConn.rollback();
    dboConn.setAutoCommit(true);
}

37. TruncateTableTest#testCursor()

Project: derby
Source File: TruncateTableTest.java
View license
/**
     * Test that TRUNCATE TABLE and DROP TABLE do not cause held cursors
     * to trip across an NPE. See DERBY-268.
     */
public void testCursor() throws Exception {
    Connection cursorConnection = openUserConnection(ALICE);
    Connection truncatorConnection = openUserConnection(ALICE);
    cursorConnection.setAutoCommit(false);
    truncatorConnection.setAutoCommit(false);
    cursorMinion(cursorConnection, truncatorConnection, "truncateTab", "truncate table ");
    cursorMinion(cursorConnection, truncatorConnection, "dropTab", "drop table ");
    cursorConnection.close();
}

38. ConnectionWrapperFactoryTest#testWrapperDelegatesAllButClose()

View license
@Test
public void testWrapperDelegatesAllButClose() throws Exception {
    Connection wrapped = wrap(connection, closeHandler);
    wrapped.commit();
    verify(closeHandler).commit(connection);
    wrapped.getAutoCommit();
    verify(connection).getAutoCommit();
    verifyZeroInteractions(closeHandler);
    wrapped.close();
    verify(connection, never()).close();
    verify(closeHandler).close(connection);
}

39. JdbcSharedConnectionTest#testSharedConnectionInGlobal()

Project: btm
Source File: JdbcSharedConnectionTest.java
View license
public void testSharedConnectionInGlobal() throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("*** testSharedConnectionInGlobal: Starting getting TM");
    }
    BitronixTransactionManager tm = TransactionManagerServices.getTransactionManager();
    tm.setTransactionTimeout(120);
    if (log.isDebugEnabled()) {
        log.debug("*** before begin");
    }
    tm.begin();
    if (log.isDebugEnabled()) {
        log.debug("*** after begin");
    }
    if (log.isDebugEnabled()) {
        log.debug("*** getting connection from DS1");
    }
    Connection connection1 = poolingDataSource1.getConnection();
    if (log.isDebugEnabled()) {
        log.debug("*** getting second connection from DS1");
    }
    Connection connection2 = poolingDataSource1.getConnection();
    PooledConnectionProxy handle1 = (PooledConnectionProxy) connection1;
    PooledConnectionProxy handle2 = (PooledConnectionProxy) connection2;
    assertSame(handle1.getProxiedDelegate(), handle2.getProxiedDelegate());
    connection1.close();
    connection2.close();
    tm.commit();
}

40. TestDataSourceXAConnectionFactory#testPhysicalClose()

View license
/**
     * JIRA: DBCP-355
     */
@Test
public void testPhysicalClose() throws Exception {
    bmds.setMaxIdle(1);
    final Connection conn1 = bmds.getConnection();
    final Connection conn2 = bmds.getConnection();
    closeCounter.set(0);
    conn1.close();
    // stays idle in the pool
    assertEquals(0, closeCounter.get());
    conn2.close();
    // can't have 2 idle ones
    assertEquals(1, closeCounter.get());
    bmds.close();
    assertEquals(2, closeCounter.get());
}

41. TestManagedDataSource#testNestedConnections()

View license
@Test
public void testNestedConnections() throws Exception {
    transactionManager.begin();
    Connection c1 = null;
    Connection c2 = null;
    c1 = newConnection();
    c2 = newConnection();
    transactionManager.commit();
    c1.close();
    c2.close();
}

42. TestPoolingDriver#testReportedBug28912()

Project: commons-dbcp
Source File: TestPoolingDriver.java
View license
/** "http://issues.apache.org/bugzilla/show_bug.cgi?id=28912" */
@Test
public void testReportedBug28912() throws Exception {
    final Connection conn1 = getConnection();
    assertNotNull(conn1);
    assertFalse(conn1.isClosed());
    conn1.close();
    final Connection conn2 = getConnection();
    assertNotNull(conn2);
    assertTrue(conn1.isClosed());
    assertFalse(conn2.isClosed());
    // should be able to call close multiple times with no effect
    conn1.close();
    assertTrue(conn1.isClosed());
    assertFalse(conn2.isClosed());
}

43. TestPStmtPooling#testMultipleClose()

Project: commons-dbcp
Source File: TestPStmtPooling.java
View license
/**
     * Verifies that executing close() on an already closed DelegatingStatement
     * that wraps a PoolablePreparedStatement does not "re-close" the PPS
     * (which could be in use by another client - see DBCP-414).
     */
@Test
public void testMultipleClose() throws Exception {
    final DataSource ds = createPDS();
    PreparedStatement stmt1 = null;
    final Connection conn = ds.getConnection();
    stmt1 = conn.prepareStatement("select 1 from dual");
    final PoolablePreparedStatement<?> pps1 = getPoolablePreparedStatement(stmt1);
    conn.close();
    // Closing conn should close stmt
    assertTrue(stmt1.isClosed());
    // Should already be closed - no-op
    stmt1.close();
    assertTrue(stmt1.isClosed());
    final Connection conn2 = ds.getConnection();
    final PreparedStatement stmt2 = conn2.prepareStatement("select 1 from dual");
    // Confirm stmt2 now wraps the same PPS wrapped by stmt1
    Assert.assertSame(pps1, getPoolablePreparedStatement(stmt2));
    // close should not cascade to PPS that stmt1 used to wrap
    stmt1.close();
    assertTrue(!stmt2.isClosed());
    // wrapped PPS needs to work here - pre DBCP-414 fix this throws
    stmt2.executeQuery();
    conn2.close();
    assertTrue(stmt1.isClosed());
    assertTrue(stmt2.isClosed());
}

44. TestPStmtPoolingBasicDataSource#testPStmtCatalog()

View license
// Bugzilla Bug 27246
// PreparedStatement cache should be different depending on the Catalog
@Test
public void testPStmtCatalog() throws Exception {
    final Connection conn = getConnection();
    conn.setCatalog("catalog1");
    final DelegatingPreparedStatement stmt1 = (DelegatingPreparedStatement) conn.prepareStatement("select 'a' from dual");
    final TesterPreparedStatement inner1 = (TesterPreparedStatement) stmt1.getInnermostDelegate();
    assertEquals("catalog1", inner1.getCatalog());
    stmt1.close();
    conn.setCatalog("catalog2");
    final DelegatingPreparedStatement stmt2 = (DelegatingPreparedStatement) conn.prepareStatement("select 'a' from dual");
    final TesterPreparedStatement inner2 = (TesterPreparedStatement) stmt2.getInnermostDelegate();
    assertEquals("catalog2", inner2.getCatalog());
    stmt2.close();
    conn.setCatalog("catalog1");
    final DelegatingPreparedStatement stmt3 = (DelegatingPreparedStatement) conn.prepareStatement("select 'a' from dual");
    final TesterPreparedStatement inner3 = (TesterPreparedStatement) stmt3.getInnermostDelegate();
    assertEquals("catalog1", inner3.getCatalog());
    stmt3.close();
    assertNotSame(inner1, inner2);
    assertSame(inner1, inner3);
}

45. J2EEDataSourceTest#testConnectionFlowCommit()

Project: derby
Source File: J2EEDataSourceTest.java
View license
/**
     * check whether commit without statement will flow by checking its transaction id
     * on client. This test is run only for client where commits without an
     * active transactions will not flow to the server.
     * DERBY-4653
     * 
     * @throws SQLException
     **/
public void testConnectionFlowCommit() throws SQLException {
    ConnectionPoolDataSource ds = J2EEDataSource.getConnectionPoolDataSource();
    PooledConnection pc = ds.getPooledConnection();
    Connection conn = pc.getConnection();
    testConnectionFlowCommitWork(conn);
    conn.close();
    //Test for XADataSource
    XADataSource xs = J2EEDataSource.getXADataSource();
    XAConnection xc = xs.getXAConnection();
    conn = xc.getConnection();
    testConnectionFlowCommitWork(conn);
    conn.close();
    //Test for DataSource
    DataSource jds = JDBCDataSource.getDataSource();
    conn = jds.getConnection();
    testConnectionFlowCommitWork(conn);
    conn.close();
}

46. J2EEDataSourceTest#testDerby3799()

Project: derby
Source File: J2EEDataSourceTest.java
View license
/**
     * Regression test for a NullPointerException when trying to use the LOB
     * stored procedures after closing and then getting a new logical
     * connection. The problem was that the LOB stored procedure objects on the
     * server side were closed and not reprepared.
     * See Jira issue DERBY-3799.
     */
public void testDerby3799() throws SQLException {
    ConnectionPoolDataSource cpDs = J2EEDataSource.getConnectionPoolDataSource();
    PooledConnection pc = cpDs.getPooledConnection();
    // Get first logical connection.
    Connection con1 = pc.getConnection();
    Statement stmt = con1.createStatement();
    ResultSet rs = stmt.executeQuery("select dClob from derby3799");
    assertTrue(rs.next());
    rs.getString(1);
    rs.close();
    con1.close();
    // Get second logical connection.
    Connection con2 = pc.getConnection();
    stmt = con2.createStatement();
    rs = stmt.executeQuery("select dClob from derby3799");
    assertTrue(rs.next());
    // NPE happened here.
    rs.getString(1);
    con2.close();
}

47. J2EEDataSourceTest#assertPooledConnIso()

Project: derby
Source File: J2EEDataSourceTest.java
View license
/**
     * Test that isolation is reset on PooledConnection.getConnection()
     * @param pooledConnType   Descripiton of the type of pooled connection
     * @param pc               PooledConnection or XAConnection  
     * @throws SQLException
     */
private void assertPooledConnIso(String pooledConnType, PooledConnection pc) throws SQLException {
    Connection conn = pc.getConnection();
    setupDerby1144Table(conn);
    // *** Test isolation level reset on conntype.getConnection()          
    conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    assertIsoLocks(conn, Connection.TRANSACTION_READ_UNCOMMITTED);
    conn.close();
    //Get a new connection with pooledConnType.getConnection()
    // Isolation level should be reset to READ_COMMITTED
    Connection newconn = pc.getConnection();
    assertIsoLocks(newconn, Connection.TRANSACTION_READ_COMMITTED);
}

48. SavepointJdbc30Test#testReleaseSavepointFromOtherTransaction()

Project: derby
Source File: SavepointJdbc30Test.java
View license
/**
     * Test 6c: TEST case just for bug 4467 // Test 10 - create a named
     * savepoint with the a generated name savepoint1 =
     * con2.setSavepoint("SAVEPT0"); // what exactly is the correct behaviour
     * here? try { savepoint2 = con2.setSavepoint(); } catch (SQLException se) {
     * System.out.println("Expected Exception is " + se.getMessage()); }
     * con2.commit();
     */
public void testReleaseSavepointFromOtherTransaction() throws SQLException {
    Connection con = getConnection();
    Savepoint savepoint1 = con.setSavepoint("s1");
    Statement s = createStatement();
    s.executeUpdate("INSERT INTO T1 VALUES(2,1)");
    Connection con2 = openDefaultConnection();
    try {
        con2.releaseSavepoint(savepoint1);
        fail("FAIL 6c - releasing another transaction's savepoint did " + "not raise error");
    } catch (SQLException se) {
        if (usingEmbedded()) {
            assertSQLState("XJ010", se);
        } else if (usingDerbyNetClient()) {
            assertSQLState("XJ008", se);
        }
    }
    con.commit();
    con2.commit();
}

49. SavepointJdbc30Test#xtestReuseNameAfterRelease()

Project: derby
Source File: SavepointJdbc30Test.java
View license
/**
     * Test43 - After releasing a savepoint, should be able to reuse it.
     */
public void xtestReuseNameAfterRelease() throws SQLException {
    Connection con = getConnection();
    Savepoint savepoint1 = con.setSavepoint("s1");
    try {
        con.setSavepoint("s1");
        fail("Should not be able to set two savepoints with the same name");
    } catch (SQLException se) {
        if (usingEmbedded()) {
            assertSQLState("3B501", se);
        } else if (usingDerbyNetClient()) {
            assertSQLState("3B002", se);
        }
    }
    con.releaseSavepoint(savepoint1);
    con.setSavepoint("s1");
    con.rollback();
}

50. SetTransactionIsolationTest#testIsolation()

View license
/**
     * test setting of isolation levels with and without lock timeouts
     * @throws SQLException
     */
public void testIsolation() throws SQLException {
    Connection conn = getConnection();
    Connection conn2 = openDefaultConnection();
    conn.setAutoCommit(false);
    // test with no lock timeouts
    for (int i = 0; i < isoLevels.length; i++) {
        checkIsolationLevelNoTimeout(conn, isoLevels[i]);
    }
    // Now do an insert to create lock timeout
    Statement stmt = conn.createStatement();
    stmt.executeUpdate("insert into t1 values(4,'Fourth Hello')");
    for (int i = 0; i < isoLevels.length; i++) checkIsolationLevelTimeout(conn2, isoLevels[i]);
    stmt.close();
    // rollback to cleanup locks from insert
    conn.rollback();
}

51. SequenceTest#test_04_ImplicitSchemaCreation()

Project: derby
Source File: SequenceTest.java
View license
public void test_04_ImplicitSchemaCreation() throws SQLException {
    Connection adminCon = openUserConnection(TEST_DBO);
    Connection alphaCon = openUserConnection(ALPHA);
    Statement stmt = alphaCon.createStatement();
    // should implicitly create schema ALPHA
    stmt.executeUpdate("CREATE SEQUENCE alpha_seq");
    stmt.executeUpdate("DROP SEQUENCE alpha_seq restrict");
    stmt.close();
    alphaCon.close();
    adminCon.close();
}

52. ViewsTest#testSelectViewFromOtherSchemaWithNoDefaultSchema()

Project: derby
Source File: ViewsTest.java
View license
/**
    * DERBY-3270 Test that we can select from a view in another schema if the
    * default schema does not exist.
    *
    * @throws SQLException
    */
public void testSelectViewFromOtherSchemaWithNoDefaultSchema() throws SQLException {
    Connection conn = openDefaultConnection("joe", "joepass");
    Statement st = conn.createStatement();
    st.execute("create table mytable(a int)");
    st.execute("insert into mytable values (99)");
    st.execute("create view myview as select * from mytable");
    st.close();
    conn.close();
    Connection conn2 = openDefaultConnection("bill", "billpass");
    Statement st2 = conn2.createStatement();
    ResultSet rs = st2.executeQuery("SELECT * FROM JOE.MYVIEW");
    JDBC.assertFullResultSet(rs, new String[][] { { "99" } });
    st2.executeUpdate("drop view joe.myview");
    st2.executeUpdate("drop table joe.mytable");
    st2.close();
    conn2.close();
}

53. RecoveryTest#testBasicRecovery()

Project: derby
Source File: RecoveryTest.java
View license
/**
     * Tests the recovery of database. The test achieves its purpose 
     * as follows:
     * Connect, create a table, commit and shutdown the database.
     * fork a jvm, add one row, commit, add another row, exit the jvm(killed).
     * Reconnect with the first jvm and verify that the first row is there 
     * and the second is not. 
     * When a new JVM connects, the log entries are read one by one and it 
     * then rolls back to the transaction boundaries, then the database is
     * in a consistent state. 
     * @throws Exception
     */
public void testBasicRecovery() throws Exception {
    Connection c = getConnection();
    c.setAutoCommit(false);
    Statement st = createStatement();
    st.executeUpdate("create table t( i int )");
    c.commit();
    TestConfiguration.getCurrent().shutdownDatabase();
    st.close();
    c.close();
    //fork JVM
    assertLaunchedJUnitTestMethod("org.apache.derbyTesting.functionTests.tests.store.RecoveryTest.launchRecoveryInsert");
    st = createStatement();
    ResultSet rs = st.executeQuery("select i from t");
    JDBC.assertFullResultSet(rs, new String[][] { { "1956" } });
}

54. AbstractConnectionProxyFactoryTest#testNewInstance()

View license
@Test
public void testNewInstance() throws SQLException {
    Connection target = Mockito.mock(Connection.class);
    ConnectionPoolCallback callback = Mockito.mock(ConnectionPoolCallback.class);
    Connection proxy = newConnectionProxyFactory().newInstance(target, callback);
    verify(callback, times(1)).acquireConnection();
    verify(callback, never()).releaseConnection(anyLong());
    proxy.clearWarnings();
    proxy.close();
    verify(target, times(1)).clearWarnings();
    verify(callback, times(1)).releaseConnection(anyLong());
    verifyNoMoreInteractions(callback);
}

55. TestCrossDbOps#testNegativeUserPrivileges()

View license
/**
   * Test Case 2.14 admin user create a new database DB_1 create TABLE_1 in DB_1
   * admin user grant INSERT to user1's group on TABLE_1 negative test case:
   * user1 try to do following on TABLE_1 will fail: --explain --analyze
   * --describe --describe function --show columns --show table status --show
   * table properties --show create table --show partitions --show indexes
   * --select * from TABLE_1.
   */
@Test
public void testNegativeUserPrivileges() throws Exception {
    Connection adminCon = context.createConnection(ADMIN1);
    Statement adminStmt = context.createStatement(adminCon);
    adminStmt.execute("use default");
    adminStmt.execute("CREATE DATABASE " + DB1);
    adminStmt.execute("create table " + DB1 + ".table_1 (id int)");
    adminStmt.execute("create table " + DB1 + ".table_2 (id int)");
    adminStmt.close();
    adminCon.close();
    // edit policy file
    policyFile.addRolesToGroup(USERGROUP1, "db1_tab1_insert", "db1_tab2_all").addPermissionsToRole("db1_tab2_all", "server=server1->db=" + DB1 + "->table=table_2").addPermissionsToRole("db1_tab1_insert", "server=server1->db=" + DB1 + "->table=table_1->action=insert").setUserGroupMapping(StaticUserGroup.getStaticMapping());
    writePolicyFile(policyFile);
    Connection userConn = context.createConnection(USER1_1);
    Statement userStmt = context.createStatement(userConn);
    context.assertAuthzException(userStmt, "select * from " + DB1 + ".table_1");
    userConn.close();
    userStmt.close();
}

56. TestCrossDbOps#testNegativeUserDMLPrivileges()

View license
/**
   * Test Case 2.16 admin user create a new database DB_1 create TABLE_1 and
   * TABLE_2 (same schema) in DB_1 admin user grant SELECT, INSERT to user1's
   * group on TABLE_2 negative test case: user1 try to do following on TABLE_1
   * will fail: --insert overwrite TABLE_2 select * from TABLE_1
   */
@Test
public void testNegativeUserDMLPrivileges() throws Exception {
    createDb(ADMIN1, DB1);
    Connection adminCon = context.createConnection(ADMIN1);
    Statement adminStmt = context.createStatement(adminCon);
    adminStmt.execute("create table " + DB1 + ".table_1 (id int)");
    adminStmt.execute("create table " + DB1 + ".table_2 (id int)");
    adminStmt.close();
    adminCon.close();
    policyFile.addPermissionsToRole("db1_tab2_all", "server=server1->db=" + DB1 + "->table=table_2").addRolesToGroup(USERGROUP1, "db1_tab2_all").setUserGroupMapping(StaticUserGroup.getStaticMapping());
    writePolicyFile(policyFile);
    Connection userConn = context.createConnection(USER1_1);
    Statement userStmt = context.createStatement(userConn);
    context.assertAuthzException(userStmt, "insert overwrite table  " + DB1 + ".table_2 select * from " + DB1 + ".table_1");
    context.assertAuthzException(userStmt, "insert overwrite directory '" + dataDir.getPath() + "' select * from  " + DB1 + ".table_1");
    userStmt.close();
    userConn.close();
}

57. DriverTest#testReadOnly()

Project: pgjdbc
Source File: DriverTest.java
View license
/*
   * Test that the readOnly property works.
   */
public void testReadOnly() throws Exception {
    // Set up log levels, etc.
    TestUtil.initDriver();
    Connection con = DriverManager.getConnection(TestUtil.getURL() + "&readOnly=true", TestUtil.getUser(), TestUtil.getPassword());
    assertNotNull(con);
    assertTrue(con.isReadOnly());
    con.close();
    con = DriverManager.getConnection(TestUtil.getURL() + "&readOnly=false", TestUtil.getUser(), TestUtil.getPassword());
    assertNotNull(con);
    assertFalse(con.isReadOnly());
    con.close();
    con = DriverManager.getConnection(TestUtil.getURL(), TestUtil.getUser(), TestUtil.getPassword());
    assertNotNull(con);
    assertFalse(con.isReadOnly());
    con.close();
}

58. DriverTest#testConnect()

Project: pgjdbc-ng
Source File: DriverTest.java
View license
/*
   * Tests parseURL (internal)
   */
/*
   * Tests the connect method by connecting to the test database
   */
@Test
public void testConnect() throws Exception {
    // Test with the url, username & password
    Connection con = DriverManager.getConnection(TestUtil.getURL(), TestUtil.getUser(), TestUtil.getPassword());
    assertNotNull(con);
    con.close();
    // Test with the username in the url
    con = DriverManager.getConnection(TestUtil.getURL("user", TestUtil.getUser(), "password", TestUtil.getPassword()));
    assertNotNull(con);
    con.close();
    // Test with failover url
    String url = "jdbc:pgsql://invalidhost.not.here," + TestUtil.getServer() + ":" + TestUtil.getPort() + "/" + TestUtil.getDatabase();
    con = DriverManager.getConnection(url, TestUtil.getUser(), TestUtil.getPassword());
    assertNotNull(con);
    con.close();
}

59. DriverTest#testReadOnly()

Project: pgjdbc-ng
Source File: DriverTest.java
View license
/*
   * Test that the readOnly property works.
   */
@Test
public void testReadOnly() throws Exception {
    Connection con = DriverManager.getConnection(TestUtil.getURL("readOnly", true), TestUtil.getUser(), TestUtil.getPassword());
    assertNotNull(con);
    assertTrue(con.isReadOnly());
    con.close();
    con = DriverManager.getConnection(TestUtil.getURL("readOnly", false), TestUtil.getUser(), TestUtil.getPassword());
    assertNotNull(con);
    assertFalse(con.isReadOnly());
    con.close();
    con = DriverManager.getConnection(TestUtil.getURL(), TestUtil.getUser(), TestUtil.getPassword());
    assertNotNull(con);
    assertFalse(con.isReadOnly());
    con.close();
}

60. TestCrossDbOps#testNegativeUserPrivileges()

Project: sentry
Source File: TestCrossDbOps.java
View license
/**
   * Test Case 2.14 admin user create a new database DB_1 create TABLE_1 in DB_1
   * admin user grant INSERT to user1's group on TABLE_1 negative test case:
   * user1 try to do following on TABLE_1 will fail: --explain --analyze
   * --describe --describe function --show columns --show table status --show
   * table properties --show create table --show partitions --show indexes
   * --select * from TABLE_1.
   */
@Test
public void testNegativeUserPrivileges() throws Exception {
    Connection adminCon = context.createConnection(ADMIN1);
    Statement adminStmt = context.createStatement(adminCon);
    adminStmt.execute("use default");
    adminStmt.execute("CREATE DATABASE " + DB1);
    adminStmt.execute("create table " + DB1 + ".table_1 (id int)");
    adminStmt.execute("create table " + DB1 + ".table_2 (id int)");
    adminStmt.close();
    adminCon.close();
    // edit policy file
    policyFile.addRolesToGroup(USERGROUP1, "db1_tab1_insert", "db1_tab2_all").addPermissionsToRole("db1_tab2_all", "server=server1->db=" + DB1 + "->table=table_2").addPermissionsToRole("db1_tab1_insert", "server=server1->db=" + DB1 + "->table=table_1->action=insert").setUserGroupMapping(StaticUserGroup.getStaticMapping());
    writePolicyFile(policyFile);
    Connection userConn = context.createConnection(USER1_1);
    Statement userStmt = context.createStatement(userConn);
    context.assertAuthzException(userStmt, "select * from " + DB1 + ".table_1");
    userConn.close();
    userStmt.close();
}

61. TestCrossDbOps#testNegativeUserDMLPrivileges()

Project: sentry
Source File: TestCrossDbOps.java
View license
/**
   * Test Case 2.16 admin user create a new database DB_1 create TABLE_1 and
   * TABLE_2 (same schema) in DB_1 admin user grant SELECT, INSERT to user1's
   * group on TABLE_2 negative test case: user1 try to do following on TABLE_1
   * will fail: --insert overwrite TABLE_2 select * from TABLE_1
   */
@Test
public void testNegativeUserDMLPrivileges() throws Exception {
    createDb(ADMIN1, DB1);
    Connection adminCon = context.createConnection(ADMIN1);
    Statement adminStmt = context.createStatement(adminCon);
    adminStmt.execute("create table " + DB1 + ".table_1 (id int)");
    adminStmt.execute("create table " + DB1 + ".table_2 (id int)");
    adminStmt.close();
    adminCon.close();
    policyFile.addPermissionsToRole("db1_tab2_all", "server=server1->db=" + DB1 + "->table=table_2").addRolesToGroup(USERGROUP1, "db1_tab2_all").setUserGroupMapping(StaticUserGroup.getStaticMapping());
    writePolicyFile(policyFile);
    Connection userConn = context.createConnection(USER1_1);
    Statement userStmt = context.createStatement(userConn);
    context.assertAuthzException(userStmt, "insert overwrite table  " + DB1 + ".table_2 select * from " + DB1 + ".table_1");
    context.assertAuthzException(userStmt, "insert overwrite directory '" + dataDir.getPath() + "' select * from  " + DB1 + ".table_1");
    userStmt.close();
    userConn.close();
}

62. TestCrossDbOps#testNegativeUserPrivileges()

Project: sentry
Source File: TestCrossDbOps.java
View license
/**
   * Test Case 2.14 admin user create a new database DB_1 create TABLE_1 in DB_1
   * admin user grant INSERT to user1's group on TABLE_1 negative test case:
   * user1 try to do following on TABLE_1 will fail: --explain --analyze
   * --describe --describe function --show columns --show table status --show
   * table properties --show create table --show partitions --show indexes
   * --select * from TABLE_1.
   */
@Test
public void testNegativeUserPrivileges() throws Exception {
    Connection adminCon = context.createConnection(ADMIN1);
    Statement adminStmt = context.createStatement(adminCon);
    adminStmt.execute("use default");
    adminStmt.execute("CREATE DATABASE " + DB1);
    adminStmt.execute("create table " + DB1 + ".table_1 (id int)");
    adminStmt.execute("create table " + DB1 + ".table_2 (id int)");
    adminStmt.close();
    adminCon.close();
    // edit policy file
    policyFile.addRolesToGroup(USERGROUP1, "db1_tab1_insert", "db1_tab2_all").addPermissionsToRole("db1_tab2_all", "server=server1->db=" + DB1 + "->table=table_2").addPermissionsToRole("db1_tab1_insert", "server=server1->db=" + DB1 + "->table=table_1->action=insert").setUserGroupMapping(StaticUserGroup.getStaticMapping());
    writePolicyFile(policyFile);
    Connection userConn = context.createConnection(USER1_1);
    Statement userStmt = context.createStatement(userConn);
    context.assertAuthzException(userStmt, "select * from " + DB1 + ".table_1");
    userConn.close();
    userStmt.close();
}

63. TestCrossDbOps#testNegativeUserDMLPrivileges()

Project: sentry
Source File: TestCrossDbOps.java
View license
/**
   * Test Case 2.16 admin user create a new database DB_1 create TABLE_1 and
   * TABLE_2 (same schema) in DB_1 admin user grant SELECT, INSERT to user1's
   * group on TABLE_2 negative test case: user1 try to do following on TABLE_1
   * will fail: --insert overwrite TABLE_2 select * from TABLE_1
   */
@Test
public void testNegativeUserDMLPrivileges() throws Exception {
    createDb(ADMIN1, DB1);
    Connection adminCon = context.createConnection(ADMIN1);
    Statement adminStmt = context.createStatement(adminCon);
    adminStmt.execute("create table " + DB1 + ".table_1 (id int)");
    adminStmt.execute("create table " + DB1 + ".table_2 (id int)");
    adminStmt.close();
    adminCon.close();
    policyFile.addPermissionsToRole("db1_tab2_all", "server=server1->db=" + DB1 + "->table=table_2").addRolesToGroup(USERGROUP1, "db1_tab2_all").setUserGroupMapping(StaticUserGroup.getStaticMapping());
    writePolicyFile(policyFile);
    Connection userConn = context.createConnection(USER1_1);
    Statement userStmt = context.createStatement(userConn);
    context.assertAuthzException(userStmt, "insert overwrite table  " + DB1 + ".table_2 select * from " + DB1 + ".table_1");
    context.assertAuthzException(userStmt, "insert overwrite directory '" + dataDir.getPath() + "' select * from  " + DB1 + ".table_1");
    userStmt.close();
    userConn.close();
}

64. TestMyDriver#main()

Project: sky-walking
Source File: TestMyDriver.java
View license
public static void main(String[] args) throws ClassNotFoundException, SQLException {
    Class.forName("test.ai.cloud.skywalking.plugin.drivermanger.MyDriver");
    String url = "jdbc:oracle:thin:@10.1.130.239:1521:ora";
    Connection con = DriverManager.getConnection(url, "edc_export", "edc_export");
    con.setAutoCommit(false);
    PreparedStatement p0 = con.prepareStatement("select 1 from dual where 1=?");
    p0.setInt(1, 1);
    p0.execute();
    con.commit();
    con.close();
}

65. MysqlJDBCTest#main()

Project: sky-walking
Source File: MysqlJDBCTest.java
View license
public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException {
    Class.forName("com.mysql.jdbc.Driver");
    String url = "tracing:jdbc:mysql://10.1.241.20:31306/sw_db?user=sw_dbusr01&password=sw_dbusr01";
    Connection con = DriverManager.getConnection(url);
    con.setAutoCommit(false);
    PreparedStatement p0 = con.prepareStatement("select 1 from dual where 1=?");
    p0.setInt(1, 1);
    p0.execute();
    con.commit();
    con.close();
    TraceTreeAssert.assertEquals(new String[][] { { "0", "jdbc:mysql://10.1.241.20:31306/sw_db?user=sw_dbusr01&password=sw_dbusr01(null)", "preaparedStatement.executeUpdate:select 1 from dual where 1=?" }, { "0", "jdbc:mysql://10.1.241.20:31306/sw_db?user=sw_dbusr01&password=sw_dbusr01(null)", "connection.commit" }, { "0", "jdbc:mysql://10.1.241.20:31306/sw_db?user=sw_dbusr01&password=sw_dbusr01(null)", "connection.close" } }, true);
}

66. OracleJDBCTest#main()

Project: sky-walking
Source File: OracleJDBCTest.java
View license
public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    String url = "jdbc:oracle:thin:@10.1.130.239:1521:ora";
    Connection con = DriverManager.getConnection(url, "edc_export", "edc_export");
    con.setAutoCommit(false);
    PreparedStatement p0 = con.prepareStatement("select 1 from dual where 1=?");
    p0.setInt(1, 1);
    p0.execute();
    con.commit();
    con.close();
    TraceTreeAssert.assertEquals(new String[][] { { "0", "jdbc:oracle:thin:@10.1.130.239:1521:ora(edc_export)", "preaparedStatement.executeUpdate:select 1 from dual where 1=?" }, { "0", "jdbc:oracle:thin:@10.1.130.239:1521:ora(edc_export)", "connection.commit" }, { "0", "jdbc:oracle:thin:@10.1.130.239:1521:ora(edc_export)", "connection.close" } }, true);
}

67. JDBCPluginTest#testMysqlJDBC()

Project: sky-walking
Source File: JDBCPluginTest.java
View license
@Test
public void testMysqlJDBC() throws ClassNotFoundException, SQLException {
    Class.forName("com.mysql.jdbc.Driver");
    String url = "jdbc:mysql://127.0.0.1:3306/test?user=root&password=root";
    Connection con = DriverManager.getConnection(url);
    con.setAutoCommit(false);
    PreparedStatement p0 = con.prepareStatement("select 1 from dual where 1=?");
    p0.setInt(1, 1);
    p0.execute();
    con.commit();
    con.close();
    TraceTreeAssert.assertEquals(new String[][] { { "0", "jdbc:mysql://127.0.0.1:3306/test?user=root&password=root(null)", "preaparedStatement.executeUpdate:select 1 from dual where 1=?" }, { "0", "jdbc:mysql://127.0.0.1:3306/test?user=root&password=root(null)", "connection.commit" }, { "0", "jdbc:mysql://127.0.0.1:3306/test?user=root&password=root(null)", "connection.close" } }, true);
    TraceTreeAssert.clearTraceData();
}

68. JDBCPluginTest#testOracleJDBC()

Project: sky-walking
Source File: JDBCPluginTest.java
View license
@Test
public void testOracleJDBC() throws ClassNotFoundException, SQLException {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    String url = "jdbc:oracle:thin:@10.1.130.239:1521:ora";
    Connection con = DriverManager.getConnection(url, "edc_export", "edc_export");
    con.setAutoCommit(false);
    PreparedStatement p0 = con.prepareStatement("select 1 from dual where 1=?");
    p0.setInt(1, 1);
    p0.execute();
    con.commit();
    con.close();
    TraceTreeAssert.assertEquals(new String[][] { { "0", "jdbc:oracle:thin:@10.1.130.239:1521:ora(edc_export)", "preaparedStatement.executeUpdate:select 1 from dual where 1=?" }, { "0", "jdbc:oracle:thin:@10.1.130.239:1521:ora(edc_export)", "connection.commit" }, { "0", "jdbc:oracle:thin:@10.1.130.239:1521:ora(edc_export)", "connection.close" } }, true);
    TraceTreeAssert.clearTraceData();
}

69. InsertQueryTest#reproduceDatabaseLocked()

Project: sqlite-jdbc
Source File: InsertQueryTest.java
View license
@Test(expected = SQLException.class)
public void reproduceDatabaseLocked() throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:sqlite:" + dbName);
    Connection conn2 = DriverManager.getConnection("jdbc:sqlite:" + dbName);
    Statement stat = conn.createStatement();
    Statement stat2 = conn2.createStatement();
    conn.setAutoCommit(false);
    stat.executeUpdate("drop table if exists sample");
    stat.executeUpdate("create table sample(id, name)");
    stat.executeUpdate("insert into sample values(1, 'leo')");
    ResultSet rs = stat2.executeQuery("select count(*) from sample");
    rs.next();
    // causes "database is locked" (SQLITE_BUSY)
    conn.commit();
}

70. TestCases#testLargeKeys()

Project: ThriftyPaxos
Source File: TestCases.java
View license
private void testLargeKeys() throws SQLException {
    if (config.memory) {
        return;
    }
    deleteDb("cases");
    Connection conn = getConnection("cases");
    Statement stat = conn.createStatement();
    stat.execute("create table test(id int primary key, name varchar)");
    stat.execute("create index on test(name)");
    stat.execute("insert into test values(1, '1' || space(1500))");
    conn.close();
    conn = getConnection("cases");
    stat = conn.createStatement();
    stat.execute("insert into test values(2, '2' || space(1500))");
    conn.close();
    conn = getConnection("cases");
    stat = conn.createStatement();
    stat.executeQuery("select name from test order by name");
    conn.close();
}

71. TestCases#testInsertDeleteRollback()

Project: ThriftyPaxos
Source File: TestCases.java
View license
private void testInsertDeleteRollback() throws SQLException {
    deleteDb("cases");
    Connection conn = getConnection("cases");
    Statement stat = conn.createStatement();
    stat.execute("set cache_size 1");
    stat.execute("SET MAX_MEMORY_ROWS " + Integer.MAX_VALUE);
    stat.execute("SET MAX_MEMORY_UNDO " + Integer.MAX_VALUE);
    stat.execute("SET MAX_OPERATION_MEMORY " + Integer.MAX_VALUE);
    stat.execute("create table test(id identity)");
    conn.setAutoCommit(false);
    stat.execute("insert into test select x from system_range(1, 11)");
    stat.execute("delete from test");
    conn.rollback();
    conn.close();
}

72. TestCases#testEmptyBtreeIndex()

Project: ThriftyPaxos
Source File: TestCases.java
View license
private void testEmptyBtreeIndex() throws SQLException {
    deleteDb("cases");
    Connection conn;
    conn = getConnection("cases");
    conn.createStatement().execute("CREATE TABLE test(id int PRIMARY KEY);");
    conn.createStatement().execute("INSERT INTO test SELECT X FROM SYSTEM_RANGE(1, 77)");
    conn.createStatement().execute("DELETE from test");
    conn.close();
    conn = getConnection("cases");
    conn.createStatement().execute("INSERT INTO test (id) VALUES (1)");
    conn.close();
    conn = getConnection("cases");
    conn.createStatement().execute("DELETE from test");
    conn.createStatement().execute("drop table test");
    conn.close();
}

73. TestCases#testDefaultQueryReconnect()

Project: ThriftyPaxos
Source File: TestCases.java
View license
private void testDefaultQueryReconnect() throws SQLException {
    trace("testDefaultQueryReconnect");
    deleteDb("cases");
    Connection conn = getConnection("cases");
    Statement stat = conn.createStatement();
    stat.execute("create table parent(id int)");
    stat.execute("insert into parent values(1)");
    stat.execute("create table test(id int default " + "(select max(id) from parent), name varchar)");
    conn.close();
    conn = getConnection("cases");
    stat = conn.createStatement();
    conn.setAutoCommit(false);
    stat.execute("insert into parent values(2)");
    stat.execute("insert into test(name) values('test')");
    ResultSet rs = stat.executeQuery("select * from test");
    rs.next();
    assertEquals(2, rs.getInt(1));
    assertFalse(rs.next());
    conn.close();
}

74. TestCases#testQuick()

Project: ThriftyPaxos
Source File: TestCases.java
View license
private void testQuick() throws SQLException {
    trace("testQuick");
    deleteDb("cases");
    Connection c0 = getConnection("cases");
    c0.createStatement().executeUpdate("create table test (ID  int PRIMARY KEY)");
    c0.createStatement().executeUpdate("insert into test values(1)");
    c0.createStatement().executeUpdate("drop table test");
    c0.createStatement().executeUpdate("create table test (ID  int PRIMARY KEY)");
    c0.close();
    c0 = getConnection("cases");
    c0.createStatement().executeUpdate("insert into test values(1)");
    c0.close();
    c0 = getConnection("cases");
    c0.close();
}

75. TestLinkedTable#testLinkedServerMode()

Project: ThriftyPaxos
Source File: TestLinkedTable.java
View license
private void testLinkedServerMode() throws SQLException {
    if (config.memory) {
        return;
    }
    // the network mode will result in a deadlock
    if (config.networked) {
        return;
    }
    deleteDb("linkedTable1");
    deleteDb("linkedTable2");
    String url2 = getURL("linkedTable2", true);
    String user = getUser(), password = getPassword();
    Connection conn = getConnection("linkedTable2");
    Statement stat = conn.createStatement();
    stat.execute("create table test(id int)");
    conn.close();
    conn = getConnection("linkedTable1");
    stat = conn.createStatement();
    stat.execute("create linked table link(null, '" + url2 + "', '" + user + "', '" + password + "', 'TEST')");
    conn.close();
    conn = getConnection("linkedTable1");
    conn.close();
}

76. TestLinkedTable#testNestedQueriesToSameTable()

Project: ThriftyPaxos
Source File: TestLinkedTable.java
View license
// this is not a bug, it is the documented behavior
//    private void testLinkAutoAdd() throws SQLException {
//        Class.forName("org.h2.Driver");
//        Connection ca =
//            DriverManager.getConnection("jdbc:h2:mem:one", "sa", "sa");
//        Connection cb =
//            DriverManager.getConnection("jdbc:h2:mem:two", "sa", "sa");
//        Statement sa = ca.createStatement();
//        Statement sb = cb.createStatement();
//        sa.execute("CREATE TABLE ONE (X NUMBER)");
//        sb.execute(
//            "CALL LINK_SCHEMA('GOOD', '', " +
//            "'jdbc:h2:mem:one', 'sa', 'sa', 'PUBLIC'); ");
//        sb.executeQuery("SELECT * FROM GOOD.ONE");
//        sa.execute("CREATE TABLE TWO (X NUMBER)");
//        sb.executeQuery("SELECT * FROM GOOD.TWO"); // FAILED
//        ca.close();
//        cb.close();
//    }
private void testNestedQueriesToSameTable() throws SQLException {
    if (config.memory) {
        return;
    }
    org.h2.Driver.load();
    deleteDb("linkedTable");
    String url = getURL("linkedTable;SHARE_LINKED_CONNECTIONS=TRUE", true);
    String user = getUser();
    String password = getPassword();
    Connection ca = getConnection(url, user, password);
    Statement sa = ca.createStatement();
    sa.execute("CREATE TABLE TEST(ID INT) AS SELECT 1");
    ca.close();
    Connection cb = DriverManager.getConnection("jdbc:h2:mem:two", "sa", "sa");
    Statement sb = cb.createStatement();
    sb.execute("CREATE LINKED TABLE T1(NULL, '" + url + "', '" + user + "', '" + password + "', 'TEST')");
    sb.executeQuery("SELECT * FROM DUAL A " + "LEFT OUTER JOIN T1 A ON A.ID=1 LEFT OUTER JOIN T1 B ON B.ID=1");
    sb.execute("DROP ALL OBJECTS");
    cb.close();
}

77. TestLinkedTable#testSharedConnection()

Project: ThriftyPaxos
Source File: TestLinkedTable.java
View license
private void testSharedConnection() throws SQLException {
    if (config.memory) {
        return;
    }
    org.h2.Driver.load();
    deleteDb("linkedTable");
    String url = getURL("linkedTable;SHARE_LINKED_CONNECTIONS=TRUE", true);
    String user = getUser();
    String password = getPassword();
    Connection ca = getConnection(url, user, password);
    Statement sa = ca.createStatement();
    sa.execute("CREATE TABLE TEST(ID INT)");
    ca.close();
    Connection cb = DriverManager.getConnection("jdbc:h2:mem:two", "sa", "sa");
    Statement sb = cb.createStatement();
    sb.execute("CREATE LINKED TABLE T1(NULL, '" + url + ";OPEN_NEW=TRUE', '" + user + "', '" + password + "', 'TEST')");
    sb.execute("CREATE LINKED TABLE T2(NULL, '" + url + ";OPEN_NEW=TRUE', '" + user + "', '" + password + "', 'TEST')");
    sb.execute("DROP ALL OBJECTS");
    cb.close();
}

78. TestLinkedTable#testLinkOtherSchema()

Project: ThriftyPaxos
Source File: TestLinkedTable.java
View license
private static void testLinkOtherSchema() throws SQLException {
    org.h2.Driver.load();
    Connection ca = DriverManager.getConnection("jdbc:h2:mem:one", "sa", "sa");
    Connection cb = DriverManager.getConnection("jdbc:h2:mem:two", "sa", "sa");
    Statement sa = ca.createStatement();
    Statement sb = cb.createStatement();
    sa.execute("CREATE TABLE GOOD (X NUMBER)");
    sa.execute("CREATE SCHEMA S");
    sa.execute("CREATE TABLE S.BAD (X NUMBER)");
    sb.execute("CALL LINK_SCHEMA('G', '', " + "'jdbc:h2:mem:one', 'sa', 'sa', 'PUBLIC'); ");
    sb.execute("CALL LINK_SCHEMA('B', '', " + "'jdbc:h2:mem:one', 'sa', 'sa', 'S'); ");
    // OK
    sb.executeQuery("SELECT * FROM G.GOOD");
    // FAILED
    sb.executeQuery("SELECT * FROM B.BAD");
    ca.close();
    cb.close();
}

79. TestLinkedTable#testLinkTwoTables()

Project: ThriftyPaxos
Source File: TestLinkedTable.java
View license
private void testLinkTwoTables() throws SQLException {
    org.h2.Driver.load();
    Connection conn = DriverManager.getConnection("jdbc:h2:mem:one", "sa", "sa");
    Statement stat = conn.createStatement();
    stat.execute("CREATE SCHEMA Y");
    stat.execute("CREATE TABLE A( C INT)");
    stat.execute("INSERT INTO A VALUES(1)");
    stat.execute("CREATE TABLE Y.A (C INT)");
    stat.execute("INSERT INTO Y.A VALUES(2)");
    Connection conn2 = DriverManager.getConnection("jdbc:h2:mem:two");
    Statement stat2 = conn2.createStatement();
    stat2.execute("CREATE LINKED TABLE one('org.h2.Driver', " + "'jdbc:h2:mem:one', 'sa', 'sa', 'Y.A');");
    stat2.execute("CREATE LINKED TABLE two('org.h2.Driver', " + "'jdbc:h2:mem:one', 'sa', 'sa', 'PUBLIC.A');");
    ResultSet rs = stat2.executeQuery("SELECT * FROM one");
    rs.next();
    assertEquals(2, rs.getInt(1));
    rs = stat2.executeQuery("SELECT * FROM two");
    rs.next();
    assertEquals(1, rs.getInt(1));
    conn.close();
    conn2.close();
}

80. TestLob#testConcurrentRemoveRead()

Project: ThriftyPaxos
Source File: TestLob.java
View license
private void testConcurrentRemoveRead() throws Exception {
    deleteDb("lob");
    final String url = getURL("lob", true);
    Connection conn = getConnection(url);
    Statement stat = conn.createStatement();
    stat.execute("set max_length_inplace_lob 5");
    stat.execute("create table lob(data clob)");
    stat.execute("insert into lob values(space(100))");
    Connection conn2 = getConnection(url);
    Statement stat2 = conn2.createStatement();
    ResultSet rs = stat2.executeQuery("select data from lob");
    rs.next();
    stat.execute("delete lob");
    InputStream in = rs.getBinaryStream(1);
    in.read();
    conn2.close();
    conn.close();
}

81. TestLob#testCleaningUpLobsOnRollback()

Project: ThriftyPaxos
Source File: TestLob.java
View license
private void testCleaningUpLobsOnRollback() throws Exception {
    if (config.mvStore) {
        return;
    }
    deleteDb("lob");
    Connection conn = getConnection("lob");
    Statement stat = conn.createStatement();
    stat.execute("CREATE TABLE test(id int, data CLOB)");
    conn.setAutoCommit(false);
    stat.executeUpdate("insert into test values (1, '" + MORE_THAN_128_CHARS + "')");
    conn.rollback();
    ResultSet rs = stat.executeQuery("select count(*) from test");
    rs.next();
    assertEquals(0, rs.getInt(1));
    rs = stat.executeQuery("select * from information_schema.lobs");
    rs = stat.executeQuery("select count(*) from information_schema.lob_data");
    rs.next();
    assertEquals(0, rs.getInt(1));
    conn.close();
}

82. TestLob#testCommitOnExclusiveConnection()

Project: ThriftyPaxos
Source File: TestLob.java
View license
private void testCommitOnExclusiveConnection() throws Exception {
    deleteDb("lob");
    Connection conn = getConnection("lob;EXCLUSIVE=1");
    Statement statement = conn.createStatement();
    statement.execute("drop table if exists TEST");
    statement.execute("create table TEST (COL INTEGER, LOB CLOB)");
    conn.setAutoCommit(false);
    statement.execute("insert into TEST (COL, LOB) values (1, '" + MORE_THAN_128_CHARS + "')");
    statement.execute("update TEST set COL=2");
    // OK
    // statement.execute("commit");
    // KO : should not hang
    conn.commit();
    conn.close();
}

83. TestRights#testGetTables()

Project: ThriftyPaxos
Source File: TestRights.java
View license
//    public void testLowerCaseUser() throws SQLException {
// Documentation: for compatibility,
// only unquoted or uppercase user names are allowed.
//        deleteDb("rights");
//        Connection conn = getConnection("rights");
//        stat = conn.createStatement();
//        stat.execute("CREATE USER \"TEST1\" PASSWORD 'abc'");
//        stat.execute("CREATE USER \"Test2\" PASSWORD 'abc'");
//        conn.close();
//        conn = getConnection("rights", "TEST1", "abc");
//        conn.close();
//        conn = getConnection("rights", "Test2", "abc");
//        conn.close();
//    }
private void testGetTables() throws SQLException {
    deleteDb("rights");
    Connection conn = getConnection("rights");
    stat = conn.createStatement();
    stat.execute("CREATE USER IF NOT EXISTS TEST PASSWORD 'TEST'");
    stat.execute("CREATE TABLE TEST(ID INT)");
    stat.execute("GRANT ALL ON TEST TO TEST");
    Connection conn2 = getConnection("rights", "TEST", getPassword("TEST"));
    DatabaseMetaData meta = conn2.getMetaData();
    meta.getTables(null, null, "%", new String[] { "TABLE", "VIEW", "SEQUENCE" });
    conn2.close();
    conn.close();
}

84. TestRights#testDropTempTables()

Project: ThriftyPaxos
Source File: TestRights.java
View license
private void testDropTempTables() throws SQLException {
    deleteDb("rights");
    Connection conn = getConnection("rights");
    stat = conn.createStatement();
    stat.execute("CREATE USER IF NOT EXISTS READER PASSWORD 'READER'");
    stat.execute("CREATE TABLE TEST(ID INT)");
    Connection conn2 = getConnection("rights", "READER", getPassword("READER"));
    Statement stat2 = conn2.createStatement();
    assertThrows(ErrorCode.NOT_ENOUGH_RIGHTS_FOR_1, stat2).execute("SELECT * FROM TEST");
    stat2.execute("CREATE LOCAL TEMPORARY TABLE IF NOT EXISTS MY_TEST(ID INT)");
    stat2.execute("INSERT INTO MY_TEST VALUES(1)");
    stat2.execute("SELECT * FROM MY_TEST");
    stat2.execute("DROP TABLE MY_TEST");
    conn2.close();
    conn.close();
}

85. TestTempTables#test()

Project: ThriftyPaxos
Source File: TestTempTables.java
View license
@Override
public void test() throws SQLException {
    deleteDb("tempTables");
    testTempSequence();
    testTempFileResultSet();
    testTempTableResultSet();
    testTransactionalTemp();
    testDeleteGlobalTempTableWhenClosing();
    Connection c1 = getConnection("tempTables");
    testAlter(c1);
    Connection c2 = getConnection("tempTables");
    testConstraints(c1, c2);
    testTables(c1, c2);
    testIndexes(c1, c2);
    c1.close();
    c2.close();
    testLotsOfTables();
    deleteDb("tempTables");
}

86. TestMvcc3#testCreateTableAsSelect()

Project: ThriftyPaxos
Source File: TestMvcc3.java
View license
private void testCreateTableAsSelect() throws SQLException {
    if (!config.mvcc) {
        return;
    }
    deleteDb("mvcc3");
    Connection c1 = getConnection("mvcc3");
    Statement s1 = c1.createStatement();
    s1.execute("CREATE TABLE TEST AS SELECT X ID, 'Hello' NAME " + "FROM SYSTEM_RANGE(1, 3)");
    Connection c2 = getConnection("mvcc3");
    Statement s2 = c2.createStatement();
    ResultSet rs = s2.executeQuery("SELECT NAME FROM TEST WHERE ID=1");
    rs.next();
    assertEquals("Hello", rs.getString(1));
    c1.close();
    c2.close();
}

87. TestMvcc3#testSequence()

Project: ThriftyPaxos
Source File: TestMvcc3.java
View license
private void testSequence() throws SQLException {
    if (config.memory) {
        return;
    }
    deleteDb("mvcc3");
    Connection conn;
    ResultSet rs;
    conn = getConnection("mvcc3");
    conn.createStatement().execute("create sequence abc");
    conn.close();
    conn = getConnection("mvcc3");
    rs = conn.createStatement().executeQuery("call abc.nextval");
    rs.next();
    assertEquals(1, rs.getInt(1));
    conn.close();
    conn = getConnection("mvcc3");
    rs = conn.createStatement().executeQuery("call abc.currval");
    rs.next();
    assertEquals(1, rs.getInt(1));
    conn.close();
}

88. TestMVTableEngine#testRollback()

Project: ThriftyPaxos
Source File: TestMVTableEngine.java
View license
private void testRollback() throws Exception {
    FileUtils.deleteRecursive(getBaseDir(), true);
    Connection conn;
    Statement stat;
    String url = "mvstore;MV_STORE=TRUE";
    conn = getConnection(url);
    stat = conn.createStatement();
    stat.execute("create table test(id identity)");
    conn.setAutoCommit(false);
    stat.execute("insert into test values(1)");
    stat.execute("delete from test");
    conn.rollback();
    conn.close();
}

89. TestUndoLogLarge#test()

Project: ThriftyPaxos
Source File: TestUndoLogLarge.java
View license
private static void test() throws SQLException {
    DeleteDbFiles.execute("data", "test", true);
    Connection conn = DriverManager.getConnection("jdbc:h2:data/test");
    Statement stat = conn.createStatement();
    stat.execute("set max_operation_memory 100");
    stat.execute("set max_memory_undo 100");
    stat.execute("create table test(id identity, name varchar)");
    conn.setAutoCommit(false);
    PreparedStatement prep = conn.prepareStatement("insert into test(name) values(space(1024*1024))");
    long time = System.currentTimeMillis();
    for (int i = 0; i < 2500; i++) {
        prep.execute();
        long now = System.currentTimeMillis();
        if (now > time + 5000) {
            System.out.println(i);
            time = now + 5000;
        }
    }
    conn.rollback();
    conn.close();
}

90. TestFileLockSerialized#testSequenceFlush()

View license
private void testSequenceFlush() throws Exception {
    deleteDb("fileLockSerialized");
    String url = "jdbc:h2:" + getBaseDir() + "/fileLockSerialized;FILE_LOCK=SERIALIZED;OPEN_NEW=TRUE";
    ResultSet rs;
    Connection conn1 = getConnection(url);
    Statement stat1 = conn1.createStatement();
    stat1.execute("create sequence seq");
    rs = stat1.executeQuery("call seq.nextval");
    rs.next();
    assertEquals(1, rs.getInt(1));
    Connection conn2 = getConnection(url);
    Statement stat2 = conn2.createStatement();
    rs = stat2.executeQuery("call seq.nextval");
    rs.next();
    assertEquals(2, rs.getInt(1));
    conn1.close();
    conn2.close();
}

91. TestFileLockSerialized#testTwoReaders()

View license
private void testTwoReaders() throws Exception {
    deleteDb("fileLockSerialized");
    String url = "jdbc:h2:" + getBaseDir() + "/fileLockSerialized;FILE_LOCK=SERIALIZED;OPEN_NEW=TRUE";
    Connection conn1 = getConnection(url);
    conn1.createStatement().execute("create table test(id int)");
    Connection conn2 = getConnection(url);
    Statement stat2 = conn2.createStatement();
    stat2.execute("drop table test");
    stat2.execute("create table test(id identity) as select 1");
    conn2.close();
    conn1.close();
    getConnection(url).close();
}

92. TestPageStoreCoverage#testIncompleteCreate()

View license
private void testIncompleteCreate() throws Exception {
    deleteDb("pageStoreCoverage");
    Connection conn;
    String fileName = getBaseDir() + "/pageStore" + Constants.SUFFIX_PAGE_FILE;
    conn = getConnection("pageStoreCoverage");
    Statement stat = conn.createStatement();
    stat.execute("drop table if exists INFORMATION_SCHEMA.LOB_DATA");
    stat.execute("drop table if exists INFORMATION_SCHEMA.LOB_MAP");
    conn.close();
    FileChannel f = FileUtils.open(fileName, "rw");
    // create a new database
    conn = getConnection("pageStoreCoverage");
    conn.close();
    f = FileUtils.open(fileName, "rw");
    f.truncate(16);
    // create a new database
    conn = getConnection("pageStoreCoverage");
    conn.close();
    deleteDb("pageStoreCoverage");
}

93. J2EEConnectionPoolTest#releaseConnection_shouldCloseConnection()

Project: vaadin
Source File: J2EEConnectionPoolTest.java
View license
@Test
public void releaseConnection_shouldCloseConnection() throws SQLException {
    Connection connection = EasyMock.createMock(Connection.class);
    connection.setAutoCommit(false);
    EasyMock.expectLastCall();
    connection.close();
    EasyMock.expectLastCall();
    DataSource ds = EasyMock.createMock(DataSource.class);
    ds.getConnection();
    EasyMock.expectLastCall().andReturn(connection);
    EasyMock.replay(connection, ds);
    J2EEConnectionPool pool = new J2EEConnectionPool(ds);
    Connection c = pool.reserveConnection();
    Assert.assertEquals(connection, c);
    pool.releaseConnection(c);
    EasyMock.verify(connection, ds);
}

94. SimpleJDBCConnectionPoolTest#releaseConnection_failingRollback_shouldCallClose()

View license
@Test
public void releaseConnection_failingRollback_shouldCallClose() throws SQLException {
    Connection c = EasyMock.createMock(Connection.class);
    c.getAutoCommit();
    EasyMock.expectLastCall().andReturn(false);
    c.rollback();
    EasyMock.expectLastCall().andThrow(new SQLException("Rollback failed"));
    c.close();
    EasyMock.expectLastCall().atLeastOnce();
    EasyMock.replay(c);
    // make sure the connection pool is initialized
    // Bypass validation
    JDBCConnectionPool realPool = ((ValidatingSimpleJDBCConnectionPool) connectionPool).getRealPool();
    realPool.reserveConnection();
    realPool.releaseConnection(c);
    EasyMock.verify(c);
}

95. NarayanaDataSourceBeanTests#shouldGetConnectionAndCommit()

View license
@Test
public void shouldGetConnectionAndCommit() throws SQLException {
    Connection mockConnection = mock(Connection.class);
    XAConnection mockXaConnection = mock(XAConnection.class);
    given(mockXaConnection.getConnection()).willReturn(mockConnection);
    given(this.dataSource.getXAConnection()).willReturn(mockXaConnection);
    Properties properties = new Properties();
    properties.put(TransactionalDriver.XADataSource, this.dataSource);
    Connection connection = this.dataSourceBean.getConnection();
    assertThat(connection).isInstanceOf(ConnectionImple.class);
    connection.commit();
    verify(this.dataSource, times(1)).getXAConnection();
    verify(mockXaConnection, times(1)).getConnection();
    verify(mockConnection, times(1)).commit();
}

96. NarayanaDataSourceBeanTests#shouldGetConnectionAndCommitWithCredentials()

View license
@Test
public void shouldGetConnectionAndCommitWithCredentials() throws SQLException {
    String username = "testUsername";
    String password = "testPassword";
    Connection mockConnection = mock(Connection.class);
    XAConnection mockXaConnection = mock(XAConnection.class);
    given(mockXaConnection.getConnection()).willReturn(mockConnection);
    given(this.dataSource.getXAConnection(username, password)).willReturn(mockXaConnection);
    Properties properties = new Properties();
    properties.put(TransactionalDriver.XADataSource, this.dataSource);
    properties.put(TransactionalDriver.userName, username);
    properties.put(TransactionalDriver.password, password);
    Connection connection = this.dataSourceBean.getConnection(username, password);
    assertThat(connection).isInstanceOf(ConnectionImple.class);
    connection.commit();
    verify(this.dataSource, times(1)).getXAConnection(username, password);
    verify(mockXaConnection, times(1)).getConnection();
    verify(mockConnection, times(1)).commit();
}

97. ErrorMessageTest#writeProtected()

Project: sqlite-jdbc
Source File: ErrorMessageTest.java
View license
@Test
public void writeProtected() throws SQLException, IOException {
    File file = File.createTempFile("error-message-test-write-protected", ".sqlite");
    file.deleteOnExit();
    Connection conn = DriverManager.getConnection("jdbc:sqlite:" + file.getAbsolutePath());
    Statement stmt = conn.createStatement();
    stmt.executeUpdate("create table sample(id, name)");
    stmt.executeUpdate("insert into sample values(1, \"foo\")");
    stmt.close();
    conn.close();
    assumeTrue(file.setReadOnly());
    conn = DriverManager.getConnection("jdbc:sqlite:" + file.getAbsolutePath());
    stmt = conn.createStatement();
    thrown.expectMessage(JUnitMatchers.containsString("[SQLITE_READONLY]"));
    stmt.executeUpdate("insert into sample values(2, \"bar\")");
    stmt.close();
    conn.close();
}

98. DirectInsert#initialInsert()

Project: ThriftyPaxos
Source File: DirectInsert.java
View license
private static void initialInsert(String url, int len) throws SQLException {
    Connection conn = DriverManager.getConnection(url + ";LOG=0");
    Statement stat = conn.createStatement();
    stat.execute("DROP TABLE IF EXISTS TEST");
    stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
    PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, 'Test' || SPACE(100))");
    long time = System.currentTimeMillis();
    for (int i = 0; i < len; i++) {
        long now = System.currentTimeMillis();
        if (now > time + 1000) {
            time = now;
            System.out.println("Inserting " + (100L * i / len) + "%");
        }
        prep.setInt(1, i);
        prep.execute();
    }
    conn.commit();
    prep.close();
    stat.close();
    conn.close();
}

99. TestCases#testReferenceLaterTable()

Project: ThriftyPaxos
Source File: TestCases.java
View license
private void testReferenceLaterTable() throws SQLException {
    deleteDb("cases");
    Connection conn = getConnection("cases");
    Statement stat = conn.createStatement();
    stat.execute("create table a(id int)");
    stat.execute("create table b(id int)");
    stat.execute("drop table a");
    assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, stat).execute("create table a(id int check id < select max(id) from b)");
    stat.execute("drop table b");
    stat.execute("create table b(id int)");
    stat.execute("create table a(id int check id < select max(id) from b)");
    conn.close();
    conn = getConnection("cases");
    conn.close();
}

100. TestCases#testCheckConstraintWithFunction()

Project: ThriftyPaxos
Source File: TestCases.java
View license
private void testCheckConstraintWithFunction() throws SQLException {
    deleteDb("cases");
    Connection conn = getConnection("cases");
    Statement stat = conn.createStatement();
    stat.execute("create alias is_email as " + "'boolean isEmail(String x) { return x != null && x.indexOf(''@'') > 0; }'");
    stat.execute("create domain email as varchar check is_email(value)");
    stat.execute("create table test(e email)");
    conn.close();
    conn = getConnection("cases");
    conn.close();
}