Java Code Examples for java.sql.Statement#getResultSet()

The following examples show how to use java.sql.Statement#getResultSet() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MultiDBLifeCycleTest.java    From Zebra with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiRouterResult3() throws Exception {
	DataSource ds = (DataSource) context.getBean("zebraDS");
	Connection conn = null;
	try {
		conn = ds.getConnection();
		Statement stmt = conn.createStatement();
		stmt.execute("select distinct name, score, type from test order by score");
		ResultSet rs = stmt.getResultSet();
		List<Integer> rows = new ArrayList<Integer>();
		while (rs.next()) {
			rows.add(rs.getInt("score"));
		}
		Assert.assertEquals(9, rows.size());

	} catch (Exception e) {
		Assert.fail();
	} finally {
		if (conn != null) {
			conn.close();
		}
	}
}
 
Example 2
Source File: JDBCDisplayUtil.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
static private void indent_DisplayResults
(PrintWriter out, Statement stmt, Connection conn, int indentLevel,
 int[] displayColumns, int[] displayColumnWidths)
	throws SQLException {

	checkNotNull(stmt, "Statement");

	ResultSet rs = stmt.getResultSet();
	if (rs != null) {
		indent_DisplayResults(out, rs, conn, indentLevel, 
							  displayColumns, displayColumnWidths);
		rs.close(); // let the result set go away
	}
	else {
		DisplayUpdateCount(out,stmt.getUpdateCount(), indentLevel);
	}

	ShowWarnings(out,stmt);
}
 
Example 3
Source File: GfxdLRUDUnit.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testReplicatedRegionLRUCountOverflowAsync() throws Exception {
  startVMs(1, 1);
  clientSQLExecute(
      1,
      " create table trade.customers (cid int not null, cust_name varchar(100)) " +
      " replicate EVICTION BY LRUCOUNT 100 EVICTACTION overflow asynchronous");
  Connection conn = TestUtil.getConnection();
  Statement s = conn.createStatement();
  insertNElements(200, s);
  Thread.sleep(5000);
  s.execute("select count(*) from trade.customers");
  ResultSet rs = s.getResultSet();
  int cnt = 0;
  if (rs.next()) {
    cnt = rs.getInt(1);
  }
  assertEquals("expected 200 elements but found " + cnt, 200, cnt);
}
 
Example 4
Source File: MultiDBLifeCycleTest.java    From Zebra with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiRouterResult14() throws Exception {
	DataSource ds = (DataSource) context.getBean("zebraDS");
	Connection conn = null;
	try {
		conn = ds.getConnection();
		Statement stmt = conn.createStatement();
		stmt.execute("select name from test where id>=1 and id<=2");
		ResultSet rs = stmt.getResultSet();
		List<String> rows = new ArrayList<String>();
		while (rs.next()) {
			rows.add(rs.getString("name"));
		}
		Assert.assertEquals(5, rows.size());
	} catch (Exception e) {
		Assert.fail();
	} finally {
		if (conn != null) {
			conn.close();
		}
	}
}
 
Example 5
Source File: GfxdLRUDUnit.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testReplicatedRegionLRUMemOverflow() throws Exception {
  startVMs(1, 1);
  clientSQLExecute(
      1,
      " create table trade.bigcustomers (cid int not null, cust_name varchar(2000), cust_addr varchar(2000), cust_addr2 varchar(2000)) " +
      " replicate EVICTION BY LRUMEMSIZE 1 EVICTACTION overflow synchronous");
  Connection conn = TestUtil.getConnection();
  PreparedStatement ps = conn.prepareStatement("insert into trade.bigcustomers values(?, ?, ?, ?)");
  insertNBigElements(2000, ps, 0);
  Statement s = conn.createStatement();
  s.execute("select count(*) from trade.bigcustomers");
  ResultSet rs = s.getResultSet();
  int cnt = 0;
  if (rs.next()) {
    cnt = rs.getInt(1);
  }
  TestUtil.getLogger().info("cnt: "+cnt);
  assertEquals("expected 2000 elements but found " + cnt, 2000, cnt);
}
 
