idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
19,400 | @ Override public void format ( Buffer buf ) { int pos = 0 ; // initial the number of records as 0 setVal ( buf , pos , Constant . defaultInstance ( INTEGER ) ) ; int flagSize = Page . maxSize ( BIGINT ) ; pos += Page . maxSize ( INTEGER ) ; // set flags for ( int i = 0 ; i < flags . length ; i ++ ) { setVal ( buf , pos , new BigIntConstant ( flags [ i ] ) ) ; pos += flagSize ; } int slotSize = BTreePage . slotSize ( sch ) ; for ( int p = pos ; p + slotSize <= Buffer . BUFFER_SIZE ; p += slotSize ) makeDefaultRecord ( buf , p ) ; } | Formats the page by initializing as many index - record slots as possible to have default values . | 161 | 20 |
19,401 | public void rollback ( ) { for ( TransactionLifecycleListener l : lifecycleListeners ) { l . onTxRollback ( this ) ; } if ( logger . isLoggable ( Level . FINE ) ) logger . fine ( "transaction " + txNum + " rolled back" ) ; } | Rolls back the current transaction . Undoes any modified values flushes those blocks writes and flushes a rollback record to the log releases all locks and unpins any pinned blocks . | 67 | 37 |
19,402 | @ Override public void setVal ( String fldName , Constant val ) { rf . setVal ( fldName , val ) ; } | Sets the value of the specified field as a Constant . | 31 | 12 |
19,403 | @ Override public Scan open ( ) { SortScan ss1 = ( SortScan ) sp1 . open ( ) ; SortScan ss2 = ( SortScan ) sp2 . open ( ) ; return new MergeJoinScan ( ss1 , ss2 , fldName1 , fldName2 ) ; } | The method first sorts its two underlying scans on their join field . It then returns a mergejoin scan of the two sorted table scans . | 65 | 27 |
19,404 | @ Override public void format ( Buffer buf ) { int slotSize = RecordPage . slotSize ( ti . schema ( ) ) ; Constant emptyFlag = new IntegerConstant ( EMPTY ) ; for ( int pos = 0 ; pos + slotSize <= Buffer . BUFFER_SIZE ; pos += slotSize ) { setVal ( buf , pos , emptyFlag ) ; makeDefaultRecord ( buf , pos ) ; } } | Formats the page by allocating as many record slots as possible given the record size . Each record slot is assigned a flag of EMPTY . Each numeric field is given a value of 0 and each string field is given a value of . | 88 | 48 |
19,405 | public void flush ( LogSeqNum lsn ) { logMgrLock . lock ( ) ; try { if ( lsn . compareTo ( lastFlushedLsn ) >= 0 ) flush ( ) ; } finally { logMgrLock . unlock ( ) ; } } | Ensures that the log records corresponding to the specified LSN has been written to disk . All earlier log records will also be written to disk . | 58 | 30 |
19,406 | @ Override public ReversibleIterator < BasicLogRecord > iterator ( ) { logMgrLock . lock ( ) ; try { flush ( ) ; return new LogIterator ( currentBlk ) ; } finally { logMgrLock . unlock ( ) ; } } | Returns an iterator for the log records which will be returned in reverse order starting with the most recent . | 55 | 20 |
19,407 | public LogSeqNum append ( Constant [ ] rec ) { logMgrLock . lock ( ) ; try { // two integers that point to the previous and next log records int recsize = pointerSize * 2 ; for ( Constant c : rec ) recsize += Page . size ( ) ; // if the log record doesn't fit, move to the next block if ( currentPos + recsize >= BLOCK_SIZE ) { flush ( ) ; appendNewBlock ( ) ; } // Get the current LSN LogSeqNum lsn = currentLSN ( ) ; // Append a record for ( Constant c : rec ) appendVal ( ) ; finalizeRecord ( ) ; // Remember this LSN lastLsn = lsn ; return lsn ; } finally { logMgrLock . unlock ( ) ; } } | Appends a log record to the file . The record contains an arbitrary array of values . The method also writes an integer to the end of each log record whose value is the offset of the corresponding integer for the previous log record . These integers allow log records to be read in reverse order . | 172 | 58 |
19,408 | public void removeAndCreateNewLog ( ) { logMgrLock . lock ( ) ; try { VanillaDb . fileMgr ( ) . delete ( logFile ) ; // Reset all the data lastLsn = LogSeqNum . DEFAULT_VALUE ; lastFlushedLsn = LogSeqNum . DEFAULT_VALUE ; // 'myPage', 'currentBlk' and 'currentPos' are reset in this method appendNewBlock ( ) ; } finally { logMgrLock . unlock ( ) ; } } | Remove the old log file and create a new one . | 111 | 11 |
19,409 | private void appendVal ( Constant val ) { myPage . setVal ( currentPos , val ) ; currentPos += Page . size ( val ) ; } | Adds the specified value to the page at the position denoted by currentPos . Then increments currentPos by the size of the value . | 32 | 27 |
19,410 | private void finalizeRecord ( ) { myPage . setVal ( currentPos , new IntegerConstant ( getLastRecordPosition ( ) ) ) ; setPreviousNextRecordPosition ( currentPos + pointerSize ) ; setLastRecordPosition ( currentPos ) ; currentPos += pointerSize ; setNextRecordPosition ( currentPos ) ; // leave for next pointer currentPos += pointerSize ; } | Sets up a circular chain of pointers to the records in the page . There is an integer added to the end of each log record whose value is the offset of the previous log record . The first four bytes of the page contain an integer whose value is the offset of the integer for the last log record in the page . | 80 | 65 |
19,411 | @ Override public Scan open ( ) { Schema sch = p . schema ( ) ; TempTable temp = new TempTable ( sch , tx ) ; Scan src = p . open ( ) ; UpdateScan dest = temp . open ( ) ; src . beforeFirst ( ) ; while ( src . next ( ) ) { dest . insert ( ) ; for ( String fldname : sch . fields ( ) ) dest . setVal ( fldname , src . getVal ( fldname ) ) ; } src . close ( ) ; dest . beforeFirst ( ) ; return dest ; } | This method loops through the underlying query copying its output records into a temporary table . It then returns a table scan for that table . | 124 | 26 |
19,412 | private static Schema schema ( SearchKeyType keyType ) { Schema sch = new Schema ( ) ; for ( int i = 0 ; i < keyType . length ( ) ; i ++ ) sch . addField ( keyFieldName ( i ) , keyType . get ( i ) ) ; sch . addField ( SCHEMA_RID_BLOCK , BIGINT ) ; sch . addField ( SCHEMA_RID_ID , INTEGER ) ; return sch ; } | Returns the schema of the index records . | 103 | 8 |
19,413 | @ Override public RecordId getDataRecordId ( ) { long blkNum = ( Long ) rf . getVal ( SCHEMA_RID_BLOCK ) . asJavaVal ( ) ; int id = ( Integer ) rf . getVal ( SCHEMA_RID_ID ) . asJavaVal ( ) ; return new RecordId ( new BlockId ( dataFileName , blkNum ) , id ) ; } | Retrieves the data record ID from the current index record . | 92 | 13 |
19,414 | @ Override public void insert ( SearchKey key , RecordId dataRecordId , boolean doLogicalLogging ) { // search the position beforeFirst ( new SearchRange ( key ) ) ; // log the logical operation starts if ( doLogicalLogging ) tx . recoveryMgr ( ) . logLogicalStart ( ) ; // insert the data rf . insert ( ) ; for ( int i = 0 ; i < keyType . length ( ) ; i ++ ) rf . setVal ( keyFieldName ( i ) , key . get ( i ) ) ; rf . setVal ( SCHEMA_RID_BLOCK , new BigIntConstant ( dataRecordId . block ( ) . number ( ) ) ) ; rf . setVal ( SCHEMA_RID_ID , new IntegerConstant ( dataRecordId . id ( ) ) ) ; // log the logical operation ends if ( doLogicalLogging ) tx . recoveryMgr ( ) . logIndexInsertionEnd ( ii . indexName ( ) , key , dataRecordId . block ( ) . number ( ) , dataRecordId . id ( ) ) ; } | Inserts a new index record into this index . | 243 | 10 |
19,415 | @ Override public void delete ( SearchKey key , RecordId dataRecordId , boolean doLogicalLogging ) { // search the position beforeFirst ( new SearchRange ( key ) ) ; // log the logical operation starts if ( doLogicalLogging ) tx . recoveryMgr ( ) . logLogicalStart ( ) ; // delete the specified entry while ( next ( ) ) if ( getDataRecordId ( ) . equals ( dataRecordId ) ) { rf . delete ( ) ; return ; } // log the logical operation ends if ( doLogicalLogging ) tx . recoveryMgr ( ) . logIndexDeletionEnd ( ii . indexName ( ) , key , dataRecordId . block ( ) . number ( ) , dataRecordId . id ( ) ) ; } | Deletes the specified index record . | 167 | 7 |
19,416 | @ Override public boolean next ( ) { if ( prodScan == null ) return false ; while ( ! prodScan . next ( ) ) if ( ! useNextChunk ( ) ) return false ; return true ; } | Moves to the next record in the current scan . If there are no more records in the current chunk then move to the next LHS record and the beginning of that chunk . If there are no more LHS records then move to the next chunk and begin again . | 46 | 54 |
19,417 | static Schema schema ( SearchKeyType keyType ) { Schema sch = new Schema ( ) ; for ( int i = 0 ; i < keyType . length ( ) ; i ++ ) sch . addField ( keyFieldName ( i ) , keyType . get ( i ) ) ; sch . addField ( SCH_CHILD , BIGINT ) ; return sch ; } | Returns the schema of the B - tree directory records . | 80 | 11 |
19,418 | public BlockId search ( SearchKey searchKey , String leafFileName , SearchPurpose purpose ) { if ( purpose == SearchPurpose . READ ) return searchForRead ( searchKey , leafFileName ) ; else if ( purpose == SearchPurpose . INSERT ) return searchForInsert ( searchKey , leafFileName ) ; else if ( purpose == SearchPurpose . DELETE ) return searchForDelete ( searchKey , leafFileName ) ; else throw new UnsupportedOperationException ( ) ; } | Returns the block number of the B - tree leaf block that contains the specified search key . | 106 | 18 |
19,419 | private int findSlotBefore ( SearchKey searchKey ) { /* * int slot = 0; while (slot < contents.getNumRecords() && * getKey(contents, slot).compareTo(searchKey) < 0) slot++; return slot * - 1; */ // Optimization: Use binary search rather than sequential search int startSlot = 0 , endSlot = currentPage . getNumRecords ( ) - 1 ; int middleSlot = ( startSlot + endSlot ) / 2 ; if ( endSlot >= 0 ) { while ( middleSlot != startSlot ) { if ( getKey ( currentPage , middleSlot , keyType . length ( ) ) . compareTo ( searchKey ) < 0 ) startSlot = middleSlot ; else endSlot = middleSlot ; middleSlot = ( startSlot + endSlot ) / 2 ; } if ( getKey ( currentPage , endSlot , keyType . length ( ) ) . compareTo ( searchKey ) < 0 ) return endSlot ; else if ( getKey ( currentPage , startSlot , keyType . length ( ) ) . compareTo ( searchKey ) < 0 ) return startSlot ; else return startSlot - 1 ; } else return - 1 ; } | Calculates the slot right before the one having the specified search key . | 256 | 15 |
19,420 | public synchronized Constant getVal ( int offset , Type type ) { int size ; byte [ ] byteVal = null ; // Check the length of bytes if ( type . isFixedSize ( ) ) { size = type . maxSize ( ) ; } else { byteVal = new byte [ ByteHelper . INT_SIZE ] ; contents . get ( offset , byteVal ) ; size = ByteHelper . toInteger ( byteVal ) ; offset += ByteHelper . INT_SIZE ; } // Get bytes and translate it to Constant byteVal = new byte [ size ] ; contents . get ( offset , byteVal ) ; return Constant . newInstance ( type , byteVal ) ; } | Returns the value at a specified offset of this page . If a constant was not stored at that offset the behavior of the method is unpredictable . | 139 | 28 |
19,421 | public synchronized void setVal ( int offset , Constant val ) { byte [ ] byteval = val . asBytes ( ) ; // Append the size of value if it is not fixed size if ( ! val . getType ( ) . isFixedSize ( ) ) { // check the field capacity and value size if ( offset + ByteHelper . INT_SIZE + byteval . length > BLOCK_SIZE ) throw new BufferOverflowException ( ) ; byte [ ] sizeBytes = ByteHelper . toBytes ( byteval . length ) ; contents . put ( offset , sizeBytes ) ; offset += sizeBytes . length ; } // Put bytes contents . put ( offset , byteval ) ; } | Writes a constant value to the specified offset on the page . | 144 | 13 |
19,422 | public static Constant newInstance ( Type type , byte [ ] val ) { switch ( type . getSqlType ( ) ) { case ( INTEGER ) : return new IntegerConstant ( val ) ; case ( BIGINT ) : return new BigIntConstant ( val ) ; case ( DOUBLE ) : return new DoubleConstant ( val ) ; case ( VARCHAR ) : return new VarcharConstant ( val , type ) ; } throw new UnsupportedOperationException ( "Unspported SQL type: " + type . getSqlType ( ) ) ; } | Constructs a new instance of the specified type with value converted from the input byte array . | 124 | 18 |
19,423 | public static Constant defaultInstance ( Type type ) { switch ( type . getSqlType ( ) ) { case ( INTEGER ) : return defaultInteger ; case ( BIGINT ) : return defaultBigInt ; case ( DOUBLE ) : return defaultDouble ; case ( VARCHAR ) : return defaultVarchar ; } throw new UnsupportedOperationException ( "Unspported SQL type: " + type . getSqlType ( ) ) ; } | Constructs a new instance of the specified type with default value . For all numeric constants the default value is 0 ; for string constants the default value is an empty string . | 97 | 34 |
19,424 | @ Override public void setReadOnly ( boolean readOnly ) throws RemoteException { if ( this . readOnly != readOnly ) { tx . commit ( ) ; this . readOnly = readOnly ; try { tx = VanillaDb . txMgr ( ) . newTransaction ( isolationLevel , readOnly ) ; } catch ( Exception e ) { throw new RemoteException ( "error creating transaction " , e ) ; } } } | Sets this connection s auto - commit mode to the given state . The default setting of auto - commit mode is true . This method may commit current transaction and start a new transaction . | 89 | 37 |
19,425 | @ Override public void commit ( ) throws RemoteException { tx . commit ( ) ; try { tx = VanillaDb . txMgr ( ) . newTransaction ( isolationLevel , readOnly ) ; } catch ( Exception e ) { throw new RemoteException ( "error creating transaction " , e ) ; } } | Commits the current transaction and begins a new one . | 64 | 11 |
19,426 | public int insertFromScan ( Scan s ) { if ( ! super . insertIntoNextEmptySlot ( ) ) { return 0 ; } for ( String fldName : sch . fields ( ) ) { Constant val = s . getVal ( fldName ) ; this . setVal ( fldName , val ) ; } if ( s . next ( ) ) return 1 ; else return - 1 ; } | Insert records to TempRecordFile for sorting at most one block long | 86 | 13 |
19,427 | public boolean copyToScan ( UpdateScan s ) { if ( ! this . next ( ) ) return false ; s . insert ( ) ; for ( String fldName : sch . fields ( ) ) { s . setVal ( fldName , this . getVal ( fldName ) ) ; } return true ; } | Copy sorted records to UpdateScan | 68 | 6 |
19,428 | static Schema schema ( SearchKeyType keyType ) { Schema sch = new Schema ( ) ; for ( int i = 0 ; i < keyType . length ( ) ; i ++ ) sch . addField ( keyFieldName ( i ) , keyType . get ( i ) ) ; sch . addField ( SCH_RID_BLOCK , BIGINT ) ; sch . addField ( SCH_RID_ID , INTEGER ) ; return sch ; } | Returns the schema of the B - tree leaf records . | 100 | 11 |
19,429 | public boolean next ( ) { while ( true ) { currentSlot ++ ; if ( ! isOverflowing ) { // not in an overflow block // if it reached the end of the block if ( currentSlot >= currentPage . getNumRecords ( ) ) { if ( getSiblingFlag ( currentPage ) != - 1 ) { moveTo ( getSiblingFlag ( currentPage ) , - 1 ) ; continue ; } return false ; // if the key of this slot match what we want } else if ( searchRange . match ( getKey ( currentPage , currentSlot , keyType . length ( ) ) ) ) { /* * Move to records in overflow blocks first. An overflow block * cannot be empty. */ if ( currentSlot == 0 && getOverflowFlag ( currentPage ) != - 1 ) { isOverflowing = true ; overflowFrom = currentPage . currentBlk ( ) . number ( ) ; moveTo ( getOverflowFlag ( currentPage ) , 0 ) ; } return true ; } else if ( searchRange . betweenMinAndMax ( getKey ( currentPage , currentSlot , keyType . length ( ) ) ) ) { continue ; } else return false ; } else { // in an overflow block // All the records in an overflow block have the same key // so that we do not need to check the key in an overflow block. if ( currentSlot >= currentPage . getNumRecords ( ) ) { moveTo ( getOverflowFlag ( currentPage ) , 0 ) ; /* * Move back to the first record in the regular block finally. */ if ( currentPage . currentBlk ( ) . number ( ) == overflowFrom ) { isOverflowing = false ; overflowFrom = - 1 ; } } return true ; } } } | Moves to the next B - tree leaf record matching the search key . | 372 | 15 |
19,430 | public DirEntry insert ( RecordId dataRecordId ) { // search range must be a constant if ( ! searchRange . isSingleValue ( ) ) throw new IllegalStateException ( ) ; // ccMgr.modifyLeafBlock(currentPage.currentBlk()); currentSlot ++ ; SearchKey searchKey = searchRange . asSearchKey ( ) ; insert ( currentSlot , searchKey , dataRecordId ) ; /* * If the inserted key is less than the key stored in the overflow * blocks, split this block to make sure that the key of the first * record in every block will be the same as the key of records in * the overflow blocks. */ if ( currentSlot == 0 && getOverflowFlag ( currentPage ) != - 1 && ! getKey ( currentPage , 1 , keyType . length ( ) ) . equals ( searchKey ) ) { SearchKey splitKey = getKey ( currentPage , 1 , keyType . length ( ) ) ; long newBlkNum = currentPage . split ( 1 , new long [ ] { getOverflowFlag ( currentPage ) , getSiblingFlag ( currentPage ) } ) ; setOverflowFlag ( currentPage , - 1 ) ; setSiblingFlag ( currentPage , newBlkNum ) ; return new DirEntry ( splitKey , newBlkNum ) ; } if ( ! currentPage . isFull ( ) ) return null ; /* * If this block is full, then split the block and return the directory * entry of the new block. */ SearchKey firstKey = getKey ( currentPage , 0 , keyType . length ( ) ) ; SearchKey lastKey = getKey ( currentPage , currentPage . getNumRecords ( ) - 1 , keyType . length ( ) ) ; if ( lastKey . equals ( firstKey ) ) { /* * If all of the records in the page have the same key, then the * block does not split; instead, all but one of the records are * placed into an overflow block. */ long overflowFlag = ( getOverflowFlag ( currentPage ) == - 1 ) ? currentPage . currentBlk ( ) . number ( ) : getOverflowFlag ( currentPage ) ; long newBlkNum = currentPage . split ( 1 , new long [ ] { overflowFlag , - 1 } ) ; setOverflowFlag ( currentPage , newBlkNum ) ; return null ; } else { int splitPos = currentPage . getNumRecords ( ) / 2 ; SearchKey splitKey = getKey ( currentPage , splitPos , keyType . length ( ) ) ; // records having the same key must be in the same block if ( splitKey . equals ( firstKey ) ) { // move right, looking for a different key while ( getKey ( currentPage , splitPos , keyType . length ( ) ) . equals ( splitKey ) ) splitPos ++ ; splitKey = getKey ( currentPage , splitPos , keyType . length ( ) ) ; } else { // move left, looking for first entry having that key while ( getKey ( currentPage , splitPos - 1 , keyType . length ( ) ) . equals ( splitKey ) ) splitPos -- ; } // split the block long newBlkNum = currentPage . split ( splitPos , new long [ ] { - 1 , getSiblingFlag ( currentPage ) } ) ; setSiblingFlag ( currentPage , newBlkNum ) ; return new DirEntry ( splitKey , newBlkNum ) ; } } | Inserts a new B - tree leaf record having the specified data record ID and the previously - specified search key . This method can only be called once immediately after construction . | 743 | 34 |
19,431 | public void delete ( RecordId dataRecordId ) { // search range must be a constant if ( ! searchRange . isSingleValue ( ) ) throw new IllegalStateException ( ) ; // delete all entry with the specific key while ( next ( ) ) if ( getDataRecordId ( ) . equals ( dataRecordId ) ) { // ccMgr.modifyLeafBlock(currentPage.currentBlk()); delete ( currentSlot ) ; break ; } if ( ! isOverflowing ) { /* * If the current regular block is empty or the key of the first * record is not equal to that of records in overflow blocks, * transfer one record from a overflow block to here (if any). */ if ( getOverflowFlag ( currentPage ) != - 1 ) { // get overflow page BlockId blk = new BlockId ( currentPage . currentBlk ( ) . fileName ( ) , getOverflowFlag ( currentPage ) ) ; ccMgr . modifyLeafBlock ( blk ) ; BTreePage overflowPage = new BTreePage ( blk , NUM_FLAGS , schema , tx ) ; SearchKey firstKey = getKey ( currentPage , 0 , keyType . length ( ) ) ; if ( ( currentPage . getNumRecords ( ) == 0 || ( overflowPage . getNumRecords ( ) != 0 && getKey ( overflowPage , 0 , keyType . length ( ) ) != firstKey ) ) ) { overflowPage . transferRecords ( overflowPage . getNumRecords ( ) - 1 , currentPage , 0 , 1 ) ; // if the overflow block is empty, make it a dead block if ( overflowPage . getNumRecords ( ) == 0 ) { long overflowFlag = ( getOverflowFlag ( overflowPage ) == currentPage . currentBlk ( ) . number ( ) ) ? - 1 : getOverflowFlag ( overflowPage ) ; setOverflowFlag ( currentPage , overflowFlag ) ; } overflowPage . close ( ) ; } } } else { /* * If the current overflow block is empty, make it a dead block. */ if ( currentPage . getNumRecords ( ) == 0 ) { // reset the overflow flag of original page BlockId blk = new BlockId ( currentPage . currentBlk ( ) . fileName ( ) , moveFrom ) ; // ccMgr.modifyLeafBlock(blk); BTreePage prePage = new BTreePage ( blk , NUM_FLAGS , schema , tx ) ; long overflowFlag = ( getOverflowFlag ( currentPage ) == prePage . currentBlk ( ) . number ( ) ) ? - 1 : getOverflowFlag ( currentPage ) ; setOverflowFlag ( prePage , overflowFlag ) ; prePage . close ( ) ; } } } | Deletes the B - tree leaf record having the specified data record ID and the previously - specified search key . This method can only be called once immediately after construction . | 595 | 33 |
19,432 | private void moveSlotBefore ( ) { /* * int slot = 0; while (slot < currentPage.getNumRecords() && * searchRange.largerThan(getKey(currentPage, slot))) slot++; * * currentSlot = slot - 1; */ // Optimization: Use binary search rather than sequential search int startSlot = 0 , endSlot = currentPage . getNumRecords ( ) - 1 ; int middleSlot = ( startSlot + endSlot ) / 2 ; SearchKey searchMin = searchRange . getMin ( ) ; if ( endSlot >= 0 ) { while ( middleSlot != startSlot ) { if ( searchMin . compareTo ( getKey ( currentPage , middleSlot , keyType . length ( ) ) ) > 0 ) startSlot = middleSlot ; else endSlot = middleSlot ; middleSlot = ( startSlot + endSlot ) / 2 ; } if ( searchMin . compareTo ( getKey ( currentPage , endSlot , keyType . length ( ) ) ) > 0 ) currentSlot = endSlot ; else if ( searchMin . compareTo ( getKey ( currentPage , startSlot , keyType . length ( ) ) ) > 0 ) currentSlot = startSlot ; else currentSlot = startSlot - 1 ; } else currentSlot = - 1 ; } | Positions the current slot right before the first index record that matches the specified search range . | 275 | 18 |
19,433 | private void moveTo ( long blkNum , int slot ) { moveFrom = currentPage . currentBlk ( ) . number ( ) ; // for deletion BlockId blk = new BlockId ( currentPage . currentBlk ( ) . fileName ( ) , blkNum ) ; ccMgr . readLeafBlock ( blk ) ; currentPage . close ( ) ; currentPage = new BTreePage ( blk , NUM_FLAGS , schema , tx ) ; currentSlot = slot ; } | Opens the page for the specified block and moves the current slot to the specified position . | 108 | 18 |
19,434 | public static Histogram syncHistogram ( Histogram hist ) { double maxRecs = 0.0 ; for ( String fld : hist . fields ( ) ) { double numRecs = 0.0 ; for ( Bucket bkt : hist . buckets ( fld ) ) numRecs += bkt . frequency ( ) ; if ( Double . compare ( numRecs , maxRecs ) > 0 ) maxRecs = numRecs ; } Histogram syncHist = new Histogram ( hist . fields ( ) ) ; for ( String fld : hist . fields ( ) ) { double numRecs = 0.0 ; for ( Bucket bkt : hist . buckets ( fld ) ) numRecs += bkt . frequency ( ) ; double extrapolation = maxRecs / numRecs ; for ( Bucket bkt : hist . buckets ( fld ) ) syncHist . addBucket ( fld , new Bucket ( bkt . valueRange ( ) , extrapolation * bkt . frequency ( ) , bkt . distinctValues ( ) , bkt . valuePercentiles ( ) ) ) ; } return syncHist ; } | Buckets of a field may be discarded during the cost estimation if its frequency is less than 1 . As a result the total frequencies of buckets may be diverse in different fields . This method synchronizes the total frequencies of different fields in the specified histogram . | 240 | 52 |
19,435 | synchronized int reserveNextCorrelationId ( VersionedIoFuture future ) { Integer next = getNextCorrelationId ( ) ; // Not likely but possible to use all IDs and start back at beginning while // old request still in progress. while ( requests . containsKey ( next ) ) { next = getNextCorrelationId ( ) ; } requests . put ( next , future ) ; return next ; } | Reserves a correlation ID by taking the next value and ensuring it is stored in the Map . | 86 | 19 |
19,436 | public static Histogram predHistogram ( Histogram hist , Predicate pred ) { if ( Double . compare ( hist . recordsOutput ( ) , 1.0 ) < 0 ) return new Histogram ( hist . fields ( ) ) ; // apply constant ranges Map < String , ConstantRange > cRanges = new HashMap < String , ConstantRange > ( ) ; for ( String fld : hist . fields ( ) ) { ConstantRange cr = pred . constantRange ( fld ) ; if ( cr != null ) cRanges . put ( fld , cr ) ; } Histogram crHist = constantRangeHistogram ( hist , cRanges ) ; // apply field joins Histogram jfHist = crHist ; Deque < String > flds = new LinkedList < String > ( jfHist . fields ( ) ) ; while ( ! flds . isEmpty ( ) ) { String fld = flds . removeFirst ( ) ; Set < String > group = pred . joinFields ( fld ) ; if ( group != null ) { flds . removeAll ( group ) ; group . add ( fld ) ; jfHist = joinFieldsHistogram ( jfHist , group ) ; } } return jfHist ; } | Returns a histogram that for each field approximates the distribution of field values from the specified histogram satisfying the specified predicate . | 269 | 25 |
19,437 | public static Histogram constantRangeHistogram ( Histogram hist , Map < String , ConstantRange > cRanges ) { if ( Double . compare ( hist . recordsOutput ( ) , 1.0 ) < 0 ) return new Histogram ( hist . fields ( ) ) ; Histogram crHist = new Histogram ( hist ) ; for ( String fld : cRanges . keySet ( ) ) { Collection < Bucket > crBkts = new ArrayList < Bucket > ( crHist . buckets ( fld ) . size ( ) ) ; ConstantRange cr = cRanges . get ( fld ) ; double freqSum = 0.0 ; for ( Bucket bkt : crHist . buckets ( fld ) ) { Bucket crBkt = constantRangeBucket ( bkt , cr ) ; if ( crBkt != null ) { crBkts . add ( crBkt ) ; freqSum += crBkt . frequency ( ) ; } } if ( Double . compare ( freqSum , 1.0 ) < 0 ) // no bucket in range return new Histogram ( hist . fields ( ) ) ; double crReduction = freqSum / crHist . recordsOutput ( ) ; if ( Double . compare ( crReduction , 1.0 ) == 0 ) continue ; // update this field's buckets crHist . setBuckets ( fld , crBkts ) ; /* * update other fields' buckets to ensure that all fields have the * same total frequencies. */ for ( String restFld : crHist . fields ( ) ) { if ( restFld . equals ( fld ) ) continue ; Collection < Bucket > restBkts = new ArrayList < Bucket > ( crHist . buckets ( restFld ) . size ( ) ) ; for ( Bucket bkt : crHist . buckets ( restFld ) ) { double restFreq = bkt . frequency ( ) * crReduction ; if ( Double . compare ( restFreq , 1.0 ) < 0 ) continue ; double restDistVals = Math . min ( bkt . distinctValues ( ) , restFreq ) ; Bucket restBkt = new Bucket ( bkt . valueRange ( ) , restFreq , restDistVals , bkt . valuePercentiles ( ) ) ; restBkts . add ( restBkt ) ; } crHist . setBuckets ( restFld , restBkts ) ; } } return syncHistogram ( crHist ) ; } | Returns a histogram that for each field approximates the distribution of values from the specified histogram falling within the specified search range . | 531 | 26 |
19,438 | public static Bucket constantRangeBucket ( Bucket bkt , ConstantRange cRange ) { ConstantRange newRange = bkt . valueRange ( ) . intersect ( cRange ) ; if ( ! newRange . isValid ( ) ) return null ; double newDistVals = bkt . distinctValues ( newRange ) ; if ( Double . compare ( newDistVals , 1.0 ) < 0 ) return null ; double newFreq = bkt . frequency ( ) * newDistVals / bkt . distinctValues ( ) ; if ( bkt . valuePercentiles ( ) == null ) return new Bucket ( newRange , newFreq , newDistVals ) ; Percentiles newPcts = bkt . valuePercentiles ( ) . percentiles ( newRange ) ; return new Bucket ( newRange , newFreq , newDistVals , newPcts ) ; } | Creates a new bucket by keeping the statistics of records and values in the specified bucket falling within the specified search range . | 189 | 24 |
19,439 | public static Histogram joinFieldsHistogram ( Histogram hist , Set < String > group ) { if ( group . size ( ) < 2 ) return new Histogram ( hist ) ; List < String > flds = new ArrayList < String > ( group ) ; Collection < Bucket > jfBkts = hist . buckets ( flds . get ( 0 ) ) ; for ( int i = 1 ; i < flds . size ( ) ; i ++ ) { Collection < Bucket > temp = jfBkts ; jfBkts = new ArrayList < Bucket > ( 2 * jfBkts . size ( ) ) ; for ( Bucket bkt1 : temp ) { for ( Bucket bkt2 : hist . buckets ( flds . get ( i ) ) ) { Bucket jfBkt = joinFieldBucket ( bkt1 , bkt2 , hist . recordsOutput ( ) ) ; if ( jfBkt != null ) jfBkts . add ( jfBkt ) ; } } } double freqSum = 0.0 ; for ( Bucket bkt : jfBkts ) freqSum += bkt . frequency ( ) ; if ( Double . compare ( freqSum , 1.0 ) < 0 ) // no joined bucket return new Histogram ( hist . fields ( ) ) ; double jfReduction = freqSum / hist . recordsOutput ( ) ; if ( Double . compare ( jfReduction , 1.0 ) == 0 ) return new Histogram ( hist ) ; Histogram jfHist = new Histogram ( hist . fields ( ) ) ; for ( String fld : hist . fields ( ) ) { if ( group . contains ( fld ) ) jfHist . setBuckets ( fld , jfBkts ) ; else { for ( Bucket bkt : hist . buckets ( fld ) ) { double restFreq = bkt . frequency ( ) * jfReduction ; if ( Double . compare ( restFreq , 1.0 ) < 0 ) continue ; double restDistVals = Math . min ( bkt . distinctValues ( ) , restFreq ) ; Bucket restBkt = new Bucket ( bkt . valueRange ( ) , restFreq , restDistVals , bkt . valuePercentiles ( ) ) ; jfHist . addBucket ( fld , restBkt ) ; } } } return syncHistogram ( jfHist ) ; } | Returns a histogram that for each field approximates the distribution of values from the specified histogram joining with other fields in the specified group . | 533 | 28 |
19,440 | public static Bucket joinFieldBucket ( Bucket bkt1 , Bucket bkt2 , double numRec ) { ConstantRange newRange = bkt1 . valueRange ( ) . intersect ( bkt2 . valueRange ( ) ) ; if ( ! newRange . isValid ( ) ) return null ; double rdv1 = bkt1 . distinctValues ( newRange ) ; double rdv2 = bkt2 . distinctValues ( newRange ) ; double newDistVals = Math . min ( rdv1 , rdv2 ) ; if ( Double . compare ( newDistVals , 1.0 ) < 0 ) return null ; double newFreq = Math . min ( bkt1 . frequency ( ) * ( bkt2 . frequency ( ) / numRec ) * ( newDistVals / bkt1 . distinctValues ( ) ) / rdv2 , bkt2 . frequency ( ) * ( bkt1 . frequency ( ) / numRec ) * ( newDistVals / bkt2 . distinctValues ( ) ) / rdv1 ) ; if ( Double . compare ( newFreq , 1.0 ) < 0 ) return null ; Bucket smaller = rdv1 < rdv2 ? bkt1 : bkt2 ; if ( smaller . valuePercentiles ( ) == null ) return new Bucket ( newRange , newFreq , newDistVals ) ; Percentiles newPcts = smaller . valuePercentiles ( ) . percentiles ( newRange ) ; return new Bucket ( newRange , newFreq , newDistVals , newPcts ) ; } | Creates a new bucket by keeping the statistics of joining records and values from the two specified buckets . | 348 | 20 |
19,441 | @ Override public Scan open ( ) { Scan s = p . open ( ) ; return new SelectScan ( s , pred ) ; } | Creates a select scan for this query . | 29 | 9 |
19,442 | public Retrofit . Builder create ( String baseUrl , ObjectMapper objectMapper ) { return new Retrofit . Builder ( ) . baseUrl ( baseUrl ) . client ( _okHttpClient ) . addConverterFactory ( JacksonConverterFactory . create ( objectMapper ) ) ; } | Creates a new builder instance with the provided base url . Initialized with a Jackson JSON converter using the provided object mapper . | 64 | 26 |
19,443 | public boolean isSatisfied ( Record rec ) { for ( Term t : terms ) if ( ! t . isSatisfied ( rec ) ) return false ; return true ; } | Returns true if this predicate evaluates to true with respect to the specified record . | 38 | 15 |
19,444 | public Predicate selectPredicate ( Schema sch ) { Predicate result = new Predicate ( ) ; for ( Term t : terms ) if ( t . isApplicableTo ( sch ) ) result . terms . add ( t ) ; if ( result . terms . size ( ) == 0 ) return null ; else return result ; } | Returns the sub - predicate that applies to the specified schema . | 70 | 12 |
19,445 | public Predicate joinPredicate ( Schema sch1 , Schema sch2 ) { Predicate result = new Predicate ( ) ; Schema newsch = new Schema ( ) ; newsch . addAll ( sch1 ) ; newsch . addAll ( sch2 ) ; for ( Term t : terms ) if ( ! t . isApplicableTo ( sch1 ) && ! t . isApplicableTo ( sch2 ) && t . isApplicableTo ( newsch ) ) result . terms . add ( t ) ; return result . terms . size ( ) == 0 ? null : result ; } | Returns the sub - predicate consisting of terms that applies to the union of the two specified schemas but not to either schema separately . | 128 | 26 |
19,446 | public ConstantRange constantRange ( String fldName ) { ConstantRange cr = null ; for ( Term t : terms ) { Constant c = t . oppositeConstant ( fldName ) ; if ( c != null ) { Operator op = t . operator ( fldName ) ; if ( op == OP_GT ) cr = cr == null ? ConstantRange . newInstance ( c , false , null , false ) : cr . applyLow ( c , false ) ; else if ( op == OP_GTE ) cr = cr == null ? ConstantRange . newInstance ( c , true , null , false ) : cr . applyLow ( c , true ) ; else if ( op == OP_EQ ) cr = cr == null ? ConstantRange . newInstance ( c ) : cr . applyConstant ( c ) ; else if ( op == OP_LTE ) cr = cr == null ? ConstantRange . newInstance ( null , false , c , true ) : cr . applyHigh ( c , true ) ; else if ( op == OP_LT ) cr = cr == null ? ConstantRange . newInstance ( null , false , c , false ) : cr . applyHigh ( c , false ) ; } } // validate the constant range if ( cr != null && cr . isValid ( ) && ( cr . hasLowerBound ( ) || cr . hasUpperBound ( ) ) ) return cr ; return null ; } | Determines if the specified field is constrained by a constant range in this predicate . If so the method returns that range . If not the method returns null . | 300 | 32 |
19,447 | public Constant getVal ( int offset , Type type ) { internalLock . readLock ( ) . lock ( ) ; try { return contents . getVal ( DATA_START_OFFSET + offset , type ) ; } finally { internalLock . readLock ( ) . unlock ( ) ; } } | Returns the value at the specified offset of this buffer s page . If an integer was not stored at that location the behavior of the method is unpredictable . | 62 | 30 |
19,448 | public void setVal ( int offset , Constant val , long txNum , LogSeqNum lsn ) { internalLock . writeLock ( ) . lock ( ) ; try { modifiedBy . add ( txNum ) ; if ( lsn != null && lsn . compareTo ( lastLsn ) > 0 ) lastLsn = lsn ; // Put the last LSN in front of the data lastLsn . writeToPage ( contents , LAST_LSN_OFFSET ) ; contents . setVal ( DATA_START_OFFSET + offset , val ) ; } finally { internalLock . writeLock ( ) . unlock ( ) ; } } | Writes a value to the specified offset of this buffer s page . This method assumes that the transaction has already written an appropriate log record . The buffer saves the id of the transaction and the LSN of the log record . A negative lsn value indicates that a log record was not necessary . | 138 | 59 |
19,449 | void flush ( ) { internalLock . writeLock ( ) . lock ( ) ; flushLock . lock ( ) ; try { if ( isNew || modifiedBy . size ( ) > 0 ) { VanillaDb . logMgr ( ) . flush ( lastLsn ) ; contents . write ( blk ) ; modifiedBy . clear ( ) ; isNew = false ; } } finally { flushLock . unlock ( ) ; internalLock . writeLock ( ) . unlock ( ) ; } } | Writes the page to its disk block if the page is dirty . The method ensures that the corresponding log record has been written to disk prior to writing the page to disk . | 102 | 35 |
19,450 | boolean isModifiedBy ( long txNum ) { internalLock . writeLock ( ) . lock ( ) ; try { return modifiedBy . contains ( txNum ) ; } finally { internalLock . writeLock ( ) . unlock ( ) ; } } | Returns true if the buffer is dirty due to a modification by the specified transaction . | 53 | 16 |
19,451 | void assignToBlock ( BlockId blk ) { internalLock . writeLock ( ) . lock ( ) ; try { flush ( ) ; this . blk = blk ; contents . read ( blk ) ; pins = 0 ; lastLsn = LogSeqNum . readFromPage ( contents , LAST_LSN_OFFSET ) ; } finally { internalLock . writeLock ( ) . unlock ( ) ; } } | Reads the contents of the specified block into the buffer s page . If the buffer was dirty then the contents of the previous page are first written to disk . | 90 | 32 |
19,452 | void assignToNew ( String fileName , PageFormatter fmtr ) { internalLock . writeLock ( ) . lock ( ) ; try { flush ( ) ; fmtr . format ( this ) ; blk = contents . append ( fileName ) ; pins = 0 ; isNew = true ; lastLsn = LogSeqNum . DEFAULT_VALUE ; } finally { internalLock . writeLock ( ) . unlock ( ) ; } } | Initializes the buffer s page according to the specified formatter and appends the page to the specified file . If the buffer was dirty then the contents of the previous page are first written to disk . | 95 | 40 |
19,453 | protected IOException toIoException ( Exception e ) { if ( e instanceof IOException ) { return ( IOException ) e ; } else { return new IOException ( "Unexpected failure" , e ) ; } } | This Exception conversion needs to return the IOException instead of throwing it this is so that the compiler can detect that for the final Exception check something is actually thrown . | 47 | 32 |
19,454 | public void createCheckpoint ( ) { if ( logger . isLoggable ( Level . INFO ) ) logger . info ( "Start creating checkpoint" ) ; if ( MY_METHOD == METHOD_MONITOR ) { if ( VanillaDb . txMgr ( ) . getNextTxNum ( ) - lastTxNum > TX_COUNT_TO_CHECKPOINT ) { Transaction tx = VanillaDb . txMgr ( ) . newTransaction ( Connection . TRANSACTION_SERIALIZABLE , false ) ; VanillaDb . txMgr ( ) . createCheckpoint ( tx ) ; tx . commit ( ) ; lastTxNum = VanillaDb . txMgr ( ) . getNextTxNum ( ) ; } } else if ( MY_METHOD == METHOD_PERIODIC ) { Transaction tx = VanillaDb . txMgr ( ) . newTransaction ( Connection . TRANSACTION_SERIALIZABLE , false ) ; VanillaDb . txMgr ( ) . createCheckpoint ( tx ) ; tx . commit ( ) ; } if ( logger . isLoggable ( Level . INFO ) ) logger . info ( "A checkpoint created" ) ; } | Create a non - quiescent checkpoint . | 246 | 9 |
19,455 | public boolean matchKeyword ( String keyword ) { return tok . ttype == StreamTokenizer . TT_WORD && tok . sval . equals ( keyword ) && keywords . contains ( tok . sval ) ; } | Returns true if the current token is the specified keyword . | 49 | 11 |
19,456 | public String eatStringConstant ( ) { if ( ! matchStringConstant ( ) ) throw new BadSyntaxException ( ) ; /* * The input string constant is a quoted string token likes 'str', and * its token type (ttype) is the quote character. So the string * constants are not converted to lower case. */ String s = tok . sval ; nextToken ( ) ; return s ; } | Throws an exception if the current token is not a string . Otherwise returns that string and moves to the next token . | 88 | 24 |
19,457 | public String eatId ( ) { if ( ! matchId ( ) ) throw new BadSyntaxException ( ) ; String s = tok . sval ; nextToken ( ) ; return s ; } | Throws an exception if the current token is not an identifier . Otherwise returns the identifier string and moves to the next token . | 42 | 25 |
19,458 | public void sample ( Record rec ) { totalRecs ++ ; if ( samples . size ( ) < MAX_SAMPLES ) { samples . add ( new Sample ( rec , schema ) ) ; updateNewValueInterval ( rec ) ; } else { double flip = random . nextDouble ( ) ; if ( flip < ( double ) MAX_SAMPLES / totalRecs ) { samples . set ( random . nextInt ( MAX_SAMPLES ) , new Sample ( rec , schema ) ) ; updateNewValueInterval ( rec ) ; } } } | Keep a record as a sample with certain probability . This method is designed to uniformly sample all records of a table under the situation where the total number of records is unknown in advance . A client should call this method when iterating through each record of a table . | 118 | 52 |
19,459 | @ Override public Scan open ( ) { TempTable tt = copyRecordsFrom ( rhs ) ; TableInfo ti = tt . getTableInfo ( ) ; Scan leftscan = lhs . open ( ) ; return new MultiBufferProductScan ( leftscan , ti , tx ) ; } | A scan for this query is created and returned as follows . First the method materializes its RHS query . It then determines the optimal chunk size based on the size of the materialized file and the number of available buffers . It creates a chunk plan for each chunk saving them in a list . Finally it creates a multiscan for this list of plans and returns that scan . | 63 | 76 |
19,460 | @ Override public boolean next ( ) throws RemoteException { try { return s . next ( ) ; } catch ( RuntimeException e ) { rconn . rollback ( ) ; throw e ; } } | Moves to the next record in the result set by moving to the next record in the saved scan . | 42 | 21 |
19,461 | @ Override public int getInt ( String fldName ) throws RemoteException { try { fldName = fldName . toLowerCase ( ) ; // to ensure case-insensitivity return ( Integer ) s . getVal ( fldName ) . castTo ( INTEGER ) . asJavaVal ( ) ; } catch ( RuntimeException e ) { rconn . rollback ( ) ; throw e ; } } | Returns the integer value of the specified field by returning the corresponding value on the saved scan . | 89 | 18 |
19,462 | @ Override public long getLong ( String fldName ) throws RemoteException { try { fldName = fldName . toLowerCase ( ) ; // to ensure case-insensitivity return ( Long ) s . getVal ( fldName ) . castTo ( BIGINT ) . asJavaVal ( ) ; } catch ( RuntimeException e ) { rconn . rollback ( ) ; throw e ; } } | Returns the long value of the specified field by returning the corresponding value on the saved scan . | 88 | 18 |
19,463 | @ Override public double getDouble ( String fldName ) throws RemoteException { try { fldName = fldName . toLowerCase ( ) ; // to ensure case-insensitivity return ( Double ) s . getVal ( fldName ) . castTo ( DOUBLE ) . asJavaVal ( ) ; } catch ( RuntimeException e ) { rconn . rollback ( ) ; throw e ; } } | Returns the double value of the specified field by returning the corresponding value on the saved scan . | 89 | 18 |
19,464 | @ Override public String getString ( String fldName ) throws RemoteException { try { fldName = fldName . toLowerCase ( ) ; // to ensure case-insensitivity return ( String ) s . getVal ( fldName ) . castTo ( VARCHAR ) . asJavaVal ( ) ; } catch ( RuntimeException e ) { rconn . rollback ( ) ; throw e ; } } | Returns the string value of the specified field by returning the corresponding value on the saved scan . | 89 | 18 |
19,465 | @ Override public void close ( ) throws RemoteException { s . close ( ) ; if ( rconn . getAutoCommit ( ) ) rconn . commit ( ) ; else rconn . endStatement ( ) ; } | Closes the result set by closing its scan . | 47 | 10 |
19,466 | @ Override public boolean next ( ) { while ( true ) { if ( rp . next ( ) ) return true ; if ( current == endBlkNum ) return false ; moveToBlock ( current + 1 ) ; } } | Moves to the next record in the current block of the chunk . If there are no more records then make the next block be current . If there are no more blocks in the chunk return false . | 49 | 40 |
19,467 | public static Type newInstance ( int sqlType ) { switch ( sqlType ) { case ( java . sql . Types . INTEGER ) : return INTEGER ; case ( java . sql . Types . BIGINT ) : return BIGINT ; case ( java . sql . Types . DOUBLE ) : return DOUBLE ; case ( java . sql . Types . VARCHAR ) : return VARCHAR ; } throw new UnsupportedOperationException ( "Unspported SQL type: " + sqlType ) ; } | Constructs a new instance corresponding to the specified SQL type . | 110 | 12 |
19,468 | public Buffer pin ( BlockId blk ) { // Try to find out if this block has been pinned by this transaction PinnedBuffer pinnedBuff = pinnedBuffers . get ( blk ) ; if ( pinnedBuff != null ) { pinnedBuff . pinnedCount ++ ; return pinnedBuff . buffer ; } // This transaction has pinned too many buffers if ( pinnedBuffers . size ( ) == BUFFER_POOL_SIZE ) throw new BufferAbortException ( ) ; // Pinning process try { Buffer buff ; long timestamp = System . currentTimeMillis ( ) ; boolean waitedBeforeGotBuffer = false ; // Try to pin a buffer or the pinned buffer for the given BlockId buff = bufferPool . pin ( blk ) ; // If there is no such buffer or no available buffer, // wait for it if ( buff == null ) { waitedBeforeGotBuffer = true ; synchronized ( bufferPool ) { waitingThreads . add ( Thread . currentThread ( ) ) ; while ( buff == null && ! waitingTooLong ( timestamp ) ) { bufferPool . wait ( MAX_TIME ) ; if ( waitingThreads . get ( 0 ) . equals ( Thread . currentThread ( ) ) ) buff = bufferPool . pin ( blk ) ; } waitingThreads . remove ( Thread . currentThread ( ) ) ; } } // If it still has no buffer after a long wait, // release and re-pin all buffers it has if ( buff == null ) { repin ( ) ; buff = pin ( blk ) ; } else { pinnedBuffers . put ( buff . block ( ) , new PinnedBuffer ( buff ) ) ; } // TODO: Add some comment here if ( waitedBeforeGotBuffer ) { synchronized ( bufferPool ) { bufferPool . notifyAll ( ) ; } } return buff ; } catch ( InterruptedException e ) { throw new BufferAbortException ( ) ; } } | Pins a buffer to the specified block potentially waiting until a buffer becomes available . If no buffer becomes available within a fixed time period then repins all currently holding blocks . | 398 | 34 |
19,469 | public Buffer pinNew ( String fileName , PageFormatter fmtr ) { if ( pinnedBuffers . size ( ) == BUFFER_POOL_SIZE ) throw new BufferAbortException ( ) ; try { Buffer buff ; long timestamp = System . currentTimeMillis ( ) ; boolean waitedBeforeGotBuffer = false ; // Try to pin a buffer or the pinned buffer for the given BlockId buff = bufferPool . pinNew ( fileName , fmtr ) ; // If there is no such buffer or no available buffer, // wait for it if ( buff == null ) { waitedBeforeGotBuffer = true ; synchronized ( bufferPool ) { waitingThreads . add ( Thread . currentThread ( ) ) ; while ( buff == null && ! waitingTooLong ( timestamp ) ) { bufferPool . wait ( MAX_TIME ) ; if ( waitingThreads . get ( 0 ) . equals ( Thread . currentThread ( ) ) ) buff = bufferPool . pinNew ( fileName , fmtr ) ; } waitingThreads . remove ( Thread . currentThread ( ) ) ; } } // If it still has no buffer after a long wait, // release and re-pin all buffers it has if ( buff == null ) { repin ( ) ; buff = pinNew ( fileName , fmtr ) ; } else { pinnedBuffers . put ( buff . block ( ) , new PinnedBuffer ( buff ) ) ; } // TODO: Add some comment here if ( waitedBeforeGotBuffer ) { synchronized ( bufferPool ) { bufferPool . notifyAll ( ) ; } } return buff ; } catch ( InterruptedException e ) { throw new BufferAbortException ( ) ; } } | Pins a buffer to a new block in the specified file potentially waiting until a buffer becomes available . If no buffer becomes available within a fixed time period then repins all currently holding blocks . | 356 | 38 |
19,470 | public void unpin ( Buffer buff ) { BlockId blk = buff . block ( ) ; PinnedBuffer pinnedBuff = pinnedBuffers . get ( blk ) ; if ( pinnedBuff != null ) { pinnedBuff . pinnedCount -- ; if ( pinnedBuff . pinnedCount == 0 ) { bufferPool . unpin ( buff ) ; pinnedBuffers . remove ( blk ) ; synchronized ( bufferPool ) { bufferPool . notifyAll ( ) ; } } } } | Unpins the specified buffer . If the buffer s pin count becomes 0 then the threads on the wait list are notified . | 99 | 24 |
19,471 | private void repin ( ) { if ( logger . isLoggable ( Level . WARNING ) ) logger . warning ( "Tx." + txNum + " is re-pinning all buffers" ) ; try { // Copy the set of pinned buffers to avoid ConcurrentModificationException List < BlockId > blksToBeRepinned = new LinkedList < BlockId > ( ) ; Map < BlockId , Integer > pinCounts = new HashMap < BlockId , Integer > ( ) ; List < Buffer > buffersToBeUnpinned = new LinkedList < Buffer > ( ) ; // Record the buffers to be un-pinned and the blocks to be re-pinned for ( Entry < BlockId , PinnedBuffer > entry : pinnedBuffers . entrySet ( ) ) { blksToBeRepinned . add ( entry . getKey ( ) ) ; pinCounts . put ( entry . getKey ( ) , entry . getValue ( ) . pinnedCount ) ; buffersToBeUnpinned . add ( entry . getValue ( ) . buffer ) ; } // Un-pin all buffers it has for ( Buffer buf : buffersToBeUnpinned ) unpin ( buf ) ; // Wait other threads pinning blocks synchronized ( bufferPool ) { bufferPool . wait ( MAX_TIME ) ; } // Re-pin all blocks for ( BlockId blk : blksToBeRepinned ) pin ( blk ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } | Unpins all currently pinned buffers of the calling transaction and repins them . | 328 | 15 |
19,472 | public static Map < String , Integer > offsetMap ( Schema sch ) { int pos = 0 ; Map < String , Integer > offsetMap = new HashMap < String , Integer > ( ) ; for ( String fldname : sch . fields ( ) ) { offsetMap . put ( fldname , pos ) ; pos += Page . maxSize ( sch . type ( fldname ) ) ; } return offsetMap ; } | Returns the map of field name to offset of a specified schema . | 90 | 13 |
19,473 | public static int recordSize ( Schema sch ) { int pos = 0 ; for ( String fldname : sch . fields ( ) ) pos += Page . maxSize ( sch . type ( fldname ) ) ; return pos < MIN_REC_SIZE ? MIN_REC_SIZE : pos ; } | Returns the number of bytes required to store a record with the specified schema in disk . | 64 | 17 |
19,474 | public Constant getVal ( String fldName ) { int position = fieldPos ( fldName ) ; return getVal ( position , ti . schema ( ) . type ( fldName ) ) ; } | Returns the value stored in the specified field of this record . | 43 | 12 |
19,475 | public void setVal ( String fldName , Constant val ) { int position = fieldPos ( fldName ) ; setVal ( position , val ) ; } | Stores a value at the specified field of this record . | 34 | 12 |
19,476 | public void delete ( RecordId nextDeletedSlot ) { Constant flag = EMPTY_CONST ; setVal ( currentPos ( ) , flag ) ; setNextDeletedSlotId ( nextDeletedSlot ) ; } | Deletes the current record . Deletion is performed by marking the record as deleted and setting the content as a pointer points to next deleted slot . | 46 | 30 |
19,477 | public boolean insertIntoTheCurrentSlot ( ) { if ( ! getVal ( currentPos ( ) , INTEGER ) . equals ( EMPTY_CONST ) ) return false ; setVal ( currentPos ( ) , INUSE_CONST ) ; return true ; } | Marks the current slot as in - used . | 58 | 10 |
19,478 | public boolean insertIntoNextEmptySlot ( ) { boolean found = searchFor ( EMPTY ) ; if ( found ) { Constant flag = INUSE_CONST ; setVal ( currentPos ( ) , flag ) ; } return found ; } | Inserts a new blank record somewhere in the page . Return false if there were no available slots . | 51 | 20 |
19,479 | public RecordId insertIntoDeletedSlot ( ) { RecordId nds = getNextDeletedSlotId ( ) ; // Important: Erase the free chain information. // If we didn't do this, it would crash when // a tx try to set a VARCHAR at this position // since the getVal would get negative size. setNextDeletedSlotId ( new RecordId ( new BlockId ( "" , 0 ) , 0 ) ) ; Constant flag = INUSE_CONST ; setVal ( currentPos ( ) , flag ) ; return nds ; } | Inserts a new blank record into this deleted slot and return the record id of the next one . | 120 | 20 |
19,480 | public void runAllSlot ( ) { moveToId ( 0 ) ; System . out . println ( "== runAllSlot start at " + currentSlot + " ==" ) ; while ( isValidSlot ( ) ) { if ( currentSlot % 10 == 0 ) System . out . print ( currentSlot + ": " ) ; int flag = ( Integer ) getVal ( currentPos ( ) , INTEGER ) . asJavaVal ( ) ; System . out . print ( flag + " " ) ; if ( ( currentSlot + 1 ) % 10 == 0 ) System . out . println ( ) ; currentSlot ++ ; } System . out . println ( "== runAllSlot end at " + currentSlot + " ==" ) ; } | Print all Slot IN_USE or EMPTY for debugging | 157 | 11 |
19,481 | public synchronized void startCollecting ( ) { paused = false ; if ( thread != null ) return ; packages = new CountMap < String > ( MAX_PACKAGES ) ; selfMethods = new CountMap < String > ( MAX_METHODS ) ; stackMethods = new CountMap < String > ( MAX_METHODS ) ; lines = new CountMap < String > ( MAX_LINES ) ; total = 0 ; started = true ; thread = new Thread ( this ) ; thread . setName ( "Profiler" ) ; thread . setDaemon ( true ) ; thread . start ( ) ; } | Start collecting profiling data . | 127 | 5 |
19,482 | public synchronized void stopCollecting ( ) { started = false ; if ( thread != null ) { try { thread . join ( ) ; } catch ( InterruptedException e ) { // ignore } thread = null ; } } | Stop collecting . | 46 | 3 |
19,483 | public String getPackageCsv ( ) { stopCollecting ( ) ; StringBuilder buff = new StringBuilder ( ) ; buff . append ( "Package,Self" ) . append ( LINE_SEPARATOR ) ; for ( String k : new TreeSet < String > ( packages . keySet ( ) ) ) { int percent = 100 * packages . get ( k ) / Math . max ( total , 1 ) ; buff . append ( k ) . append ( "," ) . append ( percent ) . append ( LINE_SEPARATOR ) ; } return buff . toString ( ) ; } | Stop and obtain the self execution time of packages each as a row in CSV format . | 124 | 17 |
19,484 | public String getTopMethods ( int num ) { stopCollecting ( ) ; CountMap < String > selfms = new CountMap < String > ( selfMethods ) ; CountMap < String > stackms = new CountMap < String > ( stackMethods ) ; StringBuilder buff = new StringBuilder ( ) ; buff . append ( "Top methods over " ) . append ( time ) . append ( " ms (" ) . append ( pauseTime ) . append ( " ms paused), with " ) . append ( total ) . append ( " counts:" ) . append ( LINE_SEPARATOR ) ; buff . append ( "Rank\tSelf\tStack\tMethod" ) . append ( LINE_SEPARATOR ) ; for ( int i = 0 , n = 0 ; selfms . size ( ) > 0 && n < num ; i ++ ) { int highest = 0 ; List < Map . Entry < String , Integer > > bests = new ArrayList < Map . Entry < String , Integer > > ( ) ; for ( Map . Entry < String , Integer > el : selfms . entrySet ( ) ) { if ( el . getValue ( ) > highest ) { bests . clear ( ) ; bests . add ( el ) ; highest = el . getValue ( ) ; } else if ( el . getValue ( ) == highest ) { bests . add ( el ) ; } } for ( Map . Entry < String , Integer > e : bests ) { selfms . remove ( e . getKey ( ) ) ; int selfPercent = 100 * highest / Math . max ( total , 1 ) ; int stackPercent = 100 * stackms . remove ( e . getKey ( ) ) / Math . max ( total , 1 ) ; buff . append ( i + 1 ) . append ( "\t" ) . append ( selfPercent ) . append ( "%\t" ) . append ( stackPercent ) . append ( "%\t" ) . append ( e . getKey ( ) ) . append ( LINE_SEPARATOR ) ; n ++ ; } } return buff . toString ( ) ; } | Stop and obtain the top methods ordered by their self execution time . | 446 | 13 |
19,485 | public String getMethodCsv ( ) { stopCollecting ( ) ; StringBuilder buff = new StringBuilder ( ) ; buff . append ( "Method,Self" ) . append ( LINE_SEPARATOR ) ; for ( String k : new TreeSet < String > ( selfMethods . keySet ( ) ) ) { int percent = 100 * selfMethods . get ( k ) / Math . max ( total , 1 ) ; buff . append ( k ) . append ( "," ) . append ( percent ) . append ( LINE_SEPARATOR ) ; } return buff . toString ( ) ; } | Stop and obtain the self execution time of methods each as a row in CSV format . | 126 | 17 |
19,486 | public String getTopLines ( int num ) { stopCollecting ( ) ; CountMap < String > ls = new CountMap < String > ( lines ) ; StringBuilder buff = new StringBuilder ( ) ; buff . append ( "Top lines over " ) . append ( time ) . append ( " ms (" ) . append ( pauseTime ) . append ( " ms paused), with " ) . append ( total ) . append ( " counts:" ) . append ( LINE_SEPARATOR ) ; for ( int i = 0 , n = 0 ; ls . size ( ) > 0 && n < num ; i ++ ) { int highest = 0 ; List < Map . Entry < String , Integer > > bests = new ArrayList < Map . Entry < String , Integer > > ( ) ; for ( Map . Entry < String , Integer > el : ls . entrySet ( ) ) { if ( el . getValue ( ) > highest ) { bests . clear ( ) ; bests . add ( el ) ; highest = el . getValue ( ) ; } else if ( el . getValue ( ) == highest ) { bests . add ( el ) ; } } for ( Map . Entry < String , Integer > e : bests ) { ls . remove ( e . getKey ( ) ) ; int percent = 100 * highest / Math . max ( total , 1 ) ; buff . append ( "Rank: " ) . append ( i + 1 ) . append ( ", Self: " ) . append ( percent ) . append ( "%, Trace: " ) . append ( LINE_SEPARATOR ) . append ( e . getKey ( ) ) . append ( LINE_SEPARATOR ) ; n ++ ; } } return buff . toString ( ) ; } | Stop and obtain the top lines ordered by their execution time . | 371 | 12 |
19,487 | public void createIndex ( String idxName , String tblName , List < String > fldNames , IndexType idxType , Transaction tx ) { // Add the index infos to the index catalog RecordFile rf = idxTi . open ( tx , true ) ; rf . insert ( ) ; rf . setVal ( ICAT_IDXNAME , new VarcharConstant ( idxName ) ) ; rf . setVal ( ICAT_TBLNAME , new VarcharConstant ( tblName ) ) ; rf . setVal ( ICAT_IDXTYPE , new IntegerConstant ( idxType . toInteger ( ) ) ) ; rf . close ( ) ; // Add the field names to the key catalog rf = keyTi . open ( tx , true ) ; for ( String fldName : fldNames ) { rf . insert ( ) ; rf . setVal ( KCAT_IDXNAME , new VarcharConstant ( idxName ) ) ; rf . setVal ( KCAT_KEYNAME , new VarcharConstant ( fldName ) ) ; rf . close ( ) ; } updateCache ( new IndexInfo ( idxName , tblName , fldNames , idxType ) ) ; } | Creates an index of the specified type for the specified field . A unique ID is assigned to this index and its information is stored in the idxcat table . | 280 | 33 |
19,488 | public List < IndexInfo > getIndexInfo ( String tblName , String fldName , Transaction tx ) { // Check the cache if ( ! loadedTables . contains ( tblName ) ) { readFromFile ( tblName , tx ) ; } // Fetch from the cache Map < String , List < IndexInfo > > iiMap = iiMapByTblAndFlds . get ( tblName ) ; if ( iiMap == null ) return Collections . emptyList ( ) ; // avoid object creation List < IndexInfo > iiList = iiMap . get ( fldName ) ; if ( iiList == null ) return Collections . emptyList ( ) ; // avoid object creation // Defense copy return new LinkedList < IndexInfo > ( iiList ) ; } | Returns a map containing the index info for all indexes on the specified table . | 165 | 15 |
19,489 | public IndexInfo getIndexInfoByName ( String idxName , Transaction tx ) { // Fetch from the cache IndexInfo ii = iiMapByIdxNames . get ( idxName ) ; if ( ii != null ) return ii ; // Read from the catalog files String tblName = null ; List < String > fldNames = new LinkedList < String > ( ) ; IndexType idxType = null ; // Find the index in the index catalog RecordFile rf = idxTi . open ( tx , true ) ; rf . beforeFirst ( ) ; while ( rf . next ( ) ) { if ( ( ( String ) rf . getVal ( ICAT_IDXNAME ) . asJavaVal ( ) ) . equals ( idxName ) ) { tblName = ( String ) rf . getVal ( ICAT_TBLNAME ) . asJavaVal ( ) ; int idxtypeVal = ( Integer ) rf . getVal ( ICAT_IDXTYPE ) . asJavaVal ( ) ; idxType = IndexType . fromInteger ( idxtypeVal ) ; break ; } } rf . close ( ) ; if ( tblName == null ) return null ; // Find the corresponding field names rf = keyTi . open ( tx , true ) ; rf . beforeFirst ( ) ; while ( rf . next ( ) ) { if ( ( ( String ) rf . getVal ( KCAT_IDXNAME ) . asJavaVal ( ) ) . equals ( idxName ) ) { fldNames . add ( ( String ) rf . getVal ( KCAT_KEYNAME ) . asJavaVal ( ) ) ; } } rf . close ( ) ; // Materialize IndexInfos ii = new IndexInfo ( idxName , tblName , fldNames , idxType ) ; updateCache ( ii ) ; return ii ; } | Returns the requested index info object with the given index name . | 409 | 12 |
19,490 | public Index open ( Transaction tx ) { TableInfo ti = VanillaDb . catalogMgr ( ) . getTableInfo ( tblName , tx ) ; if ( ti == null ) throw new TableNotFoundException ( "table '" + tblName + "' is not defined in catalog." ) ; return Index . newInstance ( this , new SearchKeyType ( ti . schema ( ) , fldNames ) , tx ) ; } | Opens the index described by this object . | 91 | 9 |
19,491 | public Constant nextVal ( Type type ) { Constant val = pg . getVal ( currentPos , type ) ; currentPos += Page . size ( val ) ; return val ; } | Returns the next value of this log record . | 37 | 9 |
19,492 | @ Override public int getColumnType ( int column ) throws RemoteException { String fldname = getColumnName ( column ) ; return schema . type ( fldname ) . getSqlType ( ) ; } | Returns the type of the specified column . The method first finds the name of the field in that column and then looks up its type in the schema . | 46 | 30 |
19,493 | @ Override public int getColumnDisplaySize ( int column ) throws RemoteException { String fldname = getColumnName ( column ) ; Type fldtype = schema . type ( fldname ) ; if ( fldtype . isFixedSize ( ) ) // 6 and 12 digits for int and double respectively return fldtype . maxSize ( ) * 8 / 5 ; return schema . type ( fldname ) . getArgument ( ) ; } | Returns the number of characters required to display the specified column . | 96 | 12 |
19,494 | @ Override public boolean next ( ) { if ( isLhsEmpty ) return false ; if ( idx . next ( ) ) { ts . moveToRecordId ( idx . getDataRecordId ( ) ) ; return true ; } else if ( ! ( isLhsEmpty = ! s . next ( ) ) ) { resetIndex ( ) ; return next ( ) ; } else return false ; } | Moves the scan to the next record . The method moves to the next index record if possible . Otherwise it moves to the next LHS record and the first index record . If there are no more LHS records the method returns false . | 86 | 48 |
19,495 | @ Override public Constant getVal ( String fldName ) { if ( ts . hasField ( fldName ) ) return ts . getVal ( fldName ) ; else return s . getVal ( fldName ) ; } | Returns the Constant value of the specified field . | 50 | 9 |
19,496 | @ Override public boolean hasField ( String fldName ) { return ts . hasField ( fldName ) || s . hasField ( fldName ) ; } | Returns true if the field is in the schema . | 36 | 10 |
19,497 | @ Override public void undo ( Transaction tx ) { LogSeqNum lsn = tx . recoveryMgr ( ) . logLogicalAbort ( this . txNum , this . lsn ) ; VanillaDb . logMgr ( ) . flush ( lsn ) ; } | Appends a Logical Abort Record to indicate the logical operation has be aborted | 59 | 16 |
19,498 | public Collection < String > getViewNamesByTable ( String tblName , Transaction tx ) { Collection < String > result = new LinkedList < String > ( ) ; TableInfo ti = tblMgr . getTableInfo ( VCAT , tx ) ; RecordFile rf = ti . open ( tx , true ) ; rf . beforeFirst ( ) ; while ( rf . next ( ) ) { Parser parser = new Parser ( ( String ) rf . getVal ( VCAT_VDEF ) . asJavaVal ( ) ) ; if ( parser . queryCommand ( ) . tables ( ) . contains ( tblName ) ) result . add ( ( String ) rf . getVal ( VCAT_VNAME ) . asJavaVal ( ) ) ; } rf . close ( ) ; return result ; } | We may have to come out a better method . | 177 | 10 |
19,499 | @ Override public boolean next ( ) { if ( ! moreGroups ) return false ; if ( aggFns != null ) for ( AggregationFn fn : aggFns ) fn . processFirst ( ss ) ; groupVal = new GroupValue ( ss , groupFlds ) ; while ( moreGroups = ss . next ( ) ) { GroupValue gv = new GroupValue ( ss , groupFlds ) ; if ( ! groupVal . equals ( gv ) ) break ; if ( aggFns != null ) for ( AggregationFn fn : aggFns ) fn . processNext ( ss ) ; } return true ; } | Moves to the next group . The key of the group is determined by the group values at the current record . The method repeatedly reads underlying records until it encounters a record having a different key . The aggregation functions are called for each record in the group . The values of the grouping fields for the group are saved . | 139 | 63 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.