rem
stringlengths
0
477k
add
stringlengths
0
313k
context
stringlengths
6
599k
if ( eof ) throw new EOFException(MessageService.getTextMessage (SQLState.STREAM_EOF));
public int read() throws IOException { if (dummyBytes != 0) { dummyBytes--; return 0; } int ret = super.read(); if (ret < 0) checkSufficientData(); return ret; }
private long getLastPageNumber(BaseContainerHandle handle) throws StandardException
protected long getLastPageNumber(BaseContainerHandle handle) throws StandardException
private long getLastPageNumber(BaseContainerHandle handle) throws StandardException { long retval; synchronized(allocCache) { retval = allocCache.getLastPageNumber(handle, firstAllocPageNumber); } return retval; }
suite.addTestSuite(MainTest.class);
public static Test suite() { TestSuite suite = new TestSuite("Test for iceClient"); //$JUnit-BEGIN$ suite.addTestSuite(MainTest.class); //$JUnit-END$ return suite; }
System.out.println("TESTING READ_ONLY TRANSACTION FOLLOWED BY WRTIABLE TRANSACTION");
System.out.println("TESTING READ_ONLY TRANSACTION FOLLOWED BY WRITABLE TRANSACTION");
protected void runTest(String[] args) throws Exception { // Check the returned type of the JDBC Connections. ij.getPropertyArg(args); Connection dmc = ij.startJBMS(); dmc.createStatement().executeUpdate("create table y(i int)"); dmc.createStatement().executeUpdate( "create procedure checkConn2(in dsname varchar(20)) " + "parameter style java language java modifies SQL DATA " + "external name 'org.apache.derbyTesting.functionTests.tests.jdbcapi." + this.getNestedMethodName() + "'"); CallableStatement cs = dmc.prepareCall("call checkConn2(?)"); cs.setString(1,"Nested"); cs.execute(); checkConnection("DriverManager ", dmc); if (testConnectionToString) checkJBMSToString(); Properties attrs = new Properties(); attrs.setProperty("databaseName", "wombat"); DataSource dscs = TestUtil.getDataSource(attrs); if (testConnectionToString) checkToString(dscs); DataSource ds = dscs; checkConnection("DataSource", ds.getConnection()); DataSource dssimple = null; if (testSimpleDataSource) { dssimple = TestUtil.getSimpleDataSource(attrs); ds = dssimple; checkConnection("SimpleDataSource", ds.getConnection()); } ConnectionPoolDataSource dsp = TestUtil.getConnectionPoolDataSource(attrs); if (testConnectionToString) checkToString(dsp); PooledConnection pc = dsp.getPooledConnection(); SecurityCheck.inspect(pc, "javax.sql.PooledConnection"); pc.addConnectionEventListener(new EventCatcher(1)); checkConnection("ConnectionPoolDataSource", pc.getConnection()); checkConnection("ConnectionPoolDataSource", pc.getConnection()); // BUG 4471 - check outstanding updates are rolled back. Connection c1 = pc.getConnection(); Statement s = c1.createStatement(); s.executeUpdate("create table t (i int)"); s.executeUpdate("insert into t values(1)"); c1.setAutoCommit(false); // this update should be rolled back s.executeUpdate("insert into t values(2)"); c1 = pc.getConnection(); ResultSet rs = c1.createStatement().executeQuery("select count(*) from t"); rs.next(); int count = rs.getInt(1); System.out.println(count == 1 ? "Changes rolled back OK in auto closed pooled connection" : ("FAIL changes committed in in auto closed pooled connection - " + count)); c1.close(); // check connection objects are closed once connection is closed try { rs.next(); System.out.println("FAIL - ResultSet is open for a closed connection obtained from PooledConnection"); } catch (SQLException sqle) { System.out.println("expected SQL Exception: (" + sqle.getSQLState() + ") " + sqle.getMessage()); } try { s.executeUpdate("update t set i = 1"); System.out.println("FAIL - Statement is open for a closed connection obtained from PooledConnection"); } catch (SQLException sqle) { System.out.println("expected SQL Exception: (" + sqle.getSQLState() + ") " + sqle.getMessage()); } pc.close(); pc = null; testPoolReset("ConnectionPoolDataSource", dsp.getPooledConnection()); XADataSource dsx = TestUtil.getXADataSource(attrs); if (testConnectionToString) checkToString(dsx); XAConnection xac = dsx.getXAConnection(); SecurityCheck.inspect(xac, "javax.sql.XAConnection"); xac.addConnectionEventListener(new EventCatcher(3)); checkConnection("XADataSource", xac.getConnection()); // BUG 4471 - check outstanding updates are rolled back wi XAConnection. c1 = xac.getConnection(); s = c1.createStatement(); s.executeUpdate("insert into t values(1)"); c1.setAutoCommit(false); // this update should be rolled back s.executeUpdate("insert into t values(2)"); c1 = xac.getConnection(); rs = c1.createStatement().executeQuery("select count(*) from t"); rs.next(); count = rs.getInt(1); rs.close(); System.out.println(count == 2 ? "Changes rolled back OK in auto closed local XAConnection" : ("FAIL changes committed in in auto closed pooled connection - " + count)); c1.close(); xac.close(); xac = null; testPoolReset("XADataSource", dsx.getXAConnection()); try { TestUtil.getConnection("","shutdown=true"); } catch (SQLException sqle) { JDBCDisplayUtil.ShowSQLException(System.out, sqle); } dmc = ij.startJBMS(); cs = dmc.prepareCall("call checkConn2(?)"); SecurityCheck.inspect(cs, "java.sql.CallableStatement"); cs.setString(1,"Nested"); cs.execute(); checkConnection("DriverManager ", dmc); // reset ds back to the Regular DataSource ds = dscs; checkConnection("DataSource", ds.getConnection()); // and back to EmbeddedSimpleDataSource if(TestUtil.isEmbeddedFramework()) { // JSR169 (SimpleDataSource) is only available on embedded. ds = dssimple; checkConnection("EmbeddedSimpleDataSource", dssimple.getConnection()); } pc = dsp.getPooledConnection(); pc.addConnectionEventListener(new EventCatcher(2)); checkConnection("ConnectionPoolDataSource", pc.getConnection()); checkConnection("ConnectionPoolDataSource", pc.getConnection()); // test "local" XAConnections xac = dsx.getXAConnection(); xac.addConnectionEventListener(new EventCatcher(4)); checkConnection("XADataSource", xac.getConnection()); checkConnection("XADataSource", xac.getConnection()); xac.close(); // test "global" XAConnections xac = dsx.getXAConnection(); xac.addConnectionEventListener(new EventCatcher(5)); XAResource xar = xac.getXAResource(); SecurityCheck.inspect(xar, "javax.transaction.xa.XAResource"); Xid xid = new cdsXid(1, (byte) 35, (byte) 47); xar.start(xid, XAResource.TMNOFLAGS); Connection xacc = xac.getConnection(); xacc.close(); checkConnection("Global XADataSource", xac.getConnection()); checkConnection("Global XADataSource", xac.getConnection()); xar.end(xid, XAResource.TMSUCCESS); checkConnection("Switch to local XADataSource", xac.getConnection()); checkConnection("Switch to local XADataSource", xac.getConnection()); Connection backtoGlobal = xac.getConnection(); xar.start(xid, XAResource.TMJOIN); checkConnection("Switch to global XADataSource", backtoGlobal); checkConnection("Switch to global XADataSource", xac.getConnection()); xar.end(xid, XAResource.TMSUCCESS); xar.commit(xid, true); xac.close(); // now some explicit tests for how connection state behaves // when switching between global transactions and local // and setting connection state. // some of this is already tested in simpleDataSource and checkDataSource // but I want to make sure I cover all situations. (djd) xac = dsx.getXAConnection(); xac.addConnectionEventListener(new EventCatcher(6)); xar = xac.getXAResource(); xid = new cdsXid(1, (byte) 93, (byte) 103); // series 1 - Single connection object Connection cs1 = xac.getConnection(); printState("initial local", cs1); xar.start(xid, XAResource.TMNOFLAGS); printState("initial X1", cs1); cs1.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); cs1.setReadOnly(true); setHoldability(cs1, false); printState("modified X1", cs1); xar.end(xid, XAResource.TMSUCCESS); // the underlying local transaction/connection must pick up the // state of the Connection handle cs1 printState("modified local", cs1); cs1.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); cs1.setReadOnly(false); setHoldability(cs1, false); printState("reset local", cs1); // now re-join the transaction, should pick up the read-only // and isolation level from the transaction, // holdability remains that of this handle. xar.start(xid, XAResource.TMJOIN); printState("re-join X1", cs1); xar.end(xid, XAResource.TMSUCCESS); // should be the same as the reset local printState("back to local (same as reset)", cs1); // test suspend/resume // now re-join the transaction, should pick up the read-only // and isolation level from the transaction, // holdability remains that of this handle. xar.start(xid, XAResource.TMJOIN); printState("re-join X1 second time", cs1); xar.end(xid, XAResource.TMSUSPEND); printState("local after suspend", cs1); xar.start(xid, XAResource.TMRESUME); printState("resume X1", cs1); xar.end(xid, XAResource.TMSUCCESS); printState("back to local (second time)", cs1); cs1.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); cs1.setReadOnly(true); setHoldability(cs1, true); cs1.close(); cs1 = xac.getConnection(); printState("new handle - local ", cs1); cs1.close(); xar.start(xid, XAResource.TMJOIN); cs1 = xac.getConnection(); printState("re-join with new handle X1", cs1); cs1.close(); xar.end(xid, XAResource.TMSUCCESS); // now get a connection (attached to a local) // attach to the global and commit it. // state should be that of the local after the commit. cs1 = xac.getConnection(); cs1.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); printState("pre-X1 commit - local", cs1); xar.start(xid, XAResource.TMJOIN); printState("pre-X1 commit - X1", cs1); xar.end(xid, XAResource.TMSUCCESS); printState("post-X1 end - local", cs1); xar.commit(xid, true); printState("post-X1 commit - local", cs1); cs1.close(); //Derby-421 Setting isolation level with SQL was not getting handled correctly System.out.println("Some more isolation testing using SQL and JDBC api"); cs1 = xac.getConnection(); s = cs1.createStatement(); printState("initial local", cs1); System.out.println("Issue setTransactionIsolation in local transaction"); cs1.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); printState("setTransactionIsolation in local", cs1); testSetIsolationWithStatement(s, xar, cs1); // now check re-use of *Statement objects across local/global connections. System.out.println("TESTING RE_USE OF STATEMENT OBJECTS"); cs1 = xac.getConnection(); // ensure read locks stay around until end-of transaction cs1.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); cs1.setAutoCommit(false); checkLocks(cs1); Statement sru1 = cs1.createStatement(); sru1.setCursorName("SN1"); sru1.executeUpdate("create table ru(i int)"); sru1.executeUpdate("insert into ru values 1,2,3"); Statement sruBatch = cs1.createStatement(); sruBatch.setCursorName("sruBatch"); Statement sruState = createFloatStatementForStateChecking(cs1); PreparedStatement psruState = createFloatStatementForStateChecking(cs1, "select i from ru where i = ?"); CallableStatement csruState = createFloatCallForStateChecking(cs1, "CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?,?)"); PreparedStatement psParams = cs1.prepareStatement("select * from ru where i > ?"); psParams.setCursorName("params"); psParams.setInt(1, 2); resultSetQuery("Params-local-1", psParams.executeQuery()); sruBatch.addBatch("insert into ru values 4"); queryOnStatement("sru1-local-1", cs1, sru1); cs1.commit(); // need to commit to switch to an global connection; xid = new cdsXid(1, (byte) 103, (byte) 119); xar.start(xid, XAResource.TMNOFLAGS); // simple case - underlying connection is re-used for global. System.out.println("Expecting downgrade because global transaction sru1-global-2 is using a statement with holdability true"); queryOnStatement("sru1-global-2", cs1, sru1); sruBatch.addBatch("insert into ru values 5"); Statement sru2 = cs1.createStatement(); sru2.setCursorName("OAK2"); queryOnStatement("sru2-global-3", cs1, sru2); System.out.println("Expecting downgrade because global transaction sru1-global-4 is using a statement with holdability true"); queryOnStatement("sru1-global-4", cs1, sru1); showStatementState("GLOBAL ", sruState); showStatementState("PS GLOBAL ", psruState); showStatementState("CS GLOBAL ", csruState); resultSetQuery("Params-global-1", psParams.executeQuery()); xar.end(xid, XAResource.TMSUCCESS); // now a new underlying connection is created queryOnStatement("sru1-local-5", cs1, sru1); queryOnStatement("sru2-local-6", cs1, sru2); sruBatch.addBatch("insert into ru values 6,7"); Statement sru3 = cs1.createStatement(); sru3.setCursorName("SF3"); queryOnStatement("sru3-local-7", cs1, sru3); // Two transactions should hold locks (global and the current XA); showStatementState("LOCAL ", sruState); showStatementState("PS LOCAL ", psruState); showStatementState("CS LOCAL ", csruState); resultSetQuery("Params-local-2", psParams.executeQuery()); checkLocks(cs1); cs1.commit(); // attach the XA transaction to another connection and see what happens XAConnection xac2 = dsx.getXAConnection(); xac2.addConnectionEventListener(new EventCatcher(5)); XAResource xar2 = xac2.getXAResource(); xar2.start(xid, XAResource.TMJOIN); Connection cs2 = xac2.getConnection(); // these statements were generated by cs1 and thus are still // in a local connection. queryOnStatement("sru1-local-8", cs1, sru1); queryOnStatement("sru2-local-9", cs1, sru2); queryOnStatement("sru3-local-10", cs1, sru3); sruBatch.addBatch("insert into ru values 8"); showStatementState("LOCAL 2 ", sruState); showStatementState("PS LOCAL 2 ", psruState); showStatementState("CS LOCAL 2", csruState); checkLocks(cs1); int[] updateCounts = sruBatch.executeBatch(); System.out.print("sruBatch update counts :"); for (int i = 0; i < updateCounts.length; i++) { System.out.print(" " + updateCounts[i] + " "); } System.out.println(":"); queryOnStatement("sruBatch", cs1, sruBatch); xar2.end(xid, XAResource.TMSUCCESS); xac2.close(); // allow close on already closed XAConnection xac2.close(); xac2.addConnectionEventListener(null); xac2.removeConnectionEventListener(null); // test methods against a closed XAConnection and its resource try { xac2.getXAResource(); } catch (SQLException sqle) { System.out.println("XAConnection.getXAResource : " + sqle.getMessage()); } try { xac2.getConnection(); } catch (SQLException sqle) { System.out.println("XAConnection.getConnection : " + sqle.getMessage()); } try { xar2.start(xid, XAResource.TMJOIN); } catch (XAException xae) { showXAException("XAResource.start", xae); } try { xar2.end(xid, XAResource.TMJOIN); } catch (XAException xae) { showXAException("XAResource.end", xae); } try { xar2.commit(xid, true); } catch (XAException xae) { showXAException("XAResource.commit", xae); } try { xar2.prepare(xid); } catch (XAException xae) { showXAException("XAResource.prepare", xae); } try { xar2.recover(0); } catch (XAException xae) { showXAException("XAResource.recover", xae); } try { xar2.prepare(xid); } catch (XAException xae) { showXAException("XAResource.prepare", xae); } try { xar2.isSameRM(xar2); } catch (XAException xae) { showXAException("XAResource.isSameRM", xae); } // Patricio (on the forum) one was having an issue with set schema not working in an XA connection. dmc = ij.startJBMS(); dmc.createStatement().executeUpdate("create schema SCHEMA_Patricio"); dmc.createStatement().executeUpdate("create table SCHEMA_Patricio.Patricio (id VARCHAR(255), value INTEGER)"); dmc.commit(); dmc.close(); XAConnection xac3 = dsx.getXAConnection(); Connection conn3 = xac3.getConnection(); Statement st3 = conn3.createStatement(); st3.execute("SET SCHEMA SCHEMA_Patricio"); st3.close(); PreparedStatement ps3 = conn3.prepareStatement("INSERT INTO Patricio VALUES (? , ?)"); ps3.setString(1, "Patricio"); ps3.setInt(2, 3); ps3.executeUpdate(); System.out.println("Patricio update count " + ps3.getUpdateCount()); ps3.close(); conn3.close(); xac3.close(); // test that an xastart in auto commit mode commits the existing work.(beetle 5178) XAConnection xac4 = dsx.getXAConnection(); Xid xid4a = new cdsXid(4, (byte) 23, (byte) 76); Connection conn4 = xac4.getConnection(); System.out.println("conn4 autcommit " + conn4.getAutoCommit()); Statement s4 = conn4.createStatement(); s4.executeUpdate("create table autocommitxastart(i int)"); s4.executeUpdate("insert into autocommitxastart values 1,2,3,4,5"); ResultSet rs4 = s4.executeQuery("select i from autocommitxastart"); rs4.next(); System.out.println("acxs " + rs4.getInt(1)); rs4.next(); System.out.println("acxs " + rs4.getInt(1)); xac4.getXAResource().start(xid4a, XAResource.TMNOFLAGS); xac4.getXAResource().end(xid4a, XAResource.TMSUCCESS); try { rs4.next(); System.out.println("acxs " + rs.getInt(1)); } catch (SQLException sqle) { System.out.println("autocommitxastart expected " + sqle.getMessage()); } conn4.setAutoCommit(false); rs4 = s4.executeQuery("select i from autocommitxastart"); rs4.next(); System.out.println("acxs " + rs4.getInt(1)); rs4.next(); System.out.println("acxs " + rs4.getInt(1)); // Get a new xid to begin another transaction. // This should give XAER_OUTSIDE exception because // the resource manager is busy in the local transaction xid4a = new cdsXid(4, (byte) 93, (byte) 103); try { xac4.getXAResource().start(xid4a, XAResource.TMNOFLAGS); } catch (XAException xae) { showXAException("autocommitxastart expected ", xae); System.out.println("Expected XA error code: " + xae.errorCode); } rs4.next(); System.out.println("acxs " + rs4.getInt(1)); rs4.close(); conn4.rollback(); conn4.close(); xac4.close(); // Test following sequence of steps // 1)start a read-only global transaction // 2)finish that read-only transaction // 3)start another global transaction System.out.println("TESTING READ_ONLY TRANSACTION FOLLOWED BY WRTIABLE TRANSACTION"); XAConnection xac5 = dsx.getXAConnection(); Xid xid5a = new cdsXid(5, (byte) 119, (byte) 129); Connection conn5 = xac5.getConnection(); Statement sru5a = conn5.createStatement(); xar = xac5.getXAResource(); xar.start(xid5a, XAResource.TMNOFLAGS); conn5.setReadOnly(true); printState("read-only XA transaction", conn5); ResultSet rs5 = sru5a.executeQuery("select count(*) from autocommitxastart"); rs5.next(); System.out.println("acxs " + rs5.getInt(1)); rs5.close(); xar.end(xid5a, XAResource.TMSUCCESS); xar.commit(xid5a, true); conn5.close(); //now start a new transaction conn5 = xac5.getConnection(); sru5a = conn5.createStatement(); xar.start(xid5a, XAResource.TMNOFLAGS); printState("Writable XA transaction", conn5); sru5a.executeUpdate("insert into autocommitxastart values 6,7"); rs5 = sru5a.executeQuery("select count(*) from autocommitxastart"); rs5.next(); System.out.println("acxs " + rs5.getInt(1)); xar.end(xid5a, XAResource.TMSUCCESS); xar.commit(xid5a, true); conn5.close(); xac5.close(); // test jira-derby 95 - a NullPointerException was returned when passing // an incorrect database name (a url in this case) - should now give error XCY00 Connection dmc95 = ij.startJBMS(); String sqls; try { testJira95ds( dmc95, "jdbc:derby:mydb" ); } catch (SQLException sqle) { sqls = sqle.getSQLState(); if (sqls.equals("XCY00")) System.out.println("; ok - expected exception: " + sqls); else System.out.println("; wrong, unexpected exception: " + sqls + " - " + sqle.toString()); } catch (Exception e) { System.out.println("; wrong, unexpected exception: " + e.toString()); } try { testJira95xads( dmc95, "jdbc:derby:wombat" ); } catch (SQLException sqle) { sqls = sqle.getSQLState(); if (sqls.equals("XCY00")) System.out.println("; ok - expected exception: " + sqls + "\n"); else System.out.println("; wrong - unexpected exception: " + sqls + " - " + sqle.toString()); } catch (Exception e) { System.out.println("; wrong, unexpected exception: " + e.toString()); } if (TestUtil.isDerbyNetClientFramework()) testClientDSConnectionAttributes(); // skip testDSRequestAuthentication for client because of this issue: // DERBY-1131 : Deprecate Derby DataSource property attributesAsPassword // First part of this test is covered by testClientDSConnectionAttributes() if (TestUtil.isDerbyNetClientFramework()) return; testDSRequestAuthentication(); }
networkServer.start(null);
networkServer.start(new PrintWriter(serverOutput));
private void startNetworkServer() { String hostName = null; int serverPort; // Determines which host and port to run the network server on // This is based how it is done in the test testSecMec.java String serverName = TestUtil.getHostName(); if (serverName.equals("localhost")) { serverPort = 1527; } else { serverPort = 20000; } try { NetworkServerControl networkServer = new NetworkServerControl(InetAddress.getByName(serverName), serverPort); networkServer.start(null); // Wait for the network server to start boolean started = false; int retries = 10; // Max retries = max seconds to wait while (!started && retries > 0) { try { // Sleep 1 second and then ping the network server Thread.sleep(1000); networkServer.ping(); // If ping does not throw an exception the server has started started = true; } catch(Exception e) { System.out.println("INFO: ping returned: " + e); retries--; } } // Check if we got a reply on ping if (!started) { System.out.println("FAIL: Failed to start network server"); } } catch (Exception e) { System.out.println("FAIL: startNetworkServer got exception: " + e); } }
if (serverOutput != null) { serverOutput.close(); }
private void stopNetworkServer() { try { NetworkServerControl networkServer = new NetworkServerControl(); networkServer.shutdown(); } catch(Exception e) { System.out.println("INFO: Network server shutdown returned: " + e); } }
int isolationLevel
int isolationLevel, int maxMemoryPerTable
int getScanArgs(TransactionController tc, MethodBuilder mb, Optimizable innerTable, OptimizablePredicateList storeRestrictionList, OptimizablePredicateList nonStoreRestrictionList, ExpressionClassBuilderInterface acb, int bulkFetch, MethodBuilder resultRowAllocator, int colRefItem, int indexColItem, int lockMode, boolean tableLocked, int isolationLevel ) throws StandardException;
flowAutoCommitIfNotAutoCommitted();
statement_.resultSetCommitting(this);
public final void closeX() throws SqlException { if (!openOnClient_) { return; } try { if (openOnServer_) { flowCloseAndAutoCommitIfNotAutoCommitted(); } else { flowAutoCommitIfNotAutoCommitted(); // in case of early close } } finally { markClosed(); connection_.CommitAndRollbackListeners_.remove(this); } flowAutoCommitIfLastOpenMultipleResultSetWasJustClosed(); if (statement_.openOnClient_ && statement_.isCatalogQuery_) { statement_.closeX(); } nullDataForGC(); }
flowAutoCommitIfLastOpenMultipleResultSetWasJustClosed();
public final void closeX() throws SqlException { if (!openOnClient_) { return; } try { if (openOnServer_) { flowCloseAndAutoCommitIfNotAutoCommitted(); } else { flowAutoCommitIfNotAutoCommitted(); // in case of early close } } finally { markClosed(); connection_.CommitAndRollbackListeners_.remove(this); } flowAutoCommitIfLastOpenMultipleResultSetWasJustClosed(); if (statement_.openOnClient_ && statement_.isCatalogQuery_) { statement_.closeX(); } nullDataForGC(); }
writeCloseAndAutoCommitIfNotAutoCommitted();
boolean performedAutoCommit = writeCloseAndAutoCommit();
void flowCloseAndAutoCommitIfNotAutoCommitted() throws SqlException { agent_.beginWriteChain(statement_); writeCloseAndAutoCommitIfNotAutoCommitted(); agent_.flow(statement_); readCloseAndAutoCommitIfNotAutoCommitted(); agent_.endReadChain(); }
readCloseAndAutoCommitIfNotAutoCommitted();
readCloseAndAutoCommit(performedAutoCommit);
void flowCloseAndAutoCommitIfNotAutoCommitted() throws SqlException { agent_.beginWriteChain(statement_); writeCloseAndAutoCommitIfNotAutoCommitted(); agent_.flow(statement_); readCloseAndAutoCommitIfNotAutoCommitted(); agent_.endReadChain(); }
closeX();
statement_.resultSetCommitting(this);
boolean nextX() throws SqlException { checkForClosedResultSet(); clearWarningsX(); wasNull_ = ResultSet.WAS_NULL_UNSET; // discard all previous updates when moving the cursor resetUpdatedColumns(); // for TYPE_FORWARD_ONLY ResultSet, just call cursor.next() if (resultSetType_ == java.sql.ResultSet.TYPE_FORWARD_ONLY) { // cursor is null for singleton selects that do not return data. isValidCursorPosition_ = (cursor_ == null) ? false : cursor_.next(); // for forward-only cursors, if qryrowset was specificed on OPNQRY or EXCSQLSTT, // then we must count the rows returned in the rowset to make sure we received a // complete rowset. if not, we need to complete the rowset on the next fetch. if (fetchSize_ != 0) { if (rowsYetToBeReceivedForRowset_ == 0) { rowsYetToBeReceivedForRowset_ = fetchSize_; } if (isValidCursorPosition_) { rowsYetToBeReceivedForRowset_--; } } // Auto-commit semantics for exhausted cursors follows. // From Connection.setAutoCommit() javadoc: // The commit occurs when the statement completes or the next execute occurs, whichever comes first. // In the case of statements returning a ResultSet object, the statement completes when the // last row of the ResultSet object has been retrieved or the ResultSet object has been closed. // In advanced cases, a single statement may return multiple results as well as output parameter values. // In these cases, the commit occurs when all results and output parameter values have been retrieved. // we will check to see if the forward only result set has gone past the end, // we will close the result set, the autocommit logic is in the closeX() method// if (!isValidCursorPosition_ && // We've gone past the end (+100)// cursor_ != null) { if ((!isValidCursorPosition_ && cursor_ != null) || (statement_.maxRows_ > 0 && cursor_.rowsRead_ > statement_.maxRows_)) { isValidCursorPosition_ = false; // if not on a valid row and the query is closed at the server. // check for an error which may have caused the cursor to terminate. // if there were no more rows because of an error, then this method // should throw an SqlException rather than just returning false. // note: closeX is still called and this will cause the // result set to be closed on the client. any additional calls to // next() will fail checkForClosedResultSet(), the query terminating exception is // only thrown once. // depending on how this works with scrollable cursors, there may be // a better way/more common place for this logic. SqlException sqlException = null; if (!openOnServer_) { int sqlcode = Utils.getSqlcodeFromSqlca(queryTerminatingSqlca_); if (sqlcode > 0 && sqlcode != 100) { accumulateWarning(new SqlWarning(agent_.logWriter_, queryTerminatingSqlca_)); } else if (sqlcode < 0) { sqlException = new SqlException(agent_.logWriter_, queryTerminatingSqlca_); } } try { closeX(); // the auto commit logic is in closeX() } catch (SqlException sqle) { sqlException = Utils.accumulateSQLException(sqle, sqlException); } if (sqlException != null) { throw sqlException; } } } // for scrollable ResultSet's, // if the "next" request is still fetching within the current rowset, // update column info from cache and increment the current row index // else // fetch the next rowset from the server else { // These flags will only be used for dynamic cursors where we don't know the row count // and can't keep track of the absolute position of the cursor. isAfterLast_ = false; isLast_ = false; // if the next row is still within the current rowset if (rowIsInCurrentRowset(firstRowInRowset_ + currentRowInRowset_ + 1, scrollOrientation_next__)) { isValidCursorPosition_ = true; currentRowInRowset_++; } else { checkAndThrowReceivedQueryTerminatingException(); isValidCursorPosition_ = getNextRowset(); } if (isValidCursorPosition_) { updateColumnInfoFromCache(); // check if there is a non-null SQLCA for the current row for rowset cursors checkRowsetSqlca(); if (isBeforeFirst_) { isFirst_ = true; } isBeforeFirst_ = false; } else { isFirst_ = false; return isValidCursorPosition_; } } // for forward-only cursors, check if rowsRead_ > maxRows_. // for scrollable cursors, check if absolute row number > maxRows_. // maxRows_ will be ignored by sensitive dynamic cursors since we don't know the rowCount if (!openOnClient_) { isValidCursorPosition_ = false; } else if (sensitivity_ != sensitivity_sensitive_dynamic__ && statement_.maxRows_ > 0 && (firstRowInRowset_ + currentRowInRowset_ > statement_.maxRows_)) { isValidCursorPosition_ = false; } return isValidCursorPosition_; }
if (sqlException != null) {
if (sqlException != null)
boolean nextX() throws SqlException { checkForClosedResultSet(); clearWarningsX(); wasNull_ = ResultSet.WAS_NULL_UNSET; // discard all previous updates when moving the cursor resetUpdatedColumns(); // for TYPE_FORWARD_ONLY ResultSet, just call cursor.next() if (resultSetType_ == java.sql.ResultSet.TYPE_FORWARD_ONLY) { // cursor is null for singleton selects that do not return data. isValidCursorPosition_ = (cursor_ == null) ? false : cursor_.next(); // for forward-only cursors, if qryrowset was specificed on OPNQRY or EXCSQLSTT, // then we must count the rows returned in the rowset to make sure we received a // complete rowset. if not, we need to complete the rowset on the next fetch. if (fetchSize_ != 0) { if (rowsYetToBeReceivedForRowset_ == 0) { rowsYetToBeReceivedForRowset_ = fetchSize_; } if (isValidCursorPosition_) { rowsYetToBeReceivedForRowset_--; } } // Auto-commit semantics for exhausted cursors follows. // From Connection.setAutoCommit() javadoc: // The commit occurs when the statement completes or the next execute occurs, whichever comes first. // In the case of statements returning a ResultSet object, the statement completes when the // last row of the ResultSet object has been retrieved or the ResultSet object has been closed. // In advanced cases, a single statement may return multiple results as well as output parameter values. // In these cases, the commit occurs when all results and output parameter values have been retrieved. // we will check to see if the forward only result set has gone past the end, // we will close the result set, the autocommit logic is in the closeX() method// if (!isValidCursorPosition_ && // We've gone past the end (+100)// cursor_ != null) { if ((!isValidCursorPosition_ && cursor_ != null) || (statement_.maxRows_ > 0 && cursor_.rowsRead_ > statement_.maxRows_)) { isValidCursorPosition_ = false; // if not on a valid row and the query is closed at the server. // check for an error which may have caused the cursor to terminate. // if there were no more rows because of an error, then this method // should throw an SqlException rather than just returning false. // note: closeX is still called and this will cause the // result set to be closed on the client. any additional calls to // next() will fail checkForClosedResultSet(), the query terminating exception is // only thrown once. // depending on how this works with scrollable cursors, there may be // a better way/more common place for this logic. SqlException sqlException = null; if (!openOnServer_) { int sqlcode = Utils.getSqlcodeFromSqlca(queryTerminatingSqlca_); if (sqlcode > 0 && sqlcode != 100) { accumulateWarning(new SqlWarning(agent_.logWriter_, queryTerminatingSqlca_)); } else if (sqlcode < 0) { sqlException = new SqlException(agent_.logWriter_, queryTerminatingSqlca_); } } try { closeX(); // the auto commit logic is in closeX() } catch (SqlException sqle) { sqlException = Utils.accumulateSQLException(sqle, sqlException); } if (sqlException != null) { throw sqlException; } } } // for scrollable ResultSet's, // if the "next" request is still fetching within the current rowset, // update column info from cache and increment the current row index // else // fetch the next rowset from the server else { // These flags will only be used for dynamic cursors where we don't know the row count // and can't keep track of the absolute position of the cursor. isAfterLast_ = false; isLast_ = false; // if the next row is still within the current rowset if (rowIsInCurrentRowset(firstRowInRowset_ + currentRowInRowset_ + 1, scrollOrientation_next__)) { isValidCursorPosition_ = true; currentRowInRowset_++; } else { checkAndThrowReceivedQueryTerminatingException(); isValidCursorPosition_ = getNextRowset(); } if (isValidCursorPosition_) { updateColumnInfoFromCache(); // check if there is a non-null SQLCA for the current row for rowset cursors checkRowsetSqlca(); if (isBeforeFirst_) { isFirst_ = true; } isBeforeFirst_ = false; } else { isFirst_ = false; return isValidCursorPosition_; } } // for forward-only cursors, check if rowsRead_ > maxRows_. // for scrollable cursors, check if absolute row number > maxRows_. // maxRows_ will be ignored by sensitive dynamic cursors since we don't know the rowCount if (!openOnClient_) { isValidCursorPosition_ = false; } else if (sensitivity_ != sensitivity_sensitive_dynamic__ && statement_.maxRows_ > 0 && (firstRowInRowset_ + currentRowInRowset_ > statement_.maxRows_)) { isValidCursorPosition_ = false; } return isValidCursorPosition_; }
}
boolean nextX() throws SqlException { checkForClosedResultSet(); clearWarningsX(); wasNull_ = ResultSet.WAS_NULL_UNSET; // discard all previous updates when moving the cursor resetUpdatedColumns(); // for TYPE_FORWARD_ONLY ResultSet, just call cursor.next() if (resultSetType_ == java.sql.ResultSet.TYPE_FORWARD_ONLY) { // cursor is null for singleton selects that do not return data. isValidCursorPosition_ = (cursor_ == null) ? false : cursor_.next(); // for forward-only cursors, if qryrowset was specificed on OPNQRY or EXCSQLSTT, // then we must count the rows returned in the rowset to make sure we received a // complete rowset. if not, we need to complete the rowset on the next fetch. if (fetchSize_ != 0) { if (rowsYetToBeReceivedForRowset_ == 0) { rowsYetToBeReceivedForRowset_ = fetchSize_; } if (isValidCursorPosition_) { rowsYetToBeReceivedForRowset_--; } } // Auto-commit semantics for exhausted cursors follows. // From Connection.setAutoCommit() javadoc: // The commit occurs when the statement completes or the next execute occurs, whichever comes first. // In the case of statements returning a ResultSet object, the statement completes when the // last row of the ResultSet object has been retrieved or the ResultSet object has been closed. // In advanced cases, a single statement may return multiple results as well as output parameter values. // In these cases, the commit occurs when all results and output parameter values have been retrieved. // we will check to see if the forward only result set has gone past the end, // we will close the result set, the autocommit logic is in the closeX() method// if (!isValidCursorPosition_ && // We've gone past the end (+100)// cursor_ != null) { if ((!isValidCursorPosition_ && cursor_ != null) || (statement_.maxRows_ > 0 && cursor_.rowsRead_ > statement_.maxRows_)) { isValidCursorPosition_ = false; // if not on a valid row and the query is closed at the server. // check for an error which may have caused the cursor to terminate. // if there were no more rows because of an error, then this method // should throw an SqlException rather than just returning false. // note: closeX is still called and this will cause the // result set to be closed on the client. any additional calls to // next() will fail checkForClosedResultSet(), the query terminating exception is // only thrown once. // depending on how this works with scrollable cursors, there may be // a better way/more common place for this logic. SqlException sqlException = null; if (!openOnServer_) { int sqlcode = Utils.getSqlcodeFromSqlca(queryTerminatingSqlca_); if (sqlcode > 0 && sqlcode != 100) { accumulateWarning(new SqlWarning(agent_.logWriter_, queryTerminatingSqlca_)); } else if (sqlcode < 0) { sqlException = new SqlException(agent_.logWriter_, queryTerminatingSqlca_); } } try { closeX(); // the auto commit logic is in closeX() } catch (SqlException sqle) { sqlException = Utils.accumulateSQLException(sqle, sqlException); } if (sqlException != null) { throw sqlException; } } } // for scrollable ResultSet's, // if the "next" request is still fetching within the current rowset, // update column info from cache and increment the current row index // else // fetch the next rowset from the server else { // These flags will only be used for dynamic cursors where we don't know the row count // and can't keep track of the absolute position of the cursor. isAfterLast_ = false; isLast_ = false; // if the next row is still within the current rowset if (rowIsInCurrentRowset(firstRowInRowset_ + currentRowInRowset_ + 1, scrollOrientation_next__)) { isValidCursorPosition_ = true; currentRowInRowset_++; } else { checkAndThrowReceivedQueryTerminatingException(); isValidCursorPosition_ = getNextRowset(); } if (isValidCursorPosition_) { updateColumnInfoFromCache(); // check if there is a non-null SQLCA for the current row for rowset cursors checkRowsetSqlca(); if (isBeforeFirst_) { isFirst_ = true; } isBeforeFirst_ = false; } else { isFirst_ = false; return isValidCursorPosition_; } } // for forward-only cursors, check if rowsRead_ > maxRows_. // for scrollable cursors, check if absolute row number > maxRows_. // maxRows_ will be ignored by sensitive dynamic cursors since we don't know the rowCount if (!openOnClient_) { isValidCursorPosition_ = false; } else if (sensitivity_ != sensitivity_sensitive_dynamic__ && statement_.maxRows_ > 0 && (firstRowInRowset_ + currentRowInRowset_ > statement_.maxRows_)) { isValidCursorPosition_ = false; } return isValidCursorPosition_; }
if (prop == null) { return; }
void updateDataSourceValues(Properties prop) { if (prop.containsKey(propertyKey_user)) { setUser(getUser(prop)); } if (prop.containsKey(propertyKey_securityMechanism)) { setSecurityMechanism(getSecurityMechanism(prop)); } if (prop.containsKey(propertyKey_traceFile)) { setTraceFile(getTraceFile(prop)); } if (prop.containsKey(propertyKey_traceDirectory)) { setTraceDirectory(getTraceDirectory(prop)); } if (prop.containsKey(propertyKey_traceFileAppend)) { setTraceFileAppend(getTraceFileAppend(prop)); } if (prop.containsKey(propertyKey_securityMechanism)) { setSecurityMechanism(getSecurityMechanism(prop)); } if (prop.containsKey(propertyKey_retrieveMessageText)) { setRetrieveMessageText(getRetrieveMessageText(prop)); } }
JBitSet parentRSNsTables, ResultSetNode childRSN) throws StandardException
JBitSet parentRSNsTables, ResultSetNode childRSN, int [] whichRC) throws StandardException
public ValueNode getScopedOperand(int whichSide, JBitSet parentRSNsTables, ResultSetNode childRSN) throws StandardException { ResultColumn rc = null; ColumnReference cr = whichSide == LEFT ? (ColumnReference)leftOperand : (ColumnReference)rightOperand; // The first thing we need to do is see if this ColumnReference // is supposed to be scoped for childRSN. We do that by figuring // out what underlying base table the column reference is pointing // to and then seeing if that base table is included in the list of // table numbers from the parentRSN. JBitSet crTables = new JBitSet(parentRSNsTables.size()); BaseTableNumbersVisitor btnVis = new BaseTableNumbersVisitor(crTables); cr.accept(btnVis); // If the column reference doesn't reference any tables, // then there's no point in mapping it to the child result // set; just return a clone of the operand. if (crTables.getFirstSetBit() == -1) { return (ValueNode)cr.getClone(); } /* If the column reference in question is not intended for * the received result set node, just leave the operand as * it is (i.e. return a clone). In the example mentioned at * the start of this method, this will happen when the operand * is X2.b and childRSN is either "select i,j from t1" or * "select i,j from t2", in which case the operand does not * apply to childRSN. When we get here and try to map the * "X1.j" operand, though, the following "contains" check will * return true and thus we can go ahead and return a scoped * version of that operand. */ if (!parentRSNsTables.contains(crTables)) { return (ValueNode)cr.getClone(); } // If the column reference is already pointing to the // correct table, then there's no need to change it. if ((childRSN.getReferencedTableMap() != null) && childRSN.getReferencedTableMap().get(cr.getTableNumber())) { return cr; } /* Find the target ResultColumn in the received result set. At * this point we know that we do in fact need to scope the column * reference for childRSN, so go ahead and do it. We get the * target column by column position instead of by name because * it's possible that the name given for the query doesn't match * the name of the actual column we're looking for. Ex. * * select * from * (select i,j from t1 union select i,j from t2) X1 (x,y), * (select a,b from t3 union select a,b from t4) X2 * where X1.x = X2.b; * * If we searched for "x" in the childRSN "select i,j from t1" * we wouldn't find it. So we have to look based on position. */ rc = childRSN.getResultColumns().getResultColumn(cr.getColumnNumber()); // rc shouldn't be null; if there was no matching ResultColumn at all, // then we shouldn't have made it this far. if (SanityManager.DEBUG) { SanityManager.ASSERT(rc != null, "Failed to locate result column when trying to " + "scope operand '" + cr.getTableName() + "." + cr.getColumnName() + "'."); } /* If the ResultColumn we found has an expression that is a * ColumnReference, then that column reference has all of the info * we need, with one exception: the columnNumber. Depending on our * depth in the tree, the ResultColumn's ColumnReference could be * pointing to a base column in the FromBaseTable. In that case the * ColumnReference will hold the column position as it is with respect * to the FromBaseTable. But when we're scoping a column reference, * we're scoping it to a ResultSetNode that sits (either directly or * indirectly) above a ProjectRestrictNode that in turn sits above the * FromBaseTable. This means that the scoped reference's columnNumber * needs to be with respect to the PRN that sits above the base table, * _not_ with respect to the FromBaseTable itself. This is important * because column "1" in the PRN might not be column "1" in the * underlying base table. For example, if we have base table TT with * four columns (a int, b int, i int, j int) and the PRN above it only * projects out columns (i,j), then column "1" for the PRN is "i", but * column "1" for base table TT is "a". On the flip side, column "3" * for base table TT is "i", but if we search the PRN's result columns * (which match the result columns for the ResultSetNode to which * we're scoping) for column "3", we won't find it. * * So what does all of that mean? It means that if the ResultColumn * we found has an expression that's a ColumnReference, we can simply * return that ColumnReference IF we set it's columnNumber correctly. * Thankfully the column reference we're trying to scope ("cr") came * from further up the tree and so it knows what the correct column * position (namely, the position w.r.t the ProjectRestrictNode above * the FromBaseTable) needs to be. So that's the column number we * use. * * As a final note, we have to be sure we only set the column * reference's column number if the reference points to a base table. * If the reference points to some other ResultSetNode--esp. another * subquery node--then it (the reference) already holds the correct * number with respect to that ResultSetNode and we don't change * it. The reason is that the reference could end up getting pushed * down further to that ResultSetNode, in which case we'll do another * scoping operation and, in order for that to be successful, the * reference to be scoped has to know what the target column number * is w.r.t to that ResultSetNode (i.e. it'll be playing the role of * "cr" as described here). */ if (rc.getExpression() instanceof ColumnReference) { // Make sure the ColumnReference's columnNumber is correct, // then just return that reference. Note: it's okay to overwrite // the columnNumber directly because when it eventually makes // it down to the PRN over the FromBaseTable, it will be remapped // for the FromBaseTable and the columnNumber will then be set // correctly. That remapping is done in the pushOptPredicate() // method of ProjectRestrictNode. ColumnReference cRef = (ColumnReference)rc.getExpression(); if (cRef.pointsToBaseTable()) cRef.setColumnNumber(cr.getColumnNumber()); return cRef; } /* We can get here if the ResultColumn's expression isn't a * ColumnReference. For example, the expression would be a * constant expression if childRSN represented something like: * * select 1, 1 from t1 * * In this case we just return a clone of the column reference * because it's scoped as far as we can take it. */ return (ValueNode)cr.getClone(); }
if (crTables.getFirstSetBit() == -1) { return (ValueNode)cr.getClone(); }
public ValueNode getScopedOperand(int whichSide, JBitSet parentRSNsTables, ResultSetNode childRSN) throws StandardException { ResultColumn rc = null; ColumnReference cr = whichSide == LEFT ? (ColumnReference)leftOperand : (ColumnReference)rightOperand; // The first thing we need to do is see if this ColumnReference // is supposed to be scoped for childRSN. We do that by figuring // out what underlying base table the column reference is pointing // to and then seeing if that base table is included in the list of // table numbers from the parentRSN. JBitSet crTables = new JBitSet(parentRSNsTables.size()); BaseTableNumbersVisitor btnVis = new BaseTableNumbersVisitor(crTables); cr.accept(btnVis); // If the column reference doesn't reference any tables, // then there's no point in mapping it to the child result // set; just return a clone of the operand. if (crTables.getFirstSetBit() == -1) { return (ValueNode)cr.getClone(); } /* If the column reference in question is not intended for * the received result set node, just leave the operand as * it is (i.e. return a clone). In the example mentioned at * the start of this method, this will happen when the operand * is X2.b and childRSN is either "select i,j from t1" or * "select i,j from t2", in which case the operand does not * apply to childRSN. When we get here and try to map the * "X1.j" operand, though, the following "contains" check will * return true and thus we can go ahead and return a scoped * version of that operand. */ if (!parentRSNsTables.contains(crTables)) { return (ValueNode)cr.getClone(); } // If the column reference is already pointing to the // correct table, then there's no need to change it. if ((childRSN.getReferencedTableMap() != null) && childRSN.getReferencedTableMap().get(cr.getTableNumber())) { return cr; } /* Find the target ResultColumn in the received result set. At * this point we know that we do in fact need to scope the column * reference for childRSN, so go ahead and do it. We get the * target column by column position instead of by name because * it's possible that the name given for the query doesn't match * the name of the actual column we're looking for. Ex. * * select * from * (select i,j from t1 union select i,j from t2) X1 (x,y), * (select a,b from t3 union select a,b from t4) X2 * where X1.x = X2.b; * * If we searched for "x" in the childRSN "select i,j from t1" * we wouldn't find it. So we have to look based on position. */ rc = childRSN.getResultColumns().getResultColumn(cr.getColumnNumber()); // rc shouldn't be null; if there was no matching ResultColumn at all, // then we shouldn't have made it this far. if (SanityManager.DEBUG) { SanityManager.ASSERT(rc != null, "Failed to locate result column when trying to " + "scope operand '" + cr.getTableName() + "." + cr.getColumnName() + "'."); } /* If the ResultColumn we found has an expression that is a * ColumnReference, then that column reference has all of the info * we need, with one exception: the columnNumber. Depending on our * depth in the tree, the ResultColumn's ColumnReference could be * pointing to a base column in the FromBaseTable. In that case the * ColumnReference will hold the column position as it is with respect * to the FromBaseTable. But when we're scoping a column reference, * we're scoping it to a ResultSetNode that sits (either directly or * indirectly) above a ProjectRestrictNode that in turn sits above the * FromBaseTable. This means that the scoped reference's columnNumber * needs to be with respect to the PRN that sits above the base table, * _not_ with respect to the FromBaseTable itself. This is important * because column "1" in the PRN might not be column "1" in the * underlying base table. For example, if we have base table TT with * four columns (a int, b int, i int, j int) and the PRN above it only * projects out columns (i,j), then column "1" for the PRN is "i", but * column "1" for base table TT is "a". On the flip side, column "3" * for base table TT is "i", but if we search the PRN's result columns * (which match the result columns for the ResultSetNode to which * we're scoping) for column "3", we won't find it. * * So what does all of that mean? It means that if the ResultColumn * we found has an expression that's a ColumnReference, we can simply * return that ColumnReference IF we set it's columnNumber correctly. * Thankfully the column reference we're trying to scope ("cr") came * from further up the tree and so it knows what the correct column * position (namely, the position w.r.t the ProjectRestrictNode above * the FromBaseTable) needs to be. So that's the column number we * use. * * As a final note, we have to be sure we only set the column * reference's column number if the reference points to a base table. * If the reference points to some other ResultSetNode--esp. another * subquery node--then it (the reference) already holds the correct * number with respect to that ResultSetNode and we don't change * it. The reason is that the reference could end up getting pushed * down further to that ResultSetNode, in which case we'll do another * scoping operation and, in order for that to be successful, the * reference to be scoped has to know what the target column number * is w.r.t to that ResultSetNode (i.e. it'll be playing the role of * "cr" as described here). */ if (rc.getExpression() instanceof ColumnReference) { // Make sure the ColumnReference's columnNumber is correct, // then just return that reference. Note: it's okay to overwrite // the columnNumber directly because when it eventually makes // it down to the PRN over the FromBaseTable, it will be remapped // for the FromBaseTable and the columnNumber will then be set // correctly. That remapping is done in the pushOptPredicate() // method of ProjectRestrictNode. ColumnReference cRef = (ColumnReference)rc.getExpression(); if (cRef.pointsToBaseTable()) cRef.setColumnNumber(cr.getColumnNumber()); return cRef; } /* We can get here if the ResultColumn's expression isn't a * ColumnReference. For example, the expression would be a * constant expression if childRSN represented something like: * * select 1, 1 from t1 * * In this case we just return a clone of the column reference * because it's scoped as far as we can take it. */ return (ValueNode)cr.getClone(); }
{ return (ValueNode)cr.getClone(); } if ((childRSN.getReferencedTableMap() != null) && childRSN.getReferencedTableMap().get(cr.getTableNumber())) { return cr; }
return (ColumnReference)cr.getClone();
public ValueNode getScopedOperand(int whichSide, JBitSet parentRSNsTables, ResultSetNode childRSN) throws StandardException { ResultColumn rc = null; ColumnReference cr = whichSide == LEFT ? (ColumnReference)leftOperand : (ColumnReference)rightOperand; // The first thing we need to do is see if this ColumnReference // is supposed to be scoped for childRSN. We do that by figuring // out what underlying base table the column reference is pointing // to and then seeing if that base table is included in the list of // table numbers from the parentRSN. JBitSet crTables = new JBitSet(parentRSNsTables.size()); BaseTableNumbersVisitor btnVis = new BaseTableNumbersVisitor(crTables); cr.accept(btnVis); // If the column reference doesn't reference any tables, // then there's no point in mapping it to the child result // set; just return a clone of the operand. if (crTables.getFirstSetBit() == -1) { return (ValueNode)cr.getClone(); } /* If the column reference in question is not intended for * the received result set node, just leave the operand as * it is (i.e. return a clone). In the example mentioned at * the start of this method, this will happen when the operand * is X2.b and childRSN is either "select i,j from t1" or * "select i,j from t2", in which case the operand does not * apply to childRSN. When we get here and try to map the * "X1.j" operand, though, the following "contains" check will * return true and thus we can go ahead and return a scoped * version of that operand. */ if (!parentRSNsTables.contains(crTables)) { return (ValueNode)cr.getClone(); } // If the column reference is already pointing to the // correct table, then there's no need to change it. if ((childRSN.getReferencedTableMap() != null) && childRSN.getReferencedTableMap().get(cr.getTableNumber())) { return cr; } /* Find the target ResultColumn in the received result set. At * this point we know that we do in fact need to scope the column * reference for childRSN, so go ahead and do it. We get the * target column by column position instead of by name because * it's possible that the name given for the query doesn't match * the name of the actual column we're looking for. Ex. * * select * from * (select i,j from t1 union select i,j from t2) X1 (x,y), * (select a,b from t3 union select a,b from t4) X2 * where X1.x = X2.b; * * If we searched for "x" in the childRSN "select i,j from t1" * we wouldn't find it. So we have to look based on position. */ rc = childRSN.getResultColumns().getResultColumn(cr.getColumnNumber()); // rc shouldn't be null; if there was no matching ResultColumn at all, // then we shouldn't have made it this far. if (SanityManager.DEBUG) { SanityManager.ASSERT(rc != null, "Failed to locate result column when trying to " + "scope operand '" + cr.getTableName() + "." + cr.getColumnName() + "'."); } /* If the ResultColumn we found has an expression that is a * ColumnReference, then that column reference has all of the info * we need, with one exception: the columnNumber. Depending on our * depth in the tree, the ResultColumn's ColumnReference could be * pointing to a base column in the FromBaseTable. In that case the * ColumnReference will hold the column position as it is with respect * to the FromBaseTable. But when we're scoping a column reference, * we're scoping it to a ResultSetNode that sits (either directly or * indirectly) above a ProjectRestrictNode that in turn sits above the * FromBaseTable. This means that the scoped reference's columnNumber * needs to be with respect to the PRN that sits above the base table, * _not_ with respect to the FromBaseTable itself. This is important * because column "1" in the PRN might not be column "1" in the * underlying base table. For example, if we have base table TT with * four columns (a int, b int, i int, j int) and the PRN above it only * projects out columns (i,j), then column "1" for the PRN is "i", but * column "1" for base table TT is "a". On the flip side, column "3" * for base table TT is "i", but if we search the PRN's result columns * (which match the result columns for the ResultSetNode to which * we're scoping) for column "3", we won't find it. * * So what does all of that mean? It means that if the ResultColumn * we found has an expression that's a ColumnReference, we can simply * return that ColumnReference IF we set it's columnNumber correctly. * Thankfully the column reference we're trying to scope ("cr") came * from further up the tree and so it knows what the correct column * position (namely, the position w.r.t the ProjectRestrictNode above * the FromBaseTable) needs to be. So that's the column number we * use. * * As a final note, we have to be sure we only set the column * reference's column number if the reference points to a base table. * If the reference points to some other ResultSetNode--esp. another * subquery node--then it (the reference) already holds the correct * number with respect to that ResultSetNode and we don't change * it. The reason is that the reference could end up getting pushed * down further to that ResultSetNode, in which case we'll do another * scoping operation and, in order for that to be successful, the * reference to be scoped has to know what the target column number * is w.r.t to that ResultSetNode (i.e. it'll be playing the role of * "cr" as described here). */ if (rc.getExpression() instanceof ColumnReference) { // Make sure the ColumnReference's columnNumber is correct, // then just return that reference. Note: it's okay to overwrite // the columnNumber directly because when it eventually makes // it down to the PRN over the FromBaseTable, it will be remapped // for the FromBaseTable and the columnNumber will then be set // correctly. That remapping is done in the pushOptPredicate() // method of ProjectRestrictNode. ColumnReference cRef = (ColumnReference)rc.getExpression(); if (cRef.pointsToBaseTable()) cRef.setColumnNumber(cr.getColumnNumber()); return cRef; } /* We can get here if the ResultColumn's expression isn't a * ColumnReference. For example, the expression would be a * constant expression if childRSN represented something like: * * select 1, 1 from t1 * * In this case we just return a clone of the column reference * because it's scoped as far as we can take it. */ return (ValueNode)cr.getClone(); }
* reference for childRSN, so go ahead and do it. We get the * target column by column position instead of by name because * it's possible that the name given for the query doesn't match * the name of the actual column we're looking for. Ex.
* reference for childRSN, so go ahead and do it. The way in * which we get the scope target column differs depending on * if childRSN corresponds to the left or right child of the * UNION node. Before explaining that, though, note that it's * not good enough to just search for the target column by * name. The reason is that it's possible the name provided * for the column reference to be scoped doesn't match the * name of the actual underlying column. Ex.
public ValueNode getScopedOperand(int whichSide, JBitSet parentRSNsTables, ResultSetNode childRSN) throws StandardException { ResultColumn rc = null; ColumnReference cr = whichSide == LEFT ? (ColumnReference)leftOperand : (ColumnReference)rightOperand; // The first thing we need to do is see if this ColumnReference // is supposed to be scoped for childRSN. We do that by figuring // out what underlying base table the column reference is pointing // to and then seeing if that base table is included in the list of // table numbers from the parentRSN. JBitSet crTables = new JBitSet(parentRSNsTables.size()); BaseTableNumbersVisitor btnVis = new BaseTableNumbersVisitor(crTables); cr.accept(btnVis); // If the column reference doesn't reference any tables, // then there's no point in mapping it to the child result // set; just return a clone of the operand. if (crTables.getFirstSetBit() == -1) { return (ValueNode)cr.getClone(); } /* If the column reference in question is not intended for * the received result set node, just leave the operand as * it is (i.e. return a clone). In the example mentioned at * the start of this method, this will happen when the operand * is X2.b and childRSN is either "select i,j from t1" or * "select i,j from t2", in which case the operand does not * apply to childRSN. When we get here and try to map the * "X1.j" operand, though, the following "contains" check will * return true and thus we can go ahead and return a scoped * version of that operand. */ if (!parentRSNsTables.contains(crTables)) { return (ValueNode)cr.getClone(); } // If the column reference is already pointing to the // correct table, then there's no need to change it. if ((childRSN.getReferencedTableMap() != null) && childRSN.getReferencedTableMap().get(cr.getTableNumber())) { return cr; } /* Find the target ResultColumn in the received result set. At * this point we know that we do in fact need to scope the column * reference for childRSN, so go ahead and do it. We get the * target column by column position instead of by name because * it's possible that the name given for the query doesn't match * the name of the actual column we're looking for. Ex. * * select * from * (select i,j from t1 union select i,j from t2) X1 (x,y), * (select a,b from t3 union select a,b from t4) X2 * where X1.x = X2.b; * * If we searched for "x" in the childRSN "select i,j from t1" * we wouldn't find it. So we have to look based on position. */ rc = childRSN.getResultColumns().getResultColumn(cr.getColumnNumber()); // rc shouldn't be null; if there was no matching ResultColumn at all, // then we shouldn't have made it this far. if (SanityManager.DEBUG) { SanityManager.ASSERT(rc != null, "Failed to locate result column when trying to " + "scope operand '" + cr.getTableName() + "." + cr.getColumnName() + "'."); } /* If the ResultColumn we found has an expression that is a * ColumnReference, then that column reference has all of the info * we need, with one exception: the columnNumber. Depending on our * depth in the tree, the ResultColumn's ColumnReference could be * pointing to a base column in the FromBaseTable. In that case the * ColumnReference will hold the column position as it is with respect * to the FromBaseTable. But when we're scoping a column reference, * we're scoping it to a ResultSetNode that sits (either directly or * indirectly) above a ProjectRestrictNode that in turn sits above the * FromBaseTable. This means that the scoped reference's columnNumber * needs to be with respect to the PRN that sits above the base table, * _not_ with respect to the FromBaseTable itself. This is important * because column "1" in the PRN might not be column "1" in the * underlying base table. For example, if we have base table TT with * four columns (a int, b int, i int, j int) and the PRN above it only * projects out columns (i,j), then column "1" for the PRN is "i", but * column "1" for base table TT is "a". On the flip side, column "3" * for base table TT is "i", but if we search the PRN's result columns * (which match the result columns for the ResultSetNode to which * we're scoping) for column "3", we won't find it. * * So what does all of that mean? It means that if the ResultColumn * we found has an expression that's a ColumnReference, we can simply * return that ColumnReference IF we set it's columnNumber correctly. * Thankfully the column reference we're trying to scope ("cr") came * from further up the tree and so it knows what the correct column * position (namely, the position w.r.t the ProjectRestrictNode above * the FromBaseTable) needs to be. So that's the column number we * use. * * As a final note, we have to be sure we only set the column * reference's column number if the reference points to a base table. * If the reference points to some other ResultSetNode--esp. another * subquery node--then it (the reference) already holds the correct * number with respect to that ResultSetNode and we don't change * it. The reason is that the reference could end up getting pushed * down further to that ResultSetNode, in which case we'll do another * scoping operation and, in order for that to be successful, the * reference to be scoped has to know what the target column number * is w.r.t to that ResultSetNode (i.e. it'll be playing the role of * "cr" as described here). */ if (rc.getExpression() instanceof ColumnReference) { // Make sure the ColumnReference's columnNumber is correct, // then just return that reference. Note: it's okay to overwrite // the columnNumber directly because when it eventually makes // it down to the PRN over the FromBaseTable, it will be remapped // for the FromBaseTable and the columnNumber will then be set // correctly. That remapping is done in the pushOptPredicate() // method of ProjectRestrictNode. ColumnReference cRef = (ColumnReference)rc.getExpression(); if (cRef.pointsToBaseTable()) cRef.setColumnNumber(cr.getColumnNumber()); return cRef; } /* We can get here if the ResultColumn's expression isn't a * ColumnReference. For example, the expression would be a * constant expression if childRSN represented something like: * * select 1, 1 from t1 * * In this case we just return a clone of the column reference * because it's scoped as far as we can take it. */ return (ValueNode)cr.getClone(); }
* If we searched for "x" in the childRSN "select i,j from t1" * we wouldn't find it. So we have to look based on position.
* If we were scoping "X1.x" and we searched for "x" in the * childRSN "select i,j from t1" we wouldn't find it. * * It is similarly incorrect to search for the target column * by position (DERBY-1633). This is a bit more subtle, but * if the child to which we're scoping is a subquery whose RCL * does not match the column ordering of the RCL for cr's source * result set, then searching by column position can yield the * wrong results, as well. For a detailed example of how this * can happen, see the fix description attached to DERBY-1633. * * So how do we find the target column, then? As mentioned * above, the way in which we get the scope target column * differs depending on if childRSN corresponds to the left * or right child of the parent UNION node. And that said, * we can tell if we're scoping a left child by looking at * "whichRC" argument: if it is -1 then we know we're scoping * to the left child of a Union; otherwise we're scoping to * the right child.
public ValueNode getScopedOperand(int whichSide, JBitSet parentRSNsTables, ResultSetNode childRSN) throws StandardException { ResultColumn rc = null; ColumnReference cr = whichSide == LEFT ? (ColumnReference)leftOperand : (ColumnReference)rightOperand; // The first thing we need to do is see if this ColumnReference // is supposed to be scoped for childRSN. We do that by figuring // out what underlying base table the column reference is pointing // to and then seeing if that base table is included in the list of // table numbers from the parentRSN. JBitSet crTables = new JBitSet(parentRSNsTables.size()); BaseTableNumbersVisitor btnVis = new BaseTableNumbersVisitor(crTables); cr.accept(btnVis); // If the column reference doesn't reference any tables, // then there's no point in mapping it to the child result // set; just return a clone of the operand. if (crTables.getFirstSetBit() == -1) { return (ValueNode)cr.getClone(); } /* If the column reference in question is not intended for * the received result set node, just leave the operand as * it is (i.e. return a clone). In the example mentioned at * the start of this method, this will happen when the operand * is X2.b and childRSN is either "select i,j from t1" or * "select i,j from t2", in which case the operand does not * apply to childRSN. When we get here and try to map the * "X1.j" operand, though, the following "contains" check will * return true and thus we can go ahead and return a scoped * version of that operand. */ if (!parentRSNsTables.contains(crTables)) { return (ValueNode)cr.getClone(); } // If the column reference is already pointing to the // correct table, then there's no need to change it. if ((childRSN.getReferencedTableMap() != null) && childRSN.getReferencedTableMap().get(cr.getTableNumber())) { return cr; } /* Find the target ResultColumn in the received result set. At * this point we know that we do in fact need to scope the column * reference for childRSN, so go ahead and do it. We get the * target column by column position instead of by name because * it's possible that the name given for the query doesn't match * the name of the actual column we're looking for. Ex. * * select * from * (select i,j from t1 union select i,j from t2) X1 (x,y), * (select a,b from t3 union select a,b from t4) X2 * where X1.x = X2.b; * * If we searched for "x" in the childRSN "select i,j from t1" * we wouldn't find it. So we have to look based on position. */ rc = childRSN.getResultColumns().getResultColumn(cr.getColumnNumber()); // rc shouldn't be null; if there was no matching ResultColumn at all, // then we shouldn't have made it this far. if (SanityManager.DEBUG) { SanityManager.ASSERT(rc != null, "Failed to locate result column when trying to " + "scope operand '" + cr.getTableName() + "." + cr.getColumnName() + "'."); } /* If the ResultColumn we found has an expression that is a * ColumnReference, then that column reference has all of the info * we need, with one exception: the columnNumber. Depending on our * depth in the tree, the ResultColumn's ColumnReference could be * pointing to a base column in the FromBaseTable. In that case the * ColumnReference will hold the column position as it is with respect * to the FromBaseTable. But when we're scoping a column reference, * we're scoping it to a ResultSetNode that sits (either directly or * indirectly) above a ProjectRestrictNode that in turn sits above the * FromBaseTable. This means that the scoped reference's columnNumber * needs to be with respect to the PRN that sits above the base table, * _not_ with respect to the FromBaseTable itself. This is important * because column "1" in the PRN might not be column "1" in the * underlying base table. For example, if we have base table TT with * four columns (a int, b int, i int, j int) and the PRN above it only * projects out columns (i,j), then column "1" for the PRN is "i", but * column "1" for base table TT is "a". On the flip side, column "3" * for base table TT is "i", but if we search the PRN's result columns * (which match the result columns for the ResultSetNode to which * we're scoping) for column "3", we won't find it. * * So what does all of that mean? It means that if the ResultColumn * we found has an expression that's a ColumnReference, we can simply * return that ColumnReference IF we set it's columnNumber correctly. * Thankfully the column reference we're trying to scope ("cr") came * from further up the tree and so it knows what the correct column * position (namely, the position w.r.t the ProjectRestrictNode above * the FromBaseTable) needs to be. So that's the column number we * use. * * As a final note, we have to be sure we only set the column * reference's column number if the reference points to a base table. * If the reference points to some other ResultSetNode--esp. another * subquery node--then it (the reference) already holds the correct * number with respect to that ResultSetNode and we don't change * it. The reason is that the reference could end up getting pushed * down further to that ResultSetNode, in which case we'll do another * scoping operation and, in order for that to be successful, the * reference to be scoped has to know what the target column number * is w.r.t to that ResultSetNode (i.e. it'll be playing the role of * "cr" as described here). */ if (rc.getExpression() instanceof ColumnReference) { // Make sure the ColumnReference's columnNumber is correct, // then just return that reference. Note: it's okay to overwrite // the columnNumber directly because when it eventually makes // it down to the PRN over the FromBaseTable, it will be remapped // for the FromBaseTable and the columnNumber will then be set // correctly. That remapping is done in the pushOptPredicate() // method of ProjectRestrictNode. ColumnReference cRef = (ColumnReference)rc.getExpression(); if (cRef.pointsToBaseTable()) cRef.setColumnNumber(cr.getColumnNumber()); return cRef; } /* We can get here if the ResultColumn's expression isn't a * ColumnReference. For example, the expression would be a * constant expression if childRSN represented something like: * * select 1, 1 from t1 * * In this case we just return a clone of the column reference * because it's scoped as far as we can take it. */ return (ValueNode)cr.getClone(); }
rc = childRSN.getResultColumns().getResultColumn(cr.getColumnNumber());
int [] sourceColPos = new int[] {-1}; ResultSetNode sourceRSN = cr.getSourceResultSet(sourceColPos); if (SanityManager.DEBUG) { SanityManager.ASSERT(sourceRSN != null, "Failed to find source result set when trying to " + "scope column reference '" + cr.getTableName() + "." + cr.getColumnName()); } rc = childRSN.getResultColumns() .getResultColumn(sourceColPos[0], sourceRSN, whichRC); } else { rc = childRSN.getResultColumns().getResultColumn(whichRC[0]); }
public ValueNode getScopedOperand(int whichSide, JBitSet parentRSNsTables, ResultSetNode childRSN) throws StandardException { ResultColumn rc = null; ColumnReference cr = whichSide == LEFT ? (ColumnReference)leftOperand : (ColumnReference)rightOperand; // The first thing we need to do is see if this ColumnReference // is supposed to be scoped for childRSN. We do that by figuring // out what underlying base table the column reference is pointing // to and then seeing if that base table is included in the list of // table numbers from the parentRSN. JBitSet crTables = new JBitSet(parentRSNsTables.size()); BaseTableNumbersVisitor btnVis = new BaseTableNumbersVisitor(crTables); cr.accept(btnVis); // If the column reference doesn't reference any tables, // then there's no point in mapping it to the child result // set; just return a clone of the operand. if (crTables.getFirstSetBit() == -1) { return (ValueNode)cr.getClone(); } /* If the column reference in question is not intended for * the received result set node, just leave the operand as * it is (i.e. return a clone). In the example mentioned at * the start of this method, this will happen when the operand * is X2.b and childRSN is either "select i,j from t1" or * "select i,j from t2", in which case the operand does not * apply to childRSN. When we get here and try to map the * "X1.j" operand, though, the following "contains" check will * return true and thus we can go ahead and return a scoped * version of that operand. */ if (!parentRSNsTables.contains(crTables)) { return (ValueNode)cr.getClone(); } // If the column reference is already pointing to the // correct table, then there's no need to change it. if ((childRSN.getReferencedTableMap() != null) && childRSN.getReferencedTableMap().get(cr.getTableNumber())) { return cr; } /* Find the target ResultColumn in the received result set. At * this point we know that we do in fact need to scope the column * reference for childRSN, so go ahead and do it. We get the * target column by column position instead of by name because * it's possible that the name given for the query doesn't match * the name of the actual column we're looking for. Ex. * * select * from * (select i,j from t1 union select i,j from t2) X1 (x,y), * (select a,b from t3 union select a,b from t4) X2 * where X1.x = X2.b; * * If we searched for "x" in the childRSN "select i,j from t1" * we wouldn't find it. So we have to look based on position. */ rc = childRSN.getResultColumns().getResultColumn(cr.getColumnNumber()); // rc shouldn't be null; if there was no matching ResultColumn at all, // then we shouldn't have made it this far. if (SanityManager.DEBUG) { SanityManager.ASSERT(rc != null, "Failed to locate result column when trying to " + "scope operand '" + cr.getTableName() + "." + cr.getColumnName() + "'."); } /* If the ResultColumn we found has an expression that is a * ColumnReference, then that column reference has all of the info * we need, with one exception: the columnNumber. Depending on our * depth in the tree, the ResultColumn's ColumnReference could be * pointing to a base column in the FromBaseTable. In that case the * ColumnReference will hold the column position as it is with respect * to the FromBaseTable. But when we're scoping a column reference, * we're scoping it to a ResultSetNode that sits (either directly or * indirectly) above a ProjectRestrictNode that in turn sits above the * FromBaseTable. This means that the scoped reference's columnNumber * needs to be with respect to the PRN that sits above the base table, * _not_ with respect to the FromBaseTable itself. This is important * because column "1" in the PRN might not be column "1" in the * underlying base table. For example, if we have base table TT with * four columns (a int, b int, i int, j int) and the PRN above it only * projects out columns (i,j), then column "1" for the PRN is "i", but * column "1" for base table TT is "a". On the flip side, column "3" * for base table TT is "i", but if we search the PRN's result columns * (which match the result columns for the ResultSetNode to which * we're scoping) for column "3", we won't find it. * * So what does all of that mean? It means that if the ResultColumn * we found has an expression that's a ColumnReference, we can simply * return that ColumnReference IF we set it's columnNumber correctly. * Thankfully the column reference we're trying to scope ("cr") came * from further up the tree and so it knows what the correct column * position (namely, the position w.r.t the ProjectRestrictNode above * the FromBaseTable) needs to be. So that's the column number we * use. * * As a final note, we have to be sure we only set the column * reference's column number if the reference points to a base table. * If the reference points to some other ResultSetNode--esp. another * subquery node--then it (the reference) already holds the correct * number with respect to that ResultSetNode and we don't change * it. The reason is that the reference could end up getting pushed * down further to that ResultSetNode, in which case we'll do another * scoping operation and, in order for that to be successful, the * reference to be scoped has to know what the target column number * is w.r.t to that ResultSetNode (i.e. it'll be playing the role of * "cr" as described here). */ if (rc.getExpression() instanceof ColumnReference) { // Make sure the ColumnReference's columnNumber is correct, // then just return that reference. Note: it's okay to overwrite // the columnNumber directly because when it eventually makes // it down to the PRN over the FromBaseTable, it will be remapped // for the FromBaseTable and the columnNumber will then be set // correctly. That remapping is done in the pushOptPredicate() // method of ProjectRestrictNode. ColumnReference cRef = (ColumnReference)rc.getExpression(); if (cRef.pointsToBaseTable()) cRef.setColumnNumber(cr.getColumnNumber()); return cRef; } /* We can get here if the ResultColumn's expression isn't a * ColumnReference. For example, the expression would be a * constant expression if childRSN represented something like: * * select 1, 1 from t1 * * In this case we just return a clone of the column reference * because it's scoped as far as we can take it. */ return (ValueNode)cr.getClone(); }
"Failed to locate result column when trying to " +
"Failed to locate scope target result column when trying to " +
public ValueNode getScopedOperand(int whichSide, JBitSet parentRSNsTables, ResultSetNode childRSN) throws StandardException { ResultColumn rc = null; ColumnReference cr = whichSide == LEFT ? (ColumnReference)leftOperand : (ColumnReference)rightOperand; // The first thing we need to do is see if this ColumnReference // is supposed to be scoped for childRSN. We do that by figuring // out what underlying base table the column reference is pointing // to and then seeing if that base table is included in the list of // table numbers from the parentRSN. JBitSet crTables = new JBitSet(parentRSNsTables.size()); BaseTableNumbersVisitor btnVis = new BaseTableNumbersVisitor(crTables); cr.accept(btnVis); // If the column reference doesn't reference any tables, // then there's no point in mapping it to the child result // set; just return a clone of the operand. if (crTables.getFirstSetBit() == -1) { return (ValueNode)cr.getClone(); } /* If the column reference in question is not intended for * the received result set node, just leave the operand as * it is (i.e. return a clone). In the example mentioned at * the start of this method, this will happen when the operand * is X2.b and childRSN is either "select i,j from t1" or * "select i,j from t2", in which case the operand does not * apply to childRSN. When we get here and try to map the * "X1.j" operand, though, the following "contains" check will * return true and thus we can go ahead and return a scoped * version of that operand. */ if (!parentRSNsTables.contains(crTables)) { return (ValueNode)cr.getClone(); } // If the column reference is already pointing to the // correct table, then there's no need to change it. if ((childRSN.getReferencedTableMap() != null) && childRSN.getReferencedTableMap().get(cr.getTableNumber())) { return cr; } /* Find the target ResultColumn in the received result set. At * this point we know that we do in fact need to scope the column * reference for childRSN, so go ahead and do it. We get the * target column by column position instead of by name because * it's possible that the name given for the query doesn't match * the name of the actual column we're looking for. Ex. * * select * from * (select i,j from t1 union select i,j from t2) X1 (x,y), * (select a,b from t3 union select a,b from t4) X2 * where X1.x = X2.b; * * If we searched for "x" in the childRSN "select i,j from t1" * we wouldn't find it. So we have to look based on position. */ rc = childRSN.getResultColumns().getResultColumn(cr.getColumnNumber()); // rc shouldn't be null; if there was no matching ResultColumn at all, // then we shouldn't have made it this far. if (SanityManager.DEBUG) { SanityManager.ASSERT(rc != null, "Failed to locate result column when trying to " + "scope operand '" + cr.getTableName() + "." + cr.getColumnName() + "'."); } /* If the ResultColumn we found has an expression that is a * ColumnReference, then that column reference has all of the info * we need, with one exception: the columnNumber. Depending on our * depth in the tree, the ResultColumn's ColumnReference could be * pointing to a base column in the FromBaseTable. In that case the * ColumnReference will hold the column position as it is with respect * to the FromBaseTable. But when we're scoping a column reference, * we're scoping it to a ResultSetNode that sits (either directly or * indirectly) above a ProjectRestrictNode that in turn sits above the * FromBaseTable. This means that the scoped reference's columnNumber * needs to be with respect to the PRN that sits above the base table, * _not_ with respect to the FromBaseTable itself. This is important * because column "1" in the PRN might not be column "1" in the * underlying base table. For example, if we have base table TT with * four columns (a int, b int, i int, j int) and the PRN above it only * projects out columns (i,j), then column "1" for the PRN is "i", but * column "1" for base table TT is "a". On the flip side, column "3" * for base table TT is "i", but if we search the PRN's result columns * (which match the result columns for the ResultSetNode to which * we're scoping) for column "3", we won't find it. * * So what does all of that mean? It means that if the ResultColumn * we found has an expression that's a ColumnReference, we can simply * return that ColumnReference IF we set it's columnNumber correctly. * Thankfully the column reference we're trying to scope ("cr") came * from further up the tree and so it knows what the correct column * position (namely, the position w.r.t the ProjectRestrictNode above * the FromBaseTable) needs to be. So that's the column number we * use. * * As a final note, we have to be sure we only set the column * reference's column number if the reference points to a base table. * If the reference points to some other ResultSetNode--esp. another * subquery node--then it (the reference) already holds the correct * number with respect to that ResultSetNode and we don't change * it. The reason is that the reference could end up getting pushed * down further to that ResultSetNode, in which case we'll do another * scoping operation and, in order for that to be successful, the * reference to be scoped has to know what the target column number * is w.r.t to that ResultSetNode (i.e. it'll be playing the role of * "cr" as described here). */ if (rc.getExpression() instanceof ColumnReference) { // Make sure the ColumnReference's columnNumber is correct, // then just return that reference. Note: it's okay to overwrite // the columnNumber directly because when it eventually makes // it down to the PRN over the FromBaseTable, it will be remapped // for the FromBaseTable and the columnNumber will then be set // correctly. That remapping is done in the pushOptPredicate() // method of ProjectRestrictNode. ColumnReference cRef = (ColumnReference)rc.getExpression(); if (cRef.pointsToBaseTable()) cRef.setColumnNumber(cr.getColumnNumber()); return cRef; } /* We can get here if the ResultColumn's expression isn't a * ColumnReference. For example, the expression would be a * constant expression if childRSN represented something like: * * select 1, 1 from t1 * * In this case we just return a clone of the column reference * because it's scoped as far as we can take it. */ return (ValueNode)cr.getClone(); }
* ColumnReference, then that column reference has all of the info * we need, with one exception: the columnNumber. Depending on our * depth in the tree, the ResultColumn's ColumnReference could be * pointing to a base column in the FromBaseTable. In that case the * ColumnReference will hold the column position as it is with respect * to the FromBaseTable. But when we're scoping a column reference, * we're scoping it to a ResultSetNode that sits (either directly or * indirectly) above a ProjectRestrictNode that in turn sits above the * FromBaseTable. This means that the scoped reference's columnNumber * needs to be with respect to the PRN that sits above the base table, * _not_ with respect to the FromBaseTable itself. This is important * because column "1" in the PRN might not be column "1" in the * underlying base table. For example, if we have base table TT with * four columns (a int, b int, i int, j int) and the PRN above it only * projects out columns (i,j), then column "1" for the PRN is "i", but * column "1" for base table TT is "a". On the flip side, column "3" * for base table TT is "i", but if we search the PRN's result columns * (which match the result columns for the ResultSetNode to which * we're scoping) for column "3", we won't find it.
* ColumnReference, then that column reference has all of the * info we need.
public ValueNode getScopedOperand(int whichSide, JBitSet parentRSNsTables, ResultSetNode childRSN) throws StandardException { ResultColumn rc = null; ColumnReference cr = whichSide == LEFT ? (ColumnReference)leftOperand : (ColumnReference)rightOperand; // The first thing we need to do is see if this ColumnReference // is supposed to be scoped for childRSN. We do that by figuring // out what underlying base table the column reference is pointing // to and then seeing if that base table is included in the list of // table numbers from the parentRSN. JBitSet crTables = new JBitSet(parentRSNsTables.size()); BaseTableNumbersVisitor btnVis = new BaseTableNumbersVisitor(crTables); cr.accept(btnVis); // If the column reference doesn't reference any tables, // then there's no point in mapping it to the child result // set; just return a clone of the operand. if (crTables.getFirstSetBit() == -1) { return (ValueNode)cr.getClone(); } /* If the column reference in question is not intended for * the received result set node, just leave the operand as * it is (i.e. return a clone). In the example mentioned at * the start of this method, this will happen when the operand * is X2.b and childRSN is either "select i,j from t1" or * "select i,j from t2", in which case the operand does not * apply to childRSN. When we get here and try to map the * "X1.j" operand, though, the following "contains" check will * return true and thus we can go ahead and return a scoped * version of that operand. */ if (!parentRSNsTables.contains(crTables)) { return (ValueNode)cr.getClone(); } // If the column reference is already pointing to the // correct table, then there's no need to change it. if ((childRSN.getReferencedTableMap() != null) && childRSN.getReferencedTableMap().get(cr.getTableNumber())) { return cr; } /* Find the target ResultColumn in the received result set. At * this point we know that we do in fact need to scope the column * reference for childRSN, so go ahead and do it. We get the * target column by column position instead of by name because * it's possible that the name given for the query doesn't match * the name of the actual column we're looking for. Ex. * * select * from * (select i,j from t1 union select i,j from t2) X1 (x,y), * (select a,b from t3 union select a,b from t4) X2 * where X1.x = X2.b; * * If we searched for "x" in the childRSN "select i,j from t1" * we wouldn't find it. So we have to look based on position. */ rc = childRSN.getResultColumns().getResultColumn(cr.getColumnNumber()); // rc shouldn't be null; if there was no matching ResultColumn at all, // then we shouldn't have made it this far. if (SanityManager.DEBUG) { SanityManager.ASSERT(rc != null, "Failed to locate result column when trying to " + "scope operand '" + cr.getTableName() + "." + cr.getColumnName() + "'."); } /* If the ResultColumn we found has an expression that is a * ColumnReference, then that column reference has all of the info * we need, with one exception: the columnNumber. Depending on our * depth in the tree, the ResultColumn's ColumnReference could be * pointing to a base column in the FromBaseTable. In that case the * ColumnReference will hold the column position as it is with respect * to the FromBaseTable. But when we're scoping a column reference, * we're scoping it to a ResultSetNode that sits (either directly or * indirectly) above a ProjectRestrictNode that in turn sits above the * FromBaseTable. This means that the scoped reference's columnNumber * needs to be with respect to the PRN that sits above the base table, * _not_ with respect to the FromBaseTable itself. This is important * because column "1" in the PRN might not be column "1" in the * underlying base table. For example, if we have base table TT with * four columns (a int, b int, i int, j int) and the PRN above it only * projects out columns (i,j), then column "1" for the PRN is "i", but * column "1" for base table TT is "a". On the flip side, column "3" * for base table TT is "i", but if we search the PRN's result columns * (which match the result columns for the ResultSetNode to which * we're scoping) for column "3", we won't find it. * * So what does all of that mean? It means that if the ResultColumn * we found has an expression that's a ColumnReference, we can simply * return that ColumnReference IF we set it's columnNumber correctly. * Thankfully the column reference we're trying to scope ("cr") came * from further up the tree and so it knows what the correct column * position (namely, the position w.r.t the ProjectRestrictNode above * the FromBaseTable) needs to be. So that's the column number we * use. * * As a final note, we have to be sure we only set the column * reference's column number if the reference points to a base table. * If the reference points to some other ResultSetNode--esp. another * subquery node--then it (the reference) already holds the correct * number with respect to that ResultSetNode and we don't change * it. The reason is that the reference could end up getting pushed * down further to that ResultSetNode, in which case we'll do another * scoping operation and, in order for that to be successful, the * reference to be scoped has to know what the target column number * is w.r.t to that ResultSetNode (i.e. it'll be playing the role of * "cr" as described here). */ if (rc.getExpression() instanceof ColumnReference) { // Make sure the ColumnReference's columnNumber is correct, // then just return that reference. Note: it's okay to overwrite // the columnNumber directly because when it eventually makes // it down to the PRN over the FromBaseTable, it will be remapped // for the FromBaseTable and the columnNumber will then be set // correctly. That remapping is done in the pushOptPredicate() // method of ProjectRestrictNode. ColumnReference cRef = (ColumnReference)rc.getExpression(); if (cRef.pointsToBaseTable()) cRef.setColumnNumber(cr.getColumnNumber()); return cRef; } /* We can get here if the ResultColumn's expression isn't a * ColumnReference. For example, the expression would be a * constant expression if childRSN represented something like: * * select 1, 1 from t1 * * In this case we just return a clone of the column reference * because it's scoped as far as we can take it. */ return (ValueNode)cr.getClone(); }
* So what does all of that mean? It means that if the ResultColumn * we found has an expression that's a ColumnReference, we can simply * return that ColumnReference IF we set it's columnNumber correctly. * Thankfully the column reference we're trying to scope ("cr") came * from further up the tree and so it knows what the correct column * position (namely, the position w.r.t the ProjectRestrictNode above * the FromBaseTable) needs to be. So that's the column number we * use.
* It is, however, possible that the ResultColumn's expression * is NOT a ColumnReference. For example, the expression would * be a constant expression if childRSN represented something * like:
public ValueNode getScopedOperand(int whichSide, JBitSet parentRSNsTables, ResultSetNode childRSN) throws StandardException { ResultColumn rc = null; ColumnReference cr = whichSide == LEFT ? (ColumnReference)leftOperand : (ColumnReference)rightOperand; // The first thing we need to do is see if this ColumnReference // is supposed to be scoped for childRSN. We do that by figuring // out what underlying base table the column reference is pointing // to and then seeing if that base table is included in the list of // table numbers from the parentRSN. JBitSet crTables = new JBitSet(parentRSNsTables.size()); BaseTableNumbersVisitor btnVis = new BaseTableNumbersVisitor(crTables); cr.accept(btnVis); // If the column reference doesn't reference any tables, // then there's no point in mapping it to the child result // set; just return a clone of the operand. if (crTables.getFirstSetBit() == -1) { return (ValueNode)cr.getClone(); } /* If the column reference in question is not intended for * the received result set node, just leave the operand as * it is (i.e. return a clone). In the example mentioned at * the start of this method, this will happen when the operand * is X2.b and childRSN is either "select i,j from t1" or * "select i,j from t2", in which case the operand does not * apply to childRSN. When we get here and try to map the * "X1.j" operand, though, the following "contains" check will * return true and thus we can go ahead and return a scoped * version of that operand. */ if (!parentRSNsTables.contains(crTables)) { return (ValueNode)cr.getClone(); } // If the column reference is already pointing to the // correct table, then there's no need to change it. if ((childRSN.getReferencedTableMap() != null) && childRSN.getReferencedTableMap().get(cr.getTableNumber())) { return cr; } /* Find the target ResultColumn in the received result set. At * this point we know that we do in fact need to scope the column * reference for childRSN, so go ahead and do it. We get the * target column by column position instead of by name because * it's possible that the name given for the query doesn't match * the name of the actual column we're looking for. Ex. * * select * from * (select i,j from t1 union select i,j from t2) X1 (x,y), * (select a,b from t3 union select a,b from t4) X2 * where X1.x = X2.b; * * If we searched for "x" in the childRSN "select i,j from t1" * we wouldn't find it. So we have to look based on position. */ rc = childRSN.getResultColumns().getResultColumn(cr.getColumnNumber()); // rc shouldn't be null; if there was no matching ResultColumn at all, // then we shouldn't have made it this far. if (SanityManager.DEBUG) { SanityManager.ASSERT(rc != null, "Failed to locate result column when trying to " + "scope operand '" + cr.getTableName() + "." + cr.getColumnName() + "'."); } /* If the ResultColumn we found has an expression that is a * ColumnReference, then that column reference has all of the info * we need, with one exception: the columnNumber. Depending on our * depth in the tree, the ResultColumn's ColumnReference could be * pointing to a base column in the FromBaseTable. In that case the * ColumnReference will hold the column position as it is with respect * to the FromBaseTable. But when we're scoping a column reference, * we're scoping it to a ResultSetNode that sits (either directly or * indirectly) above a ProjectRestrictNode that in turn sits above the * FromBaseTable. This means that the scoped reference's columnNumber * needs to be with respect to the PRN that sits above the base table, * _not_ with respect to the FromBaseTable itself. This is important * because column "1" in the PRN might not be column "1" in the * underlying base table. For example, if we have base table TT with * four columns (a int, b int, i int, j int) and the PRN above it only * projects out columns (i,j), then column "1" for the PRN is "i", but * column "1" for base table TT is "a". On the flip side, column "3" * for base table TT is "i", but if we search the PRN's result columns * (which match the result columns for the ResultSetNode to which * we're scoping) for column "3", we won't find it. * * So what does all of that mean? It means that if the ResultColumn * we found has an expression that's a ColumnReference, we can simply * return that ColumnReference IF we set it's columnNumber correctly. * Thankfully the column reference we're trying to scope ("cr") came * from further up the tree and so it knows what the correct column * position (namely, the position w.r.t the ProjectRestrictNode above * the FromBaseTable) needs to be. So that's the column number we * use. * * As a final note, we have to be sure we only set the column * reference's column number if the reference points to a base table. * If the reference points to some other ResultSetNode--esp. another * subquery node--then it (the reference) already holds the correct * number with respect to that ResultSetNode and we don't change * it. The reason is that the reference could end up getting pushed * down further to that ResultSetNode, in which case we'll do another * scoping operation and, in order for that to be successful, the * reference to be scoped has to know what the target column number * is w.r.t to that ResultSetNode (i.e. it'll be playing the role of * "cr" as described here). */ if (rc.getExpression() instanceof ColumnReference) { // Make sure the ColumnReference's columnNumber is correct, // then just return that reference. Note: it's okay to overwrite // the columnNumber directly because when it eventually makes // it down to the PRN over the FromBaseTable, it will be remapped // for the FromBaseTable and the columnNumber will then be set // correctly. That remapping is done in the pushOptPredicate() // method of ProjectRestrictNode. ColumnReference cRef = (ColumnReference)rc.getExpression(); if (cRef.pointsToBaseTable()) cRef.setColumnNumber(cr.getColumnNumber()); return cRef; } /* We can get here if the ResultColumn's expression isn't a * ColumnReference. For example, the expression would be a * constant expression if childRSN represented something like: * * select 1, 1 from t1 * * In this case we just return a clone of the column reference * because it's scoped as far as we can take it. */ return (ValueNode)cr.getClone(); }
* As a final note, we have to be sure we only set the column * reference's column number if the reference points to a base table. * If the reference points to some other ResultSetNode--esp. another * subquery node--then it (the reference) already holds the correct * number with respect to that ResultSetNode and we don't change * it. The reason is that the reference could end up getting pushed * down further to that ResultSetNode, in which case we'll do another * scoping operation and, in order for that to be successful, the * reference to be scoped has to know what the target column number * is w.r.t to that ResultSetNode (i.e. it'll be playing the role of * "cr" as described here).
* select 1, 1 from t1 * * In this case the expression does not directly reference a * column in the underlying result set and is therefore * "scoped" as far as it can go. This means that the scoped * predicate will not necessarily have column references on * both sides, even though the predicate that we're scoping * will. That's not a problem, though, since a predicate with * a column reference on one side and a non-ColumnReference * on the other is still valid.
public ValueNode getScopedOperand(int whichSide, JBitSet parentRSNsTables, ResultSetNode childRSN) throws StandardException { ResultColumn rc = null; ColumnReference cr = whichSide == LEFT ? (ColumnReference)leftOperand : (ColumnReference)rightOperand; // The first thing we need to do is see if this ColumnReference // is supposed to be scoped for childRSN. We do that by figuring // out what underlying base table the column reference is pointing // to and then seeing if that base table is included in the list of // table numbers from the parentRSN. JBitSet crTables = new JBitSet(parentRSNsTables.size()); BaseTableNumbersVisitor btnVis = new BaseTableNumbersVisitor(crTables); cr.accept(btnVis); // If the column reference doesn't reference any tables, // then there's no point in mapping it to the child result // set; just return a clone of the operand. if (crTables.getFirstSetBit() == -1) { return (ValueNode)cr.getClone(); } /* If the column reference in question is not intended for * the received result set node, just leave the operand as * it is (i.e. return a clone). In the example mentioned at * the start of this method, this will happen when the operand * is X2.b and childRSN is either "select i,j from t1" or * "select i,j from t2", in which case the operand does not * apply to childRSN. When we get here and try to map the * "X1.j" operand, though, the following "contains" check will * return true and thus we can go ahead and return a scoped * version of that operand. */ if (!parentRSNsTables.contains(crTables)) { return (ValueNode)cr.getClone(); } // If the column reference is already pointing to the // correct table, then there's no need to change it. if ((childRSN.getReferencedTableMap() != null) && childRSN.getReferencedTableMap().get(cr.getTableNumber())) { return cr; } /* Find the target ResultColumn in the received result set. At * this point we know that we do in fact need to scope the column * reference for childRSN, so go ahead and do it. We get the * target column by column position instead of by name because * it's possible that the name given for the query doesn't match * the name of the actual column we're looking for. Ex. * * select * from * (select i,j from t1 union select i,j from t2) X1 (x,y), * (select a,b from t3 union select a,b from t4) X2 * where X1.x = X2.b; * * If we searched for "x" in the childRSN "select i,j from t1" * we wouldn't find it. So we have to look based on position. */ rc = childRSN.getResultColumns().getResultColumn(cr.getColumnNumber()); // rc shouldn't be null; if there was no matching ResultColumn at all, // then we shouldn't have made it this far. if (SanityManager.DEBUG) { SanityManager.ASSERT(rc != null, "Failed to locate result column when trying to " + "scope operand '" + cr.getTableName() + "." + cr.getColumnName() + "'."); } /* If the ResultColumn we found has an expression that is a * ColumnReference, then that column reference has all of the info * we need, with one exception: the columnNumber. Depending on our * depth in the tree, the ResultColumn's ColumnReference could be * pointing to a base column in the FromBaseTable. In that case the * ColumnReference will hold the column position as it is with respect * to the FromBaseTable. But when we're scoping a column reference, * we're scoping it to a ResultSetNode that sits (either directly or * indirectly) above a ProjectRestrictNode that in turn sits above the * FromBaseTable. This means that the scoped reference's columnNumber * needs to be with respect to the PRN that sits above the base table, * _not_ with respect to the FromBaseTable itself. This is important * because column "1" in the PRN might not be column "1" in the * underlying base table. For example, if we have base table TT with * four columns (a int, b int, i int, j int) and the PRN above it only * projects out columns (i,j), then column "1" for the PRN is "i", but * column "1" for base table TT is "a". On the flip side, column "3" * for base table TT is "i", but if we search the PRN's result columns * (which match the result columns for the ResultSetNode to which * we're scoping) for column "3", we won't find it. * * So what does all of that mean? It means that if the ResultColumn * we found has an expression that's a ColumnReference, we can simply * return that ColumnReference IF we set it's columnNumber correctly. * Thankfully the column reference we're trying to scope ("cr") came * from further up the tree and so it knows what the correct column * position (namely, the position w.r.t the ProjectRestrictNode above * the FromBaseTable) needs to be. So that's the column number we * use. * * As a final note, we have to be sure we only set the column * reference's column number if the reference points to a base table. * If the reference points to some other ResultSetNode--esp. another * subquery node--then it (the reference) already holds the correct * number with respect to that ResultSetNode and we don't change * it. The reason is that the reference could end up getting pushed * down further to that ResultSetNode, in which case we'll do another * scoping operation and, in order for that to be successful, the * reference to be scoped has to know what the target column number * is w.r.t to that ResultSetNode (i.e. it'll be playing the role of * "cr" as described here). */ if (rc.getExpression() instanceof ColumnReference) { // Make sure the ColumnReference's columnNumber is correct, // then just return that reference. Note: it's okay to overwrite // the columnNumber directly because when it eventually makes // it down to the PRN over the FromBaseTable, it will be remapped // for the FromBaseTable and the columnNumber will then be set // correctly. That remapping is done in the pushOptPredicate() // method of ProjectRestrictNode. ColumnReference cRef = (ColumnReference)rc.getExpression(); if (cRef.pointsToBaseTable()) cRef.setColumnNumber(cr.getColumnNumber()); return cRef; } /* We can get here if the ResultColumn's expression isn't a * ColumnReference. For example, the expression would be a * constant expression if childRSN represented something like: * * select 1, 1 from t1 * * In this case we just return a clone of the column reference * because it's scoped as far as we can take it. */ return (ValueNode)cr.getClone(); }
ColumnReference cRef = (ColumnReference)rc.getExpression(); if (cRef.pointsToBaseTable()) cRef.setColumnNumber(cr.getColumnNumber());
ColumnReference cRef = (ColumnReference) ((ColumnReference)rc.getExpression()).getClone(); cRef.markAsScoped();
public ValueNode getScopedOperand(int whichSide, JBitSet parentRSNsTables, ResultSetNode childRSN) throws StandardException { ResultColumn rc = null; ColumnReference cr = whichSide == LEFT ? (ColumnReference)leftOperand : (ColumnReference)rightOperand; // The first thing we need to do is see if this ColumnReference // is supposed to be scoped for childRSN. We do that by figuring // out what underlying base table the column reference is pointing // to and then seeing if that base table is included in the list of // table numbers from the parentRSN. JBitSet crTables = new JBitSet(parentRSNsTables.size()); BaseTableNumbersVisitor btnVis = new BaseTableNumbersVisitor(crTables); cr.accept(btnVis); // If the column reference doesn't reference any tables, // then there's no point in mapping it to the child result // set; just return a clone of the operand. if (crTables.getFirstSetBit() == -1) { return (ValueNode)cr.getClone(); } /* If the column reference in question is not intended for * the received result set node, just leave the operand as * it is (i.e. return a clone). In the example mentioned at * the start of this method, this will happen when the operand * is X2.b and childRSN is either "select i,j from t1" or * "select i,j from t2", in which case the operand does not * apply to childRSN. When we get here and try to map the * "X1.j" operand, though, the following "contains" check will * return true and thus we can go ahead and return a scoped * version of that operand. */ if (!parentRSNsTables.contains(crTables)) { return (ValueNode)cr.getClone(); } // If the column reference is already pointing to the // correct table, then there's no need to change it. if ((childRSN.getReferencedTableMap() != null) && childRSN.getReferencedTableMap().get(cr.getTableNumber())) { return cr; } /* Find the target ResultColumn in the received result set. At * this point we know that we do in fact need to scope the column * reference for childRSN, so go ahead and do it. We get the * target column by column position instead of by name because * it's possible that the name given for the query doesn't match * the name of the actual column we're looking for. Ex. * * select * from * (select i,j from t1 union select i,j from t2) X1 (x,y), * (select a,b from t3 union select a,b from t4) X2 * where X1.x = X2.b; * * If we searched for "x" in the childRSN "select i,j from t1" * we wouldn't find it. So we have to look based on position. */ rc = childRSN.getResultColumns().getResultColumn(cr.getColumnNumber()); // rc shouldn't be null; if there was no matching ResultColumn at all, // then we shouldn't have made it this far. if (SanityManager.DEBUG) { SanityManager.ASSERT(rc != null, "Failed to locate result column when trying to " + "scope operand '" + cr.getTableName() + "." + cr.getColumnName() + "'."); } /* If the ResultColumn we found has an expression that is a * ColumnReference, then that column reference has all of the info * we need, with one exception: the columnNumber. Depending on our * depth in the tree, the ResultColumn's ColumnReference could be * pointing to a base column in the FromBaseTable. In that case the * ColumnReference will hold the column position as it is with respect * to the FromBaseTable. But when we're scoping a column reference, * we're scoping it to a ResultSetNode that sits (either directly or * indirectly) above a ProjectRestrictNode that in turn sits above the * FromBaseTable. This means that the scoped reference's columnNumber * needs to be with respect to the PRN that sits above the base table, * _not_ with respect to the FromBaseTable itself. This is important * because column "1" in the PRN might not be column "1" in the * underlying base table. For example, if we have base table TT with * four columns (a int, b int, i int, j int) and the PRN above it only * projects out columns (i,j), then column "1" for the PRN is "i", but * column "1" for base table TT is "a". On the flip side, column "3" * for base table TT is "i", but if we search the PRN's result columns * (which match the result columns for the ResultSetNode to which * we're scoping) for column "3", we won't find it. * * So what does all of that mean? It means that if the ResultColumn * we found has an expression that's a ColumnReference, we can simply * return that ColumnReference IF we set it's columnNumber correctly. * Thankfully the column reference we're trying to scope ("cr") came * from further up the tree and so it knows what the correct column * position (namely, the position w.r.t the ProjectRestrictNode above * the FromBaseTable) needs to be. So that's the column number we * use. * * As a final note, we have to be sure we only set the column * reference's column number if the reference points to a base table. * If the reference points to some other ResultSetNode--esp. another * subquery node--then it (the reference) already holds the correct * number with respect to that ResultSetNode and we don't change * it. The reason is that the reference could end up getting pushed * down further to that ResultSetNode, in which case we'll do another * scoping operation and, in order for that to be successful, the * reference to be scoped has to know what the target column number * is w.r.t to that ResultSetNode (i.e. it'll be playing the role of * "cr" as described here). */ if (rc.getExpression() instanceof ColumnReference) { // Make sure the ColumnReference's columnNumber is correct, // then just return that reference. Note: it's okay to overwrite // the columnNumber directly because when it eventually makes // it down to the PRN over the FromBaseTable, it will be remapped // for the FromBaseTable and the columnNumber will then be set // correctly. That remapping is done in the pushOptPredicate() // method of ProjectRestrictNode. ColumnReference cRef = (ColumnReference)rc.getExpression(); if (cRef.pointsToBaseTable()) cRef.setColumnNumber(cr.getColumnNumber()); return cRef; } /* We can get here if the ResultColumn's expression isn't a * ColumnReference. For example, the expression would be a * constant expression if childRSN represented something like: * * select 1, 1 from t1 * * In this case we just return a clone of the column reference * because it's scoped as far as we can take it. */ return (ValueNode)cr.getClone(); }
/* We can get here if the ResultColumn's expression isn't a * ColumnReference. For example, the expression would be a * constant expression if childRSN represented something like: * * select 1, 1 from t1 * * In this case we just return a clone of the column reference * because it's scoped as far as we can take it.
/* Else just return rc's expression. This means the scoped * predicate will have one operand that is _not_ a column * reference--but that's okay, so long as we account for * that when pushing/remapping the scoped predicate down * the query tree (see esp. "isScopedToSourceResultSet()" * in Predicate.java).
public ValueNode getScopedOperand(int whichSide, JBitSet parentRSNsTables, ResultSetNode childRSN) throws StandardException { ResultColumn rc = null; ColumnReference cr = whichSide == LEFT ? (ColumnReference)leftOperand : (ColumnReference)rightOperand; // The first thing we need to do is see if this ColumnReference // is supposed to be scoped for childRSN. We do that by figuring // out what underlying base table the column reference is pointing // to and then seeing if that base table is included in the list of // table numbers from the parentRSN. JBitSet crTables = new JBitSet(parentRSNsTables.size()); BaseTableNumbersVisitor btnVis = new BaseTableNumbersVisitor(crTables); cr.accept(btnVis); // If the column reference doesn't reference any tables, // then there's no point in mapping it to the child result // set; just return a clone of the operand. if (crTables.getFirstSetBit() == -1) { return (ValueNode)cr.getClone(); } /* If the column reference in question is not intended for * the received result set node, just leave the operand as * it is (i.e. return a clone). In the example mentioned at * the start of this method, this will happen when the operand * is X2.b and childRSN is either "select i,j from t1" or * "select i,j from t2", in which case the operand does not * apply to childRSN. When we get here and try to map the * "X1.j" operand, though, the following "contains" check will * return true and thus we can go ahead and return a scoped * version of that operand. */ if (!parentRSNsTables.contains(crTables)) { return (ValueNode)cr.getClone(); } // If the column reference is already pointing to the // correct table, then there's no need to change it. if ((childRSN.getReferencedTableMap() != null) && childRSN.getReferencedTableMap().get(cr.getTableNumber())) { return cr; } /* Find the target ResultColumn in the received result set. At * this point we know that we do in fact need to scope the column * reference for childRSN, so go ahead and do it. We get the * target column by column position instead of by name because * it's possible that the name given for the query doesn't match * the name of the actual column we're looking for. Ex. * * select * from * (select i,j from t1 union select i,j from t2) X1 (x,y), * (select a,b from t3 union select a,b from t4) X2 * where X1.x = X2.b; * * If we searched for "x" in the childRSN "select i,j from t1" * we wouldn't find it. So we have to look based on position. */ rc = childRSN.getResultColumns().getResultColumn(cr.getColumnNumber()); // rc shouldn't be null; if there was no matching ResultColumn at all, // then we shouldn't have made it this far. if (SanityManager.DEBUG) { SanityManager.ASSERT(rc != null, "Failed to locate result column when trying to " + "scope operand '" + cr.getTableName() + "." + cr.getColumnName() + "'."); } /* If the ResultColumn we found has an expression that is a * ColumnReference, then that column reference has all of the info * we need, with one exception: the columnNumber. Depending on our * depth in the tree, the ResultColumn's ColumnReference could be * pointing to a base column in the FromBaseTable. In that case the * ColumnReference will hold the column position as it is with respect * to the FromBaseTable. But when we're scoping a column reference, * we're scoping it to a ResultSetNode that sits (either directly or * indirectly) above a ProjectRestrictNode that in turn sits above the * FromBaseTable. This means that the scoped reference's columnNumber * needs to be with respect to the PRN that sits above the base table, * _not_ with respect to the FromBaseTable itself. This is important * because column "1" in the PRN might not be column "1" in the * underlying base table. For example, if we have base table TT with * four columns (a int, b int, i int, j int) and the PRN above it only * projects out columns (i,j), then column "1" for the PRN is "i", but * column "1" for base table TT is "a". On the flip side, column "3" * for base table TT is "i", but if we search the PRN's result columns * (which match the result columns for the ResultSetNode to which * we're scoping) for column "3", we won't find it. * * So what does all of that mean? It means that if the ResultColumn * we found has an expression that's a ColumnReference, we can simply * return that ColumnReference IF we set it's columnNumber correctly. * Thankfully the column reference we're trying to scope ("cr") came * from further up the tree and so it knows what the correct column * position (namely, the position w.r.t the ProjectRestrictNode above * the FromBaseTable) needs to be. So that's the column number we * use. * * As a final note, we have to be sure we only set the column * reference's column number if the reference points to a base table. * If the reference points to some other ResultSetNode--esp. another * subquery node--then it (the reference) already holds the correct * number with respect to that ResultSetNode and we don't change * it. The reason is that the reference could end up getting pushed * down further to that ResultSetNode, in which case we'll do another * scoping operation and, in order for that to be successful, the * reference to be scoped has to know what the target column number * is w.r.t to that ResultSetNode (i.e. it'll be playing the role of * "cr" as described here). */ if (rc.getExpression() instanceof ColumnReference) { // Make sure the ColumnReference's columnNumber is correct, // then just return that reference. Note: it's okay to overwrite // the columnNumber directly because when it eventually makes // it down to the PRN over the FromBaseTable, it will be remapped // for the FromBaseTable and the columnNumber will then be set // correctly. That remapping is done in the pushOptPredicate() // method of ProjectRestrictNode. ColumnReference cRef = (ColumnReference)rc.getExpression(); if (cRef.pointsToBaseTable()) cRef.setColumnNumber(cr.getColumnNumber()); return cRef; } /* We can get here if the ResultColumn's expression isn't a * ColumnReference. For example, the expression would be a * constant expression if childRSN represented something like: * * select 1, 1 from t1 * * In this case we just return a clone of the column reference * because it's scoped as far as we can take it. */ return (ValueNode)cr.getClone(); }
return (ValueNode)cr.getClone();
return rc.getExpression();
public ValueNode getScopedOperand(int whichSide, JBitSet parentRSNsTables, ResultSetNode childRSN) throws StandardException { ResultColumn rc = null; ColumnReference cr = whichSide == LEFT ? (ColumnReference)leftOperand : (ColumnReference)rightOperand; // The first thing we need to do is see if this ColumnReference // is supposed to be scoped for childRSN. We do that by figuring // out what underlying base table the column reference is pointing // to and then seeing if that base table is included in the list of // table numbers from the parentRSN. JBitSet crTables = new JBitSet(parentRSNsTables.size()); BaseTableNumbersVisitor btnVis = new BaseTableNumbersVisitor(crTables); cr.accept(btnVis); // If the column reference doesn't reference any tables, // then there's no point in mapping it to the child result // set; just return a clone of the operand. if (crTables.getFirstSetBit() == -1) { return (ValueNode)cr.getClone(); } /* If the column reference in question is not intended for * the received result set node, just leave the operand as * it is (i.e. return a clone). In the example mentioned at * the start of this method, this will happen when the operand * is X2.b and childRSN is either "select i,j from t1" or * "select i,j from t2", in which case the operand does not * apply to childRSN. When we get here and try to map the * "X1.j" operand, though, the following "contains" check will * return true and thus we can go ahead and return a scoped * version of that operand. */ if (!parentRSNsTables.contains(crTables)) { return (ValueNode)cr.getClone(); } // If the column reference is already pointing to the // correct table, then there's no need to change it. if ((childRSN.getReferencedTableMap() != null) && childRSN.getReferencedTableMap().get(cr.getTableNumber())) { return cr; } /* Find the target ResultColumn in the received result set. At * this point we know that we do in fact need to scope the column * reference for childRSN, so go ahead and do it. We get the * target column by column position instead of by name because * it's possible that the name given for the query doesn't match * the name of the actual column we're looking for. Ex. * * select * from * (select i,j from t1 union select i,j from t2) X1 (x,y), * (select a,b from t3 union select a,b from t4) X2 * where X1.x = X2.b; * * If we searched for "x" in the childRSN "select i,j from t1" * we wouldn't find it. So we have to look based on position. */ rc = childRSN.getResultColumns().getResultColumn(cr.getColumnNumber()); // rc shouldn't be null; if there was no matching ResultColumn at all, // then we shouldn't have made it this far. if (SanityManager.DEBUG) { SanityManager.ASSERT(rc != null, "Failed to locate result column when trying to " + "scope operand '" + cr.getTableName() + "." + cr.getColumnName() + "'."); } /* If the ResultColumn we found has an expression that is a * ColumnReference, then that column reference has all of the info * we need, with one exception: the columnNumber. Depending on our * depth in the tree, the ResultColumn's ColumnReference could be * pointing to a base column in the FromBaseTable. In that case the * ColumnReference will hold the column position as it is with respect * to the FromBaseTable. But when we're scoping a column reference, * we're scoping it to a ResultSetNode that sits (either directly or * indirectly) above a ProjectRestrictNode that in turn sits above the * FromBaseTable. This means that the scoped reference's columnNumber * needs to be with respect to the PRN that sits above the base table, * _not_ with respect to the FromBaseTable itself. This is important * because column "1" in the PRN might not be column "1" in the * underlying base table. For example, if we have base table TT with * four columns (a int, b int, i int, j int) and the PRN above it only * projects out columns (i,j), then column "1" for the PRN is "i", but * column "1" for base table TT is "a". On the flip side, column "3" * for base table TT is "i", but if we search the PRN's result columns * (which match the result columns for the ResultSetNode to which * we're scoping) for column "3", we won't find it. * * So what does all of that mean? It means that if the ResultColumn * we found has an expression that's a ColumnReference, we can simply * return that ColumnReference IF we set it's columnNumber correctly. * Thankfully the column reference we're trying to scope ("cr") came * from further up the tree and so it knows what the correct column * position (namely, the position w.r.t the ProjectRestrictNode above * the FromBaseTable) needs to be. So that's the column number we * use. * * As a final note, we have to be sure we only set the column * reference's column number if the reference points to a base table. * If the reference points to some other ResultSetNode--esp. another * subquery node--then it (the reference) already holds the correct * number with respect to that ResultSetNode and we don't change * it. The reason is that the reference could end up getting pushed * down further to that ResultSetNode, in which case we'll do another * scoping operation and, in order for that to be successful, the * reference to be scoped has to know what the target column number * is w.r.t to that ResultSetNode (i.e. it'll be playing the role of * "cr" as described here). */ if (rc.getExpression() instanceof ColumnReference) { // Make sure the ColumnReference's columnNumber is correct, // then just return that reference. Note: it's okay to overwrite // the columnNumber directly because when it eventually makes // it down to the PRN over the FromBaseTable, it will be remapped // for the FromBaseTable and the columnNumber will then be set // correctly. That remapping is done in the pushOptPredicate() // method of ProjectRestrictNode. ColumnReference cRef = (ColumnReference)rc.getExpression(); if (cRef.pointsToBaseTable()) cRef.setColumnNumber(cr.getColumnNumber()); return cRef; } /* We can get here if the ResultColumn's expression isn't a * ColumnReference. For example, the expression would be a * constant expression if childRSN represented something like: * * select 1, 1 from t1 * * In this case we just return a clone of the column reference * because it's scoped as far as we can take it. */ return (ValueNode)cr.getClone(); }
case StoredFormatIds.COLUMNS_PERMISSION_FINDER_V01_ID: return new DDColumnPermissionsDependableFinder(fmtId);
public Object getNewInstance() { switch (fmtId) { /* DependableFinders */ case StoredFormatIds.ALIAS_DESCRIPTOR_FINDER_V01_ID: case StoredFormatIds.CONGLOMERATE_DESCRIPTOR_FINDER_V01_ID: case StoredFormatIds.CONSTRAINT_DESCRIPTOR_FINDER_V01_ID: case StoredFormatIds.DEFAULT_DESCRIPTOR_FINDER_V01_ID: case StoredFormatIds.FILE_INFO_FINDER_V01_ID: case StoredFormatIds.SCHEMA_DESCRIPTOR_FINDER_V01_ID: case StoredFormatIds.SPS_DESCRIPTOR_FINDER_V01_ID: case StoredFormatIds.TABLE_DESCRIPTOR_FINDER_V01_ID: case StoredFormatIds.TRIGGER_DESCRIPTOR_FINDER_V01_ID: case StoredFormatIds.VIEW_DESCRIPTOR_FINDER_V01_ID: return new DDdependableFinder(fmtId); case StoredFormatIds.COLUMN_DESCRIPTOR_FINDER_V01_ID: return new DDColumnDependableFinder(fmtId); default: return null; } }
stmt.executeUpdate("CREATE TABLE blobTest8TriggerA (a BLOB(300k), b int, crc32 BIGINT)"); stmt.executeUpdate("CREATE TABLE blobTest8TriggerB (a BLOB(200k), b int, crc32 BIGINT)");
stmt.executeUpdate("CREATE TABLE blobTest8TriggerA (a BLOB(400k), b int, crc32 BIGINT)"); stmt.executeUpdate("CREATE TABLE blobTest8TriggerB (a BLOB(400k), b int, crc32 BIGINT)");
private static void blobTest8Trigger(Connection conn) { System.out.println(START + "blobTest8Trigger"); try { Statement stmt = conn.createStatement(); stmt.executeUpdate("CREATE TABLE blobTest8TriggerA (a BLOB(300k), b int, crc32 BIGINT)"); stmt.executeUpdate("CREATE TABLE blobTest8TriggerB (a BLOB(200k), b int, crc32 BIGINT)"); stmt.executeUpdate( "create trigger T8A after update on testBlob " + "referencing new as n old as o " + "for each row mode db2sql "+ "insert into blobTest8TriggerA(a, b, crc32) values (n.a, n.b, n.crc32)"); conn.commit(); ResultSet rs = stmt.executeQuery( "select a,b,crc32 from blobTest8TriggerA"); testBlobContents(rs); rs.close(); conn.commit(); stmt.executeUpdate("UPDATE testBlob set b = b + 0"); conn.commit(); rs = stmt.executeQuery( "select a,b,crc32 from blobTest8TriggerA"); testBlobContents(rs); stmt.close(); conn.commit(); System.out.println("blobTest8Trigger finished"); } catch (SQLException e) { TestUtil.dumpSQLExceptions(e); } catch (Throwable e) { System.out.println("FAIL -- unexpected exception:" + e.toString()); if (debug) e.printStackTrace(); } }
do { e.printStackTrace(System.out); e = e.getNextException(); } while (e != null);
private static void blobTest8Trigger(Connection conn) { System.out.println(START + "blobTest8Trigger"); try { Statement stmt = conn.createStatement(); stmt.executeUpdate("CREATE TABLE blobTest8TriggerA (a BLOB(300k), b int, crc32 BIGINT)"); stmt.executeUpdate("CREATE TABLE blobTest8TriggerB (a BLOB(200k), b int, crc32 BIGINT)"); stmt.executeUpdate( "create trigger T8A after update on testBlob " + "referencing new as n old as o " + "for each row mode db2sql "+ "insert into blobTest8TriggerA(a, b, crc32) values (n.a, n.b, n.crc32)"); conn.commit(); ResultSet rs = stmt.executeQuery( "select a,b,crc32 from blobTest8TriggerA"); testBlobContents(rs); rs.close(); conn.commit(); stmt.executeUpdate("UPDATE testBlob set b = b + 0"); conn.commit(); rs = stmt.executeQuery( "select a,b,crc32 from blobTest8TriggerA"); testBlobContents(rs); stmt.close(); conn.commit(); System.out.println("blobTest8Trigger finished"); } catch (SQLException e) { TestUtil.dumpSQLExceptions(e); } catch (Throwable e) { System.out.println("FAIL -- unexpected exception:" + e.toString()); if (debug) e.printStackTrace(); } }
EncryptData ed = new EncryptData(this);
containerEncrypter = new EncryptData(this);
public void encryptAllContainers(RawTransaction t) throws StandardException { EncryptData ed = new EncryptData(this); // encrypt all the conatiners in the databse ed.encryptAllContainers(t); }
ed.encryptAllContainers(t);
containerEncrypter.encryptAllContainers(t);
public void encryptAllContainers(RawTransaction t) throws StandardException { EncryptData ed = new EncryptData(this); // encrypt all the conatiners in the databse ed.encryptAllContainers(t); }
private XAStatementControl(EmbedPooledConnection xaConnection) {
private XAStatementControl(EmbedXAConnection xaConnection) {
private XAStatementControl(EmbedPooledConnection xaConnection) { this.xaConnection = xaConnection; this.realConnection = xaConnection.realConnection; this.applicationConnection = xaConnection.currentConnectionHandle; }
if (allowOnlySecurityMechanism == INVALID_OR_NOTSET_SECURITYMECHANISM)
if ((allowOnlySecurityMechanism == INVALID_OR_NOTSET_SECURITYMECHANISM) || (allowOnlySecurityMechanism == CodePoint.SECMEC_EUSRIDPWD && !SUPPORTS_EUSRIDPWD))
private void setSecurityMechanism(String s) throws Exception { allowOnlySecurityMechanism = getSecMecValue(s); if (allowOnlySecurityMechanism == INVALID_OR_NOTSET_SECURITYMECHANISM) consolePropertyMessage("DRDA_InvalidValue.U", new String [] {s, Property.DRDA_PROP_SECURITYMECHANISM}); }
int leftToRead = length; int extendedLengthByteCount = prepScalarStream(chained, chainedWithSameCorrelator, writeNullByte, leftToRead); int bytesToRead;
if (netAgent_.netConnection_.getSecurityMechanism() == NetConfiguration.SECMEC_EUSRIDDTA || netAgent_.netConnection_.getSecurityMechanism() == NetConfiguration.SECMEC_EUSRPWDDTA) { writeEncryptedScalarStream(chained, chainedWithSameCorrelator, codePoint, length, in, writeNullByte, parameterIndex);
final void writeScalarStream(boolean chained, boolean chainedWithSameCorrelator, int codePoint, int length, java.io.InputStream in, boolean writeNullByte, int parameterIndex) throws DisconnectException, SqlException { int leftToRead = length; int extendedLengthByteCount = prepScalarStream(chained, chainedWithSameCorrelator, writeNullByte, leftToRead); int bytesToRead; if (writeNullByte) { bytesToRead = Utils.min(leftToRead, DssConstants.MAX_DSS_LEN - 6 - 4 - 1 - extendedLengthByteCount); } else { bytesToRead = Utils.min(leftToRead, DssConstants.MAX_DSS_LEN - 6 - 4 - extendedLengthByteCount); } if (netAgent_.netConnection_.getSecurityMechanism() == NetConfiguration.SECMEC_EUSRIDDTA || netAgent_.netConnection_.getSecurityMechanism() == NetConfiguration.SECMEC_EUSRPWDDTA) { byte[] lengthAndCodepoint; lengthAndCodepoint = buildLengthAndCodePointForEncryptedLob(codePoint, leftToRead, writeNullByte, extendedLengthByteCount); // we need to stream the input, rather than fully materialize it // write the data byte[] clearedBytes = new byte[leftToRead]; int bytesRead = 0; int totalBytesRead = 0; int pos = 0; do { try { bytesRead = in.read(clearedBytes, pos, leftToRead); totalBytesRead += bytesRead; } catch (java.io.IOException e) { padScalarStreamForError(leftToRead, bytesToRead); // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. netAgent_.accumulateReadException(new SqlException(netAgent_.logWriter_, new ClientMessageId(SQLState.NET_IOEXCEPTION_ON_READ), new Integer(parameterIndex), e.getMessage(), e)); return; } if (bytesRead == -1) { //padScalarStreamForError(leftToRead, bytesToRead); // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. /*throw new SqlException(netAgent_.logWriter_, "End of Stream prematurely reached while reading InputStream, parameter #" + parameterIndex + ". Remaining data has been padded with 0x0.");*/ //is it OK to do a chain break Exception here. It's not good to //pad it with 0 and encrypt and send it to the server because it takes too much time //can't just throw a SQLException either because some of the data PRPSQLSTT etc have already //been sent to the server, and server is waiting for EXTDTA, server hangs for this. netAgent_.accumulateChainBreakingReadExceptionAndThrow( new DisconnectException(netAgent_, new ClientMessageId(SQLState.NET_PREMATURE_EOS_DISCONNECT), new Integer(parameterIndex))); return; /*netAgent_.accumulateReadException( new SqlException(netAgent_.logWriter_, "End of Stream prematurely reached while reading InputStream, parameter #" + parameterIndex + ". Remaining data has been padded with 0x0.")); return;*/ } else { pos += bytesRead; //offset_ += bytesRead; //comment this out for data stream encryption. leftToRead -= bytesRead; } } while (leftToRead > 0); // check to make sure that the specified length wasn't too small try { if (in.read() != -1) { // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. netAgent_.accumulateReadException(new SqlException( netAgent_.logWriter_, new ClientMessageId(SQLState.NET_INPUTSTREAM_LENGTH_TOO_SMALL), new Integer(parameterIndex))); } } catch (java.io.IOException e) { netAgent_.accumulateReadException(new SqlException( netAgent_.logWriter_, new ClientMessageId( SQLState.NET_IOEXCEPTION_ON_STREAMLEN_VERIFICATION), new Integer(parameterIndex), e.getMessage(), e)); } byte[] newClearedBytes = new byte[clearedBytes.length + lengthAndCodepoint.length]; System.arraycopy(lengthAndCodepoint, 0, newClearedBytes, 0, lengthAndCodepoint.length); System.arraycopy(clearedBytes, 0, newClearedBytes, lengthAndCodepoint.length, clearedBytes.length); //it's wrong here, need to add in the real length after the codepoing 146c byte[] encryptedBytes; encryptedBytes = netAgent_.netConnection_.getEncryptionManager(). encryptData(newClearedBytes, NetConfiguration.SECMEC_EUSRIDPWD, netAgent_.netConnection_.getTargetPublicKey(), netAgent_.netConnection_.getTargetPublicKey()); int encryptedBytesLength = encryptedBytes.length; int sendingLength = bytes_.length - offset_; if (encryptedBytesLength > (bytes_.length - offset_)) { System.arraycopy(encryptedBytes, 0, bytes_, offset_, (bytes_.length - offset_)); offset_ = 32767; try { sendBytes(netAgent_.getOutputStream()); } catch (java.io.IOException ioe) { netAgent_.throwCommunicationsFailure(ioe); } } else { System.arraycopy(encryptedBytes, 0, bytes_, offset_, encryptedBytesLength); offset_ = offset_ + encryptedBytes.length; } encryptedBytesLength = encryptedBytesLength - sendingLength; while (encryptedBytesLength > 0) { //dssLengthLocation_ = offset_; offset_ = 0; if ((encryptedBytesLength - 32765) > 0) { bytes_[offset_++] = (byte) (0xff); bytes_[offset_++] = (byte) (0xff); System.arraycopy(encryptedBytes, sendingLength, bytes_, offset_, 32765); encryptedBytesLength -= 32765; sendingLength += 32765; offset_ = 32767; try { sendBytes(netAgent_.getOutputStream()); } catch (java.io.IOException ioe) { netAgent_.throwCommunicationsFailure(ioe); } } else { int leftlength = encryptedBytesLength + 2; bytes_[offset_++] = (byte) ((leftlength >>> 8) & 0xff); bytes_[offset_++] = (byte) (leftlength & 0xff); System.arraycopy(encryptedBytes, sendingLength, bytes_, offset_, encryptedBytesLength); offset_ += encryptedBytesLength; dssLengthLocation_ = offset_; encryptedBytesLength = 0; } } } else //if not data strteam encryption { buildLengthAndCodePointForLob(codePoint, leftToRead, writeNullByte, extendedLengthByteCount); int bytesRead = 0; int totalBytesRead = 0; do { do { try { bytesRead = in.read(bytes_, offset_, bytesToRead); totalBytesRead += bytesRead; } catch (java.io.IOException e) { padScalarStreamForError(leftToRead, bytesToRead); // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. netAgent_.accumulateReadException(new SqlException( netAgent_.logWriter_, new ClientMessageId(SQLState.NET_IOEXCEPTION_ON_READ), new Integer(parameterIndex), e.getMessage(), e)); return; } if (bytesRead == -1) { padScalarStreamForError(leftToRead, bytesToRead); // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. netAgent_.accumulateReadException(new SqlException(netAgent_.logWriter_, new ClientMessageId(SQLState.NET_PREMATURE_EOS), new Integer(parameterIndex))); return; } else { bytesToRead -= bytesRead; offset_ += bytesRead; leftToRead -= bytesRead; } } while (bytesToRead > 0); bytesToRead = flushScalarStreamSegment(leftToRead, bytesToRead); } while (leftToRead > 0); // check to make sure that the specified length wasn't too small try { if (in.read() != -1) { // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. netAgent_.accumulateReadException(new SqlException(netAgent_.logWriter_, new ClientMessageId(SQLState.NET_INPUTSTREAM_LENGTH_TOO_SMALL), new Integer(parameterIndex))); } } catch (java.io.IOException e) { netAgent_.accumulateReadException(new SqlException( netAgent_.logWriter_, new ClientMessageId( SQLState.NET_IOEXCEPTION_ON_STREAMLEN_VERIFICATION), new Integer(parameterIndex), e.getMessage(), e)); } } }
if (writeNullByte) { bytesToRead = Utils.min(leftToRead, DssConstants.MAX_DSS_LEN - 6 - 4 - 1 - extendedLengthByteCount); } else { bytesToRead = Utils.min(leftToRead, DssConstants.MAX_DSS_LEN - 6 - 4 - extendedLengthByteCount); }
}else{ writePlainScalarStream(chained, chainedWithSameCorrelator, codePoint, length, in, writeNullByte, parameterIndex); }
final void writeScalarStream(boolean chained, boolean chainedWithSameCorrelator, int codePoint, int length, java.io.InputStream in, boolean writeNullByte, int parameterIndex) throws DisconnectException, SqlException { int leftToRead = length; int extendedLengthByteCount = prepScalarStream(chained, chainedWithSameCorrelator, writeNullByte, leftToRead); int bytesToRead; if (writeNullByte) { bytesToRead = Utils.min(leftToRead, DssConstants.MAX_DSS_LEN - 6 - 4 - 1 - extendedLengthByteCount); } else { bytesToRead = Utils.min(leftToRead, DssConstants.MAX_DSS_LEN - 6 - 4 - extendedLengthByteCount); } if (netAgent_.netConnection_.getSecurityMechanism() == NetConfiguration.SECMEC_EUSRIDDTA || netAgent_.netConnection_.getSecurityMechanism() == NetConfiguration.SECMEC_EUSRPWDDTA) { byte[] lengthAndCodepoint; lengthAndCodepoint = buildLengthAndCodePointForEncryptedLob(codePoint, leftToRead, writeNullByte, extendedLengthByteCount); // we need to stream the input, rather than fully materialize it // write the data byte[] clearedBytes = new byte[leftToRead]; int bytesRead = 0; int totalBytesRead = 0; int pos = 0; do { try { bytesRead = in.read(clearedBytes, pos, leftToRead); totalBytesRead += bytesRead; } catch (java.io.IOException e) { padScalarStreamForError(leftToRead, bytesToRead); // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. netAgent_.accumulateReadException(new SqlException(netAgent_.logWriter_, new ClientMessageId(SQLState.NET_IOEXCEPTION_ON_READ), new Integer(parameterIndex), e.getMessage(), e)); return; } if (bytesRead == -1) { //padScalarStreamForError(leftToRead, bytesToRead); // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. /*throw new SqlException(netAgent_.logWriter_, "End of Stream prematurely reached while reading InputStream, parameter #" + parameterIndex + ". Remaining data has been padded with 0x0.");*/ //is it OK to do a chain break Exception here. It's not good to //pad it with 0 and encrypt and send it to the server because it takes too much time //can't just throw a SQLException either because some of the data PRPSQLSTT etc have already //been sent to the server, and server is waiting for EXTDTA, server hangs for this. netAgent_.accumulateChainBreakingReadExceptionAndThrow( new DisconnectException(netAgent_, new ClientMessageId(SQLState.NET_PREMATURE_EOS_DISCONNECT), new Integer(parameterIndex))); return; /*netAgent_.accumulateReadException( new SqlException(netAgent_.logWriter_, "End of Stream prematurely reached while reading InputStream, parameter #" + parameterIndex + ". Remaining data has been padded with 0x0.")); return;*/ } else { pos += bytesRead; //offset_ += bytesRead; //comment this out for data stream encryption. leftToRead -= bytesRead; } } while (leftToRead > 0); // check to make sure that the specified length wasn't too small try { if (in.read() != -1) { // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. netAgent_.accumulateReadException(new SqlException( netAgent_.logWriter_, new ClientMessageId(SQLState.NET_INPUTSTREAM_LENGTH_TOO_SMALL), new Integer(parameterIndex))); } } catch (java.io.IOException e) { netAgent_.accumulateReadException(new SqlException( netAgent_.logWriter_, new ClientMessageId( SQLState.NET_IOEXCEPTION_ON_STREAMLEN_VERIFICATION), new Integer(parameterIndex), e.getMessage(), e)); } byte[] newClearedBytes = new byte[clearedBytes.length + lengthAndCodepoint.length]; System.arraycopy(lengthAndCodepoint, 0, newClearedBytes, 0, lengthAndCodepoint.length); System.arraycopy(clearedBytes, 0, newClearedBytes, lengthAndCodepoint.length, clearedBytes.length); //it's wrong here, need to add in the real length after the codepoing 146c byte[] encryptedBytes; encryptedBytes = netAgent_.netConnection_.getEncryptionManager(). encryptData(newClearedBytes, NetConfiguration.SECMEC_EUSRIDPWD, netAgent_.netConnection_.getTargetPublicKey(), netAgent_.netConnection_.getTargetPublicKey()); int encryptedBytesLength = encryptedBytes.length; int sendingLength = bytes_.length - offset_; if (encryptedBytesLength > (bytes_.length - offset_)) { System.arraycopy(encryptedBytes, 0, bytes_, offset_, (bytes_.length - offset_)); offset_ = 32767; try { sendBytes(netAgent_.getOutputStream()); } catch (java.io.IOException ioe) { netAgent_.throwCommunicationsFailure(ioe); } } else { System.arraycopy(encryptedBytes, 0, bytes_, offset_, encryptedBytesLength); offset_ = offset_ + encryptedBytes.length; } encryptedBytesLength = encryptedBytesLength - sendingLength; while (encryptedBytesLength > 0) { //dssLengthLocation_ = offset_; offset_ = 0; if ((encryptedBytesLength - 32765) > 0) { bytes_[offset_++] = (byte) (0xff); bytes_[offset_++] = (byte) (0xff); System.arraycopy(encryptedBytes, sendingLength, bytes_, offset_, 32765); encryptedBytesLength -= 32765; sendingLength += 32765; offset_ = 32767; try { sendBytes(netAgent_.getOutputStream()); } catch (java.io.IOException ioe) { netAgent_.throwCommunicationsFailure(ioe); } } else { int leftlength = encryptedBytesLength + 2; bytes_[offset_++] = (byte) ((leftlength >>> 8) & 0xff); bytes_[offset_++] = (byte) (leftlength & 0xff); System.arraycopy(encryptedBytes, sendingLength, bytes_, offset_, encryptedBytesLength); offset_ += encryptedBytesLength; dssLengthLocation_ = offset_; encryptedBytesLength = 0; } } } else //if not data strteam encryption { buildLengthAndCodePointForLob(codePoint, leftToRead, writeNullByte, extendedLengthByteCount); int bytesRead = 0; int totalBytesRead = 0; do { do { try { bytesRead = in.read(bytes_, offset_, bytesToRead); totalBytesRead += bytesRead; } catch (java.io.IOException e) { padScalarStreamForError(leftToRead, bytesToRead); // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. netAgent_.accumulateReadException(new SqlException( netAgent_.logWriter_, new ClientMessageId(SQLState.NET_IOEXCEPTION_ON_READ), new Integer(parameterIndex), e.getMessage(), e)); return; } if (bytesRead == -1) { padScalarStreamForError(leftToRead, bytesToRead); // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. netAgent_.accumulateReadException(new SqlException(netAgent_.logWriter_, new ClientMessageId(SQLState.NET_PREMATURE_EOS), new Integer(parameterIndex))); return; } else { bytesToRead -= bytesRead; offset_ += bytesRead; leftToRead -= bytesRead; } } while (bytesToRead > 0); bytesToRead = flushScalarStreamSegment(leftToRead, bytesToRead); } while (leftToRead > 0); // check to make sure that the specified length wasn't too small try { if (in.read() != -1) { // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. netAgent_.accumulateReadException(new SqlException(netAgent_.logWriter_, new ClientMessageId(SQLState.NET_INPUTSTREAM_LENGTH_TOO_SMALL), new Integer(parameterIndex))); } } catch (java.io.IOException e) { netAgent_.accumulateReadException(new SqlException( netAgent_.logWriter_, new ClientMessageId( SQLState.NET_IOEXCEPTION_ON_STREAMLEN_VERIFICATION), new Integer(parameterIndex), e.getMessage(), e)); } } }
if (netAgent_.netConnection_.getSecurityMechanism() == NetConfiguration.SECMEC_EUSRIDDTA || netAgent_.netConnection_.getSecurityMechanism() == NetConfiguration.SECMEC_EUSRPWDDTA) { byte[] lengthAndCodepoint; lengthAndCodepoint = buildLengthAndCodePointForEncryptedLob(codePoint, leftToRead, writeNullByte, extendedLengthByteCount); byte[] clearedBytes = new byte[leftToRead]; int bytesRead = 0; int totalBytesRead = 0; int pos = 0; do { try { bytesRead = in.read(clearedBytes, pos, leftToRead); totalBytesRead += bytesRead; } catch (java.io.IOException e) { padScalarStreamForError(leftToRead, bytesToRead); netAgent_.accumulateReadException(new SqlException(netAgent_.logWriter_, new ClientMessageId(SQLState.NET_IOEXCEPTION_ON_READ), new Integer(parameterIndex), e.getMessage(), e)); return; } if (bytesRead == -1) { netAgent_.accumulateChainBreakingReadExceptionAndThrow( new DisconnectException(netAgent_, new ClientMessageId(SQLState.NET_PREMATURE_EOS_DISCONNECT), new Integer(parameterIndex))); return; } else { pos += bytesRead; leftToRead -= bytesRead; } } while (leftToRead > 0); try { if (in.read() != -1) { netAgent_.accumulateReadException(new SqlException( netAgent_.logWriter_, new ClientMessageId(SQLState.NET_INPUTSTREAM_LENGTH_TOO_SMALL), new Integer(parameterIndex))); } } catch (java.io.IOException e) { netAgent_.accumulateReadException(new SqlException( netAgent_.logWriter_, new ClientMessageId( SQLState.NET_IOEXCEPTION_ON_STREAMLEN_VERIFICATION), new Integer(parameterIndex), e.getMessage(), e)); } byte[] newClearedBytes = new byte[clearedBytes.length + lengthAndCodepoint.length]; System.arraycopy(lengthAndCodepoint, 0, newClearedBytes, 0, lengthAndCodepoint.length); System.arraycopy(clearedBytes, 0, newClearedBytes, lengthAndCodepoint.length, clearedBytes.length); byte[] encryptedBytes; encryptedBytes = netAgent_.netConnection_.getEncryptionManager(). encryptData(newClearedBytes, NetConfiguration.SECMEC_EUSRIDPWD, netAgent_.netConnection_.getTargetPublicKey(), netAgent_.netConnection_.getTargetPublicKey()); int encryptedBytesLength = encryptedBytes.length; int sendingLength = bytes_.length - offset_; if (encryptedBytesLength > (bytes_.length - offset_)) { System.arraycopy(encryptedBytes, 0, bytes_, offset_, (bytes_.length - offset_)); offset_ = 32767; try { sendBytes(netAgent_.getOutputStream()); } catch (java.io.IOException ioe) { netAgent_.throwCommunicationsFailure(ioe); } } else { System.arraycopy(encryptedBytes, 0, bytes_, offset_, encryptedBytesLength); offset_ = offset_ + encryptedBytes.length; } encryptedBytesLength = encryptedBytesLength - sendingLength; while (encryptedBytesLength > 0) { offset_ = 0; if ((encryptedBytesLength - 32765) > 0) { bytes_[offset_++] = (byte) (0xff); bytes_[offset_++] = (byte) (0xff); System.arraycopy(encryptedBytes, sendingLength, bytes_, offset_, 32765); encryptedBytesLength -= 32765; sendingLength += 32765; offset_ = 32767; try { sendBytes(netAgent_.getOutputStream()); } catch (java.io.IOException ioe) { netAgent_.throwCommunicationsFailure(ioe); } } else { int leftlength = encryptedBytesLength + 2; bytes_[offset_++] = (byte) ((leftlength >>> 8) & 0xff); bytes_[offset_++] = (byte) (leftlength & 0xff); System.arraycopy(encryptedBytes, sendingLength, bytes_, offset_, encryptedBytesLength); offset_ += encryptedBytesLength; dssLengthLocation_ = offset_; encryptedBytesLength = 0; } } } else { buildLengthAndCodePointForLob(codePoint, leftToRead, writeNullByte, extendedLengthByteCount); int bytesRead = 0; int totalBytesRead = 0; do { do { try { bytesRead = in.read(bytes_, offset_, bytesToRead); totalBytesRead += bytesRead; } catch (java.io.IOException e) { padScalarStreamForError(leftToRead, bytesToRead); netAgent_.accumulateReadException(new SqlException( netAgent_.logWriter_, new ClientMessageId(SQLState.NET_IOEXCEPTION_ON_READ), new Integer(parameterIndex), e.getMessage(), e)); return; } if (bytesRead == -1) { padScalarStreamForError(leftToRead, bytesToRead); netAgent_.accumulateReadException(new SqlException(netAgent_.logWriter_, new ClientMessageId(SQLState.NET_PREMATURE_EOS), new Integer(parameterIndex))); return; } else { bytesToRead -= bytesRead; offset_ += bytesRead; leftToRead -= bytesRead; } } while (bytesToRead > 0); bytesToRead = flushScalarStreamSegment(leftToRead, bytesToRead); } while (leftToRead > 0); try { if (in.read() != -1) { netAgent_.accumulateReadException(new SqlException(netAgent_.logWriter_, new ClientMessageId(SQLState.NET_INPUTSTREAM_LENGTH_TOO_SMALL), new Integer(parameterIndex))); } } catch (java.io.IOException e) { netAgent_.accumulateReadException(new SqlException( netAgent_.logWriter_, new ClientMessageId( SQLState.NET_IOEXCEPTION_ON_STREAMLEN_VERIFICATION), new Integer(parameterIndex), e.getMessage(), e)); } } }
}
final void writeScalarStream(boolean chained, boolean chainedWithSameCorrelator, int codePoint, int length, java.io.InputStream in, boolean writeNullByte, int parameterIndex) throws DisconnectException, SqlException { int leftToRead = length; int extendedLengthByteCount = prepScalarStream(chained, chainedWithSameCorrelator, writeNullByte, leftToRead); int bytesToRead; if (writeNullByte) { bytesToRead = Utils.min(leftToRead, DssConstants.MAX_DSS_LEN - 6 - 4 - 1 - extendedLengthByteCount); } else { bytesToRead = Utils.min(leftToRead, DssConstants.MAX_DSS_LEN - 6 - 4 - extendedLengthByteCount); } if (netAgent_.netConnection_.getSecurityMechanism() == NetConfiguration.SECMEC_EUSRIDDTA || netAgent_.netConnection_.getSecurityMechanism() == NetConfiguration.SECMEC_EUSRPWDDTA) { byte[] lengthAndCodepoint; lengthAndCodepoint = buildLengthAndCodePointForEncryptedLob(codePoint, leftToRead, writeNullByte, extendedLengthByteCount); // we need to stream the input, rather than fully materialize it // write the data byte[] clearedBytes = new byte[leftToRead]; int bytesRead = 0; int totalBytesRead = 0; int pos = 0; do { try { bytesRead = in.read(clearedBytes, pos, leftToRead); totalBytesRead += bytesRead; } catch (java.io.IOException e) { padScalarStreamForError(leftToRead, bytesToRead); // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. netAgent_.accumulateReadException(new SqlException(netAgent_.logWriter_, new ClientMessageId(SQLState.NET_IOEXCEPTION_ON_READ), new Integer(parameterIndex), e.getMessage(), e)); return; } if (bytesRead == -1) { //padScalarStreamForError(leftToRead, bytesToRead); // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. /*throw new SqlException(netAgent_.logWriter_, "End of Stream prematurely reached while reading InputStream, parameter #" + parameterIndex + ". Remaining data has been padded with 0x0.");*/ //is it OK to do a chain break Exception here. It's not good to //pad it with 0 and encrypt and send it to the server because it takes too much time //can't just throw a SQLException either because some of the data PRPSQLSTT etc have already //been sent to the server, and server is waiting for EXTDTA, server hangs for this. netAgent_.accumulateChainBreakingReadExceptionAndThrow( new DisconnectException(netAgent_, new ClientMessageId(SQLState.NET_PREMATURE_EOS_DISCONNECT), new Integer(parameterIndex))); return; /*netAgent_.accumulateReadException( new SqlException(netAgent_.logWriter_, "End of Stream prematurely reached while reading InputStream, parameter #" + parameterIndex + ". Remaining data has been padded with 0x0.")); return;*/ } else { pos += bytesRead; //offset_ += bytesRead; //comment this out for data stream encryption. leftToRead -= bytesRead; } } while (leftToRead > 0); // check to make sure that the specified length wasn't too small try { if (in.read() != -1) { // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. netAgent_.accumulateReadException(new SqlException( netAgent_.logWriter_, new ClientMessageId(SQLState.NET_INPUTSTREAM_LENGTH_TOO_SMALL), new Integer(parameterIndex))); } } catch (java.io.IOException e) { netAgent_.accumulateReadException(new SqlException( netAgent_.logWriter_, new ClientMessageId( SQLState.NET_IOEXCEPTION_ON_STREAMLEN_VERIFICATION), new Integer(parameterIndex), e.getMessage(), e)); } byte[] newClearedBytes = new byte[clearedBytes.length + lengthAndCodepoint.length]; System.arraycopy(lengthAndCodepoint, 0, newClearedBytes, 0, lengthAndCodepoint.length); System.arraycopy(clearedBytes, 0, newClearedBytes, lengthAndCodepoint.length, clearedBytes.length); //it's wrong here, need to add in the real length after the codepoing 146c byte[] encryptedBytes; encryptedBytes = netAgent_.netConnection_.getEncryptionManager(). encryptData(newClearedBytes, NetConfiguration.SECMEC_EUSRIDPWD, netAgent_.netConnection_.getTargetPublicKey(), netAgent_.netConnection_.getTargetPublicKey()); int encryptedBytesLength = encryptedBytes.length; int sendingLength = bytes_.length - offset_; if (encryptedBytesLength > (bytes_.length - offset_)) { System.arraycopy(encryptedBytes, 0, bytes_, offset_, (bytes_.length - offset_)); offset_ = 32767; try { sendBytes(netAgent_.getOutputStream()); } catch (java.io.IOException ioe) { netAgent_.throwCommunicationsFailure(ioe); } } else { System.arraycopy(encryptedBytes, 0, bytes_, offset_, encryptedBytesLength); offset_ = offset_ + encryptedBytes.length; } encryptedBytesLength = encryptedBytesLength - sendingLength; while (encryptedBytesLength > 0) { //dssLengthLocation_ = offset_; offset_ = 0; if ((encryptedBytesLength - 32765) > 0) { bytes_[offset_++] = (byte) (0xff); bytes_[offset_++] = (byte) (0xff); System.arraycopy(encryptedBytes, sendingLength, bytes_, offset_, 32765); encryptedBytesLength -= 32765; sendingLength += 32765; offset_ = 32767; try { sendBytes(netAgent_.getOutputStream()); } catch (java.io.IOException ioe) { netAgent_.throwCommunicationsFailure(ioe); } } else { int leftlength = encryptedBytesLength + 2; bytes_[offset_++] = (byte) ((leftlength >>> 8) & 0xff); bytes_[offset_++] = (byte) (leftlength & 0xff); System.arraycopy(encryptedBytes, sendingLength, bytes_, offset_, encryptedBytesLength); offset_ += encryptedBytesLength; dssLengthLocation_ = offset_; encryptedBytesLength = 0; } } } else //if not data strteam encryption { buildLengthAndCodePointForLob(codePoint, leftToRead, writeNullByte, extendedLengthByteCount); int bytesRead = 0; int totalBytesRead = 0; do { do { try { bytesRead = in.read(bytes_, offset_, bytesToRead); totalBytesRead += bytesRead; } catch (java.io.IOException e) { padScalarStreamForError(leftToRead, bytesToRead); // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. netAgent_.accumulateReadException(new SqlException( netAgent_.logWriter_, new ClientMessageId(SQLState.NET_IOEXCEPTION_ON_READ), new Integer(parameterIndex), e.getMessage(), e)); return; } if (bytesRead == -1) { padScalarStreamForError(leftToRead, bytesToRead); // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. netAgent_.accumulateReadException(new SqlException(netAgent_.logWriter_, new ClientMessageId(SQLState.NET_PREMATURE_EOS), new Integer(parameterIndex))); return; } else { bytesToRead -= bytesRead; offset_ += bytesRead; leftToRead -= bytesRead; } } while (bytesToRead > 0); bytesToRead = flushScalarStreamSegment(leftToRead, bytesToRead); } while (leftToRead > 0); // check to make sure that the specified length wasn't too small try { if (in.read() != -1) { // set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable. netAgent_.accumulateReadException(new SqlException(netAgent_.logWriter_, new ClientMessageId(SQLState.NET_INPUTSTREAM_LENGTH_TOO_SMALL), new Integer(parameterIndex))); } } catch (java.io.IOException e) { netAgent_.accumulateReadException(new SqlException( netAgent_.logWriter_, new ClientMessageId( SQLState.NET_IOEXCEPTION_ON_STREAMLEN_VERIFICATION), new Integer(parameterIndex), e.getMessage(), e)); } } }
spsCompSchemaId = def.getUUID(); } if (SanityManager.DEBUG) { SanityManager.ASSERT(spsCompSchemaId != null, "spsCompSchemaId is null");
if (def != null) spsCompSchemaId = def.getUUID();
public void executeConstantAction(Activation activation) throws StandardException { SPSDescriptor whenspsd = null; SPSDescriptor actionspsd; LanguageConnectionContext lcc = activation.getLanguageConnectionContext(); DataDictionary dd = lcc.getDataDictionary(); DependencyManager dm = dd.getDependencyManager(); TransactionController tc = lcc.getTransactionExecute(); /* ** Indicate that we are about to modify the data dictionary. ** ** We tell the data dictionary we're done writing at the end of ** the transaction. */ dd.startWriting(lcc); SchemaDescriptor triggerSd = getSchemaDescriptorForCreate(dd, activation, triggerSchemaName); if (spsCompSchemaId == null) { SchemaDescriptor def = lcc.getDefaultSchema(); if (def.getUUID() == null) { // Descriptor for default schema is stale, // look it up in the dictionary def = dd.getSchemaDescriptor(def.getDescriptorName(), tc, false); } spsCompSchemaId = def.getUUID(); } if (SanityManager.DEBUG) { SanityManager.ASSERT(spsCompSchemaId != null, "spsCompSchemaId is null"); } String tabName; if (triggerTable != null) { triggerTableId = triggerTable.getUUID(); tabName = triggerTable.getName(); } else tabName = "with UUID " + triggerTableId; /* We need to get table descriptor again. We simply can't trust the * one we got at compile time, the lock on system table was released * when compile was done, and the table might well have been dropped. */ triggerTable = dd.getTableDescriptor(triggerTableId); if (triggerTable == null) { throw StandardException.newException( SQLState.LANG_TABLE_NOT_FOUND_DURING_EXECUTION, tabName); } /* Lock the table for DDL. Otherwise during our execution, the table * might be changed, even dropped. Beetle 4269 */ lockTableForDDL(tc, triggerTable.getHeapConglomerateId(), true); /* get triggerTable again for correctness, in case it's changed before * the lock is aquired */ triggerTable = dd.getTableDescriptor(triggerTableId); if (triggerTable == null) { throw StandardException.newException( SQLState.LANG_TABLE_NOT_FOUND_DURING_EXECUTION, tabName); } /* ** Send an invalidate on the table from which ** the triggering event emanates. This it ** to make sure that DML statements on this table ** will be recompiled. Do this before we create ** our trigger spses lest we invalidate them just ** after creating them. */ dm.invalidateFor(triggerTable, DependencyManager.CREATE_TRIGGER, lcc); /* ** Lets get our trigger id up front, we'll use it when ** we create our spses. */ UUID tmpTriggerId = dd.getUUIDFactory().createUUID(); actionSPSId = (actionSPSId == null) ? dd.getUUIDFactory().createUUID() : actionSPSId; DataDescriptorGenerator ddg = dd.getDataDescriptorGenerator(); /* ** Create the trigger descriptor first so the trigger action ** compilation can pick up the relevant trigger especially in ** the case of self triggering. */ TriggerDescriptor triggerd = ddg.newTriggerDescriptor( triggerSd, tmpTriggerId, triggerName, eventMask, isBefore, isRow, isEnabled, triggerTable, whenspsd == null ? null : whenspsd.getUUID(), actionSPSId, creationTimestamp == null ? new Timestamp(System.currentTimeMillis()) : creationTimestamp, referencedCols, originalActionText, referencingOld, referencingNew, oldReferencingName, newReferencingName); dd.addDescriptor(triggerd, triggerSd, DataDictionary.SYSTRIGGERS_CATALOG_NUM, false, tc); /* ** If we have a WHEN action we create it now. */ if (whenText != null) { whenspsd = createSPS(lcc, ddg, dd, tc, tmpTriggerId, triggerSd, whenSPSId, spsCompSchemaId, whenText, true, triggerTable); } /* ** Create the trigger action */ actionspsd = createSPS(lcc, ddg, dd, tc, tmpTriggerId, triggerSd, actionSPSId, spsCompSchemaId, actionText, false, triggerTable); /* ** Make underlying spses dependent on the trigger. */ if (whenspsd != null) { dm.addDependency(triggerd, whenspsd, lcc.getContextManager()); } dm.addDependency(triggerd, actionspsd, lcc.getContextManager()); dm.addDependency(triggerd, triggerTable, lcc.getContextManager()); dm.addDependency(actionspsd, triggerTable, lcc.getContextManager()); //store trigger's dependency on various privileges in the dependeny system storeViewTriggerDependenciesOnPrivileges(activation, triggerd); }
Object list = threadContextList.get();
ThreadLocal tcl = threadContextList; if (tcl == null) { return false; } Object list = tcl.get();
private boolean addToThreadList(Thread me, ContextManager associateCM) { Object list = threadContextList.get(); if (associateCM == list) return true; if (list == null) { threadContextList.set(associateCM); return true; } java.util.Stack stack; if (list instanceof ContextManager) { ContextManager threadsCM = (ContextManager) list; if (me == null) me = Thread.currentThread(); if (threadsCM.activeThread != me) { threadContextList.set(associateCM); return true; } stack = new java.util.Stack(); threadContextList.set(stack); for (int i = 0; i < threadsCM.activeCount; i++) { stack.push(threadsCM); } threadsCM.activeCount = -1; } else { stack = (java.util.Stack) list; } stack.push(associateCM); associateCM.activeCount = -1; if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON("memoryLeakTrace")) { if (stack.size() > 10) System.out.println("memoryLeakTrace:ContextService:threadLocal " + stack.size()); } } return false; }
threadContextList.set(associateCM);
tcl.set(associateCM);
private boolean addToThreadList(Thread me, ContextManager associateCM) { Object list = threadContextList.get(); if (associateCM == list) return true; if (list == null) { threadContextList.set(associateCM); return true; } java.util.Stack stack; if (list instanceof ContextManager) { ContextManager threadsCM = (ContextManager) list; if (me == null) me = Thread.currentThread(); if (threadsCM.activeThread != me) { threadContextList.set(associateCM); return true; } stack = new java.util.Stack(); threadContextList.set(stack); for (int i = 0; i < threadsCM.activeCount; i++) { stack.push(threadsCM); } threadsCM.activeCount = -1; } else { stack = (java.util.Stack) list; } stack.push(associateCM); associateCM.activeCount = -1; if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON("memoryLeakTrace")) { if (stack.size() > 10) System.out.println("memoryLeakTrace:ContextService:threadLocal " + stack.size()); } } return false; }
threadContextList.set(stack);
tcl.set(stack);
private boolean addToThreadList(Thread me, ContextManager associateCM) { Object list = threadContextList.get(); if (associateCM == list) return true; if (list == null) { threadContextList.set(associateCM); return true; } java.util.Stack stack; if (list instanceof ContextManager) { ContextManager threadsCM = (ContextManager) list; if (me == null) me = Thread.currentThread(); if (threadsCM.activeThread != me) { threadContextList.set(associateCM); return true; } stack = new java.util.Stack(); threadContextList.set(stack); for (int i = 0; i < threadsCM.activeCount; i++) { stack.push(threadsCM); } threadsCM.activeCount = -1; } else { stack = (java.util.Stack) list; } stack.push(associateCM); associateCM.activeCount = -1; if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON("memoryLeakTrace")) { if (stack.size() > 10) System.out.println("memoryLeakTrace:ContextService:threadLocal " + stack.size()); } } return false; }
Object list = threadContextList.get();
ThreadLocal tcl = threadContextList; if (tcl == null) { return null; } Object list = tcl.get();
public ContextManager getCurrentContextManager() { Thread me = Thread.currentThread(); Object list = threadContextList.get(); if (list instanceof ContextManager) { ContextManager cm = (ContextManager) list; if (cm.activeThread == me) return cm; return null; } if (list == null) return null; java.util.Stack stack = (java.util.Stack) list; return (ContextManager) (stack.peek()); // if (list == null) // return null; /* Thread me = Thread.currentThread(); synchronized (this) { for (Iterator i = allContexts.iterator(); i.hasNext(); ) { ContextManager cm = (ContextManager) i.next(); if (cm.activeThread == me) return cm; } } //OLDreturn (ContextManager) get(me); return null;*/ }
if (threadContextList.get() != cm) SanityManager.THROWASSERT("resetCurrentContextManager - invalid thread local " + Thread.currentThread() + " - object " + threadContextList.get());
if (tcl.get() != cm) SanityManager.THROWASSERT("resetCurrentContextManager - invalid thread local " + Thread.currentThread() + " - object " + tcl.get());
public void resetCurrentContextManager(ContextManager cm) { if (SanityManager.DEBUG) { if (Thread.currentThread() != cm.activeThread) { SanityManager.THROWASSERT("resetCurrentContextManager - mismatch threads - current" + Thread.currentThread() + " - cm's " + cm.activeThread); } if (getCurrentContextManager() != cm) { SanityManager.THROWASSERT("resetCurrentContextManager - mismatch contexts - " + Thread.currentThread()); } if (cm.activeCount < -1) { SanityManager.THROWASSERT("resetCurrentContextManager - invalid count - current" + Thread.currentThread() + " - count " + cm.activeCount); } if (cm.activeCount == 0) { SanityManager.THROWASSERT("resetCurrentContextManager - invalid count - current" + Thread.currentThread() + " - count " + cm.activeCount); } if (cm.activeCount > 0) { if (threadContextList.get() != cm) SanityManager.THROWASSERT("resetCurrentContextManager - invalid thread local " + Thread.currentThread() + " - object " + threadContextList.get()); } } if (cm.activeCount != -1) { if (--cm.activeCount == 0) cm.activeThread = null; return; } java.util.Stack stack = (java.util.Stack) threadContextList.get(); Object oldCM = stack.pop(); ContextManager nextCM = (ContextManager) stack.peek(); boolean seenMultipleCM = false; boolean seenCM = false; for (int i = 0; i < stack.size(); i++) { Object stackCM = stack.elementAt(i); if (stackCM != nextCM) seenMultipleCM = true; if (stackCM == cm) seenCM = true; } if (!seenCM) { cm.activeThread = null; cm.activeCount = 0; } if (!seenMultipleCM) { // all the context managers on the stack // are the same so reduce to a simple count. nextCM.activeCount = stack.size(); threadContextList.set(nextCM); } }
java.util.Stack stack = (java.util.Stack) threadContextList.get();
java.util.Stack stack = (java.util.Stack) tcl.get();
public void resetCurrentContextManager(ContextManager cm) { if (SanityManager.DEBUG) { if (Thread.currentThread() != cm.activeThread) { SanityManager.THROWASSERT("resetCurrentContextManager - mismatch threads - current" + Thread.currentThread() + " - cm's " + cm.activeThread); } if (getCurrentContextManager() != cm) { SanityManager.THROWASSERT("resetCurrentContextManager - mismatch contexts - " + Thread.currentThread()); } if (cm.activeCount < -1) { SanityManager.THROWASSERT("resetCurrentContextManager - invalid count - current" + Thread.currentThread() + " - count " + cm.activeCount); } if (cm.activeCount == 0) { SanityManager.THROWASSERT("resetCurrentContextManager - invalid count - current" + Thread.currentThread() + " - count " + cm.activeCount); } if (cm.activeCount > 0) { if (threadContextList.get() != cm) SanityManager.THROWASSERT("resetCurrentContextManager - invalid thread local " + Thread.currentThread() + " - object " + threadContextList.get()); } } if (cm.activeCount != -1) { if (--cm.activeCount == 0) cm.activeThread = null; return; } java.util.Stack stack = (java.util.Stack) threadContextList.get(); Object oldCM = stack.pop(); ContextManager nextCM = (ContextManager) stack.peek(); boolean seenMultipleCM = false; boolean seenCM = false; for (int i = 0; i < stack.size(); i++) { Object stackCM = stack.elementAt(i); if (stackCM != nextCM) seenMultipleCM = true; if (stackCM == cm) seenCM = true; } if (!seenCM) { cm.activeThread = null; cm.activeCount = 0; } if (!seenMultipleCM) { // all the context managers on the stack // are the same so reduce to a simple count. nextCM.activeCount = stack.size(); threadContextList.set(nextCM); } }
threadContextList.set(nextCM);
tcl.set(nextCM);
public void resetCurrentContextManager(ContextManager cm) { if (SanityManager.DEBUG) { if (Thread.currentThread() != cm.activeThread) { SanityManager.THROWASSERT("resetCurrentContextManager - mismatch threads - current" + Thread.currentThread() + " - cm's " + cm.activeThread); } if (getCurrentContextManager() != cm) { SanityManager.THROWASSERT("resetCurrentContextManager - mismatch contexts - " + Thread.currentThread()); } if (cm.activeCount < -1) { SanityManager.THROWASSERT("resetCurrentContextManager - invalid count - current" + Thread.currentThread() + " - count " + cm.activeCount); } if (cm.activeCount == 0) { SanityManager.THROWASSERT("resetCurrentContextManager - invalid count - current" + Thread.currentThread() + " - count " + cm.activeCount); } if (cm.activeCount > 0) { if (threadContextList.get() != cm) SanityManager.THROWASSERT("resetCurrentContextManager - invalid thread local " + Thread.currentThread() + " - object " + threadContextList.get()); } } if (cm.activeCount != -1) { if (--cm.activeCount == 0) cm.activeThread = null; return; } java.util.Stack stack = (java.util.Stack) threadContextList.get(); Object oldCM = stack.pop(); ContextManager nextCM = (ContextManager) stack.peek(); boolean seenMultipleCM = false; boolean seenCM = false; for (int i = 0; i < stack.size(); i++) { Object stackCM = stack.elementAt(i); if (stackCM != nextCM) seenMultipleCM = true; if (stackCM == cm) seenCM = true; } if (!seenCM) { cm.activeThread = null; cm.activeCount = 0; } if (!seenMultipleCM) { // all the context managers on the stack // are the same so reduce to a simple count. nextCM.activeCount = stack.size(); threadContextList.set(nextCM); } }
consolePropertyMessage("DRDA_Ready.I", Integer.toString(portNumber));
long startTime = System.currentTimeMillis(); consolePropertyMessage("DRDA_Ready.I", new String [] {Integer.toString(portNumber), att_srvclsnm, versionString, CheapDateFormatter.formatDate(startTime)});
public void blockingStart(PrintWriter consoleWriter) throws Exception { startNetworkServer(); setLogWriter(consoleWriter); cloudscapeLogWriter = Monitor.getStream().getPrintWriter(); if (SanityManager.DEBUG && debugOutput) { memCheck.showmem(); mc = new memCheck(200000); mc.start(); } // Open a server socket listener try{ serverSocket = (ServerSocket) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws IOException,UnknownHostException { if (hostAddress == null) hostAddress = InetAddress.getByName(hostArg); // Make a list of valid // InetAddresses for NetworkServerControl // admin commands. buildLocalAddressList(hostAddress); return new ServerSocket(portNumber ,0, hostAddress); } } ); } catch (PrivilegedActionException e) { Exception e1 = e.getException(); if (e1 instanceof IOException) consolePropertyMessage("DRDA_ListenPort.S", new String [] { Integer.toString(portNumber), hostArg}); if (e1 instanceof UnknownHostException) { consolePropertyMessage("DRDA_UnknownHost.S", hostArg); } else throw e1; } catch (Exception e) { // If we find other (unexpected) errors, we ultimately exit--so make // sure we print the error message before doing so (Beetle 5033). throwUnexpectedException(e); } consolePropertyMessage("DRDA_Ready.I", Integer.toString(portNumber)); // We accept clients on a separate thread so we don't run into a problem // blocking on the accept when trying to process a shutdown acceptClients = (Runnable)new ClientThread(this, serverSocket); Thread clientThread = (Thread) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws Exception { return new Thread(acceptClients); } } ); clientThread.start(); // wait until we are told to shutdown or someone sends an InterruptedException synchronized(shutdownSync) { try { shutdownSync.wait(); } catch (InterruptedException e) { shutdown = true; } } // Need to interrupt the memcheck thread if it is sleeping. if (mc != null) mc.interrupt(); //interrupt client thread clientThread.interrupt(); // Close out the sessions synchronized(sessionTable) { for (Enumeration e = sessionTable.elements(); e.hasMoreElements(); ) { Session session = (Session) e.nextElement(); session.close(); } } synchronized (threadList) { //interupt any connection threads still active for (int i = 0; i < threadList.size(); i++) { ((DRDAConnThread)threadList.get(i)).close(); ((DRDAConnThread)threadList.get(i)).interrupt(); } threadList.clear(); } // close the listener socket try{ serverSocket.close(); }catch(IOException e){ consolePropertyMessage("DRDA_ListenerClose.S"); } // Wake up those waiting on sessions, so // they can close down synchronized (runQueue) { runQueue.notifyAll(); } /* // Shutdown Cloudscape try { if (cloudscapeDriver != null) cloudscapeDriver.connect("jdbc:derby:;shutdown=true", (Properties) null); } catch (SQLException sqle) { // If we can't shutdown cloudscape. Perhaps authentication is // set to true or some other reason. We will just print a // message to the console and proceed. if (((EmbedSQLException)sqle).getMessageId() != SQLState.CLOUDSCAPE_SYSTEM_SHUTDOWN) consolePropertyMessage("DRDA_ShutdownWarning.I", sqle.getMessage()); } */ consolePropertyMessage("DRDA_ShutdownSuccess.I"); }
consolePropertyMessage("DRDA_ShutdownSuccess.I");
long shutdownTime = System.currentTimeMillis(); consolePropertyMessage("DRDA_ShutdownSuccess.I", new String [] {att_srvclsnm, versionString, CheapDateFormatter.formatDate(shutdownTime)});
public void blockingStart(PrintWriter consoleWriter) throws Exception { startNetworkServer(); setLogWriter(consoleWriter); cloudscapeLogWriter = Monitor.getStream().getPrintWriter(); if (SanityManager.DEBUG && debugOutput) { memCheck.showmem(); mc = new memCheck(200000); mc.start(); } // Open a server socket listener try{ serverSocket = (ServerSocket) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws IOException,UnknownHostException { if (hostAddress == null) hostAddress = InetAddress.getByName(hostArg); // Make a list of valid // InetAddresses for NetworkServerControl // admin commands. buildLocalAddressList(hostAddress); return new ServerSocket(portNumber ,0, hostAddress); } } ); } catch (PrivilegedActionException e) { Exception e1 = e.getException(); if (e1 instanceof IOException) consolePropertyMessage("DRDA_ListenPort.S", new String [] { Integer.toString(portNumber), hostArg}); if (e1 instanceof UnknownHostException) { consolePropertyMessage("DRDA_UnknownHost.S", hostArg); } else throw e1; } catch (Exception e) { // If we find other (unexpected) errors, we ultimately exit--so make // sure we print the error message before doing so (Beetle 5033). throwUnexpectedException(e); } consolePropertyMessage("DRDA_Ready.I", Integer.toString(portNumber)); // We accept clients on a separate thread so we don't run into a problem // blocking on the accept when trying to process a shutdown acceptClients = (Runnable)new ClientThread(this, serverSocket); Thread clientThread = (Thread) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws Exception { return new Thread(acceptClients); } } ); clientThread.start(); // wait until we are told to shutdown or someone sends an InterruptedException synchronized(shutdownSync) { try { shutdownSync.wait(); } catch (InterruptedException e) { shutdown = true; } } // Need to interrupt the memcheck thread if it is sleeping. if (mc != null) mc.interrupt(); //interrupt client thread clientThread.interrupt(); // Close out the sessions synchronized(sessionTable) { for (Enumeration e = sessionTable.elements(); e.hasMoreElements(); ) { Session session = (Session) e.nextElement(); session.close(); } } synchronized (threadList) { //interupt any connection threads still active for (int i = 0; i < threadList.size(); i++) { ((DRDAConnThread)threadList.get(i)).close(); ((DRDAConnThread)threadList.get(i)).interrupt(); } threadList.clear(); } // close the listener socket try{ serverSocket.close(); }catch(IOException e){ consolePropertyMessage("DRDA_ListenerClose.S"); } // Wake up those waiting on sessions, so // they can close down synchronized (runQueue) { runQueue.notifyAll(); } /* // Shutdown Cloudscape try { if (cloudscapeDriver != null) cloudscapeDriver.connect("jdbc:derby:;shutdown=true", (Properties) null); } catch (SQLException sqle) { // If we can't shutdown cloudscape. Perhaps authentication is // set to true or some other reason. We will just print a // message to the console and proceed. if (((EmbedSQLException)sqle).getMessageId() != SQLState.CLOUDSCAPE_SYSTEM_SHUTDOWN) consolePropertyMessage("DRDA_ShutdownWarning.I", sqle.getMessage()); } */ consolePropertyMessage("DRDA_ShutdownSuccess.I"); }
consolePropertyMessage("DRDA_ShutdownSuccess.I");
long shutdownTime = System.currentTimeMillis(); consolePropertyMessage("DRDA_ShutdownSuccess.I", new String [] {att_srvclsnm, versionString, CheapDateFormatter.formatDate(shutdownTime)});
public void executeWork(String args[]) throws Exception { // For convenience just use NetworkServerControlImpls log writer for user messages logWriter = makePrintWriter(System.out); int command = 0; if (args.length > 0) command = findCommand(args); else { consolePropertyMessage("DRDA_NoArgs.U"); } // if we didn't have a valid command just return - error already generated if (command == COMMAND_UNKNOWN) return; // check that we have the right number of required arguments if (commandArgs.size() != COMMAND_ARGS[command]) consolePropertyMessage("DRDA_InvalidNoArgs.U", COMMANDS[command]); int min; int max; switch (command) { case COMMAND_START: blockingStart(makePrintWriter(System.out)); break; case COMMAND_SHUTDOWN: shutdown(); consolePropertyMessage("DRDA_ShutdownSuccess.I"); break; case COMMAND_TRACE: { boolean on = isOn((String)commandArgs.elementAt(0)); trace(sessionArg, on); consoleTraceMessage(sessionArg, on); break; } case COMMAND_TRACEDIRECTORY: setTraceDirectory((String) commandArgs.elementAt(0)); consolePropertyMessage("DRDA_TraceDirectoryChange.I", traceDirectory); break; case COMMAND_TESTCONNECTION: ping(); consolePropertyMessage("DRDA_ConnectionTested.I", new String [] {hostArg, (new Integer(portNumber)).toString()}); break; case COMMAND_LOGCONNECTIONS: { boolean on = isOn((String)commandArgs.elementAt(0)); logConnections(on); consolePropertyMessage("DRDA_LogConnectionsChange.I", on ? "DRDA_ON.I" : "DRDA_OFF.I"); break; } case COMMAND_SYSINFO: { String info = sysinfo(); consoleMessage(info); break; } case COMMAND_MAXTHREADS: max = 0; try{ max = Integer.parseInt((String)commandArgs.elementAt(0)); }catch(NumberFormatException e){ consolePropertyMessage("DRDA_InvalidValue.U", new String [] {(String)commandArgs.elementAt(0), "maxthreads"}); } if (max < MIN_MAXTHREADS) consolePropertyMessage("DRDA_InvalidValue.U", new String [] {new Integer(max).toString(), "maxthreads"}); netSetMaxThreads(max); break; case COMMAND_RUNTIME_INFO: String reply = runtimeInfo(); consoleMessage(reply); break; case COMMAND_TIMESLICE: int timeslice = 0; String timeSliceArg = (String)commandArgs.elementAt(0); try{ timeslice = Integer.parseInt(timeSliceArg); }catch(NumberFormatException e){ consolePropertyMessage("DRDA_InvalidValue.U", new String [] {(String)commandArgs.elementAt(0), "timeslice"}); } if (timeslice < MIN_TIMESLICE) consolePropertyMessage("DRDA_InvalidValue.U", new String [] {new Integer(timeslice).toString(), "timeslice"}); netSetTimeSlice(timeslice); break; default: //shouldn't get here if (SanityManager.DEBUG) SanityManager.THROWASSERT("Invalid command in switch:"+ command); } }
versionString = myPVH.getVersionBuildString(false);
private void init() throws Exception { // adjust the application in accordance with derby.ui.locale and derby.ui.codeset langUtil = new LocalizedResource(null,null,DRDA_PROP_MESSAGES); serverInstance = this; //set Server attributes to be used in EXCSAT ProductVersionHolder myPVH = getNetProductVersionHolder(); att_extnam = ATT_SRVNAM + " " + java.lang.Thread.currentThread().getName(); att_srvclsnm = myPVH.getProductName(); String majorStr = String.valueOf(myPVH.getMajorVersion()); String minorStr = String.valueOf(myPVH.getMinorVersion()); // Maintenance version. Server protocol version. // Only changed if client needs to recognize a new server version. String drdaMaintStr = String.valueOf(myPVH.getDrdaMaintVersion()); // PRDID format as JCC expects it: CSSMMmx // MM = major version // mm = minor version // x = drda MaintenanceVersion prdId = DRDAConstants.DERBY_DRDA_SERVER_ID; if (majorStr.length() == 1) prdId += "0"; prdId += majorStr; if (minorStr.length() == 1) prdId += "0"; prdId += minorStr; prdId += drdaMaintStr; att_srvrlslv = prdId + "/" + myPVH.getVersionBuildString(false); // Precompute this to save some cycles prdIdBytes_ = prdId.getBytes(DEFAULT_ENCODING); if (SanityManager.DEBUG) { if (majorStr.length() > 2 || minorStr.length() > 2 || drdaMaintStr.length() > 1) SanityManager.THROWASSERT("version values out of expected range for PRDID"); } buildNumber = myPVH.getBuildNumber(); }
for( Enumeration e = ClassLoader.getSystemResources( "org/apache/derby/modules.properties");
for( Enumeration e = cl.getResources( "org/apache/derby/modules.properties");
protected Vector getDefaultImplementations() { Properties moduleList = new Properties(); boolean firstList = true; try { for( Enumeration e = ClassLoader.getSystemResources( "org/apache/derby/modules.properties"); e.hasMoreElements() ;) { URL modulesPropertiesURL = (URL) e.nextElement(); InputStream is = null; try { is = loadModuleDefinitions( modulesPropertiesURL); if( firstList) { moduleList.load( is); firstList = false; } else { // Check for duplicates Properties otherList = new Properties(); otherList.load( is); for( Enumeration newKeys = otherList.keys(); newKeys.hasMoreElements() ;) { String key = (String) newKeys.nextElement(); if( moduleList.contains( key)) // RESOLVE how do we localize messages before we have finished initialization? report( "Ignored duplicate property " + key + " in " + modulesPropertiesURL.toString()); else moduleList.setProperty( key, otherList.getProperty( key)); } } } catch (IOException ioe) { if (SanityManager.DEBUG) report("Can't load implementation list " + modulesPropertiesURL.toString() + ": " + ioe.toString()); } finally { try { if( is != null) is.close(); } catch (IOException ioe2) { } } } } catch (IOException ioe) { if (SanityManager.DEBUG) report("Can't load implementation list: " + ioe.toString()); } if( firstList) { if (SanityManager.DEBUG) report("Default implementation list not found"); return null; } return getImplementations(moduleList, true); } // end of getDefaultImplementations
RoutinePermsDescriptor key = new RoutinePermsDescriptor( this, authorizationId, (String) null);
RoutinePermsDescriptor key = new RoutinePermsDescriptor( this, authorizationId, (String) null, routineUUID);
public RoutinePermsDescriptor getRoutinePermissions( UUID routineUUID, String authorizationId) throws StandardException { RoutinePermsDescriptor key = new RoutinePermsDescriptor( this, authorizationId, (String) null); return (RoutinePermsDescriptor) getPermissions( key); } // end of getRoutinePermissions
networkServerController.start(null);
networkServerController.start(new PrintWriter(serverOutput));
protected void setUp() throws Exception { TestConfiguration config = TestConfiguration.getCurrent(); if (!config.getJDBCClient().isEmbedded()) { BaseTestCase.println("Starting network server:"); networkServerController = new NetworkServerControl (InetAddress.getByName(config.getHostName()), config.getPort()); networkServerController.start(null); final long startTime = System.currentTimeMillis(); while (true) { Thread.sleep(SLEEP_TIME); try { networkServerController.ping(); break; } catch (Exception e) { if (System.currentTimeMillis() - startTime > WAIT_TIME) { e.printStackTrace(); fail("Timed out waiting for network server to start"); } } } } }
serverOutput.close();
protected void tearDown() throws Exception { if (networkServerController != null) { networkServerController.shutdown(); } }
}
case GET_CONTAINER_NAMES_ACTION: { StorageFile seg = storageFactory.newStorageFile( "seg0"); if (seg.exists() && seg.isDirectory()) { return seg.list(); } return null; } }
public final Object run() throws Exception { switch( actionCode) { case BOOT_ACTION: readOnly = storageFactory.isReadOnlyDatabase(); supportsRandomAccess = storageFactory.supportsRandomAccess(); return null; case GET_TEMP_DIRECTORY_ACTION: return storageFactory.getTempDir(); case REMOVE_TEMP_DIRECTORY_ACTION: StorageFile tempDir = storageFactory.getTempDir(); if( tempDir != null) tempDir.deleteAll(); return null; case GET_CONTAINER_PATH_ACTION: case GET_ALTERNATE_CONTAINER_PATH_ACTION: { StringBuffer sb = new StringBuffer("seg"); sb.append(containerId.getSegmentId()); sb.append(storageFactory.getSeparator()); if( actionCode == GET_CONTAINER_PATH_ACTION) { sb.append(stub ? 'd' : 'c'); sb.append(Long.toHexString(containerId.getContainerId())); sb.append(".dat"); } else { sb.append(stub ? 'D' : 'C'); sb.append(containerId.getContainerId()); sb.append(".DAT"); } return storageFactory.newStorageFile( sb.toString()); } // end of cases GET_CONTAINER_PATH_ACTION & GET_ALTERNATE_CONTAINER_PATH_ACTION case REMOVE_STUBS_ACTION: { char separator = storageFactory.getSeparator(); StorageFile root = storageFactory.newStorageFile( null); // get all the non-temporary data segment, they start with "seg" String[] segs = root.list(); for (int s = segs.length-1; s >= 0; s--) { if (segs[s].startsWith("seg")) { StorageFile seg = storageFactory.newStorageFile(root, segs[s]); if (seg.exists() && seg.isDirectory()) { String[] files = seg.list(); for (int f = files.length-1; f >= 0 ; f--) { // stub if (files[f].startsWith("D") || // below is for track 3444 files[f].startsWith("d")) { StorageFile stub = storageFactory.newStorageFile(root, segs[s] + separator + files[f]); stub.delete(); } } } } } break; } // end of case REMOVE_STUBS_ACTION case FIND_MAX_CONTAINER_ID_ACTION: { long maxnum = 1; StorageFile seg = storageFactory.newStorageFile( "seg0"); if (seg.exists() && seg.isDirectory()) { // create an array with names of all files in seg0 String[] files = seg.list(); // loop through array looking for maximum containerid. for (int f = files.length-1; f >= 0 ; f--) { try { long fileNumber = Long.parseLong( files[f].substring(1, (files[f].length() -4)), 16); if (fileNumber > maxnum) maxnum = fileNumber; } catch (Throwable t) { // ignore errors from parse, it just means that someone put // a file in seg0 that we didn't expect. Continue with the // next one. } } } return ReuseFactory.getLong( maxnum); } // end of case FIND_MAX_CONTAINER_ID_ACTION case DELETE_IF_EXISTS_ACTION: { boolean ret = actionFile.exists() && actionFile.delete(); actionFile = null; return ret ? this : null; } // end of case DELETE_IF_EXISTS_ACTION case GET_PATH_ACTION: { String path = actionFile.getPath(); actionFile = null; return path; } // end of case GET_PATH_ACTION case POST_RECOVERY_REMOVE_ACTION: for (Enumeration e = postRecoveryRemovedFiles.elements(); e.hasMoreElements(); ) { StorageFile f = (StorageFile) e.nextElement(); if (f.exists()) f.delete(); } return null; case GET_LOCK_ON_DB_ACTION: privGetJBMSLockOnDB(); return null; case RELEASE_LOCK_ON_DB_ACTION: privReleaseJBMSLockOnDB(); return null; case RESTORE_DATA_DIRECTORY_ACTION: privRestoreDataDirectory(); return null; } return null; } // end of run
con = DriverManager.getConnection( CONFIG.getJDBCUrl() + ";create=true", CONFIG.getUserName(), CONFIG.getUserPassword());
if (!CONFIG.isSingleLegXA()) { con = DriverManager.getConnection( CONFIG.getJDBCUrl() + ";create=true", CONFIG.getUserName(), CONFIG.getUserPassword()); } else { con = getXADataSource().getXAConnection (CONFIG.getUserName(), CONFIG.getUserPassword()).getConnection(); }
public static Connection getConnection() throws SQLException { Connection con = null; JDBCClient client = CONFIG.getJDBCClient(); if (HAVE_DRIVER) { loadJDBCDriver(client.getJDBCDriverName()); con = DriverManager.getConnection( CONFIG.getJDBCUrl() + ";create=true", CONFIG.getUserName(), CONFIG.getUserPassword()); } else { //Use DataSource for JSR169 con = getDataSource().getConnection(); } return con; }
clientMessageIds.add(SQLState.CANNOT_CLOSE_ACTIVE_XA_CONNECTION); clientMessageIds.add(SQLState.XACT_SAVEPOINT_RELEASE_ROLLBACK_FAIL);
static void initClientMessageIds() { // Add message ids that don't start with XJ here clientMessageIds.add(SQLState.NO_CURRENT_CONNECTION); clientMessageIds.add(SQLState.NOT_IMPLEMENTED); }
if (costEstimate == null) { costEstimate = childResult.getCostEstimate(); }
costEstimate = childResult.getFinalCostEstimate();
private void generateMinion(ExpressionClassBuilder acb, MethodBuilder mb, boolean genChildResultSet) throws StandardException { MethodBuilder userExprFun; ValueNode searchClause = null; ValueNode equijoinClause = null; /* The tableProperties, if non-null, must be correct to get this far. * We simply call verifyProperties to set initialCapacity and * loadFactor. */ verifyProperties(getDataDictionary()); // build up the tree. /* Put the predicates back into the tree */ if (searchPredicateList != null) { // Remove any redundant predicates before restoring searchPredicateList.removeRedundantPredicates(); searchClause = searchPredicateList.restorePredicates(); /* Allow the searchPredicateList to get garbage collected now * that we're done with it. */ searchPredicateList = null; } // for the single table predicates, we generate an exprFun // that evaluates the expression of the clause // against the current row of the child's result. // if the restriction is empty, simply pass null // to optimize for run time performance. // generate the function and initializer: // Note: Boolean lets us return nulls (boolean would not) // private Boolean exprN() // { // return <<searchClause.generate(ps)>>; // } // static Method exprN = method pointer to exprN; // Map the result columns to the source columns int[] mapArray = resultColumns.mapSourceColumns(); int mapArrayItem = acb.addItem(new ReferencedColumnsDescriptorImpl(mapArray)); // Save the hash key columns FormatableIntHolder[] fihArray = FormatableIntHolder.getFormatableIntHolders(hashKeyColumns()); FormatableArrayHolder hashKeyHolder = new FormatableArrayHolder(fihArray); int hashKeyItem = acb.addItem(hashKeyHolder); /* Generate the HashTableResultSet: * arg1: childExpress - Expression for childResultSet * arg2: searchExpress - Expression for single table predicates * arg3 : equijoinExpress - Qualifier[] for hash table look up * arg4: projectExpress - Expression for projection, if any * arg5: resultSetNumber * arg6: mapArrayItem - item # for mapping of source columns * arg7: reuseResult - whether or not the result row can be reused * (ie, will it always be the same) * arg8: hashKeyItem - item # for int[] of hash column #s * arg9: removeDuplicates - don't remove duplicates in hash table (for now) * arg10: maxInMemoryRowCount - max row size for in-memory hash table * arg11: initialCapacity - initialCapacity for java.util.Hashtable * arg12 : loadFactor - loadFactor for java.util.Hashtable * arg13: estimated row count * arg14: estimated cost * arg15: close method */ acb.pushGetResultSetFactoryExpression(mb); if (genChildResultSet) childResult.generateResultSet(acb, mb); else childResult.generate((ActivationClassBuilder) acb, mb); /* Get the next ResultSet #, so that we can number this ResultSetNode, its * ResultColumnList and ResultSet. */ assignResultSetNumber(); /* Set the point of attachment in all subqueries attached * to this node. */ if (pSubqueryList != null && pSubqueryList.size() > 0) { pSubqueryList.setPointOfAttachment(resultSetNumber); if (SanityManager.DEBUG) { SanityManager.ASSERT(pSubqueryList.size() == 0, "pSubqueryList.size() expected to be 0"); } } if (rSubqueryList != null && rSubqueryList.size() > 0) { rSubqueryList.setPointOfAttachment(resultSetNumber); if (SanityManager.DEBUG) { SanityManager.ASSERT(rSubqueryList.size() == 0, "rSubqueryList.size() expected to be 0"); } } // Get the cost estimate from the child if we don't have one yet if (costEstimate == null) { costEstimate = childResult.getCostEstimate(); } // if there is no searchClause, we just want to pass null. if (searchClause == null) { mb.pushNull(ClassName.GeneratedMethod); } else { // this sets up the method and the static field. // generates: // DataValueDescriptor userExprFun { } userExprFun = acb.newUserExprFun(); // searchClause knows it is returning its value; /* generates: * return <searchClause.generate(acb)>; * and adds it to userExprFun * NOTE: The explicit cast to DataValueDescriptor is required * since the searchClause may simply be a boolean column or subquery * which returns a boolean. For example: * where booleanColumn */ searchClause.generateExpression(acb, userExprFun); userExprFun.methodReturn(); /* PUSHCOMPILER userSB.newReturnStatement(searchClause.generateExpression(acb, userSB)); */ // we are done modifying userExprFun, complete it. userExprFun.complete(); // searchClause is used in the final result set as an access of the new static // field holding a reference to this new method. // generates: // ActivationClass.userExprFun // which is the static field that "points" to the userExprFun // that evaluates the where clause. acb.pushMethodReference(mb, userExprFun); } /* Generate the qualifiers for the look up into * the hash table. */ joinPredicateList.generateQualifiers(acb, mb, (Optimizable) childResult, false); /* Determine whether or not reflection is needed for the projection. * Reflection is not needed if all of the columns map directly to source * columns. */ if (reflectionNeededForProjection()) { // for the resultColumns, we generate a userExprFun // that creates a new row from expressions against // the current row of the child's result. // (Generate optimization: see if we can simply // return the current row -- we could, but don't, optimize // the function call out and have execution understand // that a null function pointer means take the current row // as-is, with the performance trade-off as discussed above.) /* Generate the Row function for the projection */ resultColumns.generateCore(acb, mb, false); } else { mb.pushNull(ClassName.GeneratedMethod); } mb.push(resultSetNumber); mb.push(mapArrayItem); mb.push(resultColumns.reusableResult()); mb.push(hashKeyItem); mb.push(false); mb.push(-1L); mb.push(initialCapacity); mb.push(loadFactor); mb.push(costEstimate.singleScanRowCount()); mb.push(costEstimate.getEstimatedCost()); closeMethodArgument(acb, mb); mb.callMethod(VMOpcode.INVOKEINTERFACE, (String) null, "getHashTableResultSet", ClassName.NoPutResultSet, 15); }
setNull(parameterIndex, java.sql.Types.CLOB);
setNull(parameterIndex, java.sql.Types.LONGVARCHAR);
public void setAsciiStream(int parameterIndex, java.io.InputStream x, long length) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setAsciiStream", parameterIndex, "<input stream>", new Long(length)); } parameterIndex = checkSetterPreconditions(parameterIndex); parameterMetaData_.clientParamtertype_[parameterIndex - 1] = java.sql.Types.CLOB; if (x == null) { setNull(parameterIndex, java.sql.Types.CLOB); return; } if(length > Integer.MAX_VALUE) { throw new SqlException(agent_.logWriter_, new ClientMessageId(SQLState.CLIENT_LENGTH_OUTSIDE_RANGE_FOR_DATATYPE), new Long(length), new Integer(Integer.MAX_VALUE)).getSQLException(); } setInput(parameterIndex, new Clob(agent_, x, "US-ASCII", (int)length)); } } catch ( SqlException se ) { throw se.getSQLException(); } }
final int paramType = getParameterMetaData().getParameterType(parameterIndex); if( ! PossibleTypes.POSSIBLE_TYPES_IN_SET_GENERIC_SCALAR.checkType( paramType ) ){ PossibleTypes.throw22005Exception(agent_.logWriter_, java.sql.Types.BIGINT, paramType); }
public void setBigDecimal(int parameterIndex, java.math.BigDecimal x) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setBigDecimal", parameterIndex, x); } parameterIndex = checkSetterPreconditions(parameterIndex); parameterMetaData_.clientParamtertype_[parameterIndex - 1] = java.sql.Types.DECIMAL; if (x == null) { setNull(parameterIndex, java.sql.Types.DECIMAL); return; } int registerOutScale = 0; setInput(parameterIndex, x); } } catch ( SqlException se ) { throw se.getSQLException(); } }
final int paramType = getParameterMetaData().getParameterType(parameterIndex); if ( ! PossibleTypes.POSSIBLE_TYPES_IN_SET_BINARYSTREAM.checkType( paramType ) ){ PossibleTypes.throw22005Exception(agent_.logWriter_, java.sql.Types.VARBINARY, paramType ); }
public void setBinaryStream(int parameterIndex, java.io.InputStream x, long length) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setBinaryStream", parameterIndex, "<input stream>", new Long(length)); } if(length > Integer.MAX_VALUE) { throw new SqlException(agent_.logWriter_, new ClientMessageId(SQLState.CLIENT_LENGTH_OUTSIDE_RANGE_FOR_DATATYPE), new Long(length), new Integer(Integer.MAX_VALUE)).getSQLException(); } setBinaryStreamX(parameterIndex, x, (int)length); } } catch ( SqlException se ) { throw se.getSQLException(); } }
checkTypeForSetBlob(getParameterMetaData().getParameterType(parameterIndex), agent_.logWriter_);
public void setBlob(int parameterIndex, java.sql.Blob x) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setBlob", parameterIndex, x); } setBlobX(parameterIndex, x); } } catch ( SqlException se ) { throw se.getSQLException(); } }
final int paramType = getParameterMetaData().getParameterType(parameterIndex); if( ! PossibleTypes.POSSIBLE_TYPES_IN_SET_GENERIC_SCALAR.checkType(paramType) ) { PossibleTypes.throw22005Exception(agent_.logWriter_, java.sql.Types.BOOLEAN, paramType); }
public void setBoolean(int parameterIndex, boolean x) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setBoolean", parameterIndex, x); } parameterIndex = checkSetterPreconditions(parameterIndex); parameterMetaData_.clientParamtertype_[parameterIndex - 1] = java.sql.Types.BIT; setInput(parameterIndex, new Short((short) (x ? 1 : 0))); } } catch ( SqlException se ) { throw se.getSQLException(); } }
final int paramType = getParameterMetaData().getParameterType(parameterIndex); if( ! PossibleTypes.POSSIBLE_TYPES_IN_SET_GENERIC_SCALAR.checkType( paramType ) ){ PossibleTypes.throw22005Exception(agent_.logWriter_, java.sql.Types.TINYINT, paramType); }
public void setByte(int parameterIndex, byte x) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setByte", parameterIndex, x); } parameterIndex = checkSetterPreconditions(parameterIndex); parameterMetaData_.clientParamtertype_[parameterIndex - 1] = java.sql.Types.TINYINT; setInput(parameterIndex, new Short(x)); } } catch ( SqlException se ) { throw se.getSQLException(); } }
final int paramType = getParameterMetaData().getParameterType(parameterIndex); if( ! PossibleTypes.POSSIBLE_TYPES_IN_SET_BYTES.checkType( paramType ) ){ PossibleTypes.throw22005Exception(agent_.logWriter_, java.sql.Types.VARBINARY, paramType ); }
public void setBytes(int parameterIndex, byte[] x) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setBytes", parameterIndex, x); } setBytesX(parameterIndex, x); } } catch ( SqlException se ) { throw se.getSQLException(); } }
setNull(parameterIndex, java.sql.Types.CLOB);
setNull(parameterIndex, java.sql.Types.LONGVARCHAR);
public void setCharacterStream(int parameterIndex, Reader x) throws SQLException { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setCharacterStream", parameterIndex, x); } try { parameterIndex = checkSetterPreconditions(parameterIndex); parameterMetaData_.clientParamtertype_[parameterIndex -1] = java.sql.Types.CLOB; if (x == null) { setNull(parameterIndex, java.sql.Types.CLOB); return; } setInput(parameterIndex, new Clob(agent_, x)); } catch (SqlException se) { throw se.getSQLException(); } } }
checkTypeForSetClob(getParameterMetaData().getParameterType(parameterIndex), agent_.logWriter_);
public void setClob(int parameterIndex, java.sql.Clob x) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setClob", parameterIndex, x); } setClobX(parameterIndex, x); } } catch ( SqlException se ) { throw se.getSQLException(); } }
final int paramType = getParameterMetaData().getParameterType(parameterIndex); if( ! PossibleTypes.POSSIBLE_TYPES_IN_SET_DATE.checkType(paramType) ){ PossibleTypes.throw22005Exception(agent_.logWriter_ , java.sql.Types.DATE, paramType); }
public void setDate(int parameterIndex, java.sql.Date x) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setDate", parameterIndex, x); } checkForClosedStatement(); parameterIndex = checkSetterPreconditions(parameterIndex); parameterMetaData_.clientParamtertype_[parameterIndex - 1] = java.sql.Types.DATE; if (x == null) { setNull(parameterIndex, java.sql.Types.DATE); return; } setInput(parameterIndex, x); } } catch ( SqlException se ) { throw se.getSQLException(); } }
final int paramType = getParameterMetaData().getParameterType(parameterIndex); if( ! PossibleTypes.POSSIBLE_TYPES_IN_SET_GENERIC_SCALAR.checkType(paramType) ){ PossibleTypes.throw22005Exception(agent_.logWriter_, java.sql.Types.DOUBLE, paramType); }
public void setDouble(int parameterIndex, double x) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setDouble", parameterIndex, x); } parameterIndex = checkSetterPreconditions(parameterIndex); parameterMetaData_.clientParamtertype_[parameterIndex - 1] = java.sql.Types.DOUBLE; setInput(parameterIndex, new Double(x)); } } catch ( SqlException se ) { throw se.getSQLException(); } }
final int paramType = getParameterMetaData().getParameterType(parameterIndex); if( ! PossibleTypes.POSSIBLE_TYPES_IN_SET_GENERIC_SCALAR.checkType(paramType) ){ PossibleTypes.throw22005Exception(agent_.logWriter_, java.sql.Types.FLOAT, paramType); }
public void setFloat(int parameterIndex, float x) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setFloat", parameterIndex, x); } parameterIndex = checkSetterPreconditions(parameterIndex); parameterMetaData_.clientParamtertype_[parameterIndex - 1] = java.sql.Types.REAL; setInput(parameterIndex, new Float(x)); } } catch ( SqlException se ) { throw se.getSQLException(); } }
final int paramType = getParameterMetaData().getParameterType(parameterIndex); if( ! PossibleTypes.POSSIBLE_TYPES_IN_SET_GENERIC_SCALAR.checkType(paramType) ){ PossibleTypes.throw22005Exception(agent_.logWriter_, java.sql.Types.INTEGER, paramType); }
public void setInt(int parameterIndex, int x) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setInt", parameterIndex, x); } setIntX(parameterIndex, x); } } catch ( SqlException se ) { throw se.getSQLException(); } }
final int paramType = getParameterMetaData().getParameterType(parameterIndex); if( ! PossibleTypes.POSSIBLE_TYPES_IN_SET_GENERIC_SCALAR.checkType(paramType) ){ PossibleTypes.throw22005Exception(agent_.logWriter_, java.sql.Types.INTEGER, paramType); }
public void setLong(int parameterIndex, long x) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setLong", parameterIndex, x); } parameterIndex = checkSetterPreconditions(parameterIndex); parameterMetaData_.clientParamtertype_[parameterIndex - 1] = java.sql.Types.BIGINT; setInput(parameterIndex, new Long(x)); } } catch ( SqlException se ) { throw se.getSQLException(); } }
final int paramType = getParameterMetaData().getParameterType(parameterIndex) ; if( ! PossibleTypes.getPossibleTypesForNull( paramType ).checkType( jdbcType )){ PossibleTypes.throw22005Exception(agent_.logWriter_, jdbcType, paramType ); }
public void setNull(int parameterIndex, int jdbcType) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setNull", parameterIndex, jdbcType); } setNullX(parameterIndex, jdbcType); } } catch ( SqlException se ) { throw se.getSQLException(); } }
final int paramType = getParameterMetaData().getParameterType(parameterIndex); if( ! PossibleTypes.POSSIBLE_TYPES_IN_SET_GENERIC_SCALAR.checkType(paramType) ){ PossibleTypes.throw22005Exception(agent_.logWriter_, java.sql.Types.SMALLINT, paramType); }
public void setShort(int parameterIndex, short x) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setShort", parameterIndex, x); } setShortX(parameterIndex, x); } } catch ( SqlException se ) { throw se.getSQLException(); } }
final int paramType = getParameterMetaData().getParameterType(parameterIndex); if( ! PossibleTypes.POSSIBLE_TYPES_IN_SET_STRING.checkType( paramType ) ){ PossibleTypes.throw22005Exception(agent_.logWriter_ , java.sql.Types.VARCHAR, paramType); }
public void setString(int parameterIndex, String x) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setString", parameterIndex, x); } setStringX(parameterIndex, x); } } catch ( SqlException se ) { throw se.getSQLException(); } }
final int paramType = getParameterMetaData().getParameterType(parameterIndex); if( ! PossibleTypes.POSSIBLE_TYPES_IN_SET_TIME.checkType( paramType ) ){ PossibleTypes.throw22005Exception( agent_.logWriter_, java.sql.Types.TIME, paramType ); }
public void setTime(int parameterIndex, java.sql.Time x) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setTime", parameterIndex, x); } parameterIndex = checkSetterPreconditions(parameterIndex); parameterMetaData_.clientParamtertype_[parameterIndex - 1] = java.sql.Types.TIME; if (x == null) { setNull(parameterIndex, java.sql.Types.TIME); return; } setInput(parameterIndex, x); } } catch ( SqlException se ) { throw se.getSQLException(); } }
final int paramType = getParameterMetaData().getParameterType(parameterIndex); if( ! PossibleTypes.POSSIBLE_TYPES_IN_SET_TIMESTAMP.checkType( paramType ) ) { PossibleTypes.throw22005Exception(agent_.logWriter_, java.sql.Types.TIMESTAMP, paramType); }
public void setTimestamp(int parameterIndex, java.sql.Timestamp x) throws SQLException { try { synchronized (connection_) { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "setTimestamp", parameterIndex, x); } parameterIndex = checkSetterPreconditions(parameterIndex); parameterMetaData_.clientParamtertype_[parameterIndex - 1] = java.sql.Types.TIMESTAMP; if (x == null) { setNull(parameterIndex, java.sql.Types.TIMESTAMP); return; } setInput(parameterIndex, x); // once the nanosecond field of timestamp is trim to microsecond for DERBY, should we throw a warning //if (getParameterType (parameterIndex) == java.sql.Types.TIMESTAMP && x.getNanos() % 1000 != 0) // accumulateWarning (new SqlWarning (agent_.logWriter_, "DERBY timestamp can only store up to microsecond, conversion from nanosecond to microsecond causes rounding.")); } } catch ( SqlException se ) { throw se.getSQLException(); } }
String text = getBodyText(); return getConnection().createTextMessage(text);
String value = (text != null) ? text : getBodyText(); return getConnection().createTextMessage(value);
protected Message createMessage() throws Exception { String text = getBodyText(); return getConnection().createTextMessage(text); }
rs.relative(0);
private void deleteRandomSampleOfNRecords(final ResultSet rs, final Map rows, final Set deletedRows, final int k) throws SQLException { List sampledKeys = createRandomSample(rows, k); println("Sampled keys:" + sampledKeys); ResultSetMetaData meta = rs.getMetaData(); for (Iterator i = sampledKeys.iterator(); i.hasNext();) { Integer key = (Integer) i.next(); rs.absolute(key.intValue()); if (rs.rowDeleted()) continue; // skip deleting row if already deleted if (positioned) { con.createStatement().executeUpdate ("DELETE FROM T1 WHERE CURRENT OF \"" + cursorName + "\""); rs.relative(0); // If this call is not here, the old values are // returned in rs.getXXX calls } else { rs.deleteRow(); } println("Deleted row " + key); // Update the rows table rows.put(key, getRowString(rs)); // Update the updatedRows set deletedRows.add(key); } }
rs.relative(0);
private void deleteRandomSampleOfNRecords(final ResultSet rs, final Map rows, final Set deletedRows, final int k) throws SQLException { List sampledKeys = createRandomSample(rows, k); println("Sampled keys:" + sampledKeys); ResultSetMetaData meta = rs.getMetaData(); for (Iterator i = sampledKeys.iterator(); i.hasNext();) { Integer key = (Integer) i.next(); rs.absolute(key.intValue()); if (rs.rowDeleted()) continue; // skip deleting row if already deleted if (positioned) { con.createStatement().executeUpdate ("DELETE FROM T1 WHERE CURRENT OF \"" + cursorName + "\""); rs.relative(0); // If this call is not here, the old values are // returned in rs.getXXX calls } else { rs.deleteRow(); } println("Deleted row " + key); // Update the rows table rows.put(key, getRowString(rs)); // Update the updatedRows set deletedRows.add(key); } }
columnList[ SYSCOLPERMS_COLPERMSID - 1] =
columnList[ COLPERMSID_COL_NUM - 1] =
public SystemColumn[] buildColumnList() { if (columnList == null) { columnList = new SystemColumn[ COLUMN_COUNT]; columnList[ SYSCOLPERMS_COLPERMSID - 1] = new SystemColumnImpl( convertIdCase( "COLPERMSID"), SYSCOLPERMS_COLPERMSID, 0, // precision 0, // scale false, // nullability "CHAR", true, 36); columnList[ GRANTEE_COL_NUM - 1] = new SystemColumnImpl( convertIdCase( "GRANTEE"), GRANTEE_COL_NUM, 0, // precision 0, // scale false, // nullability AUTHORIZATION_ID_TYPE, AUTHORIZATION_ID_IS_BUILTIN_TYPE, AUTHORIZATION_ID_LENGTH); columnList[ GRANTOR_COL_NUM - 1] = new SystemColumnImpl( convertIdCase( "GRANTOR"), GRANTOR_COL_NUM, 0, // precision 0, // scale false, // nullability AUTHORIZATION_ID_TYPE, AUTHORIZATION_ID_IS_BUILTIN_TYPE, AUTHORIZATION_ID_LENGTH); columnList[ TABLEID_COL_NUM - 1] = new SystemColumnImpl( convertIdCase( "TABLEID"), TABLEID_COL_NUM, 0, // precision 0, // scale false, // nullability "CHAR", // dataType true, // built-in type 36); columnList[ TYPE_COL_NUM - 1] = new SystemColumnImpl( convertIdCase( "TYPE"), TYPE_COL_NUM, 0, // precision 0, // scale false, // nullability "CHAR", // dataType true, // built-in type 1); columnList[ COLUMNS_COL_NUM - 1] = new SystemColumnImpl( convertIdCase( "COLUMNS"), COLUMNS_COL_NUM, 0, // precision 0, // scale false, // nullability "org.apache.derby.iapi.services.io.FormatableBitSet", // datatype false, // built-in type DataTypeDescriptor.MAXIMUM_WIDTH_UNKNOWN // maxLength ); } return columnList; } // end of buildColumnList
SYSCOLPERMS_COLPERMSID,
COLPERMSID_COL_NUM,
public SystemColumn[] buildColumnList() { if (columnList == null) { columnList = new SystemColumn[ COLUMN_COUNT]; columnList[ SYSCOLPERMS_COLPERMSID - 1] = new SystemColumnImpl( convertIdCase( "COLPERMSID"), SYSCOLPERMS_COLPERMSID, 0, // precision 0, // scale false, // nullability "CHAR", true, 36); columnList[ GRANTEE_COL_NUM - 1] = new SystemColumnImpl( convertIdCase( "GRANTEE"), GRANTEE_COL_NUM, 0, // precision 0, // scale false, // nullability AUTHORIZATION_ID_TYPE, AUTHORIZATION_ID_IS_BUILTIN_TYPE, AUTHORIZATION_ID_LENGTH); columnList[ GRANTOR_COL_NUM - 1] = new SystemColumnImpl( convertIdCase( "GRANTOR"), GRANTOR_COL_NUM, 0, // precision 0, // scale false, // nullability AUTHORIZATION_ID_TYPE, AUTHORIZATION_ID_IS_BUILTIN_TYPE, AUTHORIZATION_ID_LENGTH); columnList[ TABLEID_COL_NUM - 1] = new SystemColumnImpl( convertIdCase( "TABLEID"), TABLEID_COL_NUM, 0, // precision 0, // scale false, // nullability "CHAR", // dataType true, // built-in type 36); columnList[ TYPE_COL_NUM - 1] = new SystemColumnImpl( convertIdCase( "TYPE"), TYPE_COL_NUM, 0, // precision 0, // scale false, // nullability "CHAR", // dataType true, // built-in type 1); columnList[ COLUMNS_COL_NUM - 1] = new SystemColumnImpl( convertIdCase( "COLUMNS"), COLUMNS_COL_NUM, 0, // precision 0, // scale false, // nullability "org.apache.derby.iapi.services.io.FormatableBitSet", // datatype false, // built-in type DataTypeDescriptor.MAXIMUM_WIDTH_UNKNOWN // maxLength ); } return columnList; } // end of buildColumnList
String colPermsUUIDString = row.getColumn( SYSCOLPERMS_COLPERMSID).getString();
String colPermsUUIDString = row.getColumn( COLPERMSID_COL_NUM).getString();
public TupleDescriptor buildDescriptor(ExecRow row, TupleDescriptor parentTuple, DataDictionary dataDictionary) throws StandardException { if( SanityManager.DEBUG) SanityManager.ASSERT( row.nColumns() == COLUMN_COUNT, "Wrong size row passed to SYSCOLPERMSRowFactory.buildDescriptor"); String colPermsUUIDString = row.getColumn( SYSCOLPERMS_COLPERMSID).getString(); UUID colPermsUUID = getUUIDFactory().recreateUUID(colPermsUUIDString); String tableUUIDString = row.getColumn( TABLEID_COL_NUM).getString(); UUID tableUUID = getUUIDFactory().recreateUUID(tableUUIDString); String type = row.getColumn( TYPE_COL_NUM).getString(); FormatableBitSet columns = (FormatableBitSet) row.getColumn( COLUMNS_COL_NUM).getObject(); if( SanityManager.DEBUG) SanityManager.ASSERT( "s".equals( type) || "S".equals( type) || "u".equals( type) || "U".equals( type) || "r".equals( type) || "R".equals( type), "Invalid type passed to SYSCOLPERMSRowFactory.buildDescriptor"); ColPermsDescriptor colPermsDesc = new ColPermsDescriptor( dataDictionary, getAuthorizationID( row, GRANTEE_COL_NUM), getAuthorizationID( row, GRANTOR_COL_NUM), tableUUID, type, columns); colPermsDesc.setUUID(colPermsUUID); return colPermsDesc; } // end of buildDescriptor
case COLPERMSID_INDEX_NUM: row.setColumn(1, getDataValueFactory().getNullChar( (StringDataValue) null)); break;
public ExecIndexRow buildEmptyIndexRow(int indexNumber, RowLocation rowLocation) throws StandardException { ExecIndexRow row = getExecutionFactory().getIndexableRow( indexColumnPositions[indexNumber].length + 1); row.setColumn( row.nColumns(), rowLocation); switch( indexNumber) { case GRANTEE_TABLE_TYPE_GRANTOR_INDEX_NUM: row.setColumn(1, getNullAuthorizationID()); // grantee row.setColumn(2, getDataValueFactory().getNullChar( (StringDataValue) null)); // table UUID row.setColumn(3, getDataValueFactory().getNullChar( (StringDataValue) null)); // type row.setColumn(4, getNullAuthorizationID()); // grantor break; } return row; } // end of buildEmptyIndexRow
case COLPERMSID_INDEX_NUM: row = getExecutionFactory().getIndexableRow( 1); String colPermsUUIDStr = perm.getObjectID().toString(); row.setColumn(1, getDataValueFactory().getCharDataValue( colPermsUUIDStr)); break;
public ExecIndexRow buildIndexKeyRow( int indexNumber, PermissionsDescriptor perm) throws StandardException { ExecIndexRow row = null; switch( indexNumber) { case GRANTEE_TABLE_TYPE_GRANTOR_INDEX_NUM: // RESOLVE We do not support the FOR GRANT OPTION, so column permission rows are unique on the // grantee, table UUID, and type columns. The grantor column will always have the name of the owner of the // table. So the index key, used for searching the index, only has grantee, table UUID, and type columns. // It does not have a grantor column. // // If we support FOR GRANT OPTION then there may be multiple table permissions rows for a // (grantee, tableID, type) combination. We must either handle the multiple rows, which is necessary for // checking permissions, or add a grantor column to the key, which is necessary for granting or revoking // permissions. row = getExecutionFactory().getIndexableRow( 3); row.setColumn(1, getAuthorizationID( perm.getGrantee())); ColPermsDescriptor colPerms = (ColPermsDescriptor) perm; String tableUUIDStr = colPerms.getTableUUID().toString(); row.setColumn(2, getDataValueFactory().getCharDataValue( tableUUIDStr)); row.setColumn(3, getDataValueFactory().getCharDataValue( colPerms.getType())); break; } return row; } // end of buildIndexKeyRow
row.setColumn( SYSCOLPERMS_COLPERMSID, dvf.getCharDataValue(colPermID));
row.setColumn( COLPERMSID_COL_NUM, dvf.getCharDataValue(colPermID));
public ExecRow makeRow(TupleDescriptor td, TupleDescriptor parent) throws StandardException { UUID oid; String colPermID = null; DataValueDescriptor grantee = null; DataValueDescriptor grantor = null; String tableID = null; String type = null; FormatableBitSet columns = null; if( td == null) { grantee = getNullAuthorizationID(); grantor = getNullAuthorizationID(); } else { ColPermsDescriptor cpd = (ColPermsDescriptor) td; oid = cpd.getUUID(); if ( oid == null ) { oid = getUUIDFactory().createUUID(); cpd.setUUID(oid); } colPermID = oid.toString(); grantee = getAuthorizationID( cpd.getGrantee()); grantor = getAuthorizationID( cpd.getGrantor()); tableID = cpd.getTableUUID().toString(); type = cpd.getType(); columns = cpd.getColumns(); } ExecRow row = getExecutionFactory().getValueRow( COLUMN_COUNT); row.setColumn( SYSCOLPERMS_COLPERMSID, dvf.getCharDataValue(colPermID)); row.setColumn( GRANTEE_COL_NUM, grantee); row.setColumn( GRANTOR_COL_NUM, grantor); row.setColumn( TABLEID_COL_NUM, dvf.getCharDataValue( tableID)); row.setColumn( TYPE_COL_NUM, dvf.getCharDataValue( type)); row.setColumn( COLUMNS_COL_NUM, dvf.getDataValue( (Object) columns)); return row; } // end of makeRow
timeLimit = Double.MAX_VALUE;
protected OptimizerImpl(OptimizableList optimizableList, OptimizablePredicateList predicateList, DataDictionary dDictionary, boolean ruleBasedOptimization, boolean noTimeout, boolean useStatistics, int maxMemoryPerTable, JoinStrategy[] joinStrategies, int tableLockThreshold, RequiredRowOrdering requiredRowOrdering, int numTablesInQuery) throws StandardException { if (SanityManager.DEBUG) { SanityManager.ASSERT(optimizableList != null, "optimizableList is not expected to be null"); } outermostCostEstimate = getNewCostEstimate(0.0d, 1.0d, 1.0d); currentCost = getNewCostEstimate(0.0d, 0.0d, 0.0d); currentSortAvoidanceCost = getNewCostEstimate(0.0d, 0.0d, 0.0d); bestCost = getNewCostEstimate(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE); // Verify that any Properties lists for user overrides are valid optimizableList.verifyProperties(dDictionary); this.numTablesInQuery = numTablesInQuery; numOptimizables = optimizableList.size(); proposedJoinOrder = new int[numOptimizables]; if (numTablesInQuery > 6) { permuteState = READY_TO_JUMP; firstLookOrder = new int[numOptimizables]; } else permuteState = NO_JUMP; /* Mark all join positions as unused */ for (int i = 0; i < numOptimizables; i++) proposedJoinOrder[i] = -1; bestJoinOrder = new int[numOptimizables]; joinPosition = -1; this.optimizableList = optimizableList; this.predicateList = predicateList; this.dDictionary = dDictionary; this.ruleBasedOptimization = ruleBasedOptimization; this.noTimeout = noTimeout; this.maxMemoryPerTable = maxMemoryPerTable; this.joinStrategies = joinStrategies; this.tableLockThreshold = tableLockThreshold; this.requiredRowOrdering = requiredRowOrdering; this.useStatistics = useStatistics; /* initialize variables for tracking permutations */ assignedTableMap = new JBitSet(numTablesInQuery); /* ** Make a map of the non-correlated tables, which are the tables ** in the list of Optimizables we're optimizing. An reference ** to a table that is not defined in the list of Optimizables ** is presumed to be correlated. */ nonCorrelatedTableMap = new JBitSet(numTablesInQuery); for (int tabCtr = 0; tabCtr < numOptimizables; tabCtr++) { Optimizable curTable = optimizableList.getOptimizable(tabCtr); nonCorrelatedTableMap.or(curTable.getReferencedTableMap()); } /* Get the time that optimization starts */ timeOptimizationStarted = System.currentTimeMillis(); reloadBestPlan = false; savedJoinOrders = null; }
timeExceeded = (currentTime - timeOptimizationStarted) > bestCost.getEstimatedCost();
timeExceeded = (currentTime - timeOptimizationStarted) > timeLimit;
public boolean getNextPermutation() throws StandardException { /* Don't get any permutations if there is nothing to optimize */ if (numOptimizables < 1) { if (optimizerTrace) { trace(NO_TABLES, 0, 0, 0.0, null); } return false; } /* Make sure that all Optimizables init their access paths. * (They wait until optimization since the access path * references the optimizer.) */ optimizableList.initAccessPaths(this); /* ** Experiments show that optimization time only starts to ** become a problem with seven tables, so only check for ** too much time if there are more than seven tables. ** Also, don't check for too much time if user has specified ** no timeout. */ if ( ( ! timeExceeded ) && (numTablesInQuery > 6) && ( ! noTimeout) ) { /* ** Stop optimizing if the time spent optimizing is greater than ** the current best cost. */ currentTime = System.currentTimeMillis(); timeExceeded = (currentTime - timeOptimizationStarted) > bestCost.getEstimatedCost(); if (optimizerTrace && timeExceeded) { trace(TIME_EXCEEDED, 0, 0, 0.0, null); } } /* ** Pick the next table in the join order, if there is an unused position ** in the join order, and the current plan is less expensive than ** the best plan so far, and the amount of time spent optimizing is ** still less than the cost of the best plan so far, and a best ** cost has been found in the current join position. Otherwise, ** just pick the next table in the current position. */ boolean joinPosAdvanced = false; if ((joinPosition < (numOptimizables - 1)) && ((currentCost.compare(bestCost) < 0) || (currentSortAvoidanceCost.compare(bestCost) < 0)) && ( ! timeExceeded ) ) { /* ** Are we either starting at the first join position (in which ** case joinPosition will be -1), or has a best cost been found ** in the current join position? The latter case might not be ** true if there is no feasible join order. */ if ((joinPosition < 0) || optimizableList.getOptimizable( proposedJoinOrder[joinPosition]). getBestAccessPath().getCostEstimate() != null) { joinPosition++; joinPosAdvanced = true; /* ** When adding a table to the join order, the best row ** row ordering for the outer tables becomes the starting ** point for the row ordering of the current table. */ bestRowOrdering.copy(currentRowOrdering); } } else if (optimizerTrace) { /* ** Not considered short-circuiting if all slots in join ** order are taken. */ if (joinPosition < (numOptimizables - 1)) { trace(SHORT_CIRCUITING, 0, 0, 0.0, null); } } if (permuteState == JUMPING && !joinPosAdvanced && joinPosition >= 0) { //not feeling well in the middle of jump rewindJoinOrder(); //fall permuteState = NO_JUMP; //give up } /* ** The join position becomes < 0 when all the permutations have been ** looked at. */ while (joinPosition >= 0) { int nextOptimizable = 0; if (desiredJoinOrderFound || timeExceeded) { /* ** If the desired join order has been found (which will happen ** if the user specifies a join order), pretend that there are ** no more optimizables at this join position. This will cause ** us to back out of the current join order. ** ** Also, don't look at any more join orders if we have taken ** too much time with this optimization. */ nextOptimizable = numOptimizables; } else if (permuteState == JUMPING) //still jumping { /* We're "jumping" to a join order that puts the optimizables ** with the lowest estimated costs first (insofar as it ** is legal to do so). The "firstLookOrder" array holds the ** ideal join order for position <joinPosition> up thru ** position <numOptimizables-1>. So here, we look at the ** ideal optimizable to place at <joinPosition> and see if ** it's legal; if it is, then we're done. Otherwise, we ** swap it with <numOptimizables-1> and see if that gives us ** a legal join order w.r.t <joinPosition>. If not, then we ** swap it with <numOptimizables-2> and check, and if that ** fails, then we swap it with <numOptimizables-3>, and so ** on. For example, assume we have 6 optimizables whose ** order from least expensive to most expensive is 2, 1, 4, ** 5, 3, 0. Assume also that we've already verified the ** legality of the first two positions--i.e. that joinPosition ** is now "2". That means that "firstLookOrder" currently ** contains the following: ** ** [ pos ] 0 1 2 3 4 5 ** [ opt ] 2 1 4 5 3 0 ** ** Then at this point, we do the following: ** ** -- Check to see if the ideal optimizable "4" is valid ** at its current position (2) ** -- If opt "4" is valid, then we're done; else we ** swap it with the value at position _5_: ** ** [ pos ] 0 1 2 3 4 5 ** [ opt ] 2 1 0 5 3 4 ** ** -- Check to see if optimizable "0" is valid at its ** new position (2). ** -- If opt "0" is valid, then we're done; else we ** put "0" back in its original position and swap ** the ideal optimizer ("4") with the value at ** position _4_: ** ** [ pos ] 0 1 2 3 4 5 ** [ opt ] 2 1 3 5 4 0 ** ** -- Check to see if optimizable "3" is valid at its ** new position (2). ** -- If opt "3" is valid, then we're done; else we ** put "3" back in its original position and swap ** the ideal optimizer ("4") with the value at ** position _3_: ** ** [ pos ] 0 1 2 3 4 5 ** [ opt ] 2 1 5 4 3 0 ** ** -- Check to see if optimizable "5" is valid at its ** new position (2). ** -- If opt "5" is valid, then we're done; else we've ** tried all the available optimizables and none ** of them are legal at position 2. In this case, ** we give up on "JUMPING" and fall back to normal ** join-order processing. */ int idealOptimizable = firstLookOrder[joinPosition]; nextOptimizable = idealOptimizable; int lookPos = numOptimizables; int lastSwappedOpt = -1; Optimizable nextOpt; for (nextOpt = optimizableList.getOptimizable(nextOptimizable); !(nextOpt.legalJoinOrder(assignedTableMap)); nextOpt = optimizableList.getOptimizable(nextOptimizable)) { // Undo last swap, if we had one. if (lastSwappedOpt >= 0) { firstLookOrder[joinPosition] = idealOptimizable; firstLookOrder[lookPos] = lastSwappedOpt; } if (lookPos > joinPosition + 1) { // we still have other possibilities; get the next // one by "swapping" it into the current position. lastSwappedOpt = firstLookOrder[--lookPos]; firstLookOrder[joinPosition] = lastSwappedOpt; firstLookOrder[lookPos] = idealOptimizable; nextOptimizable = lastSwappedOpt; } else { // we went through all of the available optimizables // and none of them were legal in the current position; // so we give up and fall back to normal processing. if (joinPosition > 0) { joinPosition--; rewindJoinOrder(); } permuteState = NO_JUMP; break; } } if (permuteState == NO_JUMP) continue; if (joinPosition == numOptimizables - 1) { // we just set the final position within our // "firstLookOrder" join order; now go ahead // and search for the best join order, starting from // the join order stored in "firstLookOrder". This // is called walking "high" because we're searching // the join orders that are at or "above" (after) the // order found in firstLookOrder. Ex. if we had three // optimizables and firstLookOrder was [1 2 0], then // the "high" would be [1 2 0], [2 0 1] and [2 1 0]; // the "low" would be [0 1 2], [0 2 1], and [1 0 2]. // We walk the "high" first, then fall back and // walk the "low". permuteState = WALK_HIGH; } } else { /* Find the next unused table at this join position */ nextOptimizable = proposedJoinOrder[joinPosition] + 1; for ( ; nextOptimizable < numOptimizables; nextOptimizable++) { boolean found = false; for (int posn = 0; posn < joinPosition; posn++) { /* ** Is this optimizable already somewhere ** in the join order? */ if (proposedJoinOrder[posn] == nextOptimizable) { found = true; break; } } /* Check to make sure that all of the next optimizable's * dependencies have been satisfied. */ if (nextOptimizable < numOptimizables) { Optimizable nextOpt = optimizableList.getOptimizable(nextOptimizable); if (! (nextOpt.legalJoinOrder(assignedTableMap))) { if (optimizerTrace) { trace(SKIPPING_JOIN_ORDER, nextOptimizable, 0, 0.0, null); } /* ** If this is a user specified join order then it is illegal. */ if ( ! optimizableList.optimizeJoinOrder()) { if (optimizerTrace) { trace(ILLEGAL_USER_JOIN_ORDER, 0, 0, 0.0, null); } throw StandardException.newException(SQLState.LANG_ILLEGAL_FORCED_JOIN_ORDER); } continue; } } if (! found) { break; } } } /* ** We are going to try an optimizable at the current join order ** position. Is there one already at that position? */ if (proposedJoinOrder[joinPosition] >= 0) { /* ** We are either going to try another table at the current ** join order position, or we have exhausted all the tables ** at the current join order position. In either case, we ** need to pull the table at the current join order position ** and remove it from the join order. */ Optimizable pullMe = optimizableList.getOptimizable( proposedJoinOrder[joinPosition]); /* ** Subtract the cost estimate of the optimizable being ** removed from the total cost estimate. ** ** The total cost is the sum of all the costs, but the total ** number of rows is the number of rows returned by the ** innermost optimizable. */ double prevRowCount; double prevSingleScanRowCount; int prevPosition = 0; if (joinPosition == 0) { prevRowCount = outermostCostEstimate.rowCount(); prevSingleScanRowCount = outermostCostEstimate.singleScanRowCount(); } else { prevPosition = proposedJoinOrder[joinPosition - 1]; CostEstimate localCE = optimizableList. getOptimizable(prevPosition). getBestAccessPath(). getCostEstimate(); prevRowCount = localCE.rowCount(); prevSingleScanRowCount = localCE.singleScanRowCount(); } /* ** If there is no feasible join order, the cost estimate ** in the best access path may never have been set. ** In this case, do not subtract anything from the ** current cost, since nothing was added to the current ** cost. */ double newCost = currentCost.getEstimatedCost(); double pullCost = 0.0; CostEstimate pullCostEstimate = pullMe.getBestAccessPath().getCostEstimate(); if (pullCostEstimate != null) { pullCost = pullCostEstimate.getEstimatedCost(); newCost -= pullCost; /* ** It's possible for newCost to go negative here due to ** loss of precision. */ if (newCost < 0.0) newCost = 0.0; } /* If we are choosing a new outer table, then * we rest the starting cost to the outermostCost. * (Thus avoiding any problems with floating point * accuracy and going negative.) */ if (joinPosition == 0) { if (outermostCostEstimate != null) { newCost = outermostCostEstimate.getEstimatedCost(); } else { newCost = 0.0; } } currentCost.setCost( newCost, prevRowCount, prevSingleScanRowCount); /* ** Subtract from the sort avoidance cost if there is a ** required row ordering. ** ** NOTE: It is not necessary here to check whether the ** best cost was ever set for the sort avoidance path, ** because it considerSortAvoidancePath() would not be ** set if there cost were not set. */ if (requiredRowOrdering != null) { if (pullMe.considerSortAvoidancePath()) { AccessPath ap = pullMe.getBestSortAvoidancePath(); double prevEstimatedCost = 0.0d; /* ** Subtract the sort avoidance cost estimate of the ** optimizable being removed from the total sort ** avoidance cost estimate. ** ** The total cost is the sum of all the costs, but the ** total number of rows is the number of rows returned ** by the innermost optimizable. */ if (joinPosition == 0) { prevRowCount = outermostCostEstimate.rowCount(); prevSingleScanRowCount = outermostCostEstimate.singleScanRowCount(); /* If we are choosing a new outer table, then * we rest the starting cost to the outermostCost. * (Thus avoiding any problems with floating point * accuracy and going negative.) */ prevEstimatedCost = outermostCostEstimate.getEstimatedCost(); } else { CostEstimate localCE = optimizableList. getOptimizable(prevPosition). getBestSortAvoidancePath(). getCostEstimate(); prevRowCount = localCE.rowCount(); prevSingleScanRowCount = localCE.singleScanRowCount(); prevEstimatedCost = currentSortAvoidanceCost.getEstimatedCost() - ap.getCostEstimate().getEstimatedCost(); } currentSortAvoidanceCost.setCost( prevEstimatedCost, prevRowCount, prevSingleScanRowCount); /* ** Remove the table from the best row ordering. ** It should not be necessary to remove it from ** the current row ordering, because it is ** maintained as we step through the access paths ** for the current Optimizable. */ bestRowOrdering.removeOptimizable( pullMe.getTableNumber()); /* ** When removing a table from the join order, ** the best row ordering for the remaining outer tables ** becomes the starting point for the row ordering of ** the current table. */ bestRowOrdering.copy(currentRowOrdering); } } /* ** Pull the predicates at from the optimizable and put ** them back in the predicate list. ** ** NOTE: This is a little inefficient because it pulls the ** single-table predicates, which are guaranteed to always ** be pushed to the same optimizable. We could make this ** leave the single-table predicates where they are. */ pullMe.pullOptPredicates(predicateList); /* ** When we pull an Optimizable we need to go through and ** load whatever best path we found for that Optimizable ** with respect to _this_ OptimizerImpl. An Optimizable ** can have different "best paths" for different Optimizer ** Impls if there are subqueries beneath it; we need to make ** sure that when we pull it, it's holding the best path as ** as we determined it to be for _us_. ** ** NOTE: We we only reload the best plan if it's necessary ** to do so--i.e. if the best plans aren't already loaded. ** The plans will already be loaded if the last complete ** join order we had was the best one so far, because that ** means we called "rememberAsBest" on every Optimizable ** in the list and, as part of that call, we will run through ** and set trulyTheBestAccessPath for the entire subtree. ** So if we haven't tried any other plans since then, ** we know that every Optimizable (and its subtree) already ** has the correct best plan loaded in its trulyTheBest ** path field. It's good to skip the load in this case ** because 'reloading best plans' involves walking the ** entire subtree of _every_ Optimizable in the list, which ** can be expensive if there are deeply nested subqueries. */ if (reloadBestPlan) pullMe.addOrLoadBestPlanMapping(false, this); /* Mark current join position as unused */ proposedJoinOrder[joinPosition] = -1; } /* Have we exhausted all the optimizables at this join position? */ if (nextOptimizable >= numOptimizables) { /* ** If we're not optimizing the join order, remember the first ** join order. */ if ( ! optimizableList.optimizeJoinOrder()) { // Verify that the user specified a legal join order if ( ! optimizableList.legalJoinOrder(numTablesInQuery)) { if (optimizerTrace) { trace(ILLEGAL_USER_JOIN_ORDER, 0, 0, 0.0, null); } throw StandardException.newException(SQLState.LANG_ILLEGAL_FORCED_JOIN_ORDER); } if (optimizerTrace) { trace(USER_JOIN_ORDER_OPTIMIZED, 0, 0, 0.0, null); } desiredJoinOrderFound = true; } if (permuteState == READY_TO_JUMP && joinPosition > 0 && joinPosition == numOptimizables-1) { permuteState = JUMPING; /* A simple heuristics is that the row count we got indicates a potentially * good join order. We'd like row count to get big as late as possible, so * that less load is carried over. */ double rc[] = new double[numOptimizables]; for (int i = 0; i < numOptimizables; i++) { firstLookOrder[i] = i; CostEstimate ce = optimizableList.getOptimizable(i). getBestAccessPath().getCostEstimate(); if (ce == null) { permuteState = READY_TO_JUMP; //come again? break; } rc[i] = ce.singleScanRowCount(); } if (permuteState == JUMPING) { boolean doIt = false; int temp; for (int i = 0; i < numOptimizables; i++) //simple selection sort { int k = i; for (int j = i+1; j < numOptimizables; j++) if (rc[j] < rc[k]) k = j; if (k != i) { rc[k] = rc[i]; //destroy the bridge temp = firstLookOrder[i]; firstLookOrder[i] = firstLookOrder[k]; firstLookOrder[k] = temp; doIt = true; } } if (doIt) { joinPosition--; rewindJoinOrder(); //jump from ground continue; } else permuteState = NO_JUMP; //never } } /* ** We have exhausted all the optimizables at this level. ** Go back up one level. */ /* Go back up one join position */ joinPosition--; /* Clear the assigned table map for the previous position * NOTE: We need to do this here to for the dependency tracking */ if (joinPosition >= 0) { Optimizable pullMe = optimizableList.getOptimizable( proposedJoinOrder[joinPosition]); /* ** Clear the bits from the table at this join position. ** This depends on them having been set previously. ** NOTE: We need to do this here to for the dependency tracking */ assignedTableMap.xor(pullMe.getReferencedTableMap()); } if (joinPosition < 0 && permuteState == WALK_HIGH) //reached peak { joinPosition = 0; //reset, fall down the hill permuteState = WALK_LOW; } continue; } /* ** We have found another optimizable to try at this join position. */ proposedJoinOrder[joinPosition] = nextOptimizable; if (permuteState == WALK_LOW) { boolean finishedCycle = true; for (int i = 0; i < numOptimizables; i++) { if (proposedJoinOrder[i] < firstLookOrder[i]) { finishedCycle = false; break; } else if (proposedJoinOrder[i] > firstLookOrder[i]) //done break; } if (finishedCycle) { // We just set proposedJoinOrder[joinPosition] above, so // if we're done we need to put it back to -1 to indicate // that it's an empty slot. Then we rewind and pull any // other Optimizables at positions < joinPosition. proposedJoinOrder[joinPosition] = -1; joinPosition--; if (joinPosition >= 0) { rewindJoinOrder(); joinPosition = -1; } permuteState = READY_TO_JUMP; return false; } } /* Re-init (clear out) the cost for the best access path * when placing a table. */ optimizableList.getOptimizable(nextOptimizable). getBestAccessPath().setCostEstimate((CostEstimate) null); /* Set the assigned table map to be exactly the tables * in the current join order. */ assignedTableMap.clearAll(); for (int index = 0; index <= joinPosition; index++) { assignedTableMap.or(optimizableList.getOptimizable(proposedJoinOrder[index]).getReferencedTableMap()); } if (optimizerTrace) { trace(CONSIDERING_JOIN_ORDER, 0, 0, 0.0, null); } Optimizable nextOpt = optimizableList.getOptimizable(nextOptimizable); nextOpt.startOptimizing(this, currentRowOrdering); pushPredicates( optimizableList.getOptimizable(nextOptimizable), assignedTableMap); return true; } return false; }
protected void prepForNextRound()
public void prepForNextRound()
protected void prepForNextRound() { // We initialize reloadBestPlan to false so that if we end up // pulling an Optimizable before we find a best join order // (which can happen if there is no valid join order for this // round) we won't inadvertently reload the best plans based // on some previous round. reloadBestPlan = false; }
bestCost = getNewCostEstimate( Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE);
protected void prepForNextRound() { // We initialize reloadBestPlan to false so that if we end up // pulling an Optimizable before we find a best join order // (which can happen if there is no valid join order for this // round) we won't inadvertently reload the best plans based // on some previous round. reloadBestPlan = false; }
if (bestCost.getEstimatedCost() < timeLimit) timeLimit = bestCost.getEstimatedCost();
private void rememberBestCost(CostEstimate currentCost, int planType) throws StandardException { foundABestPlan = true; if (optimizerTrace) { trace(CHEAPEST_PLAN_SO_FAR, 0, 0, 0.0, null); trace(PLAN_TYPE, planType, 0, 0.0, null); trace(COST_OF_CHEAPEST_PLAN_SO_FAR, 0, 0, 0.0, null); } /* Remember the current cost as best */ bestCost.setCost(currentCost); /* ** Remember the current join order and access path ** selections as best. ** NOTE: We want the optimizer trace to print out in ** join order instead of in table number order, so ** we use 2 loops. */ for (int i = 0; i < numOptimizables; i++) { bestJoinOrder[i] = proposedJoinOrder[i]; } for (int i = 0; i < numOptimizables; i++) { optimizableList.getOptimizable(bestJoinOrder[i]). rememberAsBest(planType, this); } /* Remember if a sort is not needed for this plan */ if (requiredRowOrdering != null) { if (planType == Optimizer.SORT_AVOIDANCE_PLAN) requiredRowOrdering.sortNotNeeded(); else requiredRowOrdering.sortNeeded(); } if (optimizerTrace) { if (requiredRowOrdering != null) { trace(SORT_NEEDED_FOR_ORDERING, planType, 0, 0.0, null); } trace(REMEMBERING_BEST_JOIN_ORDER, 0, 0, 0.0, null); } }
case Types.DATE: return 10;
public static int getPrecision(DataTypeDescriptor dtd) { int typeId = dtd.getTypeId().getJDBCTypeId(); switch ( typeId ) { case Types.CHAR: // CHAR et alia return their # characters... case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CLOB: case Types.BINARY: // BINARY types return their # bytes... case Types.VARBINARY: case Types.LONGVARBINARY: case Types.BLOB: return dtd.getMaximumWidth(); case Types.SMALLINT: return 5; case Types.DATE: return 10; case JDBC30Translation.SQL_TYPES_BOOLEAN: return 1; } return dtd.getPrecision(); }
ExceptionUtil.getSeverityFromIdentifier(msgid.msgid)); if ( cause != null ) { this.setThrowable(cause); }
ExceptionUtil.getSeverityFromIdentifier(msgid.msgid));
public SqlException(LogWriter logwriter, ClientMessageId msgid, Object[] args, Throwable cause) { this( logwriter, getMessageUtil().getCompleteMessage( msgid.msgid, args), ExceptionUtil.getSQLStateFromIdentifier(msgid.msgid), ExceptionUtil.getSeverityFromIdentifier(msgid.msgid)); if ( cause != null ) { this.setThrowable(cause); } }
ArrayList<String> answers;
Collection answers;
public void addAnswerToSession(HttpServletRequest request){ HttpSession session = request.getSession(); String answer = request.getParameter("answer"); ArrayList<String> answers; if(session.getAttribute("answers")==null) answers = new ArrayList<String>(); else answers = (ArrayList<String>) session.getAttribute("answers"); answers.add(answer); session.setAttribute("answers", answers); }
else answers = (ArrayList<String>) session.getAttribute("answers");
else { Object obj = session.getAttribute("answers"); if(obj instanceof PersistentList) answers = (PersistentList) obj; else answers = (ArrayList<String>) obj; }
public void addAnswerToSession(HttpServletRequest request){ HttpSession session = request.getSession(); String answer = request.getParameter("answer"); ArrayList<String> answers; if(session.getAttribute("answers")==null) answers = new ArrayList<String>(); else answers = (ArrayList<String>) session.getAttribute("answers"); answers.add(answer); session.setAttribute("answers", answers); }
ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers");
Object obj = session.getAttribute("answers"); ArrayList<String> answers = null; if(obj instanceof PersistentList){ Iterator iter = ((PersistentList) obj).iterator(); answers = new ArrayList<String>(); while(iter.hasNext()){ answers.add((String) iter.next()); } } else answers = (ArrayList<String>) session.getAttribute("answers");
public void addCheckBoxQuestionToSection(HttpServletRequest request){ HttpSession session = request.getSession(); Section section = (Section) session.getAttribute("currentSection"); String name = request.getParameter("name"); String image = request.getParameter("image"); String questionText = request.getParameter("questionTxt"); ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); // now parse different params depending on the type CheckBoxListQuestion question = new CheckBoxListQuestion(); question.setDescription(questionText); question.setSection(section); question.setTitle(name); question.setItems(answers); question.setImage(image); List<Question> quests = section.getQuestions(); quests.add(question); section.setQuestions(quests); session.setAttribute("currentSection", section); session.removeAttribute("answers"); }
else columns = (ArrayList<String>) session.getAttribute("columns");
else { Object obj = session.getAttribute("columns"); if(obj instanceof PersistentList){ PersistentList pe = (PersistentList) obj; Iterator iter = pe.iterator(); columns = new ArrayList<String>(); while(iter.hasNext()){ columns.add((String) iter.next()); } } else columns = (ArrayList<String>) session.getAttribute("columns"); }
public void addColumnToSession(HttpServletRequest request){ HttpSession session = request.getSession(); String column = request.getParameter("column"); ArrayList<String> columns; if(session.getAttribute("columns")==null) columns = new ArrayList<String>(); else columns = (ArrayList<String>) session.getAttribute("columns"); columns.add(column); session.setAttribute("columns", columns); }
ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); ArrayList<String> columns = (ArrayList<String>) session.getAttribute("columns");
Object obj = session.getAttribute("answers"); ArrayList<String> answers = null; if(obj instanceof PersistentList){ Iterator iter = ((PersistentList) obj).iterator(); answers = new ArrayList<String>(); while(iter.hasNext()){ answers.add((String) iter.next()); } } else answers = (ArrayList<String>) session.getAttribute("answers"); obj = session.getAttribute("columns"); ArrayList<String> columns = null; if(obj instanceof PersistentList){ Iterator iter = ((PersistentList) obj).iterator(); columns = new ArrayList<String>(); while(iter.hasNext()){ columns.add((String) iter.next()); } } else columns = (ArrayList<String>) session.getAttribute("columns");
public void addMatrixQuestionToSection(HttpServletRequest request){ HttpSession session = request.getSession(); Section section = (Section) session.getAttribute("currentSection"); String name = request.getParameter("name"); String image = request.getParameter("image"); String questionText = request.getParameter("questionTxt"); ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); ArrayList<String> columns = (ArrayList<String>) session.getAttribute("columns"); // now parse different params depending on the type RadioMatrixQuestion question = new RadioMatrixQuestion(columns.size(), answers.size()); question.setDescription(questionText); question.setSection(section); question.setTitle(name); question.setItems(answers); question.setColumnsTitles(columns); question.setImage(image); List<Question> quests = section.getQuestions(); quests.add(question); section.setQuestions(quests); session.setAttribute("currentSection", section); session.removeAttribute("answers"); session.removeAttribute("columns"); }
ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers");
Object obj = session.getAttribute("answers"); ArrayList<String> answers = null; if(obj instanceof PersistentList){ Iterator iter = ((PersistentList) obj).iterator(); answers = new ArrayList<String>(); while(iter.hasNext()){ answers.add((String) iter.next()); } } else answers = (ArrayList<String>) session.getAttribute("answers");
public void addNumericQuestionToSection(HttpServletRequest request){ HttpSession session = request.getSession(); Section section = (Section) session.getAttribute("currentSection"); String name = request.getParameter("name"); String image = request.getParameter("image"); String validationType = request.getParameter("validationType"); String min = request.getParameter("min"); String max = request.getParameter("max"); String total = request.getParameter("total"); String questionText = request.getParameter("questionTxt"); ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); // now parse different params depending on the type NumberListQuestion question = new NumberListQuestion(answers.size()); question.setDescription(questionText); question.setSection(section); question.setTitle(name); question.setItems(answers); if(validationType.equals("individual")){ question.setMin(Integer.parseInt(min)); question.setMax(Integer.parseInt(max)); } else if (validationType.equals("total")){ question.setTotal(Integer.parseInt(total)); } question.setImage(image); List<Question> quests = section.getQuestions(); quests.add(question); section.setQuestions(quests); session.setAttribute("currentSection", section); session.removeAttribute("answers"); }
question.setValidationType(validationType);
public void addNumericQuestionToSection(HttpServletRequest request){ HttpSession session = request.getSession(); Section section = (Section) session.getAttribute("currentSection"); String name = request.getParameter("name"); String image = request.getParameter("image"); String validationType = request.getParameter("validationType"); String min = request.getParameter("min"); String max = request.getParameter("max"); String total = request.getParameter("total"); String questionText = request.getParameter("questionTxt"); ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); // now parse different params depending on the type NumberListQuestion question = new NumberListQuestion(answers.size()); question.setDescription(questionText); question.setSection(section); question.setTitle(name); question.setItems(answers); if(validationType.equals("individual")){ question.setMin(Integer.parseInt(min)); question.setMax(Integer.parseInt(max)); } else if (validationType.equals("total")){ question.setTotal(Integer.parseInt(total)); } question.setImage(image); List<Question> quests = section.getQuestions(); quests.add(question); section.setQuestions(quests); session.setAttribute("currentSection", section); session.removeAttribute("answers"); }