Example 6
Source File: JDBCDisplayUtil.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
static private void indent_DisplayResults
(PrintWriter out, Statement stmt, Connection conn, int indentLevel,
 int[] displayColumns, int[] displayColumnWidths,
 ConsoleReader reader /* GemStoneAddition */,
 StopWatch timer /* GemStoneAddition */)
	throws SQLException {

	checkNotNull(stmt, "Statement");

	ResultSet rs = stmt.getResultSet();
	if (rs != null) {
		indent_DisplayResults(out, rs, conn, indentLevel, 
							  displayColumns, displayColumnWidths,
							  reader /* GemStoneAddition */,
							  timer /* GemStoneAddition */);
		rs.close(); // let the result set go away
	}
	else {
		DisplayUpdateCount(out,stmt.getUpdateCount(), indentLevel);
	}

	ShowWarnings(out,stmt);
}
 
Example 7
Source File: GfxdLRUDUnit.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testPRLRUCountDestroy() throws Exception {
  // The test is valid only for transaction isolation level NONE. 
  if (isTransactional) {
    return;
  }
  
  startVMs(1, 1);
  clientSQLExecute(
      1,
      " create table trade.customers (cid int not null, cust_name varchar(100))  EVICTION BY LRUCOUNT 100 EVICTACTION DESTROY");
  Connection conn = TestUtil.getConnection();
  Statement s = conn.createStatement();
  insertNElements(200, s);
  s.execute("select count(*) from trade.customers");
  ResultSet rs = s.getResultSet();
  int cnt = 0;
  if (rs.next()) {
    cnt = rs.getInt(1);
  }
  assertEquals("expected 100 elements but found " + cnt, 100, cnt);
}
 
Example 8
Source File: ExportImportTestDUnit.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Added to reproduce defect #51233.
 * Import data on selective columns using a data file. 
 * Column names are passed as parameters to the procedure.
 */
public void testImportWithSelectiveColumnNamesAsParameters_PR() throws Exception {
  try {
  // Start one client a three servers
  startVMs(1, 3);

  //create the table
  clientSQLExecute(1, "create table app.t1(flight_id int not null, "
      + "segment_number int not null, aircraft varchar(20), "
      + "CONSTRAINT FLIGHTS_PK PRIMARY KEY (FLIGHT_ID, SEGMENT_NUMBER))");

  //create import data file from which data is to be imported into the table
  PrintWriter p = new PrintWriter(new File("import_test_data.txt"));
  p.println("1354,11");
  p.println("7363,12");
  p.close();
  
  //call import data procedure passing column names as parameter 
  clientSQLExecute(1,
      "CALL SYSCS_UTIL.IMPORT_DATA('APP', 'T1', 'FLIGHT_ID,SEGMENT_NUMBER', null, 'import_test_data.txt', null, null, null, 1)");
  
  //verify data has been imported successfully
  Connection conn = TestUtil.getConnection();
  Statement st = conn.createStatement();
  st.execute("select count(*) from app.t1");
  ResultSet rs = st.getResultSet();
  assertTrue(rs.next());
  assertEquals("Number of rows in table should be 2", 2, rs.getInt(1));
  } finally {
    //delete the import data file
    new File("import_test_data.txt").delete();
  }
}
 
Example 9
Source File: StatementIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    Statement statement = connection.createStatement();
    try {
        statement.execute("select * from employee");
        ResultSet rs = statement.getResultSet();
        while (rs.next()) {
            rs.getString(1);
        }
    } finally {
        statement.close();
    }
}
 
Example 10
Source File: GfxdLRUDUnit.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testReplicatedRegionLRUHeapPercOverflow() throws Exception {
  startVMs(1, 1);
  clientSQLExecute(
      1," create diskstore teststore 'temp' ");
  clientSQLExecute(
      1,
      " create table trade.bigcustomers (cid int not null, cust_name varchar(2000), cust_addr varchar(2000), cust_addr2 varchar(2000)) " +
      " replicate EVICTION BY LRUHEAPPERCENT EVICTACTION overflow synchronous 'teststore' ");
  Connection conn = TestUtil.getConnection();
  CallableStatement cs = conn.prepareCall("call sys.set_eviction_heap_percentage(?)");
  cs.setInt(1, 25);
  cs.execute();
  float evictionHeapPercentage = Misc.getGemFireCache().getResourceManager().getEvictionHeapPercentage();
  TestUtil.getLogger().info("evictionHeapPercentage: "+evictionHeapPercentage);
  PreparedStatement ps = conn.prepareStatement("insert into trade.bigcustomers values(?, ?, ?, ?)");
  
  insertNBigElements(1000, ps, 0);
  VM servervm = this.serverVMs.get(0);
  servervm.invoke(GfxdLRUDUnit.class, "raiseFakeHeapEvictorOnEvent");
  Statement s = conn.createStatement();
  insertNBigElements(1000, ps, 1000);
  
  s.execute("select count(*) from trade.bigcustomers");
  ResultSet rs = s.getResultSet();
  int cnt = 0;
  if (rs.next()) {
    cnt = rs.getInt(1);
  }
  TestUtil.getLogger().info("cnt: "+cnt);
  assertEquals("expected 2000 elements but found " + cnt, 2000, cnt);
}
 
