rem
stringlengths 0
477k
| add
stringlengths 0
313k
| context
stringlengths 6
599k
|
---|---|---|
public void backupAndEnableLogArchiveMode(String backupDir,boolean deleteOnlineArchivedLogFiles) | public void backupAndEnableLogArchiveMode( String backupDir, boolean deleteOnlineArchivedLogFiles, boolean wait) | public void backupAndEnableLogArchiveMode(String backupDir,boolean deleteOnlineArchivedLogFiles) throws StandardException { logFactory.enableLogArchiveMode(); backup(backupDir); //After successful backup delete the archived log files //that are not necessary to do a roll-forward recovery //from this backup if requested. if(deleteOnlineArchivedLogFiles) { logFactory.deleteOnlineArchivedLogFiles(); } } |
logFactory.enableLogArchiveMode(); backup(backupDir); if(deleteOnlineArchivedLogFiles) { logFactory.deleteOnlineArchivedLogFiles(); } | boolean enabledLogArchive = false; boolean error = true; try { if(!logFactory.logArchived()) { logFactory.enableLogArchiveMode(); enabledLogArchive = true ; } backup(backupDir, wait); if (deleteOnlineArchivedLogFiles) { logFactory.deleteOnlineArchivedLogFiles(); } error = false; } finally { if(error) { if (enabledLogArchive) logFactory.disableLogArchiveMode(); } } | public void backupAndEnableLogArchiveMode(String backupDir,boolean deleteOnlineArchivedLogFiles) throws StandardException { logFactory.enableLogArchiveMode(); backup(backupDir); //After successful backup delete the archived log files //that are not necessary to do a roll-forward recovery //from this backup if requested. if(deleteOnlineArchivedLogFiles) { logFactory.deleteOnlineArchivedLogFiles(); } } |
public TableScanResultSet(long conglomId, | TableScanResultSet(long conglomId, | public TableScanResultSet(long conglomId, StaticCompiledOpenConglomInfo scoci, Activation activation, GeneratedMethod resultRowAllocator, int resultSetNumber, GeneratedMethod startKeyGetter, int startSearchOperator, GeneratedMethod stopKeyGetter, int stopSearchOperator, boolean sameStartStopPosition, Qualifier[][] qualifiers, String tableName, String userSuppliedOptimizerOverrides, String indexName, boolean isConstraint, boolean forUpdate, int colRefItem, int indexColItem, int lockMode, boolean tableLocked, int isolationLevel, int rowsPerRead, boolean oneRowScan, double optimizerEstimatedRowCount, double optimizerEstimatedCost, GeneratedMethod closeCleanup) throws StandardException { super(activation, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost); this.conglomId = conglomId; /* Static info created at compile time and can be shared across * instances of the plan. * Dynamic info created on 1st opening of this ResultSet as * it cannot be shared. */ this.scoci = scoci; if (SanityManager.DEBUG) { SanityManager.ASSERT( activation!=null, "table scan must get activation context"); SanityManager.ASSERT( resultRowAllocator!= null, "table scan must get row allocator"); if (sameStartStopPosition) { SanityManager.ASSERT(stopKeyGetter == null, "stopKeyGetter expected to be null when sameStartStopPosition is true"); } } this.resultRowAllocator = resultRowAllocator; this.startKeyGetter = startKeyGetter; this.startSearchOperator = startSearchOperator; this.stopKeyGetter = stopKeyGetter; this.stopSearchOperator = stopSearchOperator; this.sameStartStopPosition = sameStartStopPosition; this.qualifiers = qualifiers; this.tableName = tableName; this.userSuppliedOptimizerOverrides = userSuppliedOptimizerOverrides; this.indexName = indexName; this.isConstraint = isConstraint; this.forUpdate = forUpdate; this.rowsPerRead = rowsPerRead; this.oneRowScan = oneRowScan; // retrieve the valid column list from // the saved objects, if it exists this.accessedCols = null; if (colRefItem != -1) { this.accessedCols = (FormatableBitSet)(activation.getPreparedStatement(). getSavedObject(colRefItem)); } if (indexColItem != -1) { this.indexCols = (int[])(activation.getPreparedStatement(). getSavedObject(indexColItem)); } if (indexCols != null) activation.setForUpdateIndexScan(this); this.lockMode = lockMode; /* Isolation level - translate from language to store */ // If not specified, get current isolation level if (isolationLevel == ExecutionContext.UNSPECIFIED_ISOLATION_LEVEL) { isolationLevel = lcc.getCurrentIsolationLevel(); } if (isolationLevel == ExecutionContext.SERIALIZABLE_ISOLATION_LEVEL) { this.isolationLevel = TransactionController.ISOLATION_SERIALIZABLE; } else { /* NOTE: always do row locking on READ COMMITTED/UNCOMITTED scans, * unless the table is marked as table locked (in sys.systables) * This is to improve concurrency. Also see FromBaseTable's * updateTargetLockMode (KEEP THESE TWO PLACES CONSISTENT! * bug 4318). */ /* NOTE: always do row locking on READ COMMITTED/UNCOMMITTED * and repeatable read scans unless the table is marked as * table locked (in sys.systables). * * We always get instantaneous locks as we will complete * the scan before returning any rows and we will fully * requalify the row if we need to go to the heap on a next(). */ if (! tableLocked) { this.lockMode = TransactionController.MODE_RECORD; } if (isolationLevel == ExecutionContext.READ_COMMITTED_ISOLATION_LEVEL) { /* * Now we see if we can get instantaneous locks * if we are getting share locks. * (For example, we can get instantaneous locks * when doing a bulk fetch.) */ if ((! forUpdate) && canGetInstantaneousLocks()) { this.isolationLevel = TransactionController.ISOLATION_READ_COMMITTED_NOHOLDLOCK; } else { this.isolationLevel = TransactionController.ISOLATION_READ_COMMITTED; } } else if (isolationLevel == ExecutionContext.READ_UNCOMMITTED_ISOLATION_LEVEL) { this.isolationLevel = TransactionController.ISOLATION_READ_UNCOMMITTED; } else if (isolationLevel == ExecutionContext.REPEATABLE_READ_ISOLATION_LEVEL) { this.isolationLevel = TransactionController.ISOLATION_REPEATABLE_READ; } } if (SanityManager.DEBUG) { SanityManager.ASSERT( ((isolationLevel == ExecutionContext.READ_COMMITTED_ISOLATION_LEVEL) || (isolationLevel == ExecutionContext.READ_UNCOMMITTED_ISOLATION_LEVEL) || (isolationLevel == ExecutionContext.REPEATABLE_READ_ISOLATION_LEVEL) || (isolationLevel == ExecutionContext.SERIALIZABLE_ISOLATION_LEVEL)), "Invalid isolation level - " + isolationLevel); } this.closeCleanup = closeCleanup; runTimeStatisticsOn = (activation != null && activation.getLanguageConnectionContext().getRunTimeStatisticsMode()); /* Only call row allocators once */ candidate = (ExecRow) resultRowAllocator.invoke(activation); constructorTime += getElapsedMillis(beginTime); /* Always qualify the first time a row is being read */ qualify = true; currentRowIsValid = false; scanRepositioned = false; } |
double optimizerEstimatedCost, GeneratedMethod closeCleanup) | double optimizerEstimatedCost) | public TableScanResultSet(long conglomId, StaticCompiledOpenConglomInfo scoci, Activation activation, GeneratedMethod resultRowAllocator, int resultSetNumber, GeneratedMethod startKeyGetter, int startSearchOperator, GeneratedMethod stopKeyGetter, int stopSearchOperator, boolean sameStartStopPosition, Qualifier[][] qualifiers, String tableName, String userSuppliedOptimizerOverrides, String indexName, boolean isConstraint, boolean forUpdate, int colRefItem, int indexColItem, int lockMode, boolean tableLocked, int isolationLevel, int rowsPerRead, boolean oneRowScan, double optimizerEstimatedRowCount, double optimizerEstimatedCost, GeneratedMethod closeCleanup) throws StandardException { super(activation, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost); this.conglomId = conglomId; /* Static info created at compile time and can be shared across * instances of the plan. * Dynamic info created on 1st opening of this ResultSet as * it cannot be shared. */ this.scoci = scoci; if (SanityManager.DEBUG) { SanityManager.ASSERT( activation!=null, "table scan must get activation context"); SanityManager.ASSERT( resultRowAllocator!= null, "table scan must get row allocator"); if (sameStartStopPosition) { SanityManager.ASSERT(stopKeyGetter == null, "stopKeyGetter expected to be null when sameStartStopPosition is true"); } } this.resultRowAllocator = resultRowAllocator; this.startKeyGetter = startKeyGetter; this.startSearchOperator = startSearchOperator; this.stopKeyGetter = stopKeyGetter; this.stopSearchOperator = stopSearchOperator; this.sameStartStopPosition = sameStartStopPosition; this.qualifiers = qualifiers; this.tableName = tableName; this.userSuppliedOptimizerOverrides = userSuppliedOptimizerOverrides; this.indexName = indexName; this.isConstraint = isConstraint; this.forUpdate = forUpdate; this.rowsPerRead = rowsPerRead; this.oneRowScan = oneRowScan; // retrieve the valid column list from // the saved objects, if it exists this.accessedCols = null; if (colRefItem != -1) { this.accessedCols = (FormatableBitSet)(activation.getPreparedStatement(). getSavedObject(colRefItem)); } if (indexColItem != -1) { this.indexCols = (int[])(activation.getPreparedStatement(). getSavedObject(indexColItem)); } if (indexCols != null) activation.setForUpdateIndexScan(this); this.lockMode = lockMode; /* Isolation level - translate from language to store */ // If not specified, get current isolation level if (isolationLevel == ExecutionContext.UNSPECIFIED_ISOLATION_LEVEL) { isolationLevel = lcc.getCurrentIsolationLevel(); } if (isolationLevel == ExecutionContext.SERIALIZABLE_ISOLATION_LEVEL) { this.isolationLevel = TransactionController.ISOLATION_SERIALIZABLE; } else { /* NOTE: always do row locking on READ COMMITTED/UNCOMITTED scans, * unless the table is marked as table locked (in sys.systables) * This is to improve concurrency. Also see FromBaseTable's * updateTargetLockMode (KEEP THESE TWO PLACES CONSISTENT! * bug 4318). */ /* NOTE: always do row locking on READ COMMITTED/UNCOMMITTED * and repeatable read scans unless the table is marked as * table locked (in sys.systables). * * We always get instantaneous locks as we will complete * the scan before returning any rows and we will fully * requalify the row if we need to go to the heap on a next(). */ if (! tableLocked) { this.lockMode = TransactionController.MODE_RECORD; } if (isolationLevel == ExecutionContext.READ_COMMITTED_ISOLATION_LEVEL) { /* * Now we see if we can get instantaneous locks * if we are getting share locks. * (For example, we can get instantaneous locks * when doing a bulk fetch.) */ if ((! forUpdate) && canGetInstantaneousLocks()) { this.isolationLevel = TransactionController.ISOLATION_READ_COMMITTED_NOHOLDLOCK; } else { this.isolationLevel = TransactionController.ISOLATION_READ_COMMITTED; } } else if (isolationLevel == ExecutionContext.READ_UNCOMMITTED_ISOLATION_LEVEL) { this.isolationLevel = TransactionController.ISOLATION_READ_UNCOMMITTED; } else if (isolationLevel == ExecutionContext.REPEATABLE_READ_ISOLATION_LEVEL) { this.isolationLevel = TransactionController.ISOLATION_REPEATABLE_READ; } } if (SanityManager.DEBUG) { SanityManager.ASSERT( ((isolationLevel == ExecutionContext.READ_COMMITTED_ISOLATION_LEVEL) || (isolationLevel == ExecutionContext.READ_UNCOMMITTED_ISOLATION_LEVEL) || (isolationLevel == ExecutionContext.REPEATABLE_READ_ISOLATION_LEVEL) || (isolationLevel == ExecutionContext.SERIALIZABLE_ISOLATION_LEVEL)), "Invalid isolation level - " + isolationLevel); } this.closeCleanup = closeCleanup; runTimeStatisticsOn = (activation != null && activation.getLanguageConnectionContext().getRunTimeStatisticsMode()); /* Only call row allocators once */ candidate = (ExecRow) resultRowAllocator.invoke(activation); constructorTime += getElapsedMillis(beginTime); /* Always qualify the first time a row is being read */ qualify = true; currentRowIsValid = false; scanRepositioned = false; } |
this.closeCleanup = closeCleanup; | public TableScanResultSet(long conglomId, StaticCompiledOpenConglomInfo scoci, Activation activation, GeneratedMethod resultRowAllocator, int resultSetNumber, GeneratedMethod startKeyGetter, int startSearchOperator, GeneratedMethod stopKeyGetter, int stopSearchOperator, boolean sameStartStopPosition, Qualifier[][] qualifiers, String tableName, String userSuppliedOptimizerOverrides, String indexName, boolean isConstraint, boolean forUpdate, int colRefItem, int indexColItem, int lockMode, boolean tableLocked, int isolationLevel, int rowsPerRead, boolean oneRowScan, double optimizerEstimatedRowCount, double optimizerEstimatedCost, GeneratedMethod closeCleanup) throws StandardException { super(activation, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost); this.conglomId = conglomId; /* Static info created at compile time and can be shared across * instances of the plan. * Dynamic info created on 1st opening of this ResultSet as * it cannot be shared. */ this.scoci = scoci; if (SanityManager.DEBUG) { SanityManager.ASSERT( activation!=null, "table scan must get activation context"); SanityManager.ASSERT( resultRowAllocator!= null, "table scan must get row allocator"); if (sameStartStopPosition) { SanityManager.ASSERT(stopKeyGetter == null, "stopKeyGetter expected to be null when sameStartStopPosition is true"); } } this.resultRowAllocator = resultRowAllocator; this.startKeyGetter = startKeyGetter; this.startSearchOperator = startSearchOperator; this.stopKeyGetter = stopKeyGetter; this.stopSearchOperator = stopSearchOperator; this.sameStartStopPosition = sameStartStopPosition; this.qualifiers = qualifiers; this.tableName = tableName; this.userSuppliedOptimizerOverrides = userSuppliedOptimizerOverrides; this.indexName = indexName; this.isConstraint = isConstraint; this.forUpdate = forUpdate; this.rowsPerRead = rowsPerRead; this.oneRowScan = oneRowScan; // retrieve the valid column list from // the saved objects, if it exists this.accessedCols = null; if (colRefItem != -1) { this.accessedCols = (FormatableBitSet)(activation.getPreparedStatement(). getSavedObject(colRefItem)); } if (indexColItem != -1) { this.indexCols = (int[])(activation.getPreparedStatement(). getSavedObject(indexColItem)); } if (indexCols != null) activation.setForUpdateIndexScan(this); this.lockMode = lockMode; /* Isolation level - translate from language to store */ // If not specified, get current isolation level if (isolationLevel == ExecutionContext.UNSPECIFIED_ISOLATION_LEVEL) { isolationLevel = lcc.getCurrentIsolationLevel(); } if (isolationLevel == ExecutionContext.SERIALIZABLE_ISOLATION_LEVEL) { this.isolationLevel = TransactionController.ISOLATION_SERIALIZABLE; } else { /* NOTE: always do row locking on READ COMMITTED/UNCOMITTED scans, * unless the table is marked as table locked (in sys.systables) * This is to improve concurrency. Also see FromBaseTable's * updateTargetLockMode (KEEP THESE TWO PLACES CONSISTENT! * bug 4318). */ /* NOTE: always do row locking on READ COMMITTED/UNCOMMITTED * and repeatable read scans unless the table is marked as * table locked (in sys.systables). * * We always get instantaneous locks as we will complete * the scan before returning any rows and we will fully * requalify the row if we need to go to the heap on a next(). */ if (! tableLocked) { this.lockMode = TransactionController.MODE_RECORD; } if (isolationLevel == ExecutionContext.READ_COMMITTED_ISOLATION_LEVEL) { /* * Now we see if we can get instantaneous locks * if we are getting share locks. * (For example, we can get instantaneous locks * when doing a bulk fetch.) */ if ((! forUpdate) && canGetInstantaneousLocks()) { this.isolationLevel = TransactionController.ISOLATION_READ_COMMITTED_NOHOLDLOCK; } else { this.isolationLevel = TransactionController.ISOLATION_READ_COMMITTED; } } else if (isolationLevel == ExecutionContext.READ_UNCOMMITTED_ISOLATION_LEVEL) { this.isolationLevel = TransactionController.ISOLATION_READ_UNCOMMITTED; } else if (isolationLevel == ExecutionContext.REPEATABLE_READ_ISOLATION_LEVEL) { this.isolationLevel = TransactionController.ISOLATION_REPEATABLE_READ; } } if (SanityManager.DEBUG) { SanityManager.ASSERT( ((isolationLevel == ExecutionContext.READ_COMMITTED_ISOLATION_LEVEL) || (isolationLevel == ExecutionContext.READ_UNCOMMITTED_ISOLATION_LEVEL) || (isolationLevel == ExecutionContext.REPEATABLE_READ_ISOLATION_LEVEL) || (isolationLevel == ExecutionContext.SERIALIZABLE_ISOLATION_LEVEL)), "Invalid isolation level - " + isolationLevel); } this.closeCleanup = closeCleanup; runTimeStatisticsOn = (activation != null && activation.getLanguageConnectionContext().getRunTimeStatisticsMode()); /* Only call row allocators once */ candidate = (ExecRow) resultRowAllocator.invoke(activation); constructorTime += getElapsedMillis(beginTime); /* Always qualify the first time a row is being read */ qualify = true; currentRowIsValid = false; scanRepositioned = false; } |
|
if (closeCleanup != null) { try { closeCleanup.invoke(activation); } catch (StandardException se) { if (SanityManager.DEBUG) SanityManager.THROWASSERT(se); } } currentRow = null; | ; | public void close() throws StandardException { beginTime = getCurrentTimeMillis(); if ( isOpen ) { /* ** If scan tracing is turned on, print information about this ** TableScanResultSet when it is closed. */ if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON("ScanTrace")) { //traceClose(); } } // we don't want to keep around a pointer to the // row ... so it can be thrown away. // REVISIT: does this need to be in a finally // block, to ensure that it is executed? clearCurrentRow(); if (closeCleanup != null) { try { closeCleanup.invoke(activation); // let activation tidy up } catch (StandardException se) { if (SanityManager.DEBUG) SanityManager.THROWASSERT(se); } } currentRow = null; if (scanController != null) { // This is where we get the positioner info for inner tables if (runTimeStatisticsOn) { // This is where we get the scan properties for a subquery scanProperties = getScanProperties(); startPositionString = printStartPosition(); stopPositionString = printStopPosition(); } scanController.close(); scanController = null; // should not access after close activation.clearIndexScanInfo(); } scanControllerOpened = false; startPosition = null; stopPosition = null; super.close(); if (indexCols != null) { ConglomerateController borrowedBaseCC = activation.getHeapConglomerateController(); if (borrowedBaseCC != null) { borrowedBaseCC.close(); activation.clearHeapConglomerateController(); } } if (futureRowResultSet != null) futureRowResultSet.close(); } else if (SanityManager.DEBUG) SanityManager.DEBUG("CloseRepeatInfo","Close of TableScanResultSet repeated"); closeTime += getElapsedMillis(beginTime); } |
if (paramBytes==null || !useSetBinaryStream) { ps.setBytes(i+1, paramBytes); | if ( paramBytes==null ) { ps.setBytes(i+1, null ); | private void readAndSetExtParam( int i, DRDAStatement stmt, int drdaType, int extLen, boolean streamLOB) throws DRDAProtocolException, SQLException { PreparedStatement ps = stmt.getPreparedStatement(); drdaType = (drdaType & 0x000000ff); // need unsigned value boolean checkNullability = false; if (sqlamLevel >= MGRLVL_7 && FdocaConstants.isNullable(drdaType)) checkNullability = true; try { final byte[] paramBytes; final String paramString; switch (drdaType) { case DRDAConstants.DRDA_TYPE_LOBBYTES: case DRDAConstants.DRDA_TYPE_NLOBBYTES: paramString = ""; final boolean useSetBinaryStream = stmt.getParameterMetaData().getParameterType(i+1)==Types.BLOB; if (streamLOB && useSetBinaryStream) { paramBytes = null; final EXTDTAReaderInputStream stream = reader.getEXTDTAReaderInputStream(checkNullability); if (stream==null) { ps.setBytes(i+1, null); } else { ps.setBinaryStream(i+1, stream, (int) stream.getLength()); } if (SanityManager.DEBUG) { if (stream==null) { trace("parameter value : NULL"); } else { trace("parameter value will be streamed"); } } } else { paramBytes = reader.getExtData(checkNullability); if (paramBytes==null || !useSetBinaryStream) { ps.setBytes(i+1, paramBytes); } else { ps.setBinaryStream(i+1, new ByteArrayInputStream(paramBytes), paramBytes.length); } if (SanityManager.DEBUG) { if (paramBytes==null) { trace("parameter value : NULL"); } else { trace("parameter value is a LOB with length:" + paramBytes.length); } } } break; case DRDAConstants.DRDA_TYPE_LOBCSBCS: case DRDAConstants.DRDA_TYPE_NLOBCSBCS: paramBytes = reader.getExtData(checkNullability); paramString = new String(paramBytes, stmt.ccsidSBCEncoding); if (SanityManager.DEBUG) trace("parameter value is: "+ paramString); ps.setString(i+1,paramString); break; case DRDAConstants.DRDA_TYPE_LOBCDBCS: case DRDAConstants.DRDA_TYPE_NLOBCDBCS: paramBytes = reader.getExtData(checkNullability); paramString = new String(paramBytes, stmt.ccsidDBCEncoding ); if (SanityManager.DEBUG) trace("parameter value is: "+ paramString); ps.setString(i+1,paramString); break; case DRDAConstants.DRDA_TYPE_LOBCMIXED: case DRDAConstants.DRDA_TYPE_NLOBCMIXED: paramBytes = reader.getExtData(checkNullability); paramString = new String(paramBytes, stmt.ccsidMBCEncoding); if (SanityManager.DEBUG) trace("parameter value is: "+ paramString); ps.setString(i+1,paramString); break; default: paramBytes = null; paramString = ""; invalidValue(drdaType); } } catch (java.io.UnsupportedEncodingException e) { throw new SQLException (e.getMessage()); } } |
if (bigIndex < 0) { bytes[offset+(packedIndex+1)/2] = (byte) ( (b.signum()>=0)?12:13 ); } else { bytes[offset+(packedIndex+1)/2] = (byte) ( ( (unscaledStr.charAt(bigIndex)-zeroBase) << 4 ) + ( (b.signum()>=0)?12:13 ) ); } | if (bigIndex < 0) { bytes[offset+(packedIndex+1)/2] = (byte) ( (b.signum()>=0)?12:13 ); } else { bytes[offset+(packedIndex+1)/2] = (byte) ( ( (unscaledStr.charAt(bigIndex)-zeroBase) << 4 ) + ( (b.signum()>=0)?12:13 ) ); } packedIndex-=2; bigIndex-=2; } else { bigIndex = declaredScale-bigScale-1; bytes[offset+(packedIndex+1)/2] = (byte) ( (b.signum()>=0)?12:13 ); for (packedIndex-=2, bigIndex-=2; bigIndex>=0; packedIndex-=2, bigIndex-=2) bytes[offset+(packedIndex+1)/2] = (byte) 0; if (bigIndex == -1) { bytes[offset+(packedIndex+1)/2] = (byte) ( (unscaledStr.charAt(bigPrecision-1)-zeroBase) << 4 ); | private int bigDecimalToPackedDecimalBytes (java.math.BigDecimal b, int precision, int scale) throws SQLException { int declaredPrecision = precision; int declaredScale = scale; // packed decimal may only be up to 31 digits. if (declaredPrecision > 31) { // this is a bugcheck only !!! clearDdm (); throw new java.sql.SQLException ("Packed decimal may only be up to 31 digits!"); } // get absolute unscaled value of the BigDecimal as a String. String unscaledStr = b.unscaledValue().abs().toString(); // get precision of the BigDecimal. int bigPrecision = unscaledStr.length(); if (bigPrecision > 31) { clearDdm (); throw new SQLException ("The numeric literal \"" + b.toString() + "\" is not valid because its value is out of range.", "42820", -405); } int bigScale = b.scale(); int bigWholeIntegerLength = bigPrecision - bigScale; if ( (bigWholeIntegerLength > 0) && (!unscaledStr.equals ("0")) ) { // if whole integer part exists, check if overflow. int declaredWholeIntegerLength = declaredPrecision - declaredScale; if (bigWholeIntegerLength > declaredWholeIntegerLength) { clearDdm (); throw new SQLException ("Overflow occurred during numeric data type conversion of \"" + b.toString() + "\".", "22003", -413); } } // convert the unscaled value to a packed decimal bytes. // get unicode '0' value. int zeroBase = '0'; // start index in target packed decimal. int packedIndex = declaredPrecision-1; // start index in source big decimal. int bigIndex; if (bigScale >= declaredScale) { // If target scale is less than source scale, // discard excessive fraction. // set start index in source big decimal to ignore excessive fraction. bigIndex = bigPrecision-1-(bigScale-declaredScale); if (bigIndex < 0) { // all digits are discarded, so only process the sign nybble. bytes[offset+(packedIndex+1)/2] = (byte) ( (b.signum()>=0)?12:13 ); // sign nybble } else { // process the last nybble together with the sign nybble. bytes[offset+(packedIndex+1)/2] = (byte) ( ( (unscaledStr.charAt(bigIndex)-zeroBase) << 4 ) + // last nybble ( (b.signum()>=0)?12:13 ) ); // sign nybble } packedIndex-=2; bigIndex-=2; } else { // If target scale is greater than source scale, // pad the fraction with zero. // set start index in source big decimal to pad fraction with zero. bigIndex = declaredScale-bigScale-1; // process the sign nybble. bytes[offset+(packedIndex+1)/2] = (byte) ( (b.signum()>=0)?12:13 ); // sign nybble for (packedIndex-=2, bigIndex-=2; bigIndex>=0; packedIndex-=2, bigIndex-=2) bytes[offset+(packedIndex+1)/2] = (byte) 0; if (bigIndex == -1) { bytes[offset+(packedIndex+1)/2] = (byte) ( (unscaledStr.charAt(bigPrecision-1)-zeroBase) << 4 ); // high nybble packedIndex-=2; bigIndex = bigPrecision-3; } else { bigIndex = bigPrecision-2; } } // process the rest. for (; bigIndex>=0; packedIndex-=2, bigIndex-=2) { bytes[offset+(packedIndex+1)/2] = (byte) ( ( (unscaledStr.charAt(bigIndex)-zeroBase) << 4 ) + // high nybble ( unscaledStr.charAt(bigIndex+1)-zeroBase ) ); // low nybble } // process the first nybble when there is one left. if (bigIndex == -1) { bytes[offset+(packedIndex+1)/2] = (byte) (unscaledStr.charAt(0) - zeroBase); packedIndex-=2; } // pad zero in front of the big decimal if necessary. for (; packedIndex>=-1; packedIndex-=2) bytes[offset+(packedIndex+1)/2] = (byte) 0; return declaredPrecision/2 + 1; } |
bigIndex-=2; } else { bigIndex = declaredScale-bigScale-1; bytes[offset+(packedIndex+1)/2] = (byte) ( (b.signum()>=0)?12:13 ); for (packedIndex-=2, bigIndex-=2; bigIndex>=0; packedIndex-=2, bigIndex-=2) bytes[offset+(packedIndex+1)/2] = (byte) 0; if (bigIndex == -1) { bytes[offset+(packedIndex+1)/2] = (byte) ( (unscaledStr.charAt(bigPrecision-1)-zeroBase) << 4 ); packedIndex-=2; bigIndex = bigPrecision-3; } else { bigIndex = bigPrecision-2; } | bigIndex = bigPrecision-3; } else { bigIndex = bigPrecision-2; } | private int bigDecimalToPackedDecimalBytes (java.math.BigDecimal b, int precision, int scale) throws SQLException { int declaredPrecision = precision; int declaredScale = scale; // packed decimal may only be up to 31 digits. if (declaredPrecision > 31) { // this is a bugcheck only !!! clearDdm (); throw new java.sql.SQLException ("Packed decimal may only be up to 31 digits!"); } // get absolute unscaled value of the BigDecimal as a String. String unscaledStr = b.unscaledValue().abs().toString(); // get precision of the BigDecimal. int bigPrecision = unscaledStr.length(); if (bigPrecision > 31) { clearDdm (); throw new SQLException ("The numeric literal \"" + b.toString() + "\" is not valid because its value is out of range.", "42820", -405); } int bigScale = b.scale(); int bigWholeIntegerLength = bigPrecision - bigScale; if ( (bigWholeIntegerLength > 0) && (!unscaledStr.equals ("0")) ) { // if whole integer part exists, check if overflow. int declaredWholeIntegerLength = declaredPrecision - declaredScale; if (bigWholeIntegerLength > declaredWholeIntegerLength) { clearDdm (); throw new SQLException ("Overflow occurred during numeric data type conversion of \"" + b.toString() + "\".", "22003", -413); } } // convert the unscaled value to a packed decimal bytes. // get unicode '0' value. int zeroBase = '0'; // start index in target packed decimal. int packedIndex = declaredPrecision-1; // start index in source big decimal. int bigIndex; if (bigScale >= declaredScale) { // If target scale is less than source scale, // discard excessive fraction. // set start index in source big decimal to ignore excessive fraction. bigIndex = bigPrecision-1-(bigScale-declaredScale); if (bigIndex < 0) { // all digits are discarded, so only process the sign nybble. bytes[offset+(packedIndex+1)/2] = (byte) ( (b.signum()>=0)?12:13 ); // sign nybble } else { // process the last nybble together with the sign nybble. bytes[offset+(packedIndex+1)/2] = (byte) ( ( (unscaledStr.charAt(bigIndex)-zeroBase) << 4 ) + // last nybble ( (b.signum()>=0)?12:13 ) ); // sign nybble } packedIndex-=2; bigIndex-=2; } else { // If target scale is greater than source scale, // pad the fraction with zero. // set start index in source big decimal to pad fraction with zero. bigIndex = declaredScale-bigScale-1; // process the sign nybble. bytes[offset+(packedIndex+1)/2] = (byte) ( (b.signum()>=0)?12:13 ); // sign nybble for (packedIndex-=2, bigIndex-=2; bigIndex>=0; packedIndex-=2, bigIndex-=2) bytes[offset+(packedIndex+1)/2] = (byte) 0; if (bigIndex == -1) { bytes[offset+(packedIndex+1)/2] = (byte) ( (unscaledStr.charAt(bigPrecision-1)-zeroBase) << 4 ); // high nybble packedIndex-=2; bigIndex = bigPrecision-3; } else { bigIndex = bigPrecision-2; } } // process the rest. for (; bigIndex>=0; packedIndex-=2, bigIndex-=2) { bytes[offset+(packedIndex+1)/2] = (byte) ( ( (unscaledStr.charAt(bigIndex)-zeroBase) << 4 ) + // high nybble ( unscaledStr.charAt(bigIndex+1)-zeroBase ) ); // low nybble } // process the first nybble when there is one left. if (bigIndex == -1) { bytes[offset+(packedIndex+1)/2] = (byte) (unscaledStr.charAt(0) - zeroBase); packedIndex-=2; } // pad zero in front of the big decimal if necessary. for (; packedIndex>=-1; packedIndex-=2) bytes[offset+(packedIndex+1)/2] = (byte) 0; return declaredPrecision/2 + 1; } |
private void writeExtendedLengthBytes (int extendedLengthByteCount, long length) { int shiftSize = (extendedLengthByteCount -1) * 8; for (int i = 0; i < extendedLengthByteCount; i++) { bytes[offset + i] = (byte) ((length >>> shiftSize) & 0xff); shiftSize -= 8; } offset += extendedLengthByteCount; | private void writeExtendedLengthBytes (int extendedLengthByteCount, long length) { int shiftSize = (extendedLengthByteCount -1) * 8; for (int i = 0; i < extendedLengthByteCount; i++) { bytes[offset + i] = (byte) ((length >>> shiftSize) & 0xff); shiftSize -= 8; | private void writeExtendedLengthBytes (int extendedLengthByteCount, long length) { int shiftSize = (extendedLengthByteCount -1) * 8; for (int i = 0; i < extendedLengthByteCount; i++) { bytes[offset + i] = (byte) ((length >>> shiftSize) & 0xff); shiftSize -= 8; } offset += extendedLengthByteCount; } |
offset += extendedLengthByteCount; } | private void writeExtendedLengthBytes (int extendedLengthByteCount, long length) { int shiftSize = (extendedLengthByteCount -1) * 8; for (int i = 0; i < extendedLengthByteCount; i++) { bytes[offset + i] = (byte) ((length >>> shiftSize) & 0xff); shiftSize -= 8; } offset += extendedLengthByteCount; } |
|
int codePoint, EXTDTAInputStream in, boolean writeNullByte) throws DRDAProtocolException { int spareDssLength = prepScalarStream( chainedWithSameCorrelator, codePoint, writeNullByte); int bytesRead = 0; int totalBytesRead = 0; | int codePoint, EXTDTAInputStream in, boolean writeNullByte) throws DRDAProtocolException { | protected void writeScalarStream (boolean chainedWithSameCorrelator, int codePoint, EXTDTAInputStream in, boolean writeNullByte) throws DRDAProtocolException { // Stream equivalent of "beginDss"... int spareDssLength = prepScalarStream( chainedWithSameCorrelator, codePoint, writeNullByte); // write the data int bytesRead = 0; int totalBytesRead = 0; try { OutputStream out = placeLayerBStreamingBuffer( agent.getOutputStream() ); boolean isLastSegment = false; while( !isLastSegment ){ int spareBufferLength = bytes.length - offset; if( SanityManager.DEBUG ){ if( PropertyUtil.getSystemProperty("derby.debug.suicideOfLayerBStreaming") != null ) throw new IOException(); } bytesRead = in.read(bytes, offset, Math.min(spareDssLength, spareBufferLength)); totalBytesRead += bytesRead; offset += bytesRead; spareDssLength -= bytesRead; spareBufferLength -= bytesRead; isLastSegment = peekStream(in) < 0; if(isLastSegment || spareDssLength == 0){ flushScalarStreamSegment (isLastSegment, out); if( ! isLastSegment ) spareDssLength = DssConstants.MAX_DSS_LENGTH - 2; } } out.flush(); }catch(IOException e){ agent.markCommunicationsFailure ("DDMWriter.writeScalarStream()", "", e.getMessage(), "*"); } } |
try { OutputStream out = placeLayerBStreamingBuffer( agent.getOutputStream() ); boolean isLastSegment = false; while( !isLastSegment ){ int spareBufferLength = bytes.length - offset; if( SanityManager.DEBUG ){ if( PropertyUtil.getSystemProperty("derby.debug.suicideOfLayerBStreaming") != null ) throw new IOException(); } bytesRead = in.read(bytes, offset, Math.min(spareDssLength, spareBufferLength)); totalBytesRead += bytesRead; offset += bytesRead; spareDssLength -= bytesRead; spareBufferLength -= bytesRead; | protected void writeScalarStream (boolean chainedWithSameCorrelator, int codePoint, EXTDTAInputStream in, boolean writeNullByte) throws DRDAProtocolException { // Stream equivalent of "beginDss"... int spareDssLength = prepScalarStream( chainedWithSameCorrelator, codePoint, writeNullByte); // write the data int bytesRead = 0; int totalBytesRead = 0; try { OutputStream out = placeLayerBStreamingBuffer( agent.getOutputStream() ); boolean isLastSegment = false; while( !isLastSegment ){ int spareBufferLength = bytes.length - offset; if( SanityManager.DEBUG ){ if( PropertyUtil.getSystemProperty("derby.debug.suicideOfLayerBStreaming") != null ) throw new IOException(); } bytesRead = in.read(bytes, offset, Math.min(spareDssLength, spareBufferLength)); totalBytesRead += bytesRead; offset += bytesRead; spareDssLength -= bytesRead; spareBufferLength -= bytesRead; isLastSegment = peekStream(in) < 0; if(isLastSegment || spareDssLength == 0){ flushScalarStreamSegment (isLastSegment, out); if( ! isLastSegment ) spareDssLength = DssConstants.MAX_DSS_LENGTH - 2; } } out.flush(); }catch(IOException e){ agent.markCommunicationsFailure ("DDMWriter.writeScalarStream()", "", e.getMessage(), "*"); } } |
|
isLastSegment = peekStream(in) < 0; if(isLastSegment || spareDssLength == 0){ flushScalarStreamSegment (isLastSegment, out); if( ! isLastSegment ) spareDssLength = DssConstants.MAX_DSS_LENGTH - 2; | int spareDssLength = prepScalarStream( chainedWithSameCorrelator, codePoint, writeNullByte); int bytesRead = 0; int totalBytesRead = 0; | protected void writeScalarStream (boolean chainedWithSameCorrelator, int codePoint, EXTDTAInputStream in, boolean writeNullByte) throws DRDAProtocolException { // Stream equivalent of "beginDss"... int spareDssLength = prepScalarStream( chainedWithSameCorrelator, codePoint, writeNullByte); // write the data int bytesRead = 0; int totalBytesRead = 0; try { OutputStream out = placeLayerBStreamingBuffer( agent.getOutputStream() ); boolean isLastSegment = false; while( !isLastSegment ){ int spareBufferLength = bytes.length - offset; if( SanityManager.DEBUG ){ if( PropertyUtil.getSystemProperty("derby.debug.suicideOfLayerBStreaming") != null ) throw new IOException(); } bytesRead = in.read(bytes, offset, Math.min(spareDssLength, spareBufferLength)); totalBytesRead += bytesRead; offset += bytesRead; spareDssLength -= bytesRead; spareBufferLength -= bytesRead; isLastSegment = peekStream(in) < 0; if(isLastSegment || spareDssLength == 0){ flushScalarStreamSegment (isLastSegment, out); if( ! isLastSegment ) spareDssLength = DssConstants.MAX_DSS_LENGTH - 2; } } out.flush(); }catch(IOException e){ agent.markCommunicationsFailure ("DDMWriter.writeScalarStream()", "", e.getMessage(), "*"); } } |
} } out.flush(); }catch(IOException e){ agent.markCommunicationsFailure ("DDMWriter.writeScalarStream()", "", e.getMessage(), "*"); } } | try { OutputStream out = placeLayerBStreamingBuffer( agent.getOutputStream() ); boolean isLastSegment = false; while( !isLastSegment ){ int spareBufferLength = bytes.length - offset; if( SanityManager.DEBUG ){ if( PropertyUtil.getSystemProperty("derby.debug.suicideOfLayerBStreaming") != null ) throw new IOException(); } bytesRead = in.read(bytes, offset, Math.min(spareDssLength, spareBufferLength)); totalBytesRead += bytesRead; offset += bytesRead; spareDssLength -= bytesRead; spareBufferLength -= bytesRead; isLastSegment = peekStream(in) < 0; if(isLastSegment || spareDssLength == 0){ flushScalarStreamSegment (isLastSegment, out); if( ! isLastSegment ) spareDssLength = DssConstants.MAX_DSS_LENGTH - 2; } } out.flush(); }catch(IOException e){ agent.markCommunicationsFailure ("DDMWriter.writeScalarStream()", "", e.getMessage(), "*"); } } | protected void writeScalarStream (boolean chainedWithSameCorrelator, int codePoint, EXTDTAInputStream in, boolean writeNullByte) throws DRDAProtocolException { // Stream equivalent of "beginDss"... int spareDssLength = prepScalarStream( chainedWithSameCorrelator, codePoint, writeNullByte); // write the data int bytesRead = 0; int totalBytesRead = 0; try { OutputStream out = placeLayerBStreamingBuffer( agent.getOutputStream() ); boolean isLastSegment = false; while( !isLastSegment ){ int spareBufferLength = bytes.length - offset; if( SanityManager.DEBUG ){ if( PropertyUtil.getSystemProperty("derby.debug.suicideOfLayerBStreaming") != null ) throw new IOException(); } bytesRead = in.read(bytes, offset, Math.min(spareDssLength, spareBufferLength)); totalBytesRead += bytesRead; offset += bytesRead; spareDssLength -= bytesRead; spareBufferLength -= bytesRead; isLastSegment = peekStream(in) < 0; if(isLastSegment || spareDssLength == 0){ flushScalarStreamSegment (isLastSegment, out); if( ! isLastSegment ) spareDssLength = DssConstants.MAX_DSS_LENGTH - 2; } } out.flush(); }catch(IOException e){ agent.markCommunicationsFailure ("DDMWriter.writeScalarStream()", "", e.getMessage(), "*"); } } |
Object [][] expectedRows, boolean allAsTrimmedStrings) throws SQLException { int rows; ResultSetMetaData rsmd = rs.getMetaData(); Assert.assertEquals("Unexpected column count:", expectedRows[0].length, rsmd.getColumnCount()); for (rows = 0; rs.next(); rows++) { if (rows < expectedRows.length) { assertRowInResultSet(rs, rows + 1, expectedRows[rows], allAsTrimmedStrings); } } Assert.assertEquals("Unexpected row count:", expectedRows.length, rows); } | String [][] expectedRows) throws SQLException { assertFullResultSet(rs, expectedRows, true); } | public static void assertFullResultSet(ResultSet rs, Object [][] expectedRows, boolean allAsTrimmedStrings) throws SQLException { int rows; ResultSetMetaData rsmd = rs.getMetaData(); // Assert that we have the right number of columns. Assert.assertEquals("Unexpected column count:", expectedRows[0].length, rsmd.getColumnCount()); for (rows = 0; rs.next(); rows++) { /* If we have more actual rows than expected rows, don't * try to assert the row. Instead just keep iterating * to see exactly how many rows the actual result set has. */ if (rows < expectedRows.length) { assertRowInResultSet(rs, rows + 1, expectedRows[rows], allAsTrimmedStrings); } } // And finally, assert the row count. Assert.assertEquals("Unexpected row count:", expectedRows.length, rows); } |
":\n Expected: " + expectedRow[i] + "\n Found: " + obj); | ":\n Expected: >" + expectedRow[i] + "<\n Found: >" + obj + "<"); | private static void assertRowInResultSet(ResultSet rs, int rowNum, Object [] expectedRow, boolean asTrimmedStrings) throws SQLException { String s; boolean ok; Object obj = null; ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 0; i < expectedRow.length; i++) { if (asTrimmedStrings) { // Trim the expected value, if non-null. if (expectedRow[i] != null) expectedRow[i] = ((String)expectedRow[i]).trim(); /* Different clients can return different values for * boolean columns--namely, 0/1 vs false/true. So in * order to keep things uniform, take boolean columns * and get the JDBC string version. Note: since * Derby doesn't have a BOOLEAN type, we assume that * if the column's type is SMALLINT and the expected * value's string form is "true" or "false", then the * column is intended to be a mock boolean column. */ if ((expectedRow[i] != null) && (rsmd.getColumnType(i+1) == Types.SMALLINT)) { s = expectedRow[i].toString(); if (s.equals("true") || s.equals("false")) obj = (rs.getShort(i+1) == 0) ? "false" : "true"; } else { obj = rs.getString(i+1); // Trim the rs string. if (obj != null) obj = ((String)obj).trim(); } } else obj = rs.getObject(i+1); ok = (rs.wasNull() && (expectedRow[i] == null)) || (!rs.wasNull() && (expectedRow[i] != null) && expectedRow[i].equals(obj)); if (!ok) { Assert.fail("Column value mismatch @ column '" + rsmd.getColumnName(i+1) + "', row " + rowNum + ":\n Expected: " + expectedRow[i] + "\n Found: " + obj); } } } |
closeMethodArgument(acb, mb); return 15; | return 14; | private int getScanArguments(ActivationClassBuilder acb, MethodBuilder mb) throws StandardException { int rclSize = resultColumns.size(); FormatableBitSet referencedCols = new FormatableBitSet(rclSize); int erdNumber = -1; int numSet = 0; // Get our final cost estimate. costEstimate = getFinalCostEstimate(); for (int index = 0; index < rclSize; index++) { ResultColumn rc = (ResultColumn) resultColumns.elementAt(index); if (rc.isReferenced()) { referencedCols.set(index); numSet++; } } // Only add referencedCols if not all columns are accessed if (numSet != numVTICols) { erdNumber = acb.addItem(referencedCols); } // compileTimeConstants can be null int ctcNumber = acb.addItem(compileTimeConstants); acb.pushThisAsActivation(mb); // arg 1 // get a function to allocate scan rows of the right shape and size resultColumns.generateHolder(acb, mb); // arg 2 // For a Version 2 VTI we never maintain the java.sql.PreparedStatement // from compile time to execute time. This would rquire the PreparedStatement // to be shareable across multiple connections, which is not the model for // java.sql.PreparedStatement. // For a Version 2 VTI we do pass onto the ResultSet the re-useability // of the java.sql.PreparedStatement at runtime. The java.sql.PreparedStatement // is re-uesable if // // o No ? or ColumnReferences in parameters boolean reuseablePs = version2 && (getNodesFromParameters(ParameterNode.class).size() == 0) && (getNodesFromParameters(ColumnReference.class).size() == 0); mb.push(resultSetNumber); // arg 3 // The generated method for the constructor generateConstructor(acb, mb, reuseablePs); // arg 4 // Pass in the class name mb.push(newInvocation.getJavaClassName()); // arg 5 if (restrictionList != null) { restrictionList.generateQualifiers(acb, mb, this, true); } else mb.pushNull(ClassName.Qualifier + "[][]"); // Pass in the erdNumber for the referenced column FormatableBitSet mb.push(erdNumber); // arg 6 // Whether or not this is a version 2 VTI mb.push(version2); mb.push(reuseablePs); mb.push(ctcNumber); // Whether or not this is a target VTI mb.push(isTarget); // isolation level of the scan (if specified) mb.push(getCompilerContext().getScanIsolationLevel()); // estimated row count mb.push(costEstimate.rowCount()); // estimated cost mb.push(costEstimate.getEstimatedCost()); // let the superclass deal with statement level argument closeMethodArgument(acb, mb); return 15; } |
newdssLength += continueHeaderLength; | newdssLength += (continueHeaderLength-2); | private void compressBLayerData (int continueDssHeaderCount) throws DRDAProtocolException { // jump to the last continuation header. int tempPos = 0; for (int i = 0; i < continueDssHeaderCount; i++) { // the first may be less than the size of a full DSS if (i == 0) { // only jump by the number of bytes remaining in the current DSS tempPos = pos + dssLength; } else { // all other jumps are for a full continued DSS tempPos += DssConstants.MAX_DSS_LENGTH; } } // for each of the DSS headers to remove, // read out the continuation header and increment the DSS length by the // size of the continuation bytes, then shift the continuation data as needed. int shiftSize = 0; int bytesToShift = 0; int continueHeaderLength = 0; int newdssLength = 0; for (int i = 0; i < continueDssHeaderCount; i++) { continueHeaderLength = ((buffer[tempPos] & 0xff) << 8) + ((buffer[tempPos + 1] & 0xff) << 0); if (i == 0) { // if this is the last one (farthest down stream and first to strip out) if ((continueHeaderLength & DssConstants.CONTINUATION_BIT) == DssConstants.CONTINUATION_BIT) { // the last DSS header is again continued continueHeaderLength = DssConstants.MAX_DSS_LENGTH; dssIsContinued = true; } else { // the last DSS header was not contiued so update continue state flag dssIsContinued = false; } // the very first shift size is 2 shiftSize = 2; } else { // already removed the last header so make sure the chaining flag is on if ((continueHeaderLength & DssConstants.CONTINUATION_BIT) == DssConstants.CONTINUATION_BIT) { continueHeaderLength = DssConstants.MAX_DSS_LENGTH; } else { // this is a syntax error but not really certain which one. // for now pick 0x02 which is DSS header Length does not // match the number // of bytes of data found. agent.throwSyntaxrm(CodePoint.SYNERRCD_DSS_LENGTH_BYTE_NUMBER_MISMATCH, DRDAProtocolException.NO_CODPNT_ARG); } // increase the shift size by 2 shiftSize += 2; } // it is a syntax error if the DSS continuation is less // than or equal to two if (continueHeaderLength <= 2) { agent.throwSyntaxrm(CodePoint.SYNERRCD_DSS_CONT_LESS_OR_EQUAL_2, DRDAProtocolException.NO_CODPNT_ARG); } newdssLength += continueHeaderLength; // calculate the number of bytes to shift if (i == (continueDssHeaderCount - 1)) bytesToShift = DssConstants.MAX_DSS_LENGTH; else bytesToShift = dssLength; tempPos -= (shiftSize - 1); System.arraycopy(buffer, tempPos, buffer, tempPos - bytesToShift + shiftSize , bytesToShift); tempPos -= bytesToShift; tempPos += (shiftSize + 1); } // reposition the start of the data after the final DSS shift. pos = tempPos; } |
if (i == (continueDssHeaderCount - 1)) | if (i != (continueDssHeaderCount - 1)) | private void compressBLayerData (int continueDssHeaderCount) throws DRDAProtocolException { // jump to the last continuation header. int tempPos = 0; for (int i = 0; i < continueDssHeaderCount; i++) { // the first may be less than the size of a full DSS if (i == 0) { // only jump by the number of bytes remaining in the current DSS tempPos = pos + dssLength; } else { // all other jumps are for a full continued DSS tempPos += DssConstants.MAX_DSS_LENGTH; } } // for each of the DSS headers to remove, // read out the continuation header and increment the DSS length by the // size of the continuation bytes, then shift the continuation data as needed. int shiftSize = 0; int bytesToShift = 0; int continueHeaderLength = 0; int newdssLength = 0; for (int i = 0; i < continueDssHeaderCount; i++) { continueHeaderLength = ((buffer[tempPos] & 0xff) << 8) + ((buffer[tempPos + 1] & 0xff) << 0); if (i == 0) { // if this is the last one (farthest down stream and first to strip out) if ((continueHeaderLength & DssConstants.CONTINUATION_BIT) == DssConstants.CONTINUATION_BIT) { // the last DSS header is again continued continueHeaderLength = DssConstants.MAX_DSS_LENGTH; dssIsContinued = true; } else { // the last DSS header was not contiued so update continue state flag dssIsContinued = false; } // the very first shift size is 2 shiftSize = 2; } else { // already removed the last header so make sure the chaining flag is on if ((continueHeaderLength & DssConstants.CONTINUATION_BIT) == DssConstants.CONTINUATION_BIT) { continueHeaderLength = DssConstants.MAX_DSS_LENGTH; } else { // this is a syntax error but not really certain which one. // for now pick 0x02 which is DSS header Length does not // match the number // of bytes of data found. agent.throwSyntaxrm(CodePoint.SYNERRCD_DSS_LENGTH_BYTE_NUMBER_MISMATCH, DRDAProtocolException.NO_CODPNT_ARG); } // increase the shift size by 2 shiftSize += 2; } // it is a syntax error if the DSS continuation is less // than or equal to two if (continueHeaderLength <= 2) { agent.throwSyntaxrm(CodePoint.SYNERRCD_DSS_CONT_LESS_OR_EQUAL_2, DRDAProtocolException.NO_CODPNT_ARG); } newdssLength += continueHeaderLength; // calculate the number of bytes to shift if (i == (continueDssHeaderCount - 1)) bytesToShift = DssConstants.MAX_DSS_LENGTH; else bytesToShift = dssLength; tempPos -= (shiftSize - 1); System.arraycopy(buffer, tempPos, buffer, tempPos - bytesToShift + shiftSize , bytesToShift); tempPos -= bytesToShift; tempPos += (shiftSize + 1); } // reposition the start of the data after the final DSS shift. pos = tempPos; } |
tempPos -= (shiftSize - 1); System.arraycopy(buffer, tempPos, buffer, tempPos - bytesToShift + shiftSize , bytesToShift); tempPos -= bytesToShift; tempPos += (shiftSize + 1); | tempPos -= (bytesToShift - 2); System.arraycopy(buffer, tempPos - shiftSize, buffer, tempPos, bytesToShift); | private void compressBLayerData (int continueDssHeaderCount) throws DRDAProtocolException { // jump to the last continuation header. int tempPos = 0; for (int i = 0; i < continueDssHeaderCount; i++) { // the first may be less than the size of a full DSS if (i == 0) { // only jump by the number of bytes remaining in the current DSS tempPos = pos + dssLength; } else { // all other jumps are for a full continued DSS tempPos += DssConstants.MAX_DSS_LENGTH; } } // for each of the DSS headers to remove, // read out the continuation header and increment the DSS length by the // size of the continuation bytes, then shift the continuation data as needed. int shiftSize = 0; int bytesToShift = 0; int continueHeaderLength = 0; int newdssLength = 0; for (int i = 0; i < continueDssHeaderCount; i++) { continueHeaderLength = ((buffer[tempPos] & 0xff) << 8) + ((buffer[tempPos + 1] & 0xff) << 0); if (i == 0) { // if this is the last one (farthest down stream and first to strip out) if ((continueHeaderLength & DssConstants.CONTINUATION_BIT) == DssConstants.CONTINUATION_BIT) { // the last DSS header is again continued continueHeaderLength = DssConstants.MAX_DSS_LENGTH; dssIsContinued = true; } else { // the last DSS header was not contiued so update continue state flag dssIsContinued = false; } // the very first shift size is 2 shiftSize = 2; } else { // already removed the last header so make sure the chaining flag is on if ((continueHeaderLength & DssConstants.CONTINUATION_BIT) == DssConstants.CONTINUATION_BIT) { continueHeaderLength = DssConstants.MAX_DSS_LENGTH; } else { // this is a syntax error but not really certain which one. // for now pick 0x02 which is DSS header Length does not // match the number // of bytes of data found. agent.throwSyntaxrm(CodePoint.SYNERRCD_DSS_LENGTH_BYTE_NUMBER_MISMATCH, DRDAProtocolException.NO_CODPNT_ARG); } // increase the shift size by 2 shiftSize += 2; } // it is a syntax error if the DSS continuation is less // than or equal to two if (continueHeaderLength <= 2) { agent.throwSyntaxrm(CodePoint.SYNERRCD_DSS_CONT_LESS_OR_EQUAL_2, DRDAProtocolException.NO_CODPNT_ARG); } newdssLength += continueHeaderLength; // calculate the number of bytes to shift if (i == (continueDssHeaderCount - 1)) bytesToShift = DssConstants.MAX_DSS_LENGTH; else bytesToShift = dssLength; tempPos -= (shiftSize - 1); System.arraycopy(buffer, tempPos, buffer, tempPos - bytesToShift + shiftSize , bytesToShift); tempPos -= bytesToShift; tempPos += (shiftSize + 1); } // reposition the start of the data after the final DSS shift. pos = tempPos; } |
dssLength += newdssLength; | private void compressBLayerData (int continueDssHeaderCount) throws DRDAProtocolException { // jump to the last continuation header. int tempPos = 0; for (int i = 0; i < continueDssHeaderCount; i++) { // the first may be less than the size of a full DSS if (i == 0) { // only jump by the number of bytes remaining in the current DSS tempPos = pos + dssLength; } else { // all other jumps are for a full continued DSS tempPos += DssConstants.MAX_DSS_LENGTH; } } // for each of the DSS headers to remove, // read out the continuation header and increment the DSS length by the // size of the continuation bytes, then shift the continuation data as needed. int shiftSize = 0; int bytesToShift = 0; int continueHeaderLength = 0; int newdssLength = 0; for (int i = 0; i < continueDssHeaderCount; i++) { continueHeaderLength = ((buffer[tempPos] & 0xff) << 8) + ((buffer[tempPos + 1] & 0xff) << 0); if (i == 0) { // if this is the last one (farthest down stream and first to strip out) if ((continueHeaderLength & DssConstants.CONTINUATION_BIT) == DssConstants.CONTINUATION_BIT) { // the last DSS header is again continued continueHeaderLength = DssConstants.MAX_DSS_LENGTH; dssIsContinued = true; } else { // the last DSS header was not contiued so update continue state flag dssIsContinued = false; } // the very first shift size is 2 shiftSize = 2; } else { // already removed the last header so make sure the chaining flag is on if ((continueHeaderLength & DssConstants.CONTINUATION_BIT) == DssConstants.CONTINUATION_BIT) { continueHeaderLength = DssConstants.MAX_DSS_LENGTH; } else { // this is a syntax error but not really certain which one. // for now pick 0x02 which is DSS header Length does not // match the number // of bytes of data found. agent.throwSyntaxrm(CodePoint.SYNERRCD_DSS_LENGTH_BYTE_NUMBER_MISMATCH, DRDAProtocolException.NO_CODPNT_ARG); } // increase the shift size by 2 shiftSize += 2; } // it is a syntax error if the DSS continuation is less // than or equal to two if (continueHeaderLength <= 2) { agent.throwSyntaxrm(CodePoint.SYNERRCD_DSS_CONT_LESS_OR_EQUAL_2, DRDAProtocolException.NO_CODPNT_ARG); } newdssLength += continueHeaderLength; // calculate the number of bytes to shift if (i == (continueDssHeaderCount - 1)) bytesToShift = DssConstants.MAX_DSS_LENGTH; else bytesToShift = dssLength; tempPos -= (shiftSize - 1); System.arraycopy(buffer, tempPos, buffer, tempPos - bytesToShift + shiftSize , bytesToShift); tempPos -= bytesToShift; tempPos += (shiftSize + 1); } // reposition the start of the data after the final DSS shift. pos = tempPos; } |
|
if (length < dssLength) | if (length < DssConstants.MAX_DSS_LENGTH) | protected byte[] readBytes (int length) throws DRDAProtocolException { byte[] b; if (length < dssLength) { ensureBLayerDataInBuffer (length, ADJUST_LENGTHS); b = new byte[length]; System.arraycopy(buffer,pos,b,0,length); pos +=length; } else b = getExtData(length,false); return b; } |
case SYSREQUIREDPERM_CATALOG_NUM: retval = new TabInfoImpl(new SYSREQUIREDPERMRowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; | protected TabInfo getNonCoreTIByNumber(int catalogNumber) throws StandardException { int nonCoreNum = catalogNumber - NUM_CORE; // Look up the TabInfo in the array. This does not have to be // synchronized, because getting a reference is atomic. TabInfo retval = noncoreInfo[nonCoreNum]; if (retval == null) { // If we did not find the TabInfo, get the right one and // load it into the array. There is a small chance that // two threads will do this at the same time. The code will // work properly in that case, since storing a reference // is atomic (although we could get extra object instantiation // if two threads come through here at the same time. UUIDFactory luuidFactory = uuidFactory; switch (catalogNumber) { case SYSCONSTRAINTS_CATALOG_NUM: retval = new TabInfoImpl(new SYSCONSTRAINTSRowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; case SYSKEYS_CATALOG_NUM: retval = new TabInfoImpl(new SYSKEYSRowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; case SYSDEPENDS_CATALOG_NUM: retval = new TabInfoImpl(new SYSDEPENDSRowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; case SYSVIEWS_CATALOG_NUM: retval = new TabInfoImpl(new SYSVIEWSRowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; case SYSCHECKS_CATALOG_NUM: retval = new TabInfoImpl(new SYSCHECKSRowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; case SYSFOREIGNKEYS_CATALOG_NUM: retval = new TabInfoImpl(new SYSFOREIGNKEYSRowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; case SYSSTATEMENTS_CATALOG_NUM: retval = new TabInfoImpl(new SYSSTATEMENTSRowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; case SYSFILES_CATALOG_NUM: retval = new TabInfoImpl(new SYSFILESRowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; case SYSALIASES_CATALOG_NUM: retval = new TabInfoImpl(new SYSALIASESRowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; case SYSTRIGGERS_CATALOG_NUM: retval = new TabInfoImpl(new SYSTRIGGERSRowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; case SYSSTATISTICS_CATALOG_NUM: retval = new TabInfoImpl(new SYSSTATISTICSRowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; case SYSDUMMY1_CATALOG_NUM: retval = new TabInfoImpl(new SYSDUMMY1RowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; case SYSTABLEPERMS_CATALOG_NUM: retval = new TabInfoImpl(new SYSTABLEPERMSRowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; case SYSCOLPERMS_CATALOG_NUM: retval = new TabInfoImpl(new SYSCOLPERMSRowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; case SYSROUTINEPERMS_CATALOG_NUM: retval = new TabInfoImpl(new SYSROUTINEPERMSRowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; case SYSREQUIREDPERM_CATALOG_NUM: retval = new TabInfoImpl(new SYSREQUIREDPERMRowFactory( luuidFactory, exFactory, dvf, convertIdToLower)); break; } initSystemIndexVariables(retval); noncoreInfo[nonCoreNum] = retval; } return retval; } |
|
if (!TestUtil.isJCCFramework()) { testSecurityMechanism("john","sarah",new Short(SECMEC_EUSRIDPWD),"SECMEC_EUSRIDPWD:"); } | public void getConnectionUsingDataSource() { // bug in jcc, throws error with null password //testSecurityMechanism("sarah",null,new Short(SECMEC_USRIDONL),"SECMEC_USRIDONL:"); testSecurityMechanism("john","sarah",new Short(SECMEC_USRIDPWD),"SECMEC_USRIDPWD:"); // Disable this test because ibm142, sun jce does not Diffie Helman prime of 32 bytes // and so this security mechanism wont work in that case //testSecurityMechanism("john","sarah",new Short(SECMEC_EUSRIDPWD),"SECMEC_EUSRIDPWD:"); } |
|
dumpSQLException(sqle.getNextException()); | public void getConnectionUsingDriverManager(String dbUrl, String msg) { try { DriverManager.getConnection(dbUrl); System.out.println(msg +" "+dbUrl ); } catch(SQLException sqle) { System.out.println(msg +" "+dbUrl +" - EXCEPTION "+ sqle.getMessage()); } } |
|
getConnectionUsingDriverManager(getJDBCUrl("wombat","user=neelima;password=lee;securityMechanism="+SECMEC_EUSRIDPWD),"T5:"); | protected void runTest() { // Test cases with get connection via drivermanager and using // different security mechanisms. // Network server supports SECMEC_USRIDPWD, SECMEC_USRIDONL,SECMEC_EUSRIDPWD System.out.println("Checking security mechanism authentication with DriverManager"); // DERBY-300; Creation of SQLWarning on a getConnection causes hang on // 131 vms when server and client are in same vm. // To avoid hitting this case with 1.3.1 vms, dont try to send create=true // if database is already created as otherwise it will lead to a SQLWarning if ( dbNotCreated ) { getConnectionUsingDriverManager(getJDBCUrl("wombat;create=true","user=neelima;password=lee;securityMechanism="+SECMEC_USRIDPWD),"T4:"); dbNotCreated = false; } else getConnectionUsingDriverManager(getJDBCUrl("wombat","user=neelima;password=lee;securityMechanism="+SECMEC_USRIDPWD),"T4:"); getConnectionUsingDriverManager(getJDBCUrl("wombat",null),"T1:"); getConnectionUsingDriverManager(getJDBCUrl("wombat","user=max"),"T2:"); getConnectionUsingDriverManager(getJDBCUrl("wombat","user=neelima;password=lee"),"T3:"); // Disable because ibm142 doesnt support DiffieHelman prime of 32 bytes // Also Sun JCE doesnt support it. //getConnectionUsingDriverManager(getJDBCUrl("wombat","user=neelima;password=lee;securityMechanism="+SECMEC_EUSRIDPWD),"T5:"); getConnectionUsingDriverManager(getJDBCUrl("wombat","user=neelima;securityMechanism="+SECMEC_USRIDONL),"T6:"); // disable as ibm142 and sun jce doesnt support DH prime of 32 bytes //getConnectionUsingDriverManager(getJDBCUrl("wombat","user=neelima;password=lee;securityMechanism="+SECMEC_USRENCPWD),"T7:"); getConnectionUsingDriverManager(getJDBCUrl("wombat","user=neelima;password=lee;securityMechanism="+SECMEC_USRIDONL),"T8:"); getConnectionUsingDataSource(); } |
|
catch (Exception e) | catch (SQLException sqle) | public void testSecurityMechanism(String user, String password,Short secmec,String msg) { Connection conn; String securityMechanismProperty = "SecurityMechanism"; Class[] argType = { Short.TYPE }; String methodName = TestUtil.getSetterName(securityMechanismProperty); Object[] args = new Short[1]; args[0] = secmec; try { DataSource ds = getDS("wombat", user,password); Method sh = ds.getClass().getMethod(methodName, argType); sh.invoke(ds, args); conn = ds.getConnection(); conn.close(); System.out.println(msg +" OK"); } catch (Exception e) { System.out.println(msg +"EXCEPTION testSecurityMechanism() " + e.getMessage()); } } |
System.out.println(msg +"EXCEPTION testSecurityMechanism() " + e.getMessage()); | System.out.println(msg +"EXCEPTION testSecurityMechanism() " + sqle.getMessage()); dumpSQLException(sqle.getNextException()); | public void testSecurityMechanism(String user, String password,Short secmec,String msg) { Connection conn; String securityMechanismProperty = "SecurityMechanism"; Class[] argType = { Short.TYPE }; String methodName = TestUtil.getSetterName(securityMechanismProperty); Object[] args = new Short[1]; args[0] = secmec; try { DataSource ds = getDS("wombat", user,password); Method sh = ds.getClass().getMethod(methodName, argType); sh.invoke(ds, args); conn = ds.getConnection(); conn.close(); System.out.println(msg +" OK"); } catch (Exception e) { System.out.println(msg +"EXCEPTION testSecurityMechanism() " + e.getMessage()); } } |
catch (Exception e) { System.out.println("UNEXPECTED EXCEPTION!!!" +msg); e.printStackTrace(); } | public void testSecurityMechanism(String user, String password,Short secmec,String msg) { Connection conn; String securityMechanismProperty = "SecurityMechanism"; Class[] argType = { Short.TYPE }; String methodName = TestUtil.getSetterName(securityMechanismProperty); Object[] args = new Short[1]; args[0] = secmec; try { DataSource ds = getDS("wombat", user,password); Method sh = ds.getClass().getMethod(methodName, argType); sh.invoke(ds, args); conn = ds.getConnection(); conn.close(); System.out.println(msg +" OK"); } catch (Exception e) { System.out.println(msg +"EXCEPTION testSecurityMechanism() " + e.getMessage()); } } |
|
if (junitXASingle) jvmProps.addElement ("junit.xa.single=true"); | private static String[] buildTestCommand(String propString, String systemHome, String scriptPath) throws FileNotFoundException, IOException, Exception { //System.out.println("testType: " + testType); String ij = ""; // Create the test command line if (testType.equals("sql")) ij = "ij"; jvm jvm = null; // to quiet compiler jvm = jvm.getJvm(jvmName); if (javaCmd != null) jvm.setJavaCmd(javaCmd); if ( (classpath != null) && (classpath.length()>0) ) jvm.setClasspath(classpath); Vector jvmProps = new Vector(); if ( testType.equals("java") || testType.equals("demo") ) addStandardTestJvmProps(jvmProps,systemHome, outDir.getCanonicalPath(),null); else if ( (runDir != null) && (runDir.exists()) ) addStandardTestJvmProps(jvmProps,systemHome, runDir.getCanonicalPath(),jvm); else addStandardTestJvmProps(jvmProps,systemHome, outDir.getCanonicalPath(),jvm); if ( (testJavaFlags != null) && (testJavaFlags.length()>0) ) { String parsedFlags = setTestJavaFlags(testJavaFlags); StringTokenizer st = new StringTokenizer(parsedFlags," "); while (st.hasMoreTokens()) { jvmflags = (jvmflags==null?"":jvmflags) + " " + st.nextToken(); } } if ( ij.startsWith("ij") ) jvmProps.addElement("ij.defaultResourcePackage=" + defaultPackageName); if ( (framework != null) ) { jvmProps.addElement("framework=" + framework); if ((hostName != null) && (!hostName.equals("localhost"))) jvmProps.addElement("hostName=" + hostName); } // if we're not jdk15, don't, we'll skip if ((testEncoding != null) && (jvmName.equals("jdk15"))) { jvmProps.addElement("derbyTesting.encoding=" + testEncoding); jvmProps.addElement("file.encoding=" + testEncoding); jvmflags = (jvmflags==null?"":jvmflags+" ") + "-Dfile.encoding=" + testEncoding; } if ( (jvmflags != null) && (jvmflags.length()>0) ) { jvm.setFlags(jvmflags); } if (testType.equals("multi")) { if ( (jvmflags != null) && (jvmflags.indexOf("mx") == -1) ) jvm.setMx(64*1024*1024); // -mx64m // MultiTest is special case, so pass on properties // related to encryption to MultiTest jvmProps.addElement("encryption="+encryption); Properties props = new Properties(); // parse and get only the special properties that are needed for the url SpecialFlags.parse(testSpecialProps, props, new Properties()); String encryptionAlgorithm = props.getProperty("testEncryptionAlgorithm"); if(encryptionAlgorithm != null) jvmProps.addElement("encryptionAlgorithm=\""+ Attribute.CRYPTO_ALGORITHM +"="+encryptionAlgorithm+"\""); } jvm.setD(jvmProps); // set security properties if (!runWithoutSecurityManager) jvm.setSecurityProps(); else System.out.println("-- SecurityManager not installed --"); Vector v = jvm.getCommandLine(); if ( ij.startsWith("ij") ) { // As of cn1411-20030930 IBM jvm the system takes the default // console encoding which in the US, on windows, is Cp437. // Sun jvms, however, always force a console encoding of 1252. // To get the same result for ibm141 & jdk14*, the harness needs to // force the console encoding to Cp1252 for ij tests - unless // we're on non-ascii systems. String isNotAscii = System.getProperty("platform.notASCII"); if ( (isNotAscii == null) || (isNotAscii.equals("false"))) v.addElement("-Dconsole.encoding=Cp1252" ); v.addElement("org.apache.derby.tools." + ij); if (ij.equals("ij")) { //TODO: is there a setting/property we could check after which // we can use v.addElement("-fr"); (read from the classpath?) // then we can also use v.addElement(scriptFile); v.addElement("-f"); v.addElement(outDir.toString() + File.separatorChar + scriptFileName); } v.addElement("-p"); v.addElement(propString); } else if ( testType.equals("java") ) { if (javaPath.length() > 0) v.addElement(javaPath + "." + testBase); else v.addElement(testBase); if (propString.length() > 0) { v.addElement("-p"); v.addElement(propString); } } else if (testType.equals("unit")) { v.addElement("org.apache.derbyTesting.unitTests.harness.UnitTestMain"); v.addElement("-p"); v.addElement(propString); } else if (testType.equals("junit")) { v.addElement("junit.textui.TestRunner"); if (javaPath.length() > 0) { v.addElement(javaPath + "." + testBase); } else { v.addElement(testBase); } } else if ( testType.equals("multi") ) { System.out.println("scriptiflename is: " + scriptFileName); v.addElement("org.apache.derbyTesting.functionTests.harness.MultiTest"); v.addElement(scriptFileName); v.addElement("-i"); v.addElement(mtestdir); v.addElement("-o"); v.addElement(outDir.getPath()); v.addElement("-p"); v.addElement(propString); } // Now convert the vector into a string array String[] sCmd = new String[v.size()]; for (int i = 0; i < v.size(); i++) { sCmd[i] = (String)v.elementAt(i); } return sCmd; } |
|
String junitXAProp = sp.getProperty ("junit.xa.single"); if (junitXAProp != null && junitXAProp.equals ("true")) { junitXASingle = true; } | private static JavaVersionHolder getProperties(Properties sp) throws Exception { // Get any properties specified on the command line searchCP = sp.getProperty("ij.searchClassPath"); String frameworkp = sp.getProperty("framework"); if (frameworkp != null) framework = frameworkp; if (framework == null) framework = "embedded"; if (!verifyFramework(framework)) framework = ""; else driverName = NetServer.getDriverName(framework); hostName = sp.getProperty("hostName"); // force hostName to localhost if it is not set if (hostName == null) hostName="localhost"; String generateUTF8OutProp = sp.getProperty("generateUTF8Out"); if (generateUTF8OutProp != null && generateUTF8OutProp.equals("true")) generateUTF8Out = true; // Some tests will not work with some frameworks, // so check suite exclude files for tests to be skipped String skipFile = framework + ".exclude"; if (!framework.equals("")) { skiptest = (SkipTest.skipIt(skipFile, scriptName)); // in addition, check to see if the test should get skipped // because it's not suitable for a remotely started server if (!skiptest) { if (!hostName.equals("localhost")) { skipFile = framework + "Remote.exclude"; skiptest = (SkipTest.skipIt(skipFile, scriptName)); } } if (skiptest) // if we're skipping... addSkiptestReason("Test skipped: listed in " + skipFile + " file, skipping test: " + scriptName); } jvmName = sp.getProperty("jvm"); //System.out.println("jvmName is: " + jvmName); if ( (jvmName == null) || (jvmName.length()==0) || (jvmName.equals("jview"))) { javaVersion = System.getProperty("java.version"); //System.out.println("javaVersion is: " + javaVersion); } else javaVersion = jvmName; //hang on a minute - if j9, we need to check further String javavmVersion; if (sp.getProperty("java.vm.name").equals("J9")) javavmVersion = (sp.getProperty("java.vm.version")); else javavmVersion = javaVersion; JavaVersionHolder jvh = new JavaVersionHolder(javavmVersion); majorVersion = jvh.getMajorVersion(); minorVersion = jvh.getMinorVersion(); iminor = jvh.getMinorNumber(); imajor = jvh.getMajorNumber(); if ( (jvmName == null) || (!jvmName.equals("jview")) ) { if ( (iminor < 2) && (imajor < 2) ) jvmName = "currentjvm"; else { if (System.getProperty("java.vm.vendor").startsWith("IBM")) { if (System.getProperty("java.vm.name").equals("J9")) { if (System.getProperty("com.ibm.oti.configuration").equals("foun10")) { jvmName = "j9_foundation"; } else { // for reporting; first extend javaVersion javaVersion = javaVersion + " - " + majorVersion + "." + minorVersion; // up to j9 2.1 (jdk 1.3.1 subset) the results are the same for all versions, // or we don't care about it anymore. Switch back to 1.3. (java.version) values. if ((imajor <= 2) && (iminor < 2)) { majorVersion = "1"; minorVersion = "3"; imajor = 1; iminor = 3; } jvmName = "j9_" + majorVersion + minorVersion; } } else jvmName = "ibm" + majorVersion + minorVersion; } else jvmName = "jdk" + majorVersion + minorVersion; } } testEncoding = sp.getProperty("derbyTesting.encoding"); if ((testEncoding != null) && (!jvmName.equals("jdk15"))) { skiptest = true; addSkiptestReason("derbyTesting.encoding can only be used with jdk15, skipping test"); } javaCmd = sp.getProperty("javaCmd"); bootcp = sp.getProperty("bootcp"); jvmflags = sp.getProperty("jvmflags"); testJavaFlags = sp.getProperty("testJavaFlags"); classpath = sp.getProperty("classpath"); //System.out.println("classpath set to: " + classpath); classpathServer = sp.getProperty("classpathServer"); if ( (classpathServer == null) || (classpathServer.startsWith("${")) ) classpathServer = classpath; //System.out.println("classpathServer set to: " + classpathServer); jarfile = sp.getProperty("jarfile"); String upg = sp.getProperty("upgradetest"); if (upg != null) { upg = upg.toLowerCase(); if (upg.equals("true")) upgradetest = true; } if ( framework.equals("DerbyNet") && (! jvmName.equals("j9_foundation"))) { Class c = null; Method m = null; Object o = null; Integer i = null; try { c = Class.forName("com.ibm.db2.jcc.DB2Driver"); o = c.newInstance(); m = c.getMethod("getMajorVersion", null); i = (Integer)m.invoke(o, null); jccMajor = i.intValue(); m = c.getMethod("getMinorVersion", null); i = (Integer)m.invoke(o, null); jccMinor = i.intValue(); } catch (ClassNotFoundException e) {} String excludeJcc = sp.getProperty("excludeJCC"); try { RunList.checkClientExclusion(excludeJcc, "JCC", jccMajor, jccMinor, javaVersion); } catch (Exception e) { skiptest = true; addSkiptestReason(e.getMessage()); } } String sysdiff = sp.getProperty("systemdiff"); if (sysdiff != null) { sysdiff = sysdiff.toLowerCase(); if (sysdiff.equals("true")) systemdiff = true; } String keep = sp.getProperty("keepfiles"); if (keep != null) { keep = keep.toLowerCase(); if (keep.equals("true")) keepfiles = true; } String encrypt = sp.getProperty("encryption"); if ( (encrypt != null) && (encrypt.equalsIgnoreCase("true")) ) encryption = true; String jdk12ext = sp.getProperty("jdk12exttest"); if ( (jdk12ext != null) && (jdk12ext.equalsIgnoreCase("true")) ) jdk12exttest = true; // applied to jdk12 or higher if ( encryption || jdk12exttest ) { // Must be running jdk12 or higher and must have extensions if ( iminor < 2 ) // this is 1.1.x { skiptest = true; addSkiptestReason("Test skipped: encryption or jdk12exttest requires jdk12 or higher; this is jdk1"+iminor+", skipping test: " + scriptFileName); } else // now check for extensions { try { Class jtaClass = Class.forName("javax.transaction.xa.Xid"); } catch (ClassNotFoundException cnfe) { // at least one of the extension classes was not found skiptest = true; addSkiptestReason("Test skipped: javax.transaction.xa.Xid not found, skipping test: " + scriptFileName); } try { Class jdbcClass = Class.forName("javax.sql.RowSet"); } catch (ClassNotFoundException cnfe2) { // at least one of the extension classes was not found skiptest = true; addSkiptestReason("Test skipped: javax.sql.RowSet not found, skipping test: " + scriptFileName); } } } runningdir = sp.getProperty("rundir"); if (runningdir == null) runningdir = ""; outputdir = sp.getProperty("outputdir"); if (outputdir == null) outputdir = ""; canondir = sp.getProperty("canondir"); canonpath = sp.getProperty("canonpath"); testOutName = sp.getProperty("testoutname"); useOutput = new Boolean(sp.getProperty("useoutput","true")).booleanValue(); outcopy = new Boolean(sp.getProperty("outcopy","false")).booleanValue(); mtestdir = sp.getProperty("mtestdir"); // used by multi tests if (mtestdir == null) mtestdir = ""; String usepr = sp.getProperty("useprocess"); if (usepr != null) { usepr = usepr.toLowerCase(); if (usepr.equals("false")) useprocess = false; else useprocess = true; } else useprocess = true; // if the hostName is something other than localhost, we must // be trying to connect to a remote server, and so, // startServer should be false. if (!hostName.equals("localhost")) { startServer=false; } String nosed = sp.getProperty("skipsed"); if (nosed != null) { nosed = nosed.toLowerCase(); if (nosed.equals("true")) skipsed = true; } String dbug = sp.getProperty("verbose"); if (dbug != null) { dbug = dbug.toLowerCase(); if (dbug.equals("true")) verbose = true; } String rstderr = sp.getProperty("reportstderr"); if (rstderr != null) { rstderr = rstderr.toLowerCase(); if (rstderr.equals("false")) reportstderr = false; } // default to -1 (no timeout) if no property is set if (timeoutStr == null) { timeoutStr = sp.getProperty("timeout", "-1"); //System.out.println("+++setting timeoutStr to " + timeoutStr + " in RunTest::getProperties"); } else { //System.out.println("+++timeoutStr was already " + timeoutStr + " in RunTest::getProperties"); } try { timeout = Integer.parseInt(timeoutStr); } catch (NumberFormatException nfe) { timeout = -1; } //System.out.println("RunTest timeout is: " + timeout); testSpecialProps = sp.getProperty("testSpecialProps"); if (useprocess) { String defrespckg = sp.getProperty("ij.defaultResourcePackage"); if (defrespckg != null) // if not set there is a default defined { defaultPackageName = defrespckg; if (!defaultPackageName.endsWith("/")) defaultPackageName += "/"; } usesystem = sp.getProperty("usesystem"); } // Some tests will not run well in a suite with use process false // with some frameworks, so skip if (!useprocess && !skiptest ) { String tsuiteName = null; if (suiteName != null) tsuiteName = suiteName; else tsuiteName = sp.getProperty("suitename"); if ( (tsuiteName != null) && (tsuiteName.length()>0) ) { skipFile = framework + "Useprocess.exclude"; if (!framework.equals("")) { skiptest = (SkipTest.skipIt(skipFile, scriptName)); if (skiptest) { skiptest=true; addSkiptestReason("Test " + scriptName + " skipped, " + "listed in " + framework + "Useprocess.exclude file."); } } } } if ( (useprocess) || (suiteName == null) ) { if (useprocess) suiteName = sp.getProperty("suitename"); if ( (suiteName != null) && (suiteName.length()>0) ) { // This is a suite run isSuiteRun = true; if (useprocess) // If a suite, it could be part of a top suite topsuiteName = sp.getProperty("topsuitename"); topsuitedir = sp.getProperty("topsuitedir"); topreportdir = sp.getProperty("topreportdir"); } } String uscdb = sp.getProperty("useCommonDB"); if (uscdb != null && uscdb.equals("true")) useCommonDB = true; return jvh; } |
|
markClosed(); connection_.openStatements_.remove(this); } if (resultSetMetaData_ != null) { resultSetMetaData_.markClosed(); resultSetMetaData_ = null; | markClosed(true); | public void closeX() throws SqlException { if (!openOnClient_) { return; } // Regardless of whether or not this statement is in the prepared state, // we need to close any open cursors for this statement on the server. int numberOfResultSetsToClose = (resultSetList_ == null) ? 0 : resultSetList_.length; boolean willTickleServer = willTickleServer(numberOfResultSetsToClose, true); try { if (willTickleServer) { flowClose(); } else { flowCloseOutsideUOW(); } } finally { markClosed(); connection_.openStatements_.remove(this); } // push the mark close of rsmd into Statement.markClosed() method if (resultSetMetaData_ != null) { resultSetMetaData_.markClosed(); resultSetMetaData_ = null; } } |
synchronized (connection_) { closeX(); } | markClosed(); | protected void finalize() throws java.lang.Throwable { if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "finalize"); } if (openOnClient_) { synchronized (connection_) { closeX(); } } super.finalize(); } |
openOnClient_ = false; markResultSetsClosed(); removeClientCursorNameFromCache(); markPreparedStatementForAutoGeneratedKeysClosed(); markClosedOnServer(); | markClosed(false); | void markClosed() { openOnClient_ = false; markResultSetsClosed(); // in case a cursorName was set on the Statement but the Statement was // never used to execute a query, the cursorName will not be removed // when the resultSets are mark closed, so we need to remove the // cursorName form the cache. removeClientCursorNameFromCache(); markPreparedStatementForAutoGeneratedKeysClosed(); markClosedOnServer(); } |
accumulateWarning(new SqlWarning(agent_.logWriter_, "Insensitive updatable result sets are not supported by server; remapping to insensitive read-only cursor")); | accumulateWarning(new SqlWarning(agent_.logWriter_, new MessageId(SQLState.INSENSITIVE_UPDATABLE_NOT_SUPPORTED))); | private int downgradeResultSetConcurrency(int resultSetConcurrency, int resultSetType) { if (resultSetConcurrency == java.sql.ResultSet.CONCUR_UPDATABLE && resultSetType == java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE) { accumulateWarning(new SqlWarning(agent_.logWriter_, "Insensitive updatable result sets are not supported by server; remapping to insensitive read-only cursor")); return java.sql.ResultSet.CONCUR_READ_ONLY; } return resultSetConcurrency; } |
accumulateWarning(new SqlWarning(agent_.logWriter_, "Scroll sensitive result sets are not supported by server; remapping to forward-only cursor")); | accumulateWarning(new SqlWarning(agent_.logWriter_, new MessageId(SQLState.SCROLL_SENSITIVE_NOT_SUPPORTED))); | private int downgradeResultSetType(int resultSetType) { if (resultSetType == java.sql.ResultSet.TYPE_SCROLL_SENSITIVE) { accumulateWarning(new SqlWarning(agent_.logWriter_, "Scroll sensitive result sets are not supported by server; remapping to forward-only cursor")); return java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE; } return resultSetType; } |
return warnings_; | return warnings_ == null ? null : warnings_.getSQLWarning(); | public java.sql.SQLWarning getWarnings() { if (agent_.loggingEnabled()) { agent_.logWriter_.traceExit(this, "getWarnings", warnings_); } return warnings_; } |
return (ColPermsDescriptor) getPermissions( key); | return getUncachedColPermsDescriptor( key ); | public ColPermsDescriptor getColumnPermissions( UUID colPermsUUID) throws StandardException { ColPermsDescriptor key = new ColPermsDescriptor( this, colPermsUUID); return (ColPermsDescriptor) getPermissions( key); } |
EmbeddedXADataSource dscsx = new EmbeddedXADataSource(); dscsx.setDatabaseName("wombat"); | Properties attrs = new Properties(); attrs.setProperty("databaseName", "wombat"); XADataSource dscsx = TestUtil.getXADataSource(attrs); | private void checkXAHoldability() { System.out.println("START XA HOLDABILITY TEST"); try { EmbeddedXADataSource dscsx = new EmbeddedXADataSource(); dscsx.setDatabaseName("wombat"); XAConnection xac = dscsx.getXAConnection("fred", "wilma"); XAResource xr = xac.getXAResource(); Xid xid = getXid(25, (byte) 21, (byte) 01); Connection conn1 = xac.getConnection(); System.out.println("By default, autocommit is " + conn1.getAutoCommit() + " for a connection"); System.out.println("Default holdability for a connection is HOLD_CURSORS_OVER_COMMIT"); System.out.println("CONNECTION(not in xa transaction yet) HOLDABILITY " + (conn1.getHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); //start a global transaction and default holdability and autocommit will be switched to match Derby XA restrictions xr.start(xid, XAResource.TMNOFLAGS); System.out.println("Notice that autocommit now is " + conn1.getAutoCommit() + " for connection because it is part of the global transaction"); System.out.println("Notice that connection's holdability at this point is CLOSE_CURSORS_AT_COMMIT because it is part of the global transaction"); System.out.println("CONNECTION(in xa transaction) HOLDABILITY " + (conn1.getHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); xr.end(xid, XAResource.TMSUCCESS); conn1.commit(); conn1.close(); xid = getXid(27, (byte) 21, (byte) 01); xr.start(xid, XAResource.TMNOFLAGS); conn1 = xac.getConnection(); System.out.println("CONNECTION(in xa transaction) HOLDABILITY " + (conn1.getHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); System.out.println("Autocommit on Connection inside global transaction has been set correctly to " + conn1.getAutoCommit()); xr.end(xid, XAResource.TMSUCCESS); conn1.rollback(); Connection conn = xac.getConnection(); conn.setAutoCommit(false); conn.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); System.out.println("CONNECTION(non-xa) HOLDABILITY " + (conn.getHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); Statement s = conn.createStatement(); System.out.println("STATEMENT HOLDABILITY " + (s.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); s.executeUpdate("create table hold_30 (id int not null primary key, b char(30))"); s.executeUpdate("insert into hold_30 values (1,'init2'), (2, 'init3'), (3,'init3')"); s.executeUpdate("insert into hold_30 values (4,'init4'), (5, 'init5'), (6,'init6')"); s.executeUpdate("insert into hold_30 values (7,'init7'), (8, 'init8'), (9,'init9')"); System.out.println("STATEMENT HOLDABILITY " + (s.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); Statement sh = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); PreparedStatement psh = conn.prepareStatement("select id from hold_30 for update", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); CallableStatement csh = conn.prepareCall("select id from hold_30 for update", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); System.out.println("STATEMENT HOLDABILITY " + (sh.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); System.out.println("PREPARED STATEMENT HOLDABILITY " + (psh.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); System.out.println("CALLABLE STATEMENT HOLDABILITY " + (csh.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); ResultSet rsh = sh.executeQuery("select id from hold_30 for update"); rsh.next(); System.out.println("H@1 id " + rsh.getInt(1)); rsh.next(); System.out.println("H@2 id " + rsh.getInt(1)); conn.commit(); rsh.next(); System.out.println("H@3 id " + rsh.getInt(1)); conn.commit(); xid = getXid(23, (byte) 21, (byte) 01); xr.start(xid, XAResource.TMNOFLAGS); Statement stmtInsideGlobalTransaction = conn.createStatement(); PreparedStatement prepstmtInsideGlobalTransaction = conn.prepareStatement("select id from hold_30"); CallableStatement callablestmtInsideGlobalTransaction = conn.prepareCall("select id from hold_30"); System.out.println("CONNECTION(xa) HOLDABILITY " + (conn.getHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); System.out.println("STATEMENT(this one was created with holdability false, outside the global transaction. Check it's holdability inside global transaction) HOLDABILITY " + (s.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); System.out.println("STATEMENT(this one was created with holdability true, outside the global transaction. Check it's holdability inside global transaction) HOLDABILITY " + (sh.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); System.out.println("STATEMENT(this one was created with default holdability inside this global transaction. Check it's holdability) HOLDABILITY " + (stmtInsideGlobalTransaction.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); System.out.println("PREPAREDSTATEMENT(this one was created with default holdability inside this global transaction. Check it's holdability) HOLDABILITY " + (prepstmtInsideGlobalTransaction.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); System.out.println("CALLABLESTATEMENT(this one was created with default holdability inside this global transaction. Check it's holdability) HOLDABILITY " + (callablestmtInsideGlobalTransaction.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); ResultSet rsx = s.executeQuery("select id from hold_30 for update"); rsx.next(); System.out.println("X@1 id " + rsx.getInt(1)); rsx.next(); System.out.println("X@2 id " + rsx.getInt(1)); xr.end(xid, XAResource.TMSUCCESS); // result set should not be useable, since it is part of a detached // XAConnection try { rsx.next(); System.out.println("FAIL - rsx's connection not active id " + rsx.getInt(1)); } catch (SQLException sqle) { System.out.println("Expected SQLException " + sqle.getMessage()); } // result set should not be useable, it should have been closed by the xa start. try { rsh.next(); System.out.println("FAIL - rsh's should be closed " + rsx.getInt(1)); } catch (SQLException sqle) { System.out.println("Expected SQLException " + sqle.getMessage()); } System.out.println("resume XA transaction and keep using rs"); xr.start(xid, XAResource.TMJOIN); Statement stmtAfterGlobalTransactionResume = conn.createStatement(); PreparedStatement prepstmtAfterGlobalTransactionResume = conn.prepareStatement("select id from hold_30"); CallableStatement callablestmtAfterGlobalTransactionResume = conn.prepareCall("select id from hold_30"); System.out.println("Check holdability of various jdbc objects after resuming XA transaction"); System.out.println("CONNECTION(xa) HOLDABILITY " + (conn.getHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); System.out.println("STATEMENT(this one was created with holdability false, outside the global transaction. Check it's holdability inside global transaction) HOLDABILITY " + (s.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); System.out.println("STATEMENT(this one was created with holdability true, outside the global transaction. Check it's holdability inside global transaction) HOLDABILITY " + (sh.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); System.out.println("STATEMENT(this one was created with default holdability inside the global transaction when it was first started. Check it's holdability) HOLDABILITY " + (stmtInsideGlobalTransaction.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); System.out.println("PREPAREDSTATEMENT(this one was created with default holdability inside the global transaction when it was first started. Check it's holdability) HOLDABILITY " + (prepstmtInsideGlobalTransaction.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); System.out.println("CALLABLESTATEMENT(this one was created with default holdability inside the global transaction when it was first started. Check it's holdability) HOLDABILITY " + (callablestmtInsideGlobalTransaction.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); System.out.println("STATEMENT(this one was created with default holdability after the global transaction was resumed. Check it's holdability) HOLDABILITY " + (stmtAfterGlobalTransactionResume.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); System.out.println("PREPAREDSTATEMENT(this one was created with default holdability after the global transaction was resumed. Check it's holdability) HOLDABILITY " + (prepstmtAfterGlobalTransactionResume.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); System.out.println("CALLABLESTATEMENT(this one was created with default holdability after the global transaction was resumed. Check it's holdability) HOLDABILITY " + (callablestmtAfterGlobalTransactionResume.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); rsx.next(); System.out.println("X@3 id " + rsx.getInt(1)); xr.end(xid, XAResource.TMSUCCESS); if (xr.prepare(xid) != XAResource.XA_RDONLY) xr.commit(xid, false); // try again once the xa transaction has been committed. try { rsx.next(); System.out.println("FAIL - rsx's connection not active id (B)" + rsx.getInt(1)); } catch (SQLException sqle) { System.out.println("Expected SQLException " + sqle.getMessage()); } try { rsh.next(); System.out.println("FAIL - rsh's should be closed (B) " + rsx.getInt(1)); } catch (SQLException sqle) { System.out.println("Expected SQLException " + sqle.getMessage()); } System.out.println("Set connection to hold "); conn.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT); System.out.println("CONNECTION(held) HOLDABILITY " + (conn.getHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); xid = getXid(24, (byte) 21, (byte) 01); xr.start(xid, XAResource.TMNOFLAGS); System.out.println("CONNECTION(xa) HOLDABILITY " + (conn.getHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); try { conn.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT); System.out.println("FAIL allowed to set hold mode in xa transaction"); } catch (SQLException sqle) { System.out.println("Expected SQLException(setHoldability) " + sqle.getMessage()); } // try to create a statement with held attributes try { Statement shxa = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); System.out.println("FAIL opened statement with hold cursor attribute in global transaction"); } catch (SQLException sqle) { System.out.println("Expected SQLException (Statement hold) " + sqle.getMessage()); } try { Statement shxa = conn.prepareStatement("select id from hold_30", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); System.out.println("FAIL opened statement with hold cursor attribute in global transaction"); } catch (SQLException sqle) { System.out.println("Expected SQLException (PreparedStatement hold) " + sqle.getMessage()); } try { Statement shxa = conn.prepareCall("CALL XXX.TTT()", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); System.out.println("FAIL opened statement with hold cursor attribute in global transaction"); } catch (SQLException sqle) { System.out.println("Expected SQLException (CallableStatement hold) " + sqle.getMessage()); } // check we cannot use a holdable statement set up in local mode. System.out.println("STATEMENT HOLDABILITY " + (sh.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); try { sh.executeQuery("select id from hold_30"); System.out.println("FAIL used held statement in global transaction"); } catch (SQLException sqle) { System.out.println("Expected SQLException (local Statement hold) " + sqle.getMessage()); } try { sh.execute("select id from hold_30"); System.out.println("FAIL used held statement in global transaction"); } catch (SQLException sqle) { System.out.println("Expected SQLException (local Statement hold) " + sqle.getMessage()); } System.out.println("PREPARED STATEMENT HOLDABILITY " + (psh.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); try { psh.executeQuery(); System.out.println("FAIL used held prepared statement in global transaction"); } catch (SQLException sqle) { System.out.println("Expected SQLException (local PreparedStatement hold) " + sqle.getMessage()); } try { psh.execute(); System.out.println("FAIL used held prepared statement in global transaction"); } catch (SQLException sqle) { System.out.println("Expected SQLException (local PreparedStatement hold) " + sqle.getMessage()); } System.out.println("CALLABLE STATEMENT HOLDABILITY " + (csh.getResultSetHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); try { csh.executeQuery(); System.out.println("FAIL used held callable statement in global transaction"); } catch (SQLException sqle) { System.out.println("Expected SQLException (local CallableStatement hold) " + sqle.getMessage()); } try { csh.execute(); System.out.println("FAIL used held callable statement in global transaction"); } catch (SQLException sqle) { System.out.println("Expected SQLException (local CallableStatement hold) " + sqle.getMessage()); } // but an update works sh.executeUpdate("insert into hold_30 values(10, 'init10')"); xr.end(xid, XAResource.TMSUCCESS); System.out.println("CONNECTION(held) HOLDABILITY " + (conn.getHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT)); conn.close(); System.out.println("PASS XA HOLDABILITY TEST"); } catch (XAException xae) { System.out.println("XAException error code " + xae.errorCode); xae.printStackTrace(System.out); Throwable t = xae.getCause(); if (t instanceof SQLException) JDBCDisplayUtil.ShowSQLException(System.out, (SQLException) t); } catch (SQLException sqle) { JDBCDisplayUtil.ShowSQLException(System.out, sqle); } catch (Throwable t) { t.printStackTrace(System.out); } System.out.flush(); } |
public ResultColumnList getAllResultColumns(String allTableName) | public ResultColumnList getAllResultColumns(TableName allTableName) | public ResultColumnList getAllResultColumns(String allTableName) throws StandardException { /* We need special processing when there is a USING clause. * The resulting table will be the join columns from * the outer table followed by the non-join columns from * left side plus the non-join columns from the right side. */ if (usingClause == null) { return getAllResultColumnsNoUsing(allTableName); } /* Get the logical left side of the join. * This is where the join columns come from. * (For RIGHT OUTER JOIN, the left is the right * and the right is the left and the JOIN is the NIOJ). */ ResultSetNode logicalLeftRS = getLogicalLeftResultSet(); // Get the join columns ResultColumnList joinRCL = logicalLeftRS.getAllResultColumns( null). getJoinColumns(usingClause); // Get the left and right RCLs ResultColumnList leftRCL = leftResultSet.getAllResultColumns(allTableName); ResultColumnList rightRCL = rightResultSet.getAllResultColumns(allTableName); /* Chop the join columns out of the both left and right. * Thanks to the ANSI committee, the join columns * do not belong to either table. */ if (leftRCL != null) { leftRCL.removeJoinColumns(usingClause); } if (rightRCL != null) { rightRCL.removeJoinColumns(usingClause); } /* If allTableName is null, then we want to return the splicing * of the join columns followed by the non-join columns from * the left followed by the non-join columns from the right. * If not, then at most 1 side should match. * NOTE: We need to make sure that the RC's VirtualColumnIds * are correct (1 .. size). */ if (leftRCL == null) { rightRCL.resetVirtualColumnIds(); return rightRCL; } else if (rightRCL == null) { leftRCL.resetVirtualColumnIds(); return leftRCL; } else { /* Both sides are non-null. This should only happen * if allTableName is null. */ if (SanityManager.DEBUG) { if (allTableName != null) { SanityManager.THROWASSERT( "allTableName (" + allTableName + ") expected to be null"); } } joinRCL.destructiveAppend(leftRCL); joinRCL.destructiveAppend(rightRCL); joinRCL.resetVirtualColumnIds(); return joinRCL; } } |
private ResultColumnList getAllResultColumnsNoUsing(String allTableName) | private ResultColumnList getAllResultColumnsNoUsing(TableName allTableName) | private ResultColumnList getAllResultColumnsNoUsing(String allTableName) throws StandardException { ResultColumnList leftRCL = leftResultSet.getAllResultColumns(allTableName); ResultColumnList rightRCL = rightResultSet.getAllResultColumns(allTableName); /* If allTableName is null, then we want to return the spliced * left and right RCLs. If not, then at most 1 side should match. */ if (leftRCL == null) { return rightRCL; } else if (rightRCL == null) { return leftRCL; } else { /* Both sides are non-null. This should only happen * if allTableName is null. */ if (SanityManager.DEBUG) { if (allTableName != null) { SanityManager.THROWASSERT( "allTableName (" + allTableName + ") expected to be null"); } } // Return a spliced copy of the 2 lists ResultColumnList tempList = (ResultColumnList) getNodeFactory().getNode( C_NodeTypes.RESULT_COLUMN_LIST, getContextManager()); tempList.nondestructiveAppend(leftRCL); tempList.nondestructiveAppend(rightRCL); return tempList; } } |
double optimizerEstimatedCost, GeneratedMethod c) throws StandardException | double optimizerEstimatedCost) throws StandardException | public ScrollInsensitiveResultSet(NoPutResultSet source, Activation activation, int resultSetNumber, int sourceRowWidth, double optimizerEstimatedRowCount, double optimizerEstimatedCost, GeneratedMethod c) throws StandardException { super(activation, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost); this.source = source; this.sourceRowWidth = sourceRowWidth; keepAfterCommit = activation.getResultSetHoldability(); maxRows = activation.getMaxRows(); if (SanityManager.DEBUG) { SanityManager.ASSERT(maxRows != -1, "maxRows not expected to be -1"); } closeCleanup = c; constructorTime += getElapsedMillis(beginTime); positionInHashTable = new SQLInteger(); needsRepositioning = false; if (isForUpdate()) { target = ((CursorActivation)activation).getTargetResultSet(); extraColumns = LAST_EXTRA_COLUMN + 1; } else { target = null; extraColumns = 1; } } |
closeCleanup = c; | public ScrollInsensitiveResultSet(NoPutResultSet source, Activation activation, int resultSetNumber, int sourceRowWidth, double optimizerEstimatedRowCount, double optimizerEstimatedCost, GeneratedMethod c) throws StandardException { super(activation, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost); this.source = source; this.sourceRowWidth = sourceRowWidth; keepAfterCommit = activation.getResultSetHoldability(); maxRows = activation.getMaxRows(); if (SanityManager.DEBUG) { SanityManager.ASSERT(maxRows != -1, "maxRows not expected to be -1"); } closeCleanup = c; constructorTime += getElapsedMillis(beginTime); positionInHashTable = new SQLInteger(); needsRepositioning = false; if (isForUpdate()) { target = ((CursorActivation)activation).getTargetResultSet(); extraColumns = LAST_EXTRA_COLUMN + 1; } else { target = null; extraColumns = 1; } } |
|
if (closeCleanup != null) { closeCleanup.invoke(activation); } | public void close() throws StandardException { beginTime = getCurrentTimeMillis(); if ( isOpen ) { if (closeCleanup != null) { closeCleanup.invoke(activation); // let activation tidy up } currentRow = null; source.close(); if (ht != null) { ht.close(); ht = null; } super.close(); } else if (SanityManager.DEBUG) SanityManager.DEBUG("CloseRepeatInfo","Close of ScrollInsensitiveResultSet repeated"); setBeforeFirstRow(); closeTime += getElapsedMillis(beginTime); } |
|
getResourceTests(conn); | private static void readOnlyTest(DataSource ds) throws SQLException { try { Connection conn = ds.getConnection(); Statement s = conn.createStatement(); JDBC.assertFullResultSet( s.executeQuery("SELECT id, e_mail, ok from EMC.CONTACTS ORDER BY 1"), new String[][] { {"0", "[email protected]", null}, {"1", "[email protected]", null}, {"2", "[email protected]", null}, {"3", "[email protected]", null}, {"4", "[email protected]", "0"}, {"5", "[email protected]", "1"}, }); JDBC.assertFullResultSet( s.executeQuery("SELECT id, e_mail, \"emcAddOn\".VALIDCONTACT(e_mail) from EMC.CONTACTS ORDER BY 1"), new String[][] { {"0", "[email protected]", "0"}, {"1", "[email protected]", "0"}, {"2", "[email protected]", "0"}, {"3", "[email protected]", "0"}, {"4", "[email protected]", "0"}, {"5", "[email protected]", "1"}, }); assertStatementError("25502", s, "INSERT INTO EMC.CONTACTS values(3, 'no@is_read_only.gov', NULL)"); assertStatementError("25502", s, "CALL EMC.ADDCONTACT(3, 'really@is_read_only.gov')"); // Disabled due to DERBY-552 // getResourceTests(conn); // Disabled due to DERBY-553 // signersTests(conn); // ensure that a read-only database automatically gets table locking conn.setAutoCommit(false); JDBC.assertDrainResults( s.executeQuery("select * from EMC.CONTACTS WITH RR")); JDBC.assertFullResultSet( s.executeQuery( "select TYPE, MODE, TABLENAME from syscs_diag.lock_table"), new String[][] { {"TABLE", "S", "CONTACTS"}, }); s.close(); conn.rollback(); conn.setAutoCommit(true); conn.close(); } finally { JDBCDataSource.shutdownDatabase(ds); } } |
|
throw StandardException.newException( SQLState.SERVICE_DIRECTORY_CREATE_ERROR, dataDirectory, ioe); | throw StandardException.newException( SQLState.SERVICE_DIRECTORY_CREATE_ERROR, ioe, dataDirectory); | public void boot(boolean create, Properties startParams) throws StandardException { jbmsVersion = Monitor.getMonitor().getEngineVersion(); dataDirectory = startParams.getProperty(PersistentService.ROOT); UUIDFactory uf = Monitor.getMonitor().getUUIDFactory(); identifier = uf.createUUID(); PersistentService ps = Monitor.getMonitor().getServiceType(this); try { storageFactory = ps.getStorageFactoryInstance( true, dataDirectory, startParams.getProperty(Property.STORAGE_TEMP_DIRECTORY, PropertyUtil.getSystemProperty(Property.STORAGE_TEMP_DIRECTORY)), identifier.toANSIidentifier()); } catch( IOException ioe) { if( create) throw StandardException.newException( SQLState.SERVICE_DIRECTORY_CREATE_ERROR, dataDirectory, ioe); else throw StandardException.newException( SQLState.DATABASE_NOT_FOUND, ioe, dataDirectory); } if( storageFactory instanceof WritableStorageFactory) writableStorageFactory = (WritableStorageFactory) storageFactory; actionCode = BOOT_ACTION; try{ AccessController.doPrivileged( this); } catch( PrivilegedActionException pae) { } // BOOT_ACTION does not throw any exceptions. String value = startParams.getProperty(Property.FORCE_DATABASE_LOCK, PropertyUtil.getSystemProperty(Property.FORCE_DATABASE_LOCK)); throwDBlckException = Boolean.valueOf( (value != null ? value.trim() : value)).booleanValue(); if (!isReadOnly()) // read only db, not interested in filelock getJBMSLockOnDB(identifier, uf, dataDirectory); // restoreFrom and createFrom operations also need to know if database is encrypted String dataEncryption = startParams.getProperty(Attribute.DATA_ENCRYPTION); databaseEncrypted = Boolean.valueOf(dataEncryption).booleanValue(); //If the database is being restored/created from backup //the restore the data directory(seg*) from backup String restoreFrom =null; restoreFrom = startParams.getProperty(Attribute.CREATE_FROM); if(restoreFrom == null) restoreFrom = startParams.getProperty(Attribute.RESTORE_FROM); if(restoreFrom == null) restoreFrom = startParams.getProperty(Attribute.ROLL_FORWARD_RECOVERY_FROM); if(restoreFrom !=null) { try{ restoreDataDirectory(restoreFrom); }catch(StandardException se) { releaseJBMSLockOnDB(); throw se; } } logMsg(LINE); long bootTime = System.currentTimeMillis(); logMsg(CheapDateFormatter.formatDate(bootTime) + MessageService.getTextMessage(MessageId.STORE_BOOT_MSG, jbmsVersion, identifier, dataDirectory)); uf = null; CacheFactory cf = (CacheFactory) Monitor.startSystemModule(org.apache.derby.iapi.reference.Module.CacheFactory); int pageCacheSize = getIntParameter( RawStoreFactory.PAGE_CACHE_SIZE_PARAMETER, null, RawStoreFactory.PAGE_CACHE_SIZE_DEFAULT, RawStoreFactory.PAGE_CACHE_SIZE_MINIMUM, RawStoreFactory.PAGE_CACHE_SIZE_MAXIMUM); pageCache = cf.newCacheManager(this, "PageCache", pageCacheSize / 2, pageCacheSize); int fileCacheSize = getIntParameter( "derby.storage.fileCacheSize", null, 100, 2, 100); containerCache = cf.newCacheManager(this, "ContainerCache", fileCacheSize / 2, fileCacheSize); if (create) { String noLog = startParams.getProperty(Property.CREATE_WITH_NO_LOG); inCreateNoLog = (noLog != null && Boolean.valueOf(noLog).booleanValue()); } freezeSemaphore = new Object(); droppedTableStubInfo = new Hashtable(); // If derby.system.durability=test then set flags to disable sync of // data pages at allocation when file is grown, disable sync of data // writes during checkpoint if (Property.DURABILITY_TESTMODE_NO_SYNC.equalsIgnoreCase( PropertyUtil.getSystemProperty(Property.DURABILITY_PROPERTY))) { // - disable syncing of data during checkpoint. dataNotSyncedAtCheckpoint = true; // - disable syncing of data during page allocation. dataNotSyncedAtAllocation = true; // log message stating that derby.system.durability // is set to a mode, where syncs wont be forced and the // possible consequences of setting this mode Monitor.logMessage(MessageService.getTextMessage( MessageId.STORE_DURABILITY_TESTMODE_NO_SYNC, Property.DURABILITY_PROPERTY, Property.DURABILITY_TESTMODE_NO_SYNC)); } fileHandler = new RFResource( this); } // end of boot |
tableName = dd.getTableDescriptor(tableUUID).getName(); | if (tableUUID != null) tableName = dd.getTableDescriptor(tableUUID).getName(); | public TablePermsDescriptor( DataDictionary dd, String grantee, String grantor, UUID tableUUID, String selectPriv, String deletePriv, String insertPriv, String updatePriv, String referencesPriv, String triggerPriv) throws StandardException { super (dd, grantee, grantor); this.tableUUID = tableUUID; this.selectPriv = selectPriv; this.deletePriv = deletePriv; this.insertPriv = insertPriv; this.updatePriv = updatePriv; this.referencesPriv = referencesPriv; this.triggerPriv = triggerPriv; tableName = dd.getTableDescriptor(tableUUID).getName(); } |
if (RowUtil.isRowEmpty(this.init_startKeyValue, (FormatableBitSet) null)) | if (RowUtil.isRowEmpty(this.init_startKeyValue)) | private void initScanParams( DataValueDescriptor[] startKeyValue, int startSearchOperator, Qualifier qualifier[][], DataValueDescriptor[] stopKeyValue, int stopSearchOperator) throws StandardException { // startKeyValue init. this.init_startKeyValue = startKeyValue; if (RowUtil.isRowEmpty(this.init_startKeyValue, (FormatableBitSet) null)) this.init_startKeyValue = null; // startSearchOperator init. this.init_startSearchOperator = startSearchOperator; // qualifier init. if ((qualifier != null) && (qualifier .length == 0)) qualifier = null; this.init_qualifier = qualifier; // stopKeyValue init. this.init_stopKeyValue = stopKeyValue; if (RowUtil.isRowEmpty(this.init_stopKeyValue, (FormatableBitSet) null)) this.init_stopKeyValue = null; // stopSearchOperator init. this.init_stopSearchOperator = stopSearchOperator; // reset the "current" position to starting condition. // RESOLVE (mmm) - "compile" this. scan_position = new BTreeRowPosition(); scan_position.init(); scan_position.current_lock_template = new DataValueDescriptor[this.init_template.length]; scan_position.current_lock_template[this.init_template.length - 1] = scan_position.current_lock_row_loc = (RowLocation) ((RowLocation) init_template[init_template.length - 1]).cloneObject(); // Verify that all columns in start key value, stop key value, and // qualifiers are present in the list of columns described by the // scanColumnList. if (SanityManager.DEBUG) { if (init_scanColumnList != null) { // verify that all columns specified in qualifiers, start // and stop positions are specified in the scanColumnList. FormatableBitSet required_cols; if (qualifier != null) required_cols = RowUtil.getQualifierBitSet(qualifier); else required_cols = new FormatableBitSet(0); // add in start columns if (this.init_startKeyValue != null) { required_cols.grow(this.init_startKeyValue.length); for (int i = 0; i < this.init_startKeyValue.length; i++) required_cols.set(i); } if (this.init_stopKeyValue != null) { required_cols.grow(this.init_stopKeyValue.length); for (int i = 0; i < this.init_stopKeyValue.length; i++) required_cols.set(i); } FormatableBitSet required_cols_and_scan_list = (FormatableBitSet) required_cols.clone(); required_cols_and_scan_list.and(init_scanColumnList); // FormatableBitSet equals requires the two FormatableBitSets to be of same // length. required_cols.grow(init_scanColumnList.size()); if (!required_cols_and_scan_list.equals(required_cols)) { SanityManager.THROWASSERT( "Some column specified in a Btree " + " qualifier/start/stop list is " + "not represented in the scanColumnList." + "\n:required_cols_and_scan_list = " + required_cols_and_scan_list + "\n;required_cols = " + required_cols + "\n;init_scanColumnList = " + init_scanColumnList); } } } } |
if (RowUtil.isRowEmpty(this.init_stopKeyValue, (FormatableBitSet) null)) | if (RowUtil.isRowEmpty(this.init_stopKeyValue)) | private void initScanParams( DataValueDescriptor[] startKeyValue, int startSearchOperator, Qualifier qualifier[][], DataValueDescriptor[] stopKeyValue, int stopSearchOperator) throws StandardException { // startKeyValue init. this.init_startKeyValue = startKeyValue; if (RowUtil.isRowEmpty(this.init_startKeyValue, (FormatableBitSet) null)) this.init_startKeyValue = null; // startSearchOperator init. this.init_startSearchOperator = startSearchOperator; // qualifier init. if ((qualifier != null) && (qualifier .length == 0)) qualifier = null; this.init_qualifier = qualifier; // stopKeyValue init. this.init_stopKeyValue = stopKeyValue; if (RowUtil.isRowEmpty(this.init_stopKeyValue, (FormatableBitSet) null)) this.init_stopKeyValue = null; // stopSearchOperator init. this.init_stopSearchOperator = stopSearchOperator; // reset the "current" position to starting condition. // RESOLVE (mmm) - "compile" this. scan_position = new BTreeRowPosition(); scan_position.init(); scan_position.current_lock_template = new DataValueDescriptor[this.init_template.length]; scan_position.current_lock_template[this.init_template.length - 1] = scan_position.current_lock_row_loc = (RowLocation) ((RowLocation) init_template[init_template.length - 1]).cloneObject(); // Verify that all columns in start key value, stop key value, and // qualifiers are present in the list of columns described by the // scanColumnList. if (SanityManager.DEBUG) { if (init_scanColumnList != null) { // verify that all columns specified in qualifiers, start // and stop positions are specified in the scanColumnList. FormatableBitSet required_cols; if (qualifier != null) required_cols = RowUtil.getQualifierBitSet(qualifier); else required_cols = new FormatableBitSet(0); // add in start columns if (this.init_startKeyValue != null) { required_cols.grow(this.init_startKeyValue.length); for (int i = 0; i < this.init_startKeyValue.length; i++) required_cols.set(i); } if (this.init_stopKeyValue != null) { required_cols.grow(this.init_stopKeyValue.length); for (int i = 0; i < this.init_stopKeyValue.length; i++) required_cols.set(i); } FormatableBitSet required_cols_and_scan_list = (FormatableBitSet) required_cols.clone(); required_cols_and_scan_list.and(init_scanColumnList); // FormatableBitSet equals requires the two FormatableBitSets to be of same // length. required_cols.grow(init_scanColumnList.size()); if (!required_cols_and_scan_list.equals(required_cols)) { SanityManager.THROWASSERT( "Some column specified in a Btree " + " qualifier/start/stop list is " + "not represented in the scanColumnList." + "\n:required_cols_and_scan_list = " + required_cols_and_scan_list + "\n;required_cols = " + required_cols + "\n;init_scanColumnList = " + init_scanColumnList); } } } } |
setTransactionIsolationStmt = null; if (getTransactionIsolationStmt != null) { try { getTransactionIsolationStmt.close(); } catch (SQLException se) { accumulatedExceptions = Utils.accumulateSQLException( se, accumulatedExceptions); } } getTransactionIsolationStmt = null; | private void closeResourcesX() throws SQLException { try { checkForTransactionInProgress(); } catch ( SqlException e ) { throw e.getSQLException(); } resetConnectionAtFirstSql_ = false; // unset indicator of deferred reset SQLException accumulatedExceptions = null; if (setTransactionIsolationStmt != null) { try { setTransactionIsolationStmt.close(); } catch (SQLException se) { accumulatedExceptions = se; } } try { flowClose(); } catch (SqlException e) { accumulatedExceptions = Utils.accumulateSQLException( e.getSQLException(), accumulatedExceptions); } markClosed(); try { agent_.close(); } catch (SqlException e) { throw Utils.accumulateSQLException(e.getSQLException(), accumulatedExceptions); } } |
|
return isolation_; | autoCommit_ = false; if (getTransactionIsolationStmt == null || !(getTransactionIsolationStmt.openOnClient_ && getTransactionIsolationStmt.openOnServer_)) { getTransactionIsolationStmt = createStatementX(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY, holdability()); } rs = getTransactionIsolationStmt.executeQuery("values current isolation"); rs.next(); String isolationStr = rs.getString(1); isolation_ = translateIsolation(isolationStr); rs.close(); | public int getTransactionIsolation() throws SQLException { try { checkForClosedConnection(); if (agent_.loggingEnabled()) { agent_.logWriter_.traceExit(this, "getTransactionIsolation", isolation_); } return isolation_; } catch ( SqlException se ) { throw se.getSQLException(); } } |
finally { autoCommit_ = currentAutoCommit; if(rs != null) rs.close(); } return isolation_; | public int getTransactionIsolation() throws SQLException { try { checkForClosedConnection(); if (agent_.loggingEnabled()) { agent_.logWriter_.traceExit(this, "getTransactionIsolation", isolation_); } return isolation_; } catch ( SqlException se ) { throw se.getSQLException(); } } |
|
public JSQLType getJSQLType ( ) | public JSQLType getJSQLType () throws StandardException | public JSQLType getJSQLType ( ) { if ( jsqlType == null ) { if ( value.isParameterNode() ) { jsqlType = ((ParameterNode) value).getJSQLType(); } else { DataTypeDescriptor dtd = value.getTypeServices(); if (dtd != null) jsqlType = new JSQLType( dtd ); } } return jsqlType; } |
if ( value.isParameterNode() ) | if ( value.requiresTypeFromContext()) | public JSQLType getJSQLType ( ) { if ( jsqlType == null ) { if ( value.isParameterNode() ) { jsqlType = ((ParameterNode) value).getJSQLType(); } else { DataTypeDescriptor dtd = value.getTypeServices(); if (dtd != null) jsqlType = new JSQLType( dtd ); } } return jsqlType; } |
jsqlType = ((ParameterNode) value).getJSQLType(); | ParameterNode pn; if (value instanceof UnaryOperatorNode) pn = ((UnaryOperatorNode)value).getParameterOperand(); else pn = (ParameterNode) (value); jsqlType = pn.getJSQLType(); | public JSQLType getJSQLType ( ) { if ( jsqlType == null ) { if ( value.isParameterNode() ) { jsqlType = ((ParameterNode) value).getJSQLType(); } else { DataTypeDescriptor dtd = value.getTypeServices(); if (dtd != null) jsqlType = new JSQLType( dtd ); } } return jsqlType; } |
throws StandardException | public String getJavaTypeName() { JSQLType myType = getJSQLType(); if ( myType == null ) { return ""; } else { return mapToTypeID( myType ).getCorrespondingJavaTypeName(); } } |
|
if (!JDBC.classpathHasXalanAndJAXP()) | if (!XML.classpathHasXalanAndJAXP()) | public static Test suite() { TestSuite suite = new TestSuite("XML Missing Classes Suite"); if (!JDBC.classpathHasXalanAndJAXP()) { // Run this test in embedded and client modes. suite.addTest(TestConfiguration.defaultSuite( XMLMissingClassesTest.class)); } return suite; } |
private String[] getContainerNames() | private synchronized String[] getContainerNames() | private String[] getContainerNames() { actionCode = GET_CONTAINER_NAMES_ACTION; try{ return (String[]) AccessController.doPrivileged( this); } catch( PrivilegedActionException pae){ return null;} } |
execCmdDumpResults(new String[]{IjCmd,(altExtinDir + sep + SqlDir + sep + jccSqlFile)}); execCmdDumpResults(new String[]{IjCmd,(SqlDir + sep + jccSqlFile)}); | ExecProcUtil.execCmdDumpResults(new String[]{IjCmd,(altExtinDir + sep + SqlDir + sep + jccSqlFile)},vCmd,bos); ExecProcUtil.execCmdDumpResults(new String[]{IjCmd,(SqlDir + sep + jccSqlFile)},vCmd,bos); | public static void main (String args[]) throws Exception { if ((System.getProperty("java.vm.name") != null) && System.getProperty("java.vm.name").equals("J9")) jvm = jvm.getJvm("j9_13"); else jvm = jvm.getJvm("currentjvm"); // ensure compatibility vCmd = jvm.getCommandLine(); sep = System.getProperty("file.separator"); try { /************************************************************ * Test comments in front of select's doesn't cause problems ************************************************************/ //create wombat database NetworkServerControl server = new NetworkServerControl(); System.out.println("Testing various ij connections and comments in front of selects"); // first, we have to massage the .sql file to replace localhost, if // there is a system property set. String hostName=TestUtil.getHostName(); if (TestUtil.isJCCFramework()){ // use jccSqlfile if (!hostName.equals("localhost")) massageSqlFile(hostName,jccSqlFile); if (useAltExtinDir) execCmdDumpResults(new String[]{IjCmd,(altExtinDir + sep + SqlDir + sep + jccSqlFile)}); execCmdDumpResults(new String[]{IjCmd,(SqlDir + sep + jccSqlFile)}); } else { // Derby Client // use clientSqlFile if(!hostName.equals("localhost")) { massageSqlFile(hostName,clientSqlFile); if (useAltExtinDir) execCmdDumpResults(new String[]{IjCmd,(altExtinDir + sep + SqlDir + sep + clientSqlFile)}); } execCmdDumpResults(new String[]{IjCmd,(SqlDir + sep + clientSqlFile)}); } System.out.println("End test"); } catch (Exception e) { e.printStackTrace(); } } |
execCmdDumpResults(new String[]{IjCmd,(altExtinDir + sep + SqlDir + sep + clientSqlFile)}); | ExecProcUtil.execCmdDumpResults(new String[]{IjCmd,(altExtinDir + sep + SqlDir + sep + clientSqlFile)},vCmd,bos); | public static void main (String args[]) throws Exception { if ((System.getProperty("java.vm.name") != null) && System.getProperty("java.vm.name").equals("J9")) jvm = jvm.getJvm("j9_13"); else jvm = jvm.getJvm("currentjvm"); // ensure compatibility vCmd = jvm.getCommandLine(); sep = System.getProperty("file.separator"); try { /************************************************************ * Test comments in front of select's doesn't cause problems ************************************************************/ //create wombat database NetworkServerControl server = new NetworkServerControl(); System.out.println("Testing various ij connections and comments in front of selects"); // first, we have to massage the .sql file to replace localhost, if // there is a system property set. String hostName=TestUtil.getHostName(); if (TestUtil.isJCCFramework()){ // use jccSqlfile if (!hostName.equals("localhost")) massageSqlFile(hostName,jccSqlFile); if (useAltExtinDir) execCmdDumpResults(new String[]{IjCmd,(altExtinDir + sep + SqlDir + sep + jccSqlFile)}); execCmdDumpResults(new String[]{IjCmd,(SqlDir + sep + jccSqlFile)}); } else { // Derby Client // use clientSqlFile if(!hostName.equals("localhost")) { massageSqlFile(hostName,clientSqlFile); if (useAltExtinDir) execCmdDumpResults(new String[]{IjCmd,(altExtinDir + sep + SqlDir + sep + clientSqlFile)}); } execCmdDumpResults(new String[]{IjCmd,(SqlDir + sep + clientSqlFile)}); } System.out.println("End test"); } catch (Exception e) { e.printStackTrace(); } } |
execCmdDumpResults(new String[]{IjCmd,(SqlDir + sep + clientSqlFile)}); | ExecProcUtil.execCmdDumpResults(new String[]{IjCmd,(SqlDir + sep + clientSqlFile)},vCmd,bos); | public static void main (String args[]) throws Exception { if ((System.getProperty("java.vm.name") != null) && System.getProperty("java.vm.name").equals("J9")) jvm = jvm.getJvm("j9_13"); else jvm = jvm.getJvm("currentjvm"); // ensure compatibility vCmd = jvm.getCommandLine(); sep = System.getProperty("file.separator"); try { /************************************************************ * Test comments in front of select's doesn't cause problems ************************************************************/ //create wombat database NetworkServerControl server = new NetworkServerControl(); System.out.println("Testing various ij connections and comments in front of selects"); // first, we have to massage the .sql file to replace localhost, if // there is a system property set. String hostName=TestUtil.getHostName(); if (TestUtil.isJCCFramework()){ // use jccSqlfile if (!hostName.equals("localhost")) massageSqlFile(hostName,jccSqlFile); if (useAltExtinDir) execCmdDumpResults(new String[]{IjCmd,(altExtinDir + sep + SqlDir + sep + jccSqlFile)}); execCmdDumpResults(new String[]{IjCmd,(SqlDir + sep + jccSqlFile)}); } else { // Derby Client // use clientSqlFile if(!hostName.equals("localhost")) { massageSqlFile(hostName,clientSqlFile); if (useAltExtinDir) execCmdDumpResults(new String[]{IjCmd,(altExtinDir + sep + SqlDir + sep + clientSqlFile)}); } execCmdDumpResults(new String[]{IjCmd,(SqlDir + sep + clientSqlFile)}); } System.out.println("End test"); } catch (Exception e) { e.printStackTrace(); } } |
tempPos -= (shiftSize - 1); for (int j = 0; j < bytesToShift; j++) { buffer_[tempPos + shiftSize] = buffer_[tempPos]; tempPos--; } tempPos += (shiftSize + 1); | tempPos -= (bytesToShift - 2); System.arraycopy(buffer_, tempPos - shiftSize, buffer_, tempPos , bytesToShift); | private final void compressBLayerData(int continueDssHeaderCount) throws org.apache.derby.client.am.DisconnectException { int tempPos = 0; // jump to the last continuation header. for (int i = 0; i < continueDssHeaderCount; i++) { // the first may be less than the size of a full dss if (i == 0) { // only jump by the number of bytes remaining in the current dss tempPos = pos_ + dssLength_; } else { // all other jumps are for a full continued dss tempPos += 32767; } } // for each of the dss headers to remove, // read out the continuation header and increment the dss length by the // size of the conitnation bytes, then shift the continuation data as needed. int shiftSize = 0; int bytesToShift = 0; int continueHeaderLength = 0; int newDssLength = 0; for (int i = 0; i < continueDssHeaderCount; i++) { continueHeaderLength = ((buffer_[tempPos] & 0xFF) << 8) + ((buffer_[tempPos + 1] & 0xFF) << 0); if (i == 0) { // if this is the last one (farthest down stream and first to strip out) if ((continueHeaderLength & 0x8000) == 0x8000) { // the last dss header is again continued continueHeaderLength = 32767; dssIsContinued_ = true; } else { // the last dss header was not contiued so update continue state flag dssIsContinued_ = false; } // the very first shift size is 2 shiftSize = 2; } else { // already removed the last header so make sure the chaining flag is on if ((continueHeaderLength & 0x8000) == 0x8000) { continueHeaderLength = 32767; } else { // this is a syntax error but not really certain which one. // for now pick 0x02 which is Dss header Length does not match the number // of bytes of data found. doSyntaxrmSemantics(CodePoint.SYNERRCD_DSS_LENGTH_BYTE_NUMBER_MISMATCH); } // increase the shift size by 2 shiftSize += 2; } // it is a syntax error if the dss continuation is less than or equal to two if (continueHeaderLength <= 2) { doSyntaxrmSemantics(CodePoint.SYNERRCD_DSS_CONT_LESS_OR_EQUAL_2); } newDssLength += (continueHeaderLength - 2); // calculate the number of bytes to shift if (i != (continueDssHeaderCount - 1)) { bytesToShift = 32767; } else { bytesToShift = dssLength_; } tempPos -= (shiftSize - 1); // perform the compress for (int j = 0; j < bytesToShift; j++) { buffer_[tempPos + shiftSize] = buffer_[tempPos]; tempPos--; } tempPos += (shiftSize + 1); } // reposition the start of the data after the final dss shift. pos_ = tempPos; dssLength_ = dssLength_ + newDssLength; } |
case 9: String lStringA32672 = new String(Formatters.repeatChar("a",32672)); String lStringB32672 = new String(Formatters.repeatChar("b",32672)); String lStringC32672 = new String(Formatters.repeatChar("c",32672)); String lStringD32672 = new String(Formatters.repeatChar("d",32672)); insertInBig(conn, lStringA32672, lStringB32672, lStringC32672, lStringD32672); break; | public static void bigTestData(int i) throws SQLException { Connection conn = DriverManager.getConnection("jdbc:default:connection"); switch (i) { case 1: String largeStringA10000 = new String(Formatters.repeatChar("a",10000)); String largeStringB10000 = new String(Formatters.repeatChar("b",10000)); String largeStringC10000 = new String(Formatters.repeatChar("c",10000)); String largeStringD10000 = new String(Formatters.repeatChar("d",10000)); insertInBig(conn, largeStringA10000, largeStringB10000, largeStringC10000, largeStringD10000); break; case 2: largeStringA10000 = new String(Formatters.repeatChar("e",10000)); largeStringB10000 = new String(Formatters.repeatChar("f",10000)); largeStringC10000 = new String(Formatters.repeatChar("g",10000)); largeStringD10000 = new String(Formatters.repeatChar("h",10000)); insertInBig(conn, largeStringA10000, largeStringB10000, largeStringC10000, largeStringD10000); break; case 3: largeStringA10000 = new String(Formatters.repeatChar("i",10000)); largeStringB10000 = new String(Formatters.repeatChar("j",10000)); largeStringC10000 = new String(Formatters.repeatChar("k",10000)); largeStringD10000 = new String(Formatters.repeatChar("l",10000)); insertInBig(conn, largeStringA10000, largeStringB10000, largeStringC10000, largeStringD10000); break; case 4: largeStringA10000 = new String(Formatters.repeatChar("m",10000)); largeStringB10000 = new String(Formatters.repeatChar("n",10000)); largeStringC10000 = new String(Formatters.repeatChar("o",10000)); largeStringD10000 = new String(Formatters.repeatChar("p",10000)); insertInBig(conn, largeStringA10000, largeStringB10000, largeStringC10000, largeStringD10000); break; case 5: String largeStringA30000 = new String(Formatters.repeatChar("a",30000)); String largeStringB2752 = new String(Formatters.repeatChar("b",2752)); PreparedStatement ps = conn.prepareStatement("insert into big values (?, ?)"); ps.setString(1, largeStringA30000); ps.setString(2, largeStringB2752); ps.executeUpdate(); ps.close(); break; case 6: largeStringA30000 = new String(Formatters.repeatChar("a",30000)); String largeStringB2750 = new String(Formatters.repeatChar("b",2750)); ps = conn.prepareStatement("insert into big values (?, ?)"); ps.setString(1, largeStringA30000); ps.setString(2, largeStringB2750); ps.executeUpdate(); ps.close(); break; case 7: String largeStringA40000 = new String(Formatters.repeatChar("a",40000)); ps = conn.prepareStatement("insert into big values (?)"); ps.setString(1, largeStringA40000); ps.executeUpdate(); ps.close(); break; case 8: largeStringA40000 = new String(Formatters.repeatChar("a",40000)); String largeStringB40000 = new String(Formatters.repeatChar("b",40000)); String largeStringC40000 = new String(Formatters.repeatChar("c",40000)); ps = conn.prepareStatement("insert into big values (?, ?, ?)"); ps.setString(1, largeStringA40000); ps.setString(2, largeStringB40000); ps.setString(3, largeStringC40000); ps.executeUpdate(); largeStringA40000 = new String(Formatters.repeatChar("d",40000)); largeStringB40000 = new String(Formatters.repeatChar("e",40000)); largeStringC40000 = new String(Formatters.repeatChar("f",40000)); ps.setString(1, largeStringA40000); ps.setString(2, largeStringB40000); ps.setString(3, largeStringC40000); ps.executeUpdate(); ps.close(); break; } conn.close(); } |
|
dd.dropAllTableAndColPermDescriptors(tableId, tc); | public void executeConstantAction( Activation activation ) throws StandardException { TableDescriptor td; UUID tableID; ConglomerateDescriptor[] cds; LanguageConnectionContext lcc = activation.getLanguageConnectionContext(); DataDictionary dd = lcc.getDataDictionary(); DependencyManager dm = dd.getDependencyManager(); TransactionController tc = lcc.getTransactionExecute(); if ((sd != null) && sd.getSchemaName().equals(SchemaDescriptor.STD_DECLARED_GLOBAL_TEMPORARY_TABLES_SCHEMA_NAME)) { td = lcc.getTableDescriptorForDeclaredGlobalTempTable(tableName); //check if this is a temp table before checking data dictionary if (td == null) //td null here means it is not a temporary table. Look for table in physical SESSION schema td = dd.getTableDescriptor(tableName, sd); if (td == null) //td null means tableName is not a temp table and it is not a physical table in SESSION schema { throw StandardException.newException(SQLState.LANG_TABLE_NOT_FOUND_DURING_EXECUTION, fullTableName); } if (td.getTableType() == TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE) { dm.invalidateFor(td, DependencyManager.DROP_TABLE, lcc); tc.dropConglomerate(td.getHeapConglomerateId()); lcc.dropDeclaredGlobalTempTable(tableName); return; } } /* Lock the table before we access the data dictionary * to prevent deadlocks. * * Note that for DROP TABLE replayed at Targets during REFRESH, * the conglomerateNumber will be 0. That's ok. During REFRESH, * we don't need to lock the conglomerate. */ if ( conglomerateNumber != 0 ) { lockTableForDDL(tc, conglomerateNumber, true); } /* ** Inform the data dictionary that we are about to write to it. ** There are several calls to data dictionary "get" methods here ** that might be done in "read" mode in the data dictionary, but ** it seemed safer to do this whole operation in "write" mode. ** ** We tell the data dictionary we're done writing at the end of ** the transaction. */ dd.startWriting(lcc); /* Get the table descriptor. */ td = dd.getTableDescriptor(tableId); if (td == null) { throw StandardException.newException(SQLState.LANG_TABLE_NOT_FOUND_DURING_EXECUTION, fullTableName); } /* Get an exclusive table lock on the table. */ long heapId = td.getHeapConglomerateId(); lockTableForDDL(tc, heapId, true); /* Drop the triggers */ GenericDescriptorList tdl = dd.getTriggerDescriptors(td); Enumeration descs = tdl.elements(); while (descs.hasMoreElements()) { TriggerDescriptor trd = (TriggerDescriptor) descs.nextElement(); DropTriggerConstantAction.dropTriggerDescriptor(lcc, dm, dd, tc, trd, activation); } /* Drop all defaults */ ColumnDescriptorList cdl = td.getColumnDescriptorList(); int cdlSize = cdl.size(); for (int index = 0; index < cdlSize; index++) { ColumnDescriptor cd = (ColumnDescriptor) cdl.elementAt(index); // If column has a default we drop the default and // any dependencies if (cd.getDefaultInfo() != null) { DefaultDescriptor defaultDesc = cd.getDefaultDescriptor(dd); dm.clearDependencies(lcc, defaultDesc); } } /* Drop the columns */ dd.dropAllColumnDescriptors(tableId, tc); /* Drop the constraints */ dropAllConstraintDescriptors(td, activation); /* ** Drop all the conglomerates. Drop the heap last, because the ** store needs it for locking the indexes when they are dropped. */ cds = td.getConglomerateDescriptors(); long[] dropped = new long[cds.length - 1]; int numDropped = 0; for (int index = 0; index < cds.length; index++) { ConglomerateDescriptor cd = cds[index]; /* if it's for an index, since similar indexes share one * conglomerate, we only drop the conglomerate once */ if (cd.getConglomerateNumber() != heapId) { long thisConglom = cd.getConglomerateNumber(); int i; for (i = 0; i < numDropped; i++) { if (dropped[i] == thisConglom) break; } if (i == numDropped) // not dropped { dropped[numDropped++] = thisConglom; tc.dropConglomerate(thisConglom); dd.dropStatisticsDescriptors(td.getUUID(), cd.getUUID(), tc); } } } /* Prepare all dependents to invalidate. (This is there chance * to say that they can't be invalidated. For example, an open * cursor referencing a table/view that the user is attempting to * drop.) If no one objects, then invalidate any dependent objects. * We check for invalidation before we drop the table descriptor * since the table descriptor may be looked up as part of * decoding tuples in SYSDEPENDS. */ dm.invalidateFor(td, DependencyManager.DROP_TABLE, lcc); /* Drop the table */ dd.dropTableDescriptor(td, sd, tc); /* Drop the conglomerate descriptors */ dd.dropAllConglomerateDescriptors(td, tc); /* Drop the store element at last, to prevent dangling reference * for open cursor, beetle 4393. */ tc.dropConglomerate(heapId); } |
|
newHighestPage = CompressedNumber.readInt(in); num_pages_truncated = CompressedNumber.readInt(in); | if( !(this instanceof CompressSpacePageOperation10_2) ) { newHighestPage = in.readInt(); num_pages_truncated = CompressedNumber.readInt(in); } | public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); newHighestPage = CompressedNumber.readInt(in); num_pages_truncated = CompressedNumber.readInt(in); } |
CompressedNumber.writeInt(out, newHighestPage); CompressedNumber.writeInt(out, num_pages_truncated); | if( !(this instanceof CompressSpacePageOperation10_2) ) { out.writeInt(newHighestPage); CompressedNumber.writeInt(out, num_pages_truncated); } | public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); CompressedNumber.writeInt(out, newHighestPage); CompressedNumber.writeInt(out, num_pages_truncated); } |
public ScalarAggregateResultSet(NoPutResultSet s, | ScalarAggregateResultSet(NoPutResultSet s, | public ScalarAggregateResultSet(NoPutResultSet s, boolean isInSortedOrder, int aggregateItem, Activation a, GeneratedMethod ra, int resultSetNumber, boolean singleInputRow, double optimizerEstimatedRowCount, double optimizerEstimatedCost, GeneratedMethod c) throws StandardException { super(s, aggregateItem, a, ra, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost, c); this.isInSortedOrder = isInSortedOrder; // source expected to be non-null, mystery stress test bug // - sometimes get NullPointerException in openCore(). if (SanityManager.DEBUG) { SanityManager.ASSERT(source != null, "SARS(), source expected to be non-null"); } sortTemplateRow = getExecutionFactory().getIndexableRow((ExecRow) rowAllocator.invoke(activation)); this.singleInputRow = singleInputRow; if (SanityManager.DEBUG) { SanityManager.DEBUG("AggregateTrace","execution time: "+ a.getPreparedStatement().getSavedObject(aggregateItem)); } constructorTime += getElapsedMillis(beginTime); } |
double optimizerEstimatedCost, GeneratedMethod c) throws StandardException | double optimizerEstimatedCost) throws StandardException | public ScalarAggregateResultSet(NoPutResultSet s, boolean isInSortedOrder, int aggregateItem, Activation a, GeneratedMethod ra, int resultSetNumber, boolean singleInputRow, double optimizerEstimatedRowCount, double optimizerEstimatedCost, GeneratedMethod c) throws StandardException { super(s, aggregateItem, a, ra, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost, c); this.isInSortedOrder = isInSortedOrder; // source expected to be non-null, mystery stress test bug // - sometimes get NullPointerException in openCore(). if (SanityManager.DEBUG) { SanityManager.ASSERT(source != null, "SARS(), source expected to be non-null"); } sortTemplateRow = getExecutionFactory().getIndexableRow((ExecRow) rowAllocator.invoke(activation)); this.singleInputRow = singleInputRow; if (SanityManager.DEBUG) { SanityManager.DEBUG("AggregateTrace","execution time: "+ a.getPreparedStatement().getSavedObject(aggregateItem)); } constructorTime += getElapsedMillis(beginTime); } |
super(s, aggregateItem, a, ra, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost, c); | super(s, aggregateItem, a, ra, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost); | public ScalarAggregateResultSet(NoPutResultSet s, boolean isInSortedOrder, int aggregateItem, Activation a, GeneratedMethod ra, int resultSetNumber, boolean singleInputRow, double optimizerEstimatedRowCount, double optimizerEstimatedCost, GeneratedMethod c) throws StandardException { super(s, aggregateItem, a, ra, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost, c); this.isInSortedOrder = isInSortedOrder; // source expected to be non-null, mystery stress test bug // - sometimes get NullPointerException in openCore(). if (SanityManager.DEBUG) { SanityManager.ASSERT(source != null, "SARS(), source expected to be non-null"); } sortTemplateRow = getExecutionFactory().getIndexableRow((ExecRow) rowAllocator.invoke(activation)); this.singleInputRow = singleInputRow; if (SanityManager.DEBUG) { SanityManager.DEBUG("AggregateTrace","execution time: "+ a.getPreparedStatement().getSavedObject(aggregateItem)); } constructorTime += getElapsedMillis(beginTime); } |
if (closeCleanup != null) { closeCleanup.invoke(activation); } | public void close() throws StandardException { beginTime = getCurrentTimeMillis(); if ( isOpen ) { // we don't want to keep around a pointer to the // row ... so it can be thrown away. // REVISIT: does this need to be in a finally // block, to ensure that it is executed? clearCurrentRow(); if (closeCleanup != null) { closeCleanup.invoke(activation); // let activation tidy up } countOfRows = 0; currentRow = null; sourceExecIndexRow = null; source.close(); super.close(); } else if (SanityManager.DEBUG) SanityManager.DEBUG("CloseRepeatInfo","Close of SortResultSet repeated"); closeTime += getElapsedMillis(beginTime); nextSatisfied = false; isOpen = false; } |
|
currentRow = null; | public void close() throws StandardException { beginTime = getCurrentTimeMillis(); if ( isOpen ) { // we don't want to keep around a pointer to the // row ... so it can be thrown away. // REVISIT: does this need to be in a finally // block, to ensure that it is executed? clearCurrentRow(); if (closeCleanup != null) { closeCleanup.invoke(activation); // let activation tidy up } countOfRows = 0; currentRow = null; sourceExecIndexRow = null; source.close(); super.close(); } else if (SanityManager.DEBUG) SanityManager.DEBUG("CloseRepeatInfo","Close of SortResultSet repeated"); closeTime += getElapsedMillis(beginTime); nextSatisfied = false; isOpen = false; } |
|
dd.updateSYSCOLPERMSforAddColumnToUserTable(td.getUUID(), tc); | private void addNewColumnToTable(Activation activation, int ix) throws StandardException { LanguageConnectionContext lcc = activation.getLanguageConnectionContext(); DataDictionary dd = lcc.getDataDictionary(); DependencyManager dm = dd.getDependencyManager(); TransactionController tc = lcc.getTransactionExecute(); ColumnDescriptor columnDescriptor = td.getColumnDescriptor(columnInfo[ix].name); DataValueDescriptor storableDV; int colNumber = td.getMaxColumnID() + ix; DataDescriptorGenerator ddg = dd.getDataDescriptorGenerator(); /* We need to verify that the table does not have an existing * column with the same name before we try to add the new * one as addColumnDescriptor() is a void method. */ if (columnDescriptor != null) { throw StandardException.newException( SQLState.LANG_OBJECT_ALREADY_EXISTS_IN_OBJECT, columnDescriptor.getDescriptorType(), columnInfo[ix].name, td.getDescriptorType(), td.getQualifiedName()); } if (columnInfo[ix].defaultValue != null) storableDV = columnInfo[ix].defaultValue; else storableDV = columnInfo[ix].dataType.getNull(); // Add the column to the conglomerate.(Column ids in store are 0-based) tc.addColumnToConglomerate(td.getHeapConglomerateId(), colNumber, storableDV); UUID defaultUUID = columnInfo[ix].newDefaultUUID; /* Generate a UUID for the default, if one exists * and there is no default id yet. */ if (columnInfo[ix].defaultInfo != null && defaultUUID == null) { defaultUUID = dd.getUUIDFactory().createUUID(); } // Add the column to syscolumns. // Column ids in system tables are 1-based columnDescriptor = new ColumnDescriptor( columnInfo[ix].name, colNumber + 1, columnInfo[ix].dataType, columnInfo[ix].defaultValue, columnInfo[ix].defaultInfo, td, defaultUUID, columnInfo[ix].autoincStart, columnInfo[ix].autoincInc ); dd.addDescriptor(columnDescriptor, td, DataDictionary.SYSCOLUMNS_CATALOG_NUM, false, tc); // now add the column to the tables column descriptor list. td.getColumnDescriptorList().add(columnDescriptor); if (columnDescriptor.isAutoincrement()) { updateNewAutoincrementColumn(activation, columnInfo[ix].name, columnInfo[ix].autoincStart, columnInfo[ix].autoincInc); } // Update the new column to its default, if it has a non-null default if (columnDescriptor.hasNonNullDefault()) { updateNewColumnToDefault(activation, columnInfo[ix].name, columnInfo[ix].defaultInfo.getDefaultText(), lcc); } } |
|
if (agent_.loggingEnabled()) { agent_.logWriter_.traceExit(this, "getBoolean", result); } | public boolean getBoolean(int column) throws SQLException { try { closeCloseFilterInputStream(); if (agent_.loggingEnabled()) { agent_.logWriter_.traceEntry(this, "getBoolean", column); } checkGetterPreconditions(column); boolean result = false; if (wasNonNullSensitiveUpdate(column) || isOnInsertRow_) { if (isOnInsertRow_ && updatedColumns_[column - 1] == null) { result = false; } else { result = agent_.crossConverters_.setBooleanFromObject( updatedColumns_[column - 1], resultSetMetaData_.types_[column - 1]); } } else { result = isNull(column) ? false : cursor_.getBoolean(column); } setWasNull(column); // Placed close to the return to minimize risk of thread interference return result; } catch ( SqlException se ) { throw se.getSQLException(); } } |
|
markClosed(); connection_.CommitAndRollbackListeners_.remove(this); | markClosed(true); | public final void closeX() throws SqlException { if (!openOnClient_) { return; } try { if (openOnServer_) { flowCloseAndAutoCommitIfNotAutoCommitted(); } else { statement_.resultSetCommitting(this); } } finally { markClosed(); connection_.CommitAndRollbackListeners_.remove(this); } if (statement_.openOnClient_ && statement_.isCatalogQuery_) { statement_.closeX(); } nullDataForGC(); } |
openOnClient_ = false; openOnServer_ = false; statement_.resetCursorNameAndRemoveFromWhereCurrentOfMappings(); statement_.removeClientCursorNameFromCache(); markPositionedUpdateDeletePreparedStatementsClosed(); | markClosed(false); | void markClosed() { openOnClient_ = false; openOnServer_ = false; statement_.resetCursorNameAndRemoveFromWhereCurrentOfMappings(); // for SELECT...FOR UPDATE queries statement_.removeClientCursorNameFromCache(); markPositionedUpdateDeletePreparedStatementsClosed(); } |
childResult = childResult.modifyAccessPaths(); | childResult = childResult.modifyAccessPaths(restrictionList); | public Optimizable modifyAccessPath(JBitSet outerTables) throws StandardException { boolean origChildOptimizable = true; /* It is okay to optimize most nodes multiple times. However, * modifying the access path is something that should only be done * once per node. One reason for this is that the predicate list * will be empty after the 1st call, and we assert that it should * be non-empty. Multiple calls to modify the access path can * occur when there is a non-flattenable FromSubquery (or view). */ if (accessPathModified) { return this; } /* ** Do nothing if the child result set is not optimizable, as there ** can be nothing to modify. */ boolean alreadyPushed = false; if ( ! (childResult instanceof Optimizable)) { // Remember that the original child was not Optimizable origChildOptimizable = false; childResult = childResult.modifyAccessPaths(); /* Mark this node as having the truly ... for * the underlying tree. */ hasTrulyTheBestAccessPath = true; /* Replace this PRN with a HRN if we are doing a hash join */ if (trulyTheBestAccessPath.getJoinStrategy().isHashJoin()) { if (SanityManager.DEBUG) { SanityManager.ASSERT(restrictionList != null, "restrictionList expected to be non-null"); SanityManager.ASSERT(restrictionList.size() != 0, "restrictionList.size() expected to be non-zero"); } /* We're doing a hash join on an arbitary result set. * We need to get the table number from this node when * dividing up the restriction list for a hash join. * We need to explicitly remember this. */ getTableNumberHere = true; } else { /* We consider materialization into a temp table as a last step. * Currently, we only materialize VTIs that are inner tables * and can't be instantiated multiple times. In the future we * will consider materialization as a cost based option. */ return (Optimizable) considerMaterialization(outerTables); } } /* If the child is not a FromBaseTable, then we want to * keep going down the tree. (Nothing to do at this node.) */ else if (!(childResult instanceof FromBaseTable)) { /* Make sure that we have a join strategy */ if (trulyTheBestAccessPath.getJoinStrategy() == null) { trulyTheBestAccessPath = (AccessPathImpl) ((Optimizable) childResult).getTrulyTheBestAccessPath(); } // If the childResult is a SetOperatorNode (esp. a UnionNode), // then it's possible that predicates in our restrictionList are // supposed to be pushed further down the tree (as of DERBY-805). // We passed the restrictionList down when we optimized the child // so that the relevant predicates could be pushed further as part // of the optimization process; so now that we're finalizing the // paths, we need to do the same thing: i.e. pass restrictionList // down so that the predicates that need to be pushed further // _can_ be pushed further. if (childResult instanceof SetOperatorNode) { childResult = (ResultSetNode) ((SetOperatorNode) childResult).modifyAccessPath( outerTables, restrictionList); // Take note of the fact that we already pushed predicates // as part of the modifyAccessPaths call. This is necessary // because there may still be predicates in restrictionList // that we intentionally decided not to push (ex. if we're // going to do hash join then we chose to not push the join // predicates). Whatever the reason for not pushing the // predicates, we have to make sure we don't inadvertenly // push them later (esp. as part of the "pushUsefulPredicates" // call below). alreadyPushed = true; } else { childResult = (ResultSetNode) ((FromTable) childResult). modifyAccessPath(outerTables); } } // If we're doing a hash join with _this_ PRN (as opposed to // with this PRN's child) then we don't attempt to push // predicates down. There are two reasons for this: 1) // we don't want to push the equijoin predicate that is // required for the hash join, and 2) if we're doing a // hash join then we're going to materialize this node, // but if we push predicates before materialization, we // can end up with incorrect results (esp. missing rows). // So don't push anything in this case. boolean hashJoinWithThisPRN = hasTrulyTheBestAccessPath && (trulyTheBestAccessPath.getJoinStrategy() != null) && trulyTheBestAccessPath.getJoinStrategy().isHashJoin(); if ((restrictionList != null) && !alreadyPushed && !hashJoinWithThisPRN) { restrictionList.pushUsefulPredicates((Optimizable) childResult); } /* ** The optimizer's decision on the access path for the child result ** set may require the generation of extra result sets. For ** example, if it chooses an index, we need an IndexToBaseRowNode ** above the FromBaseTable (and the FromBaseTable has to change ** its column list to match that of the index. */ if (origChildOptimizable) { childResult = childResult.changeAccessPath(); } accessPathModified = true; /* ** Replace this PRN with a HTN if a hash join ** is being done at this node. (Hash join on a scan ** is a special case and is handled at the FBT.) */ if (trulyTheBestAccessPath.getJoinStrategy() != null && trulyTheBestAccessPath.getJoinStrategy().isHashJoin()) { return replaceWithHashTableNode(); } /* We consider materialization into a temp table as a last step. * Currently, we only materialize VTIs that are inner tables * and can't be instantiated multiple times. In the future we * will consider materialization as a cost based option. */ return (Optimizable) considerMaterialization(outerTables); } |
RemapCRsVisitor rcrv = new RemapCRsVisitor(true); ((Predicate) optimizablePredicate).getAndNode().accept(rcrv); | Predicate pred = (Predicate)optimizablePredicate; if (!pred.remapScopedPred()) { RemapCRsVisitor rcrv = new RemapCRsVisitor(true); pred.getAndNode().accept(rcrv); } | public boolean pushOptPredicate(OptimizablePredicate optimizablePredicate) throws StandardException { if (SanityManager.DEBUG) { SanityManager.ASSERT(optimizablePredicate instanceof Predicate, "optimizablePredicate expected to be instanceof Predicate"); SanityManager.ASSERT(! optimizablePredicate.hasSubquery() && ! optimizablePredicate.hasMethodCall(), "optimizablePredicate either has a subquery or a method call"); } /* Add the matching predicate to the restrictionList */ if (restrictionList == null) { restrictionList = (PredicateList) getNodeFactory().getNode( C_NodeTypes.PREDICATE_LIST, getContextManager()); } restrictionList.addPredicate((Predicate) optimizablePredicate); /* Remap all of the ColumnReferences to point to the * source of the values. */ RemapCRsVisitor rcrv = new RemapCRsVisitor(true); ((Predicate) optimizablePredicate).getAndNode().accept(rcrv); return true; } |
{ length += offset; if (length > bytes.length) { if (SanityManager.DEBUG) { agent.trace("DANGER - Expensive expansion of buffer"); } byte newBytes[] = new byte[Math.max (bytes.length << 1, length)]; System.arraycopy (bytes, 0, newBytes, 0, offset); bytes = newBytes; | { length += offset; if (length > bytes.length) { if (SanityManager.DEBUG) { agent.trace("DANGER - Expensive expansion of buffer"); | private void ensureLength (int length) { length += offset; if (length > bytes.length) { if (SanityManager.DEBUG) { agent.trace("DANGER - Expensive expansion of buffer"); } byte newBytes[] = new byte[Math.max (bytes.length << 1, length)]; System.arraycopy (bytes, 0, newBytes, 0, offset); bytes = newBytes; } } |
} | private void ensureLength (int length) { length += offset; if (length > bytes.length) { if (SanityManager.DEBUG) { agent.trace("DANGER - Expensive expansion of buffer"); } byte newBytes[] = new byte[Math.max (bytes.length << 1, length)]; System.arraycopy (bytes, 0, newBytes, 0, offset); bytes = newBytes; } } |
|
for (int i = 0; i < extendedLengthByteCount; i++) { bytes[offset + i] = (byte) ((length >>> shiftSize) & 0xff); shiftSize -= 8; | for (int i = 0; i < extendedLengthByteCount; i++) { bytes[offset + i] = (byte) ((length >>> shiftSize) & 0xff); shiftSize -= 8; } offset += extendedLengthByteCount; | private void writeExtendedLengthBytes (int extendedLengthByteCount, long length) { int shiftSize = (extendedLengthByteCount -1) * 8; for (int i = 0; i < extendedLengthByteCount; i++) { bytes[offset + i] = (byte) ((length >>> shiftSize) & 0xff); shiftSize -= 8; } offset += extendedLengthByteCount; } |
offset += extendedLengthByteCount; } | private void writeExtendedLengthBytes (int extendedLengthByteCount, long length) { int shiftSize = (extendedLengthByteCount -1) * 8; for (int i = 0; i < extendedLengthByteCount; i++) { bytes[offset + i] = (byte) ((length >>> shiftSize) & 0xff); shiftSize -= 8; } offset += extendedLengthByteCount; } |
|
{ try { writeBytes(s.getBytes(NetworkServerControlImpl.DEFAULT_ENCODING)); } catch (Exception e) { agent.agentError("Encoding " + NetworkServerControlImpl.DEFAULT_ENCODING + " not supported"); } | { try { writeBytes(s.getBytes(NetworkServerControlImpl.DEFAULT_ENCODING)); } catch (Exception e) { agent.agentError("Encoding " + NetworkServerControlImpl.DEFAULT_ENCODING + " not supported"); | protected void writeString(String s) throws DRDAProtocolException { try { writeBytes(s.getBytes(NetworkServerControlImpl.DEFAULT_ENCODING)); } catch (Exception e) { //this should never happen agent.agentError("Encoding " + NetworkServerControlImpl.DEFAULT_ENCODING + " not supported"); } } |
} | protected void writeString(String s) throws DRDAProtocolException { try { writeBytes(s.getBytes(NetworkServerControlImpl.DEFAULT_ENCODING)); } catch (Exception e) { //this should never happen agent.agentError("Encoding " + NetworkServerControlImpl.DEFAULT_ENCODING + " not supported"); } } |
|
if (synctype == NetXAResource.XARETVAL_XARDONLY) { | if (synctype == XAResource.XA_RDONLY) { | protected int readXaPrepare(NetConnection conn) throws DisconnectException { startSameIdChainParse(); int synctype = parseSYNCCTLreply(conn); endOfSameIdChainData(); NetXACallInfo callInfo = conn.xares_.callInfoArray_[conn.currXACallInfoOffset_]; if (synctype == NetXAResource.XARETVAL_XARDONLY) { // xaretval of read-only, make sure flag agrees callInfo.setReadOnlyTransactionFlag(true); } else { // xaretval NOT read-only, make sure flag agrees callInfo.setReadOnlyTransactionFlag(false); } return synctype; } |
System.out.println(lookupMessage("CSLOOK_Usage")); | System.out.println(lookupMessage("DBLOOK_Usage")); | public dblook(String[] args) { // Adjust the application in accordance with derby.ui.locale // and derby.ui.codeset langUtil = LocalizedResource.getInstance(); // Initialize class variables. initState(); // Parse the command line. if (!parseArgs(args)) { System.out.println(lookupMessage("CSLOOK_Usage")); System.exit(1); } showVariables(); if (!loadDriver()) { // Failed when loading the driver. We already printed // the exception, so just return. return; } schemaMap = new HashMap(); tableIdToNameMap = new HashMap(); } |
Logs.reportMessage("CSLOOK_FileCreation"); | Logs.reportMessage("DBLOOK_FileCreation"); | private void showVariables() { if (ddlFileName != null) { Logs.reportString("============================\n"); Logs.reportMessage("CSLOOK_FileCreation"); if (verbose) writeVerboseOutput("CSLOOK_OutputLocation", ddlFileName); } Logs.reportMessage("CSLOOK_Timestamp", new Timestamp(System.currentTimeMillis()).toString()); Logs.reportMessage("CSLOOK_DBName", sourceDBName); Logs.reportMessage("CSLOOK_DBUrl", sourceDBUrl); if (tableList != null) Logs.reportMessage("CSLOOK_TargetTables"); if (schemaParam != null) Logs.reportMessage("CSLOOK_TargetSchema", stripQuotes(schemaParam)); Logs.reportString("appendLogs: " + appendLogs + "\n"); return; } |
writeVerboseOutput("CSLOOK_OutputLocation", | writeVerboseOutput("DBLOOK_OutputLocation", | private void showVariables() { if (ddlFileName != null) { Logs.reportString("============================\n"); Logs.reportMessage("CSLOOK_FileCreation"); if (verbose) writeVerboseOutput("CSLOOK_OutputLocation", ddlFileName); } Logs.reportMessage("CSLOOK_Timestamp", new Timestamp(System.currentTimeMillis()).toString()); Logs.reportMessage("CSLOOK_DBName", sourceDBName); Logs.reportMessage("CSLOOK_DBUrl", sourceDBUrl); if (tableList != null) Logs.reportMessage("CSLOOK_TargetTables"); if (schemaParam != null) Logs.reportMessage("CSLOOK_TargetSchema", stripQuotes(schemaParam)); Logs.reportString("appendLogs: " + appendLogs + "\n"); return; } |
Logs.reportMessage("CSLOOK_Timestamp", | Logs.reportMessage("DBLOOK_Timestamp", | private void showVariables() { if (ddlFileName != null) { Logs.reportString("============================\n"); Logs.reportMessage("CSLOOK_FileCreation"); if (verbose) writeVerboseOutput("CSLOOK_OutputLocation", ddlFileName); } Logs.reportMessage("CSLOOK_Timestamp", new Timestamp(System.currentTimeMillis()).toString()); Logs.reportMessage("CSLOOK_DBName", sourceDBName); Logs.reportMessage("CSLOOK_DBUrl", sourceDBUrl); if (tableList != null) Logs.reportMessage("CSLOOK_TargetTables"); if (schemaParam != null) Logs.reportMessage("CSLOOK_TargetSchema", stripQuotes(schemaParam)); Logs.reportString("appendLogs: " + appendLogs + "\n"); return; } |
Logs.reportMessage("CSLOOK_DBName", sourceDBName); Logs.reportMessage("CSLOOK_DBUrl", sourceDBUrl); | Logs.reportMessage("DBLOOK_DBName", sourceDBName); Logs.reportMessage("DBLOOK_DBUrl", sourceDBUrl); | private void showVariables() { if (ddlFileName != null) { Logs.reportString("============================\n"); Logs.reportMessage("CSLOOK_FileCreation"); if (verbose) writeVerboseOutput("CSLOOK_OutputLocation", ddlFileName); } Logs.reportMessage("CSLOOK_Timestamp", new Timestamp(System.currentTimeMillis()).toString()); Logs.reportMessage("CSLOOK_DBName", sourceDBName); Logs.reportMessage("CSLOOK_DBUrl", sourceDBUrl); if (tableList != null) Logs.reportMessage("CSLOOK_TargetTables"); if (schemaParam != null) Logs.reportMessage("CSLOOK_TargetSchema", stripQuotes(schemaParam)); Logs.reportString("appendLogs: " + appendLogs + "\n"); return; } |
Logs.reportMessage("CSLOOK_TargetTables"); | Logs.reportMessage("DBLOOK_TargetTables"); | private void showVariables() { if (ddlFileName != null) { Logs.reportString("============================\n"); Logs.reportMessage("CSLOOK_FileCreation"); if (verbose) writeVerboseOutput("CSLOOK_OutputLocation", ddlFileName); } Logs.reportMessage("CSLOOK_Timestamp", new Timestamp(System.currentTimeMillis()).toString()); Logs.reportMessage("CSLOOK_DBName", sourceDBName); Logs.reportMessage("CSLOOK_DBUrl", sourceDBUrl); if (tableList != null) Logs.reportMessage("CSLOOK_TargetTables"); if (schemaParam != null) Logs.reportMessage("CSLOOK_TargetSchema", stripQuotes(schemaParam)); Logs.reportString("appendLogs: " + appendLogs + "\n"); return; } |
Logs.reportMessage("CSLOOK_TargetSchema", stripQuotes(schemaParam)); | Logs.reportMessage("DBLOOK_TargetSchema", stripQuotes(schemaParam)); | private void showVariables() { if (ddlFileName != null) { Logs.reportString("============================\n"); Logs.reportMessage("CSLOOK_FileCreation"); if (verbose) writeVerboseOutput("CSLOOK_OutputLocation", ddlFileName); } Logs.reportMessage("CSLOOK_Timestamp", new Timestamp(System.currentTimeMillis()).toString()); Logs.reportMessage("CSLOOK_DBName", sourceDBName); Logs.reportMessage("CSLOOK_DBUrl", sourceDBUrl); if (tableList != null) Logs.reportMessage("CSLOOK_TargetTables"); if (schemaParam != null) Logs.reportMessage("CSLOOK_TargetSchema", stripQuotes(schemaParam)); Logs.reportString("appendLogs: " + appendLogs + "\n"); return; } |
ps.execute(); | try { ResultSet rs = ps.executeQuery(); rs.next(); System.out.println("Jira 44 failed (didn't get SQLSTATE 22019)"); rs.close(); } catch (SQLException e) { if (!"22019".equals(e.getSQLState())) { System.out.println("Jira 44 failed."); e.printStackTrace(System.out); } } | public static void main(String[] args) { Connection con = null; Statement s; CallableStatement cs; PreparedStatement ps; ParameterMetaData paramMetaData; System.out.println("Test parameterMetaDataJdbc30 starting"); try { // use the ij utility to read the property file and // make the initial connection. ij.getPropertyArg(args); con = ij.startJBMS(); con.setAutoCommit(true); // make sure it is true isDerbyNet = TestUtil.isNetFramework(); s = con.createStatement(); /* Create the table and do any other set-up */ TestUtil.cleanUpTest(s, testObjects); setUpTest(s); s.executeUpdate("create function RDB(P1 INT) RETURNS DECIMAL(10,2) language java external name 'org.apache.derbyTesting.functionTests.tests.lang.outparams30.returnsBigDecimal' parameter style java"); //first testing a callable statement s.executeUpdate("create procedure dummyint(in a integer, in b integer, out c integer, inout d integer) language java external name 'org.apache.derbyTesting.functionTests.tests.jdbcapi.parameterMetaDataJdbc30.dummyint' parameter style java"); cs = con.prepareCall("CALL dummyint(?,?,?,?)"); // parameters 1 and 2 are input only cs.setInt(1,1); cs.setInt(2,1); //parameter 3 is output only cs.registerOutParameter(3,Types.INTEGER); // parameter 4 is input and output Object x = new Integer(1); cs.setObject(4,x, Types.INTEGER); cs.registerOutParameter(4,Types.INTEGER); //verify the meta data for the parameters paramMetaData = cs.getParameterMetaData(); System.out.println("parameters count for callable statement is " + paramMetaData.getParameterCount()); // TODO: Some of the OUT params are getting reported as IN_OUT for embedded. // Network server reports it correctly. dumpParameterMetaData(paramMetaData); cs.execute(); //bug 4450 - parameter meta data info for the return parameter was giving //null pointer exception. In the past, we didn't need to keep the return //parameter info for callable statement execution and hence we never //generated the meta data for it. To fix the problem, at the parsing time, //I set a flag if the call statement is of ? = form. If so, the first //parameter is a return parameter and save it's meta data rather than //discarding it. System.out.println("Bug 4450 - generate metadata for return parameter"); cs = con.prepareCall("? = call RDB(?)"); paramMetaData = cs.getParameterMetaData(); System.out.println("param count is: "+paramMetaData.getParameterCount()); dumpParameterMetaData(paramMetaData); //next testing a prepared statement ps = con.prepareStatement("insert into t values(?, ?, ?, ?, ?)"); ps.setNull(1, java.sql.Types.CHAR); ps.setInt(2, 1); ps.setNull(3, java.sql.Types.INTEGER); ps.setBigDecimal(4,new BigDecimal("1")); ps.setNull(5, java.sql.Types.DATE); paramMetaData = ps.getParameterMetaData(); System.out.println("parameters count for prepared statement is " + paramMetaData.getParameterCount()); // JCC seems to report these parameters as MODE_UNKNOWN, where as Derby uses MODE_IN // JCC behaviour with network server matches its behaviour with DB2 // getPrecision() returns 0 for CHAR/DATE/BIT types for Derby. JCC shows maxlen dumpParameterMetaData(paramMetaData); ps.execute(); //bug 4533 - associated parameters should not be included in the parameter meta data list //Following statement systab will generate 4 associated parameters for the 2 //user parameters. This results in total 6 parameters for the prepared statement //internally. But we should only show 2 user visible parameters through //getParameterMetaData(). System.out.println("Bug 4533 - hide associated parameters"); ps = con.prepareStatement("select * from sys.systables where " + " tablename like ? and tableID like ?"); ps.setString (1, "SYS%"); ps.setString (2, "8000001%"); paramMetaData = ps.getParameterMetaData(); System.out.println("parameters count for prepared statement is " + paramMetaData.getParameterCount()); dumpParameterMetaData(paramMetaData); ps.execute(); // variation, and also test out empty string in the escape (jira 44). System.out.println("variation 1, testing jira 44"); ps = con.prepareStatement("select * from sys.systables where tablename like ? escape ?"); ps.setString (1, "SYS%"); ps.setString (2, ""); paramMetaData = ps.getParameterMetaData(); System.out.println("parameters count for prepared statement is " + paramMetaData.getParameterCount()); dumpParameterMetaData(paramMetaData); ps.execute(); // the test no longer tests 4552, but kept as an interesting test scenario // bug 4552 - no parameters would be returned for execute statement using // System.out.println("Bug 4552 - no parameters would be returned for execute statement using"); // orig: ps = con.prepareStatement("execute statement systab using values('SYS%','8000001%')"); ps = con.prepareStatement("select * from sys.systables where tablename like 'SYS%' and tableID like '8000001%'"); paramMetaData = ps.getParameterMetaData(); System.out.println("parameters count for prepared statement is " + paramMetaData.getParameterCount()); dumpParameterMetaData(paramMetaData); ps.execute(); //Bug 4654 - Null Pointer exception while executuing a select with a //where clause parameter of type 'TRUE' or 'FALSE' constants. The existing prior to //exposing parameter metadata didn't need to fill in metadata information for where //clause parameter in the example above. // This no longer makes sense, for we cannot take BOOLEANs anymore. // replace with a simple where 1 = ?. Which would take either 1 for true, or 0 for false System.out.println("Bug 4654 - fill in where clause parameter type info"); ps = con.prepareStatement("select * from t where 1=? for update"); paramMetaData = ps.getParameterMetaData(); System.out.println("parameters count for prepared statement is " + paramMetaData.getParameterCount()); dumpParameterMetaData(paramMetaData); dumpParameterMetaDataNegative(paramMetaData); //ps.setBoolean(1,true); ps.setInt(1,1); ps.execute(); System.out.println("test: no parameter for the statement and then do getParameterMetaData()"); ps = con.prepareStatement("select * from t"); paramMetaData = ps.getParameterMetaData(); System.out.println("parameters count for prepared statement is " + paramMetaData.getParameterCount()); dumpParameterMetaData(paramMetaData); ps.execute(); cs.close(); ps.close(); System.out.println("test: the scale returned should be the one set by registerOutParameter"); s.executeUpdate("create procedure dummy_numeric_Proc(out a NUMERIC(30,15), out b NUMERIC(30,15)) language java parameter style java external name 'org.apache.derbyTesting.functionTests.tests.jdbcapi.parameterMetaDataJdbc30.dummy_numeric_Proc'"); cs = con.prepareCall("CALL dummy_numeric_Proc(?,?)"); cs.registerOutParameter(1, Types.NUMERIC); cs.registerOutParameter(2, Types.NUMERIC,15); cs.execute(); dumpParameterMetaData(cs.getParameterMetaData()); cs.close(); System.out.println("Behaviour of meta data and out params after re-compile"); cs = con.prepareCall("CALL dummyint(?,?,?,?)"); cs.registerOutParameter(3,Types.INTEGER); cs.registerOutParameter(4,Types.INTEGER); cs.setInt(1,1); cs.setInt(2,1); cs.setInt(4,4); dumpParameterMetaData(cs.getParameterMetaData()); cs.execute(); System.out.println("DUMMYINT alias returned " + cs.getInt(4)); s.executeUpdate("drop procedure dummyint"); s.executeUpdate("create procedure dummyint(in a integer, in b integer, out c integer, inout d integer) language java external name 'org.apache.derbyTesting.functionTests.tests.jdbcapi.parameterMetaDataJdbc30.dummyint2' parameter style java"); cs.execute(); dumpParameterMetaData(cs.getParameterMetaData()); cs.setInt(4, 6); // following is incorrect sequence, should execute first, then get // but leaving it in as an additional negative test. see beetle 5886 System.out.println("DUMMYINT alias returned " + cs.getInt(4)); cs.execute(); System.out.println("DUMMYINT alias returned " + cs.getInt(4)); cs.close(); // temp disable for network server if (!isDerbyNet) { // Java procedure support System.out.println("ParameterMetaData for Java procedures with INTEGER parameters"); s.execute("CREATE PROCEDURE PMDI(IN pmdI_1 INTEGER, IN pmdI_2 INTEGER, INOUT pmdI_3 INTEGER, OUT pmdI_4 INTEGER) language java parameter style java external name 'org.apache.derbyTesting.functionTests.tests.jdbcapi.parameterMetaDataJdbc30.dummyint'"); cs = con.prepareCall("CALL PMDI(?, ?, ?, ?)"); dumpParameterMetaData(cs.getParameterMetaData()); cs.close(); s.execute("DROP PROCEDURE PMDI"); System.out.println("ParameterMetaData for Java procedures with CHAR parameters"); s.execute("CREATE PROCEDURE PMDC(IN pmdI_1 CHAR(10), IN pmdI_2 VARCHAR(25), INOUT pmdI_3 CHAR(19), OUT pmdI_4 VARCHAR(32)) language java parameter style java external name 'org.apache.derbyTesting.functionTests.tests.jdbcapi.parameterMetaDataJdbc30.dummyString'"); cs = con.prepareCall("CALL PMDC(?, ?, ?, ?)"); dumpParameterMetaData(cs.getParameterMetaData()); cs.close(); s.execute("DROP PROCEDURE PMDC"); System.out.println("ParameterMetaData for Java procedures with DECIMAL parameters"); s.execute("CREATE PROCEDURE PMDD(IN pmdI_1 DECIMAL(5,3), IN pmdI_2 DECIMAL(4,2), INOUT pmdI_3 DECIMAL(9,0), OUT pmdI_4 DECIMAL(10,2)) language java parameter style java external name 'org.apache.derbyTesting.functionTests.tests.jdbcapi.parameterMetaDataJdbc30.dummyDecimal'"); cs = con.prepareCall("CALL PMDD(?, ?, ?, ?)"); dumpParameterMetaData(cs.getParameterMetaData()); cs.close(); System.out.println("ParameterMetaData for Java procedures with some literal parameters"); cs = con.prepareCall("CALL PMDD(32.4, ?, ?, ?)"); dumpParameterMetaData(cs.getParameterMetaData()); cs.close(); cs = con.prepareCall("CALL PMDD(32.4, 47.9, ?, ?)"); dumpParameterMetaData(cs.getParameterMetaData()); cs.close(); cs = con.prepareCall("CALL PMDD(?, 38.2, ?, ?)"); dumpParameterMetaData(cs.getParameterMetaData()); cs.close(); s.execute("DROP PROCEDURE PMDD"); } s.close(); con = ij.startJBMS(); con.setAutoCommit(true); // make sure it is true s = con.createStatement(); TestUtil.cleanUpTest(s, testObjects); s.close(); con.close(); } catch (SQLException e) { dumpSQLExceptions(e); } catch (Throwable e) { System.out.println("FAIL -- unexpected exception:"); e.printStackTrace(System.out); } System.out.println("Test parameterMetaDataJdbc30 finished"); } |
public DistinctGroupedAggregateResultSet(NoPutResultSet s, | DistinctGroupedAggregateResultSet(NoPutResultSet s, | public DistinctGroupedAggregateResultSet(NoPutResultSet s, boolean isInSortedOrder, int aggregateItem, int orderingItem, Activation a, GeneratedMethod ra, int maxRowSize, int resultSetNumber, double optimizerEstimatedRowCount, double optimizerEstimatedCost, GeneratedMethod c) throws StandardException { super(s, isInSortedOrder, aggregateItem, orderingItem, a, ra, maxRowSize, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost, c); } |
double optimizerEstimatedCost, GeneratedMethod c) throws StandardException | double optimizerEstimatedCost) throws StandardException | public DistinctGroupedAggregateResultSet(NoPutResultSet s, boolean isInSortedOrder, int aggregateItem, int orderingItem, Activation a, GeneratedMethod ra, int maxRowSize, int resultSetNumber, double optimizerEstimatedRowCount, double optimizerEstimatedCost, GeneratedMethod c) throws StandardException { super(s, isInSortedOrder, aggregateItem, orderingItem, a, ra, maxRowSize, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost, c); } |
a, ra, maxRowSize, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost, c); | a, ra, maxRowSize, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost); | public DistinctGroupedAggregateResultSet(NoPutResultSet s, boolean isInSortedOrder, int aggregateItem, int orderingItem, Activation a, GeneratedMethod ra, int maxRowSize, int resultSetNumber, double optimizerEstimatedRowCount, double optimizerEstimatedCost, GeneratedMethod c) throws StandardException { super(s, isInSortedOrder, aggregateItem, orderingItem, a, ra, maxRowSize, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost, c); } |
in_ = actualConn_.getInputStream(); out_ = actualConn_.getOutputStream(); | in_ = actualConn_.getNetConnection().getInputStream(); out_ = actualConn_.getNetConnection().getOutputStream(); | public void saveConnectionVariables() { in_ = actualConn_.getInputStream(); out_ = actualConn_.getOutputStream(); crrtkn_ = actualConn_.getCorrelatorToken(); } |
if (!checkVersion(RawStoreFactory.DERBY_STORE_MAJOR_VERSION_10, RawStoreFactory.DERBY_STORE_MINOR_VERSION_1)) maxLogFileNumber = LogCounter.DERBY_10_0_MAX_LOGFILE_NUMBER; | public void boot(boolean create, Properties startParams) throws StandardException { dataDirectory = startParams.getProperty(PersistentService.ROOT); logDevice = startParams.getProperty(Attribute.LOG_DEVICE); if( logDevice != null) { // in case the user specifies logDevice in URL form String logDeviceURL = null; try { URL url = new URL(logDevice); logDeviceURL = url.getFile(); } catch (MalformedURLException ex) {} if (logDeviceURL != null) logDevice = logDeviceURL; } //check whether we are restoring from backup restoreLogs(startParams); //if user does not set the right value for the log buffer size, //default value is used instead. logBufferSize = PropertyUtil.getSystemInt(org.apache.derby.iapi.reference.Property.LOG_BUFFER_SIZE, LOG_BUFFER_SIZE_MIN, LOG_BUFFER_SIZE_MAX, DEFAULT_LOG_BUFFER_SIZE); if( logStorageFactory == null) getLogStorageFactory(); if (logDevice != null) { // in case the user specifies logDevice in URL form String logDeviceURL = null; try { URL url = new URL(logDevice); logDeviceURL = url.getFile(); } catch (MalformedURLException ex) {} if (logDeviceURL != null) logDevice = logDeviceURL; // Make sure we find the log, do not assume it is OK that the log // is not there because it could be a user typo. if (!create) { StorageFile checklogDir = logStorageFactory.newStorageFile( LogFactory.LOG_DIRECTORY_NAME); if (!privExists(checklogDir)) { throw StandardException.newException( SQLState.LOG_FILE_NOT_FOUND, checklogDir.getPath()); } } } jbmsVersion = Monitor.getMonitor().getEngineVersion(); String dataEncryption = startParams.getProperty(Attribute.DATA_ENCRYPTION); databaseEncrypted = Boolean.valueOf(dataEncryption).booleanValue(); String logArchiveMode = startParams.getProperty(Property.LOG_ARCHIVE_MODE); logArchived = Boolean.valueOf(logArchiveMode).booleanValue(); //get log factorty properties if any set in derby.properties getLogFactoryProperties(null); /* check if the storage factory supports write sync(rws). If so, use it unless * derby.storage.fileSyncTransactionLog property is set true by user. */ if (logStorageFactory.supportsRws()) { //write sync can be used in the jvm that database is running on. //disable write sync if derby.storage.fileSyncTransactionLog is true isWriteSynced = !(PropertyUtil.getSystemBoolean(Property.FILESYNC_TRANSACTION_LOG)); } else { isWriteSynced = false; } // If derby.system.durability=test is set,then set flag to // disable sync of log records at commit and log file before // data page makes it to disk if (Property.DURABILITY_TESTMODE_NO_SYNC.equalsIgnoreCase( PropertyUtil.getSystemProperty(Property.DURABILITY_PROPERTY))) { // disable syncing of log. logNotSynced = true; //if log not being synced;files shouldn't be open in write sync mode isWriteSynced = false; } // try to access the log // if it doesn't exist, create it. // if it does exist, run recovery boolean createNewLog = create; if (SanityManager.DEBUG) SanityManager.ASSERT(fid != -1, "invalid log format Id"); checkpointInstant = LogCounter.INVALID_LOG_INSTANT; try { StorageFile logControlFileName = getControlFileName(); StorageFile logFile; if (!createNewLog) { if (privExists(logControlFileName)) { checkpointInstant = readControlFile(logControlFileName, startParams); // in case system was running previously with // derby.system.durability=test then print a message // to the derby log if (wasDBInDurabilityTestModeNoSync) { // print message stating that the database was // previously atleast at one time running with // derby.system.durability=test mode Monitor.logMessage(MessageService.getTextMessage( MessageId.LOG_WAS_IN_DURABILITY_TESTMODE_NO_SYNC, Property.DURABILITY_PROPERTY, Property.DURABILITY_TESTMODE_NO_SYNC)); } if (checkpointInstant == LogCounter.INVALID_LOG_INSTANT && getMirrorControlFileName().exists()) { checkpointInstant = readControlFile( getMirrorControlFileName(), startParams); } } else if (logDevice != null) { // Do not throw this error if logDevice is null because // in a read only configuration, it is acceptable // to not have a log directory. But clearly, if the // logDevice property is set, then it should be there. throw StandardException.newException( SQLState.LOG_FILE_NOT_FOUND, logControlFileName.getPath()); } if (checkpointInstant != LogCounter.INVALID_LOG_INSTANT) logFileNumber = LogCounter.getLogFileNumber(checkpointInstant); else logFileNumber = 1; logFile = getLogFileName(logFileNumber); // if log file is not there or if it is of the wrong format, create a // brand new log file and do not attempt to recover the database if (!privExists(logFile)) { if (logDevice != null) { throw StandardException.newException( SQLState.LOG_FILE_NOT_FOUND, logControlFileName.getPath()); } logErrMsg(MessageService.getTextMessage( MessageId.LOG_MAYBE_INCONSISTENT, logFile.getPath())); createNewLog = true; } else if (!verifyLogFormat(logFile, logFileNumber)) { Monitor.logTextMessage(MessageId.LOG_DELETE_INCOMPATIBLE_FILE, logFile); // blow away the log file if possible if (!privDelete(logFile) && logFileNumber == 1) { logErrMsgForDurabilityTestModeNoSync(); throw StandardException.newException( SQLState.LOG_INCOMPATIBLE_FORMAT, dataDirectory); } // If logFileNumber > 1, we are not going to write that // file just yet. Just leave it be and carry on. Maybe // when we get there it can be deleted. createNewLog = true; } } if (createNewLog) { // brand new log. Start from log file number 1. // create or overwrite the log control file with an invalid // checkpoint instant since there is no checkpoint yet if (writeControlFile(logControlFileName, LogCounter.INVALID_LOG_INSTANT)) { firstLogFileNumber = 1; logFileNumber = 1; if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON(TEST_MAX_LOGFILE_NUMBER)) { // set the value to be two less than max possible // log number, test case will perform some ops to // hit the max number case. firstLogFileNumber = LogCounter.MAX_LOGFILE_NUMBER -2; logFileNumber = LogCounter.MAX_LOGFILE_NUMBER -2; } } logFile = getLogFileName(logFileNumber); if (privExists(logFile)) { // this log file maybe there because the system may have // crashed right after a log switch but did not write // out any log record Monitor.logTextMessage( MessageId.LOG_DELETE_OLD_FILE, logFile); if (!privDelete(logFile)) { logErrMsgForDurabilityTestModeNoSync(); throw StandardException.newException( SQLState.LOG_INCOMPATIBLE_FORMAT, dataDirectory); } } // don't need to try to delete it, we know it isn't there firstLog = privRandomAccessFile(logFile, "rw"); if (!initLogFile(firstLog, logFileNumber, LogCounter.INVALID_LOG_INSTANT)) { throw StandardException.newException( SQLState.LOG_SEGMENT_NOT_EXIST, logFile.getPath()); } endPosition = firstLog.getFilePointer(); lastFlush = firstLog.getFilePointer(); //if write sync is true , prellocate the log file //and reopen the file in rws mode. if(isWriteSynced) { //extend the file by wring zeros to it preAllocateNewLogFile(firstLog); firstLog.close(); firstLog= privRandomAccessFile(logFile, "rws"); //postion the log at the current log end postion firstLog.seek(endPosition); } if (SanityManager.DEBUG) { SanityManager.ASSERT( endPosition == LOG_FILE_HEADER_SIZE, "empty log file has wrong size"); } } else { // read only database ReadOnlyDB = true; logOut = null; firstLog = null; } recoveryNeeded = false; } else { // log file exist, need to run recovery recoveryNeeded = true; } } catch (IOException ioe) { throw Monitor.exceptionStartingModule(ioe); } } // end of boot |
|
if (logFileNumber+1 >= LogCounter.MAX_LOGFILE_NUMBER) | if (logFileNumber+1 >= maxLogFileNumber) | private void switchLogFile() throws StandardException { boolean switchedOver = false; ///////////////////////////////////////////////////// // Freeze the log for the switch over to a new log file. // This blocks out any other threads from sending log // record to the log stream. // // The switching of the log file and checkpoint are really // independent events, they are tied together just because a // checkpoint is the natural place to switch the log and vice // versa. This could happen before the cache is flushed or // after the checkpoint log record is written. ///////////////////////////////////////////////////// synchronized (this) { // Make sure that this thread of control is guaranteed to complete // it's work of switching the log file without having to give up // the semaphore to a backup or another flusher. Do this by looping // until we have the semaphore, the log is not being flushed, and // the log is not frozen for backup. Track (2985). while(logBeingFlushed | isFrozen) { try { wait(); } catch (InterruptedException ie) { throw StandardException.interrupt(ie); } } // we have an empty log file here, refuse to switch. if (endPosition == LOG_FILE_HEADER_SIZE) { if (SanityManager.DEBUG) { Monitor.logMessage("not switching from an empty log file (" + logFileNumber + ")"); } return; } // log file isn't being flushed right now and logOut is not being // used. StorageFile newLogFile = getLogFileName(logFileNumber+1); if (logFileNumber+1 >= LogCounter.MAX_LOGFILE_NUMBER) { throw StandardException.newException( SQLState.LOG_EXCEED_MAX_LOG_FILE_NUMBER, new Long(LogCounter.MAX_LOGFILE_NUMBER)); } StorageRandomAccessFile newLog = null; // the new log file try { // if the log file exist and cannot be deleted, cannot // switch log right now if (privExists(newLogFile) && !privDelete(newLogFile)) { logErrMsg(MessageService.getTextMessage( MessageId.LOG_NEW_LOGFILE_EXIST, newLogFile.getPath())); return; } try { newLog = privRandomAccessFile(newLogFile, "rw"); } catch (IOException ioe) { newLog = null; } if (newLog == null || !privCanWrite(newLogFile)) { if (newLog != null) newLog.close(); newLog = null; return; } if (initLogFile(newLog, logFileNumber+1, LogCounter.makeLogInstantAsLong(logFileNumber, endPosition))) { // New log file init ok, close the old one and // switch over, after this point, need to shutdown the // database if any error crops up switchedOver = true; // write out an extra 0 at the end to mark the end of the log // file. logOut.writeEndMarker(0); endPosition += 4; //set that we are in log switch to prevent flusher //not requesting to switch log again inLogSwitch = true; // flush everything including the int we just wrote flush(logFileNumber, endPosition); // simulate out of log error after the switch over if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON(TEST_SWITCH_LOG_FAIL2)) throw new IOException("TestLogSwitchFail2"); } logOut.close(); // close the old log file logWrittenFromLastCheckPoint += endPosition; endPosition = newLog.getFilePointer(); lastFlush = endPosition; if(isWriteSynced) { //extend the file by wring zeros to it preAllocateNewLogFile(newLog); newLog.close(); newLog= privRandomAccessFile(newLogFile, "rws"); newLog.seek(endPosition); } logOut = new LogAccessFile(this, newLog, logBufferSize); newLog = null; if (SanityManager.DEBUG) { if (endPosition != LOG_FILE_HEADER_SIZE) SanityManager.THROWASSERT( "new log file has unexpected size" + + endPosition); } logFileNumber++; if (SanityManager.DEBUG) { SanityManager.ASSERT(endPosition == LOG_FILE_HEADER_SIZE, "empty log file has wrong size"); } } else // something went wrong, delete the half baked file { newLog.close(); newLog = null; if (privExists(newLogFile)) privDelete(newLogFile); newLogFile = null; logErrMsg(MessageService.getTextMessage( MessageId.LOG_CANNOT_CREATE_NEW, newLogFile.getPath())); } } catch (IOException ioe) { inLogSwitch = false; // switching log file is an optional operation and there is no direct user // control. Just sends a warning message to whomever, if any, // system adminstrator there may be logErrMsg(MessageService.getTextMessage( MessageId.LOG_CANNOT_CREATE_NEW_DUETO, newLogFile.getPath(), ioe.toString())); try { if (newLog != null) { newLog.close(); newLog = null; } } catch (IOException ioe2) {} if (newLogFile != null && privExists(newLogFile)) { privDelete(newLogFile); newLogFile = null; } if (switchedOver) // error occur after old log file has been closed! { logOut = null; // limit any damage throw markCorrupt( StandardException.newException( SQLState.LOG_IO_ERROR, ioe)); } } inLogSwitch = false; } // unfreezes the log } |
new Long(LogCounter.MAX_LOGFILE_NUMBER)); | new Long(maxLogFileNumber)); | private void switchLogFile() throws StandardException { boolean switchedOver = false; ///////////////////////////////////////////////////// // Freeze the log for the switch over to a new log file. // This blocks out any other threads from sending log // record to the log stream. // // The switching of the log file and checkpoint are really // independent events, they are tied together just because a // checkpoint is the natural place to switch the log and vice // versa. This could happen before the cache is flushed or // after the checkpoint log record is written. ///////////////////////////////////////////////////// synchronized (this) { // Make sure that this thread of control is guaranteed to complete // it's work of switching the log file without having to give up // the semaphore to a backup or another flusher. Do this by looping // until we have the semaphore, the log is not being flushed, and // the log is not frozen for backup. Track (2985). while(logBeingFlushed | isFrozen) { try { wait(); } catch (InterruptedException ie) { throw StandardException.interrupt(ie); } } // we have an empty log file here, refuse to switch. if (endPosition == LOG_FILE_HEADER_SIZE) { if (SanityManager.DEBUG) { Monitor.logMessage("not switching from an empty log file (" + logFileNumber + ")"); } return; } // log file isn't being flushed right now and logOut is not being // used. StorageFile newLogFile = getLogFileName(logFileNumber+1); if (logFileNumber+1 >= LogCounter.MAX_LOGFILE_NUMBER) { throw StandardException.newException( SQLState.LOG_EXCEED_MAX_LOG_FILE_NUMBER, new Long(LogCounter.MAX_LOGFILE_NUMBER)); } StorageRandomAccessFile newLog = null; // the new log file try { // if the log file exist and cannot be deleted, cannot // switch log right now if (privExists(newLogFile) && !privDelete(newLogFile)) { logErrMsg(MessageService.getTextMessage( MessageId.LOG_NEW_LOGFILE_EXIST, newLogFile.getPath())); return; } try { newLog = privRandomAccessFile(newLogFile, "rw"); } catch (IOException ioe) { newLog = null; } if (newLog == null || !privCanWrite(newLogFile)) { if (newLog != null) newLog.close(); newLog = null; return; } if (initLogFile(newLog, logFileNumber+1, LogCounter.makeLogInstantAsLong(logFileNumber, endPosition))) { // New log file init ok, close the old one and // switch over, after this point, need to shutdown the // database if any error crops up switchedOver = true; // write out an extra 0 at the end to mark the end of the log // file. logOut.writeEndMarker(0); endPosition += 4; //set that we are in log switch to prevent flusher //not requesting to switch log again inLogSwitch = true; // flush everything including the int we just wrote flush(logFileNumber, endPosition); // simulate out of log error after the switch over if (SanityManager.DEBUG) { if (SanityManager.DEBUG_ON(TEST_SWITCH_LOG_FAIL2)) throw new IOException("TestLogSwitchFail2"); } logOut.close(); // close the old log file logWrittenFromLastCheckPoint += endPosition; endPosition = newLog.getFilePointer(); lastFlush = endPosition; if(isWriteSynced) { //extend the file by wring zeros to it preAllocateNewLogFile(newLog); newLog.close(); newLog= privRandomAccessFile(newLogFile, "rws"); newLog.seek(endPosition); } logOut = new LogAccessFile(this, newLog, logBufferSize); newLog = null; if (SanityManager.DEBUG) { if (endPosition != LOG_FILE_HEADER_SIZE) SanityManager.THROWASSERT( "new log file has unexpected size" + + endPosition); } logFileNumber++; if (SanityManager.DEBUG) { SanityManager.ASSERT(endPosition == LOG_FILE_HEADER_SIZE, "empty log file has wrong size"); } } else // something went wrong, delete the half baked file { newLog.close(); newLog = null; if (privExists(newLogFile)) privDelete(newLogFile); newLogFile = null; logErrMsg(MessageService.getTextMessage( MessageId.LOG_CANNOT_CREATE_NEW, newLogFile.getPath())); } } catch (IOException ioe) { inLogSwitch = false; // switching log file is an optional operation and there is no direct user // control. Just sends a warning message to whomever, if any, // system adminstrator there may be logErrMsg(MessageService.getTextMessage( MessageId.LOG_CANNOT_CREATE_NEW_DUETO, newLogFile.getPath(), ioe.toString())); try { if (newLog != null) { newLog.close(); newLog = null; } } catch (IOException ioe2) {} if (newLogFile != null && privExists(newLogFile)) { privDelete(newLogFile); newLogFile = null; } if (switchedOver) // error occur after old log file has been closed! { logOut = null; // limit any damage throw markCorrupt( StandardException.newException( SQLState.LOG_IO_ERROR, ioe)); } } inLogSwitch = false; } // unfreezes the log } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.