Example 11
Source File: ITJDBCDriverTest.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Test
public void testResultSet() throws Exception {
    String sql = "select LSTG_FORMAT_NAME, sum(price) as GMV, count(1) as TRANS_CNT from test_kylin_fact \n"
            + " group by LSTG_FORMAT_NAME ";

    Connection conn = getConnection();
    Statement statement = conn.createStatement();

    statement.execute(sql);

    ResultSet rs = statement.getResultSet();

    int count = 0;
    while (rs.next()) {
        count++;
        String lstg = rs.getString(1);
        double gmv = rs.getDouble(2);
        int trans_count = rs.getInt(3);

        System.out.println("Get a line: LSTG_FORMAT_NAME=" + lstg + ", GMV=" + gmv + ", TRANS_CNT=" + trans_count);
    }

    Assert.assertTrue(count > 0);
    statement.close();
    rs.close();
    conn.close();

}
 
Example 12
Source File: CreateTableTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testMemScaleDDL() throws Exception {
  System.setProperty("gemfire.off-heap-memory-size", "128m");
  Properties props = new Properties();
  int mcastPort = AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS);
  props.put("mcast-port", String.valueOf(mcastPort));    
  Connection conn = TestUtil.getConnection(props);
  Statement st = conn.createStatement();
  
  st.execute("create table mytab(col1 int primary key, col2 varchar(10)) offheap");
  LocalRegion region = (LocalRegion)Misc.getRegion("APP/MYTAB", true, false);
  RegionAttributes<?, ?> ra = region.getAttributes();
  assertTrue(ra.getEnableOffHeapMemory());
  
  PreparedStatement ps = conn.prepareStatement("insert into mytab values (?, ?)");
  for (int i = 0; i < 12345; i++) {
    ps.setInt(1, i);
    ps.setString(2, "abcdefghij");
    ps.execute();
  }
  
  st.execute("select * from mytab where col1 = 7");
  ResultSet rs = st.getResultSet();
  assertTrue(rs.next());
  assertEquals(7, rs.getInt(1));
  assertEquals("abcdefghij", rs.getString(2));
  rs.close();
}
 
Example 13
Source File: QueryTimeOutDUnit.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
   * 
   * @param timOutOnCallableStmt - time out (in seconds) set on the outer 
   * callable stmt
   */
  public static void myProc1(int timOutOnCallableStmt, 
      int[] count, ResultSet[] resultSet1,
      ResultSet[] resultSet2,
      ProcedureExecutionContext ctx) 
          throws SQLException, InterruptedException {
    Connection conn = ctx.getConnection();
//    Connection conn = DriverManager.getConnection("jdbc:default:connection");
    Statement stmt = conn.createStatement();
    
    // make sure that the timeout for statement in proc is same as 
    // that of outer callable statement's time out
    assertEquals(timOutOnCallableStmt, stmt.getQueryTimeout());
    
    // introduce delay so that the procedure times out
    Thread.sleep(1500);
    // check whether the outer callable statement is cancelled
    ctx.checkQueryCancelled();
    fail("The procedure should have failed due to " +
    		"query time out (SQLState:XCL52");
    
    stmt.execute("select * from mytable");
    resultSet1[0] = stmt.getResultSet();
    
    Statement stmt3 = conn.createStatement();
    stmt3 .execute("select count(*) from mytable");
    stmt3.getResultSet().next();
    Integer cnt = stmt3.getResultSet().getInt(1);
    count[0] = cnt;
    
    Statement stmt2 = conn.createStatement();
    stmt2.execute("select count(*) from mytable");
    resultSet2[0] = stmt2.getResultSet();
  }
 
Example 14
Source File: TransExpJdbc.java    From CQL with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void processEn(En en, Schema<Ty, En, Sym, Fk, Att> sch, Connection conn, String q) throws Exception {
	Statement stmt = conn.createStatement();
	stmt.execute(q);
	ResultSet rs = stmt.getResultSet();
	ResultSetMetaData rsmd = rs.getMetaData();
	int columnsNumber = rsmd.getColumnCount();
	if (columnsNumber != 2) {
		stmt.close();
		rs.close();
		throw new RuntimeException("Error in " + en + ": Expected 2 columns but received " + columnsNumber);
	}
	while (rs.next()) {
		Object gen = rs.getObject(1);
		if (gen == null) {
			stmt.close();
			rs.close();
			throw new RuntimeException("Error in " + en + ": Encountered a NULL generator in column 1");
		}
		Object gen2 = rs.getObject(2);
		if (gen2 == null) {
			stmt.close();
			rs.close();
			throw new RuntimeException("Error in " + en + ": Encountered a NULL generator in column 2");
		}
		gens.put(InstExpImport.toGen(en, gen.toString(), op),
				Term.Gen(InstExpImport.toGen(en, gen2.toString(), op)));
	}
	stmt.close();
	rs.close();
}
 
Example 15
Source File: SingleDBLifeCycleTest.java    From Zebra with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiRouterResult2() throws Exception {
	DataSource ds = (DataSource) context.getBean("zebraDS");
	Connection conn = null;
	try {
		conn = ds.getConnection();
		Statement stmt = conn.createStatement();
		stmt.execute("select score from test where id!=1 order by score");
		ResultSet rs = stmt.getResultSet();
		List<Integer> rows = new ArrayList<Integer>();
		while (rs.next()) {
			rows.add(rs.getInt("score"));
		}
		Assert.assertEquals(14, rows.size());
		int index = 0;
		for (int i = 1; i <= 8; i++) {
			if (i == 2) {
				continue;
			}
			Assert.assertEquals(i, rows.get(index).intValue());
			Assert.assertEquals(i, rows.get(index + 1).intValue());
			index += 2;
		}
	} catch (Exception e) {
		Assert.fail();
	} finally {
		if (conn != null) {
			conn.close();
		}
	}
}
 
Example 16
Source File: GfxdLRUDUnit.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void testPRLRUHeapPercDestroy() throws Exception {
  // The test is valid only for transaction isolation level NONE. 
  if (isTransactional) {
    return;
  }

  startVMs(1, 1);
  clientSQLExecute(1, "create table trade.bigcustomers (cid int not null, cust_addr clob) " +
  		"EVICTION BY LRUHEAPPERCENT EVICTACTION destroy");
  Connection conn = TestUtil.getConnection();
  CallableStatement cs = conn.prepareCall("call sys.set_critical_heap_percentage_sg(?, ?)");
  cs.setInt(1, 90);
  cs.setNull(2, Types.VARCHAR);
  cs.execute();
  cs = conn.prepareCall("call sys.set_eviction_heap_percentage_sg(?, ?)");
  cs.setInt(1, 25);
  cs.setNull(2, Types.VARCHAR);
  cs.execute();
  float evictionHeapPercentage = Misc.getGemFireCache().getResourceManager().getEvictionHeapPercentage();
  assertEquals(Float.valueOf(25), evictionHeapPercentage);
  VM servervm = this.serverVMs.get(0);
  servervm.invoke(GfxdLRUDUnit.class, "assertHeapPercentage", new Object[] {Float.valueOf(evictionHeapPercentage)});
  PreparedStatement ps = conn.prepareStatement("insert into trade.bigcustomers values(?, ?)");
  
  insertNBigElements2(200, ps, 0);
  final Statement s = conn.createStatement();

  servervm.invoke(GfxdLRUDUnit.class, "logVMHeapSizeAndCurrentHeapSize");
  final WaitCriterion waitCond = new WaitCriterion() {
    @Override
    public boolean done() {
      try {
        s.execute("select count(*) from trade.bigcustomers");
        ResultSet rs = s.getResultSet();
        int cnt = 0;
        if (rs.next()) {
          cnt = rs.getInt(1);
        }
        TestUtil.getLogger().info("cnt: " + cnt);
        return (cnt < 200);
      } catch (SQLException sqle) {
        fail("unexpected exception " + sqle, sqle);
        return false;
      }
    }

    @Override
    public String description() {
      return "waiting for LRU destroy";
    }
  };
  waitForCriterion(waitCond, 60000, 500, true);
}
 
Example 17
Source File: SelectForUpdateInTransactionDUnit.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void testSelectForUpdate_RR_composite_key_partially_in_projection() throws Exception {
  startVMs(2, 2);

  String jdbcSQL = "create table Employee "
      + "(firstname varchar(50) not null, lastname varchar(50) not null, "
      + "workdept varchar(50), bonus int not null, primary key (firstname, lastname)) replicate";
  
  clientSQLExecute(1, jdbcSQL);
  
  jdbcSQL = "insert into employee values('neeraj', 'kumar', 'rnd', 0), "
      + "('asif', 'shahid', 'rnd', 0), "
      + "('dada', 'ji', 'rnd', 0), ('sum', 'wale', 'rnd', 0)";

  clientSQLExecute(1, jdbcSQL);

  String sql = "SELECT firstname, workdept, bonus "
      + "FROM EMPLOYEE FOR UPDATE of BONUS";

  final java.sql.Connection conn = TestUtil.getConnection();

  Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
      ResultSet.CONCUR_UPDATABLE, ResultSet.CLOSE_CURSORS_AT_COMMIT);

  conn.setTransactionIsolation(getIsolationLevel());
  conn.setAutoCommit(false);

  stmt.execute(sql);

  String conflictSql = "update employee set workdept = 'xxx' "
      + "where lastname = 'kumar'";

  this.serverVMs.get(0).invoke(getClass(), "verifyUpdateConflict",
      new Object[] { conflictSql, Boolean.TRUE, getIsolationLevel() });

  this.serverVMs.get(1).invoke(getClass(), "verifyUpdateConflict",
      new Object[] { conflictSql, Boolean.TRUE, getIsolationLevel() });

  String noConflictSql = "update employee set workdept = 'xxx' "
      + "where lastname = 'wale'";

  this.serverVMs.get(0).invoke(getClass(), "verifyUpdateConflict",
      new Object[] { noConflictSql, Boolean.TRUE, getIsolationLevel() });

  this.serverVMs.get(1).invoke(getClass(), "verifyUpdateConflict",
      new Object[] { noConflictSql, Boolean.TRUE, getIsolationLevel() });

  this.serverVMs.get(0).invoke(getClass(), "executeSelectForUpdateQuery",
      new Object[] { sql, Boolean.TRUE, getIsolationLevel() });

  ResultSet uprs = stmt.getResultSet();

  String theDept = "rnd";
  while (uprs.next()) {
    String workDept = uprs.getString("WORKDEPT");
    if (workDept.equals(theDept)) {
      uprs.updateInt("bonus", 10);
      uprs.updateRow();
    }
  }
  conn.commit();
  sql = "select * from employee";

  stmt.execute(sql);
  ResultSet rs = stmt.getResultSet();
  int cnt = 0;
  while(rs.next()) {
    cnt++;
    int bonus = rs.getInt(4);
    assertEquals(10, bonus);
  }
  assertEquals(4, cnt);
  
  conn.commit();
  sqlExecuteVerify(new int[] { 1 }, new int[] {1}, sql, goldenTextFile, "equal_bonus");
}
 
Example 18
Source File: ResultSetTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that <code>ResultSet.isClosed()</code> returns the
 * correct value in different situations.
 *
 * @throws SQLException	Thrown if some unexpected error happens
 */
public void testIsClosed() throws SQLException{
    
    Statement stmt = createStatement();
    
    // simple open/read/close test
    ResultSet rs = stmt.executeQuery("values(1)");
    assertFalse("rs should be open", rs.isClosed());
    while (rs.next());
    assertFalse("rs should be open", rs.isClosed());
    rs.close();
    assertTrue("rs should be closed", rs.isClosed());
    
    // execute and re-execute statement
    rs = stmt.executeQuery("values(1)");
    assertFalse("rs should be open", rs.isClosed());
    ResultSet rs2 = stmt.executeQuery("values(1)");
    assertTrue("rs should be closed", rs.isClosed());
    assertFalse("rs2 should be open", rs2.isClosed());
    
    // re-execute another statement on the same connection
    Statement stmt2 = createStatement();
    rs = stmt2.executeQuery("values(1)");
    assertFalse("rs2 should be open" ,rs2.isClosed());
    assertFalse("rs should be open", rs.isClosed());
    
    // retrieve multiple result sets
    stmt.execute("create procedure retrieve_result_sets() " +
            "parameter style java language java external name " +
            "'org.apache.derbyTesting.functionTests.tests." +
            "jdbc4.ResultSetTest.threeResultSets' " +
            "dynamic result sets 3 reads sql data");
    stmt.execute("call retrieve_result_sets()");
    ResultSet[] rss = new ResultSet[3];
    int count = 0;
    do {
        rss[count] = stmt.getResultSet();
        assertFalse("rss[" + count + "] should be open", rss[count].isClosed());
        
        if (count > 0) {
            assertTrue("rss[" + (count-1) + "] should be closed", rss[count-1].isClosed());
        }
        ++count;
    } while (stmt.getMoreResults());
    assertEquals("expected three result sets", 3, count);
    stmt.execute("drop procedure retrieve_result_sets");
    
    // close statement
    rs = stmt2.executeQuery("values(1)");
    stmt2.close();
    assertTrue("rs should be closed", rs.isClosed());
    
    // close connection
    Connection conn2 = openDefaultConnection();
    stmt2 = conn2.createStatement();
    rs = stmt2.executeQuery("values(1)");
    conn2.close();
    assertTrue("rs should be closed", rs.isClosed());
    
    stmt.close();
    stmt2.close();
}
 
Example 19
Source File: SelectForUpdateInTransactionDUnit.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void testSelectForUpdate_RR_key_not_in_projection_and_whereClause() throws Exception {
  startVMs(2, 2);

  clientSQLExecute(1, "create schema myapp");
  
  String jdbcSQL = "create table myapp.Employee "
      + "(firstname varchar(50) not null, lastname varchar(50) not null, "
      + "workdept varchar(50), bonus int not null, primary key (firstname)) replicate";
  
  clientSQLExecute(1, jdbcSQL);
  
  jdbcSQL = "insert into myapp.employee values('neeraj', 'kumar', 'rnd', 0), "
      + "('asif', 'shahid', 'rnd', 0), "
      + "('dada', 'ji', 'rnd', 0), ('sum', 'wale', 'rnd', 0)";

  clientSQLExecute(1, jdbcSQL);

  String sql = "SELECT workdept, bonus "
      + "FROM myapp.EMPLOYEE where lastname = 'kumar' FOR UPDATE of BONUS";

  final java.sql.Connection conn = TestUtil.getConnection();

  Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
      ResultSet.CONCUR_UPDATABLE, ResultSet.CLOSE_CURSORS_AT_COMMIT);

  conn.setTransactionIsolation(getIsolationLevel());
  conn.setAutoCommit(false);

  stmt.execute(sql);

  String conflictSql = "update myapp.employee set workdept = 'xxx' "
      + "where lastname = 'kumar'";

  this.serverVMs.get(0).invoke(getClass(), "verifyLocalConflict",
      new Object[] { "/MYAPP/EMPLOYEE", "neeraj", Boolean.TRUE });

  this.serverVMs.get(1).invoke(getClass(), "verifyLocalConflict",
      new Object[] { "/MYAPP/EMPLOYEE", "neeraj", Boolean.TRUE });

  this.serverVMs.get(0).invoke(getClass(), "verifyUpdateConflict",
      new Object[] { conflictSql, Boolean.TRUE, getIsolationLevel() });

  this.serverVMs.get(1).invoke(getClass(), "verifyUpdateConflict",
      new Object[] { conflictSql, Boolean.TRUE, getIsolationLevel() });

  String noConflictSql = "update myapp.employee set workdept = 'xxx' "
      + "where lastname = 'wale'";

  this.serverVMs.get(0).invoke(getClass(), "verifyUpdateConflict",
      new Object[] { noConflictSql, Boolean.FALSE, getIsolationLevel() });

  this.serverVMs.get(1).invoke(getClass(), "verifyUpdateConflict",
      new Object[] { noConflictSql, Boolean.FALSE, getIsolationLevel() });

  this.serverVMs.get(0).invoke(getClass(), "executeSelectForUpdateQuery",
      new Object[] { sql, Boolean.TRUE, getIsolationLevel() });

  ResultSet uprs = stmt.getResultSet();

  String theDept = "rnd";
  while (uprs.next()) {
    String workDept = uprs.getString("WORKDEPT");
    if (workDept.equals(theDept)) {
      uprs.updateInt("bonus", 10);
      uprs.updateRow();
    }
  }
  conn.commit();
  
  sql = "select * from myapp.employee where lastname = 'kumar'";
  stmt.execute(sql);
  ResultSet rs = stmt.getResultSet();
  int cnt = 0;
  while(rs.next()) {
    cnt++;
    int bonus = rs.getInt(4);
    assertEquals(10, bonus);
  }
  assertEquals(1, cnt);
  
  conn.commit();
}
 
Example 20
Source File: CreateHDFSStoreTest.java    From gemfirexd-oss with Apache License 2.0 2 votes vote down vote up
public void testBug49794() throws Exception {    
          Connection conn = TestUtil.getConnection();
          Statement st = conn.createStatement();          
          ResultSet rs = null;          
          
          st.execute("create table t1 (col1 int primary key, col2 int) partition by primary key");
         
//          st.execute("create table t2 (col1 int primary key, col2 int) partition by primary key");
          
          st.execute("create table t3 (col1 int primary key, col2 int) partition by primary key");
          
//          st.execute("create trigger tg1 NO CASCADE BEFORE INSERT on t1 referencing NEW_TABLE as newtable for each STATEMENT " +
//          "insert into t2 values (select * from newtable)");
          
//          st.execute("create trigger tg2 NO CASCADE BEFORE INSERT on t1 referencing new as newinsert for each ROW " +
//              "insert into t2 values (newinsert.col1, newinsert.col2)");
          
          st.execute("create trigger tg3 AFTER INSERT on t1 referencing new as newinsert for each ROW " +
          "insert into t3 values (newinsert.col1, newinsert.col2)");
          
//          st.execute("create trigger tg4 AFTER INSERT on t1 referencing NEW_TABLE as newtable for each STATEMENT " +
//          "insert into t3 values (select * from newtable)");
  
//          st.execute("create trigger tg5 NO CASCADE BEFORE UPDATE on t1 referencing OLD_TABLE as oldtable for each STATEMENT " +
//          "update t2 set col2 = col2 + 1 where col1 in (select col1 from oldtable)");
          
//          st.execute("create trigger tg6 NO CASCADE BEFORE UPDATE on t1 referencing new as newupdate for each ROW " +
//              "update t2 set col2 = col2 + 1 where col1 = newupdate.col1");
          
          st.execute("create trigger tg7 AFTER UPDATE on t1 referencing new as newupdate for each ROW " +
          "update t3 set col2 = col2 + 1 where col1 = newupdate.col1");
          
//          st.execute("create trigger tg8 AFTER UPDATE on t1 referencing OLD_TABLE as oldtable for each STATEMENT " +
//          "update t3 set col2 = col2 + 1 where col1 in (select col1 from oldtable)");
         
          st.execute("insert into t1 values (12, 34)");
                   
          st.execute("update t1 set col2 = col2 + 1 where col1 = 12");
          
          //PUT DML as UPDATE
          st.execute("put into t1 values (12, 56)");
          
          //PUT DML as INSERT
          st.execute("put into t1 values (78, 90)");
          
          
          
          Object[][] expectedOutput1 = new Object[][] { new Object[] { 12, 56 }, new Object[] {78, 90} };
//          Object[][] expectedOutput2 = new Object[][] { new Object[] { 12, 35 } };
          Object[][] expectedOutput3 = new Object[][] { new Object[] { 12, 35 } };
          
          st.execute("select * from t1");
          rs = st.getResultSet();
          JDBC.assertUnorderedResultSet(rs, expectedOutput1, false);
          
//          st.execute("select * from t2");
//          rs = st.getResultSet();
//          JDBC.assertUnorderedResultSet(rs, expectedOutput2, false);
          
          st.execute("select * from t3");
          rs = st.getResultSet();
          JDBC.assertUnorderedResultSet(rs, expectedOutput3, false);
        }