idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
31,500
synchronized void mergeRollback ( Row row ) { RowActionBase action = this ; RowActionBase head = null ; RowActionBase tail = null ; if ( type == RowActionBase . ACTION_DELETE_FINAL || type == RowActionBase . ACTION_NONE ) { return ; } do { if ( action . rolledback ) { if ( tail != null ) { tail . next = null ; } } else { if ( head == null ) { head = tail = action ; } else { tail . next = action ; tail = action ; } } action = action . next ; } while ( action != null ) ; if ( head == null ) { boolean exists = ( type == RowActionBase . ACTION_DELETE ) ; if ( exists ) { setAsNoOp ( row ) ; } else { setAsDeleteFinal ( ) ; } } else { if ( head != this ) { setAsAction ( head ) ; } } }
merge rolled back actions
31,501
private void adjustReplicationFactorForURI ( HttpPut httpPut ) throws URISyntaxException { String queryString = httpPut . getURI ( ) . getQuery ( ) ; if ( ! StringUtils . isEmpty ( queryString ) && queryString . contains ( "op=CREATE" ) && ( queryString . contains ( "replication=" ) || ! StringUtils . isEmpty ( m_blockReplication ) ) ) { rateLimitedLogWarn ( m_logger , "Set block replication factor in the target system." ) ; if ( ! StringUtils . isEmpty ( m_blockReplication ) && ! queryString . contains ( "replication=" ) ) { StringBuilder builder = new StringBuilder ( 128 ) ; builder . append ( queryString ) . append ( "&replication=" ) . append ( m_blockReplication ) ; URI oldUri = httpPut . getURI ( ) ; URI newUri = new URI ( oldUri . getScheme ( ) , oldUri . getAuthority ( ) , oldUri . getPath ( ) , builder . toString ( ) , oldUri . getFragment ( ) ) ; httpPut . setURI ( newUri ) ; } } }
append replication factor to the URI for CREATE operation if the factor is not in URI
31,502
private List < NameValuePair > sign ( URI uri , final List < NameValuePair > params ) { Preconditions . checkNotNull ( m_secret ) ; final List < NameValuePair > sortedParams = Lists . newArrayList ( params ) ; Collections . sort ( sortedParams , new Comparator < NameValuePair > ( ) { public int compare ( NameValuePair left , NameValuePair right ) { return left . getName ( ) . compareTo ( right . getName ( ) ) ; } } ) ; final StringBuilder paramSb = new StringBuilder ( ) ; String separator = "" ; for ( NameValuePair param : sortedParams ) { paramSb . append ( separator ) . append ( param . getName ( ) ) ; if ( param . getValue ( ) != null ) { paramSb . append ( "=" ) . append ( param . getValue ( ) ) ; } separator = "&" ; } final StringBuilder baseSb = new StringBuilder ( ) ; baseSb . append ( m_method ) . append ( '\n' ) ; baseSb . append ( uri . getHost ( ) ) . append ( '\n' ) ; baseSb . append ( uri . getPath ( ) . isEmpty ( ) ? '/' : uri . getPath ( ) ) . append ( '\n' ) ; baseSb . append ( paramSb . toString ( ) ) ; final Mac hmac ; final Key key ; try { hmac = Mac . getInstance ( m_signatureMethod ) ; key = new SecretKeySpec ( m_secret . getBytes ( Charsets . UTF_8 ) , m_signatureMethod ) ; hmac . init ( key ) ; } catch ( NoSuchAlgorithmException e ) { rateLimitedLogError ( m_logger , "Fail to get HMAC instance %s" , Throwables . getStackTraceAsString ( e ) ) ; return null ; } catch ( InvalidKeyException e ) { rateLimitedLogError ( m_logger , "Fail to sign the message %s" , Throwables . getStackTraceAsString ( e ) ) ; return null ; } sortedParams . add ( new BasicNameValuePair ( m_signatureName , NVPairsDecoder . percentEncode ( Encoder . base64Encode ( hmac . doFinal ( baseSb . toString ( ) . getBytes ( Charsets . UTF_8 ) ) ) ) ) ) ; return sortedParams ; }
Calculate the signature of the request using the specified secret key .
31,503
public final FluentIterable < T > preOrderTraversal ( final T root ) { checkNotNull ( root ) ; return new FluentIterable < T > ( ) { public UnmodifiableIterator < T > iterator ( ) { return preOrderIterator ( root ) ; } } ; }
Returns an unmodifiable iterable over the nodes in a tree structure using pre - order traversal . That is each node s subtrees are traversed after the node itself is returned .
31,504
public final FluentIterable < T > breadthFirstTraversal ( final T root ) { checkNotNull ( root ) ; return new FluentIterable < T > ( ) { public UnmodifiableIterator < T > iterator ( ) { return new BreadthFirstIterator ( root ) ; } } ; }
Returns an unmodifiable iterable over the nodes in a tree structure using breadth - first traversal . That is all the nodes of depth 0 are returned then depth 1 then 2 and so on .
31,505
public String getUserName ( ) throws SQLException { ResultSet rs = execute ( "CALL USER()" ) ; rs . next ( ) ; String result = rs . getString ( 1 ) ; rs . close ( ) ; return result ; }
Retrieves the user name as known to this database .
31,506
public boolean isReadOnly ( ) throws SQLException { ResultSet rs = execute ( "CALL isReadOnlyDatabase()" ) ; rs . next ( ) ; boolean result = rs . getBoolean ( 1 ) ; rs . close ( ) ; return result ; }
Retrieves whether this database is in read - only mode .
31,507
private StringBuffer toQueryPrefixNoSelect ( String t ) { StringBuffer sb = new StringBuffer ( 255 ) ; return sb . append ( t ) . append ( whereTrue ) ; }
Retrieves &lt ; expression&gt ; WHERE 1 = 1 in string
31,508
public static ConstantValueExpression makeExpression ( VoltType dataType , String value ) { ConstantValueExpression constantExpr = new ConstantValueExpression ( ) ; constantExpr . setValueType ( dataType ) ; constantExpr . setValue ( value ) ; return constantExpr ; }
Create a new CVE for a given type and value
31,509
Result executeUpdateStatement ( Session session ) { int count = 0 ; Expression [ ] colExpressions = updateExpressions ; HashMappedList rowset = new HashMappedList ( ) ; Type [ ] colTypes = baseTable . getColumnTypes ( ) ; RangeIteratorBase it = RangeVariable . getIterator ( session , targetRangeVariables ) ; Expression checkCondition = null ; if ( targetTable != baseTable ) { checkCondition = ( ( TableDerived ) targetTable ) . getQueryExpression ( ) . getMainSelect ( ) . checkQueryCondition ; } while ( it . next ( ) ) { session . sessionData . startRowProcessing ( ) ; Row row = it . getCurrentRow ( ) ; Object [ ] data = row . getData ( ) ; Object [ ] newData = getUpdatedData ( session , baseTable , updateColumnMap , colExpressions , colTypes , data ) ; if ( checkCondition != null ) { it . currentData = newData ; boolean check = checkCondition . testCondition ( session ) ; if ( ! check ) { throw Error . error ( ErrorCode . X_44000 ) ; } } rowset . add ( row , newData ) ; } count = update ( session , baseTable , rowset ) ; return Result . getUpdateCountResult ( count ) ; }
Executes an UPDATE statement . It is assumed that the argument is of the correct type .
31,510
Result executeMergeStatement ( Session session ) { Result resultOut = null ; RowSetNavigator generatedNavigator = null ; PersistentStore store = session . sessionData . getRowStore ( baseTable ) ; if ( generatedIndexes != null ) { resultOut = Result . newUpdateCountResult ( generatedResultMetaData , 0 ) ; generatedNavigator = resultOut . getChainedResult ( ) . getNavigator ( ) ; } int count = 0 ; RowSetNavigatorClient newData = new RowSetNavigatorClient ( 8 ) ; HashMappedList updateRowSet = new HashMappedList ( ) ; RangeVariable [ ] joinRangeIterators = targetRangeVariables ; RangeIterator [ ] rangeIterators = new RangeIterator [ joinRangeIterators . length ] ; for ( int i = 0 ; i < joinRangeIterators . length ; i ++ ) { rangeIterators [ i ] = joinRangeIterators [ i ] . getIterator ( session ) ; } for ( int currentIndex = 0 ; 0 <= currentIndex ; ) { RangeIterator it = rangeIterators [ currentIndex ] ; boolean beforeFirst = it . isBeforeFirst ( ) ; if ( it . next ( ) ) { if ( currentIndex < joinRangeIterators . length - 1 ) { currentIndex ++ ; continue ; } } else { if ( currentIndex == 1 && beforeFirst ) { Object [ ] data = getMergeInsertData ( session ) ; if ( data != null ) { newData . add ( data ) ; } } it . reset ( ) ; currentIndex -- ; continue ; } if ( updateExpressions != null ) { Row row = it . getCurrentRow ( ) ; Object [ ] data = getUpdatedData ( session , baseTable , updateColumnMap , updateExpressions , baseTable . getColumnTypes ( ) , row . getData ( ) ) ; updateRowSet . add ( row , data ) ; } } if ( updateRowSet . size ( ) > 0 ) { count = update ( session , baseTable , updateRowSet ) ; } newData . beforeFirst ( ) ; while ( newData . hasNext ( ) ) { Object [ ] data = newData . getNext ( ) ; baseTable . insertRow ( session , store , data ) ; if ( generatedNavigator != null ) { Object [ ] generatedValues = getGeneratedColumns ( data ) ; generatedNavigator . add ( generatedValues ) ; } } baseTable . fireAfterTriggers ( session , Trigger . INSERT_AFTER , newData ) ; count += newData . getSize ( ) ; if ( resultOut == null ) { return Result . getUpdateCountResult ( count ) ; } else { resultOut . setUpdateCount ( count ) ; return resultOut ; } }
Executes a MERGE statement . It is assumed that the argument is of the correct type .
31,511
Result executeDeleteStatement ( Session session ) { int count = 0 ; RowSetNavigatorLinkedList oldRows = new RowSetNavigatorLinkedList ( ) ; RangeIterator it = RangeVariable . getIterator ( session , targetRangeVariables ) ; while ( it . next ( ) ) { Row currentRow = it . getCurrentRow ( ) ; oldRows . add ( currentRow ) ; } count = delete ( session , baseTable , oldRows ) ; if ( restartIdentity && targetTable . identitySequence != null ) { targetTable . identitySequence . reset ( ) ; } return Result . getUpdateCountResult ( count ) ; }
Executes a DELETE statement . It is assumed that the argument is of the correct type .
31,512
int delete ( Session session , Table table , RowSetNavigator oldRows ) { if ( table . fkMainConstraints . length == 0 ) { deleteRows ( session , table , oldRows ) ; oldRows . beforeFirst ( ) ; if ( table . hasTrigger ( Trigger . DELETE_AFTER ) ) { table . fireAfterTriggers ( session , Trigger . DELETE_AFTER , oldRows ) ; } return oldRows . getSize ( ) ; } HashSet path = session . sessionContext . getConstraintPath ( ) ; HashMappedList tableUpdateList = session . sessionContext . getTableUpdateList ( ) ; if ( session . database . isReferentialIntegrity ( ) ) { oldRows . beforeFirst ( ) ; while ( oldRows . hasNext ( ) ) { oldRows . next ( ) ; Row row = oldRows . getCurrentRow ( ) ; path . clear ( ) ; checkCascadeDelete ( session , table , tableUpdateList , row , false , path ) ; } } if ( session . database . isReferentialIntegrity ( ) ) { oldRows . beforeFirst ( ) ; while ( oldRows . hasNext ( ) ) { oldRows . next ( ) ; Row row = oldRows . getCurrentRow ( ) ; path . clear ( ) ; checkCascadeDelete ( session , table , tableUpdateList , row , true , path ) ; } } oldRows . beforeFirst ( ) ; while ( oldRows . hasNext ( ) ) { oldRows . next ( ) ; Row row = oldRows . getCurrentRow ( ) ; if ( ! row . isDeleted ( session ) ) { table . deleteNoRefCheck ( session , row ) ; } } for ( int i = 0 ; i < tableUpdateList . size ( ) ; i ++ ) { Table targetTable = ( Table ) tableUpdateList . getKey ( i ) ; HashMappedList updateList = ( HashMappedList ) tableUpdateList . get ( i ) ; if ( updateList . size ( ) > 0 ) { targetTable . updateRowSet ( session , updateList , null , true ) ; updateList . clear ( ) ; } } oldRows . beforeFirst ( ) ; if ( table . hasTrigger ( Trigger . DELETE_AFTER ) ) { table . fireAfterTriggers ( session , Trigger . DELETE_AFTER , oldRows ) ; } path . clear ( ) ; return oldRows . getSize ( ) ; }
Highest level multiple row delete method . Corresponds to an SQL DELETE .
31,513
static void mergeUpdate ( HashMappedList rowSet , Row row , Object [ ] newData , int [ ] cols ) { Object [ ] data = ( Object [ ] ) rowSet . get ( row ) ; if ( data != null ) { for ( int j = 0 ; j < cols . length ; j ++ ) { data [ cols [ j ] ] = newData [ cols [ j ] ] ; } } else { rowSet . add ( row , newData ) ; } }
Merges a triggered change with a previous triggered change or adds to list .
31,514
static boolean mergeKeepUpdate ( Session session , HashMappedList rowSet , int [ ] cols , Type [ ] colTypes , Row row , Object [ ] newData ) { Object [ ] data = ( Object [ ] ) rowSet . get ( row ) ; if ( data != null ) { if ( IndexAVL . compareRows ( row . getData ( ) , newData , cols , colTypes ) != 0 && IndexAVL . compareRows ( newData , data , cols , colTypes ) != 0 ) { return false ; } for ( int j = 0 ; j < cols . length ; j ++ ) { newData [ cols [ j ] ] = data [ cols [ j ] ] ; } rowSet . put ( row , newData ) ; } else { rowSet . add ( row , newData ) ; } return true ; }
Merge the full triggered change with the updated row or add to list . Return false if changes conflict .
31,515
protected ExportRowData decodeRow ( byte [ ] rowData ) throws IOException { ExportRow row = ExportRow . decodeRow ( m_legacyRow , getPartition ( ) , m_startTS , rowData ) ; return new ExportRowData ( row . values , row . partitionValue , row . partitionId ) ; }
Decode a byte array of row data into ExportRowData
31,516
public boolean writeRow ( Object row [ ] , CSVWriter writer , boolean skipinternal , BinaryEncoding binaryEncoding , SimpleDateFormat dateFormatter ) { int firstfield = getFirstField ( skipinternal ) ; try { String [ ] fields = new String [ m_tableSchema . size ( ) - firstfield ] ; for ( int i = firstfield ; i < m_tableSchema . size ( ) ; i ++ ) { if ( row [ i ] == null ) { fields [ i - firstfield ] = "NULL" ; } else if ( m_tableSchema . get ( i ) == VoltType . VARBINARY && binaryEncoding != null ) { if ( binaryEncoding == BinaryEncoding . HEX ) { fields [ i - firstfield ] = Encoder . hexEncode ( ( byte [ ] ) row [ i ] ) ; } else { fields [ i - firstfield ] = Encoder . base64Encode ( ( byte [ ] ) row [ i ] ) ; } } else if ( m_tableSchema . get ( i ) == VoltType . STRING ) { fields [ i - firstfield ] = ( String ) row [ i ] ; } else if ( m_tableSchema . get ( i ) == VoltType . TIMESTAMP && dateFormatter != null ) { TimestampType timestamp = ( TimestampType ) row [ i ] ; fields [ i - firstfield ] = dateFormatter . format ( timestamp . asApproximateJavaDate ( ) ) ; } else { fields [ i - firstfield ] = row [ i ] . toString ( ) ; } } writer . writeNext ( fields ) ; } catch ( Exception x ) { x . printStackTrace ( ) ; return false ; } return true ; }
This is for legacy connector .
31,517
public final int setPartitionColumnName ( String partitionColumnName ) { if ( partitionColumnName == null || partitionColumnName . trim ( ) . isEmpty ( ) ) { return PARTITION_ID_INDEX ; } int idx = - 1 ; for ( String name : m_source . columnNames ) { if ( name . equalsIgnoreCase ( partitionColumnName ) ) { idx = m_source . columnNames . indexOf ( name ) ; break ; } } if ( idx == - 1 ) { m_partitionColumnIndex = PARTITION_ID_INDEX ; m_logger . error ( "Export configuration error: specified " + m_source . tableName + "." + partitionColumnName + " does not exist. A default partition or routing key will be used." ) ; } else { m_partitionColumnIndex = idx ; } return m_partitionColumnIndex ; }
Used for override of column for partitioning . This is for legacy connector only .
31,518
public static void registerShutdownHook ( int priority , boolean runOnCrash , Runnable action ) { m_instance . addHook ( priority , runOnCrash , action ) ; ShutdownHooks . m_crashMessage = true ; }
Register an action to be run when the JVM exits .
31,519
SocketAddress getRemoteSocketAddress ( ) { try { return ( ( SocketChannel ) sendThread . sockKey . channel ( ) ) . socket ( ) . getRemoteSocketAddress ( ) ; } catch ( NullPointerException e ) { return null ; } }
Returns the address to which the socket is connected .
31,520
SocketAddress getLocalSocketAddress ( ) { try { return ( ( SocketChannel ) sendThread . sockKey . channel ( ) ) . socket ( ) . getLocalSocketAddress ( ) ; } catch ( NullPointerException e ) { return null ; } }
Returns the local address to which the socket is bound .
31,521
private static String makeThreadName ( String suffix ) { String name = Thread . currentThread ( ) . getName ( ) . replaceAll ( "-EventThread" , "" ) ; return name + suffix ; }
Guard against creating - EventThread - EventThread - EventThread - ... thread names when ZooKeeper object is being created from within a watcher . See ZOOKEEPER - 795 for details .
31,522
public void commit ( Xid xid , boolean onePhase ) throws XAException { System . err . println ( "Performing a " + ( onePhase ? "1-phase" : "2-phase" ) + " commit on " + xid ) ; JDBCXAResource resource = xaDataSource . getResource ( xid ) ; if ( resource == null ) { throw new XAException ( "The XADataSource has no such Xid: " + xid ) ; } resource . commitThis ( onePhase ) ; }
Per the JDBC 3 . 0 spec this commits the transaction for the specified Xid not necessarily for the transaction associated with this XAResource object .
31,523
public boolean isSameRM ( XAResource xares ) throws XAException { if ( ! ( xares instanceof JDBCXAResource ) ) { return false ; } return xaDataSource == ( ( JDBCXAResource ) xares ) . getXADataSource ( ) ; }
Stub . See implementation comment in the method for why this is not implemented yet .
31,524
public int prepare ( Xid xid ) throws XAException { validateXid ( xid ) ; if ( state != XA_STATE_ENDED ) { throw new XAException ( "Invalid XAResource state" ) ; } state = XA_STATE_PREPARED ; return XA_OK ; }
Vote on whether to commit the global transaction .
31,525
public void rollback ( Xid xid ) throws XAException { JDBCXAResource resource = xaDataSource . getResource ( xid ) ; if ( resource == null ) { throw new XAException ( "The XADataSource has no such Xid in prepared state: " + xid ) ; } resource . rollbackThis ( ) ; }
Per the JDBC 3 . 0 spec this rolls back the transaction for the specified Xid not necessarily for the transaction associated with this XAResource object .
31,526
private void processValue ( String value ) { if ( hasValueSeparator ( ) ) { char sep = getValueSeparator ( ) ; int index = value . indexOf ( sep ) ; while ( index != - 1 ) { if ( values . size ( ) == numberOfArgs - 1 ) { break ; } add ( value . substring ( 0 , index ) ) ; value = value . substring ( index + 1 ) ; index = value . indexOf ( sep ) ; } } add ( value ) ; }
Processes the value . If this Option has a value separator the value will have to be parsed into individual tokens . When n - 1 tokens have been processed and there are more value separators in the value parsing is ceased and the remaining characters are added as a single token .
31,527
public boolean enterWhenUninterruptibly ( Guard guard , long time , TimeUnit unit ) { final long timeoutNanos = toSafeNanos ( time , unit ) ; if ( guard . monitor != this ) { throw new IllegalMonitorStateException ( ) ; } final ReentrantLock lock = this . lock ; long startTime = 0L ; boolean signalBeforeWaiting = lock . isHeldByCurrentThread ( ) ; boolean interrupted = Thread . interrupted ( ) ; try { if ( fair || ! lock . tryLock ( ) ) { startTime = initNanoTime ( timeoutNanos ) ; for ( long remainingNanos = timeoutNanos ; ; ) { try { if ( lock . tryLock ( remainingNanos , TimeUnit . NANOSECONDS ) ) { break ; } else { return false ; } } catch ( InterruptedException interrupt ) { interrupted = true ; remainingNanos = remainingNanos ( startTime , timeoutNanos ) ; } } } boolean satisfied = false ; try { while ( true ) { try { if ( guard . isSatisfied ( ) ) { satisfied = true ; } else { final long remainingNanos ; if ( startTime == 0L ) { startTime = initNanoTime ( timeoutNanos ) ; remainingNanos = timeoutNanos ; } else { remainingNanos = remainingNanos ( startTime , timeoutNanos ) ; } satisfied = awaitNanos ( guard , remainingNanos , signalBeforeWaiting ) ; } return satisfied ; } catch ( InterruptedException interrupt ) { interrupted = true ; signalBeforeWaiting = false ; } } } finally { if ( ! satisfied ) { lock . unlock ( ) ; } } } finally { if ( interrupted ) { Thread . currentThread ( ) . interrupt ( ) ; } } }
Enters this monitor when the guard is satisfied . Blocks at most the given time including both the time to acquire the lock and the time to wait for the guard to be satisfied .
31,528
public boolean enterIfInterruptibly ( Guard guard , long time , TimeUnit unit ) throws InterruptedException { if ( guard . monitor != this ) { throw new IllegalMonitorStateException ( ) ; } final ReentrantLock lock = this . lock ; if ( ! lock . tryLock ( time , unit ) ) { return false ; } boolean satisfied = false ; try { return satisfied = guard . isSatisfied ( ) ; } finally { if ( ! satisfied ) { lock . unlock ( ) ; } } }
Enters this monitor if the guard is satisfied . Blocks at most the given time acquiring the lock but does not wait for the guard to be satisfied and may be interrupted .
31,529
public boolean waitFor ( Guard guard , long time , TimeUnit unit ) throws InterruptedException { final long timeoutNanos = toSafeNanos ( time , unit ) ; if ( ! ( ( guard . monitor == this ) & lock . isHeldByCurrentThread ( ) ) ) { throw new IllegalMonitorStateException ( ) ; } if ( guard . isSatisfied ( ) ) { return true ; } if ( Thread . interrupted ( ) ) { throw new InterruptedException ( ) ; } return awaitNanos ( guard , timeoutNanos , true ) ; }
Waits for the guard to be satisfied . Waits at most the given time and may be interrupted . May be called only by a thread currently occupying this monitor .
31,530
public void ack ( long hsId , boolean isEOS , long targetId , int blockIndex ) { rejoinLog . debug ( "Queue ack for hsId:" + hsId + " isEOS: " + isEOS + " targetId:" + targetId + " blockIndex: " + blockIndex ) ; m_blockIndices . offer ( Pair . of ( hsId , new RejoinDataAckMessage ( isEOS , targetId , blockIndex ) ) ) ; }
Ack with a positive block index .
31,531
public boolean absolute ( int row ) throws SQLException { checkClosed ( ) ; if ( rowCount == 0 ) { if ( row == 0 ) { return true ; } return false ; } if ( row == 0 ) { beforeFirst ( ) ; return true ; } if ( rowCount + row < 0 ) { beforeFirst ( ) ; return false ; } if ( row > rowCount ) { cursorPosition = Position . afterLast ; if ( row == rowCount + 1 ) { return true ; } else { return false ; } } try { if ( row < 0 ) { row += rowCount ; row ++ ; } if ( table . getActiveRowIndex ( ) > row || cursorPosition != Position . middle ) { table . resetRowPosition ( ) ; table . advanceToRow ( 0 ) ; } cursorPosition = Position . middle ; return table . advanceToRow ( row - 1 ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
Moves the cursor to the given row number in this ResultSet object .
31,532
public int findColumn ( String columnLabel ) throws SQLException { checkClosed ( ) ; try { return table . getColumnIndex ( columnLabel ) + 1 ; } catch ( IllegalArgumentException iax ) { throw SQLError . get ( iax , SQLError . COLUMN_NOT_FOUND , columnLabel ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
Maps the given ResultSet column label to its ResultSet column index .
31,533
public BigDecimal getBigDecimal ( int columnIndex ) throws SQLException { checkColumnBounds ( columnIndex ) ; try { final VoltType type = table . getColumnType ( columnIndex - 1 ) ; BigDecimal decimalValue = null ; switch ( type ) { case TINYINT : decimalValue = new BigDecimal ( table . getLong ( columnIndex - 1 ) ) ; break ; case SMALLINT : decimalValue = new BigDecimal ( table . getLong ( columnIndex - 1 ) ) ; break ; case INTEGER : decimalValue = new BigDecimal ( table . getLong ( columnIndex - 1 ) ) ; break ; case BIGINT : decimalValue = new BigDecimal ( table . getLong ( columnIndex - 1 ) ) ; break ; case FLOAT : decimalValue = new BigDecimal ( table . getDouble ( columnIndex - 1 ) ) ; break ; case DECIMAL : decimalValue = table . getDecimalAsBigDecimal ( columnIndex - 1 ) ; break ; default : throw new IllegalArgumentException ( "Cannot get BigDecimal value for column type '" + type + "'" ) ; } return table . wasNull ( ) ? null : decimalValue ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
ResultSet object as a java . math . BigDecimal with full precision .
31,534
public InputStream getBinaryStream ( int columnIndex ) throws SQLException { checkColumnBounds ( columnIndex ) ; try { return new ByteArrayInputStream ( table . getStringAsBytes ( columnIndex - 1 ) ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
ResultSet object as a stream of uninterpreted bytes .
31,535
public Blob getBlob ( int columnIndex ) throws SQLException { checkColumnBounds ( columnIndex ) ; try { return new SerialBlob ( table . getStringAsBytes ( columnIndex - 1 ) ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
ResultSet object as a Blob object in the Java programming language .
31,536
public boolean getBoolean ( int columnIndex ) throws SQLException { checkColumnBounds ( columnIndex ) ; try { return ( new Long ( table . getLong ( columnIndex - 1 ) ) ) . intValue ( ) == 1 ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
ResultSet object as a boolean in the Java programming language .
31,537
public byte getByte ( int columnIndex ) throws SQLException { checkColumnBounds ( columnIndex ) ; try { Long longValue = getPrivateInteger ( columnIndex ) ; if ( longValue > Byte . MAX_VALUE || longValue < Byte . MIN_VALUE ) { throw new SQLException ( "Value out of byte range" ) ; } return longValue . byteValue ( ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
ResultSet object as a byte in the Java programming language .
31,538
public byte [ ] getBytes ( int columnIndex ) throws SQLException { checkColumnBounds ( columnIndex ) ; try { if ( table . getColumnType ( columnIndex - 1 ) == VoltType . STRING ) return table . getStringAsBytes ( columnIndex - 1 ) ; else if ( table . getColumnType ( columnIndex - 1 ) == VoltType . VARBINARY ) return table . getVarbinary ( columnIndex - 1 ) ; else throw SQLError . get ( SQLError . CONVERSION_NOT_FOUND , table . getColumnType ( columnIndex - 1 ) , "byte[]" ) ; } catch ( SQLException x ) { throw x ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
ResultSet object as a byte array in the Java programming language .
31,539
public Clob getClob ( int columnIndex ) throws SQLException { checkColumnBounds ( columnIndex ) ; try { return new SerialClob ( table . getString ( columnIndex - 1 ) . toCharArray ( ) ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
ResultSet object as a Clob object in the Java programming language .
31,540
public float getFloat ( int columnIndex ) throws SQLException { checkColumnBounds ( columnIndex ) ; try { final VoltType type = table . getColumnType ( columnIndex - 1 ) ; Double doubleValue = null ; switch ( type ) { case TINYINT : doubleValue = new Double ( table . getLong ( columnIndex - 1 ) ) ; break ; case SMALLINT : doubleValue = new Double ( table . getLong ( columnIndex - 1 ) ) ; break ; case INTEGER : doubleValue = new Double ( table . getLong ( columnIndex - 1 ) ) ; break ; case BIGINT : doubleValue = new Double ( table . getLong ( columnIndex - 1 ) ) ; break ; case FLOAT : doubleValue = new Double ( table . getDouble ( columnIndex - 1 ) ) ; break ; case DECIMAL : doubleValue = table . getDecimalAsBigDecimal ( columnIndex - 1 ) . doubleValue ( ) ; break ; default : throw new IllegalArgumentException ( "Cannot get float value for column type '" + type + "'" ) ; } if ( table . wasNull ( ) ) { doubleValue = new Double ( 0 ) ; } else if ( Math . abs ( doubleValue ) > new Double ( Float . MAX_VALUE ) ) { throw new SQLException ( "Value out of float range" ) ; } return doubleValue . floatValue ( ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
ResultSet object as a float in the Java programming language .
31,541
public int getInt ( int columnIndex ) throws SQLException { checkColumnBounds ( columnIndex ) ; try { Long longValue = getPrivateInteger ( columnIndex ) ; if ( longValue > Integer . MAX_VALUE || longValue < Integer . MIN_VALUE ) { throw new SQLException ( "Value out of int range" ) ; } return longValue . intValue ( ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
ResultSet object as an int in the Java programming language .
31,542
public long getLong ( int columnIndex ) throws SQLException { checkColumnBounds ( columnIndex ) ; try { Long longValue = getPrivateInteger ( columnIndex ) ; return longValue ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
ResultSet object as a long in the Java programming language .
31,543
public Reader getNCharacterStream ( int columnIndex ) throws SQLException { checkColumnBounds ( columnIndex ) ; try { String value = table . getString ( columnIndex - 1 ) ; if ( ! wasNull ( ) ) return new StringReader ( value ) ; return null ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
ResultSet object as a java . io . Reader object .
31,544
public NClob getNClob ( int columnIndex ) throws SQLException { checkColumnBounds ( columnIndex ) ; try { return new JDBC4NClob ( table . getString ( columnIndex - 1 ) . toCharArray ( ) ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
ResultSet object as a NClob object in the Java programming language .
31,545
public Object getObject ( int columnIndex ) throws SQLException { checkColumnBounds ( columnIndex ) ; try { VoltType type = table . getColumnType ( columnIndex - 1 ) ; if ( type == VoltType . TIMESTAMP ) return getTimestamp ( columnIndex ) ; else return table . get ( columnIndex - 1 , type ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
ResultSet object as an Object in the Java programming language .
31,546
public short getShort ( int columnIndex ) throws SQLException { checkColumnBounds ( columnIndex ) ; try { Long longValue = getPrivateInteger ( columnIndex ) ; if ( longValue > Short . MAX_VALUE || longValue < Short . MIN_VALUE ) { throw new SQLException ( "Value out of short range" ) ; } return longValue . shortValue ( ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
ResultSet object as a short in the Java programming language .
31,547
public InputStream getUnicodeStream ( int columnIndex ) throws SQLException { checkColumnBounds ( columnIndex ) ; throw SQLError . noSupport ( ) ; }
Deprecated . use getCharacterStream in place of getUnicodeStream
31,548
public InputStream getUnicodeStream ( String columnLabel ) throws SQLException { return getUnicodeStream ( findColumn ( columnLabel ) ) ; }
Deprecated . use getCharacterStream instead
31,549
public boolean last ( ) throws SQLException { checkClosed ( ) ; if ( rowCount == 0 ) { return false ; } try { if ( cursorPosition != Position . middle ) { cursorPosition = Position . middle ; table . resetRowPosition ( ) ; table . advanceToRow ( 0 ) ; } return table . advanceToRow ( rowCount - 1 ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
Moves the cursor to the last row in this ResultSet object .
31,550
public boolean next ( ) throws SQLException { checkClosed ( ) ; if ( cursorPosition == Position . afterLast || table . getActiveRowIndex ( ) == rowCount - 1 ) { cursorPosition = Position . afterLast ; return false ; } if ( cursorPosition == Position . beforeFirst ) { cursorPosition = Position . middle ; } try { return table . advanceRow ( ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
Moves the cursor forward one row from its current position .
31,551
public boolean previous ( ) throws SQLException { checkClosed ( ) ; if ( cursorPosition == Position . afterLast ) { return last ( ) ; } if ( cursorPosition == Position . beforeFirst || table . getActiveRowIndex ( ) <= 0 ) { beforeFirst ( ) ; return false ; } try { int tempRowIndex = table . getActiveRowIndex ( ) ; table . resetRowPosition ( ) ; table . advanceToRow ( 0 ) ; return table . advanceToRow ( tempRowIndex - 1 ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
Moves the cursor to the previous row in this ResultSet object .
31,552
public boolean relative ( int rows ) throws SQLException { checkClosed ( ) ; if ( rowCount == 0 ) { return false ; } if ( cursorPosition == Position . afterLast && rows > 0 ) { return false ; } if ( cursorPosition == Position . beforeFirst && rows <= 0 ) { return false ; } if ( table . getActiveRowIndex ( ) + rows >= rowCount ) { cursorPosition = Position . afterLast ; if ( table . getActiveRowIndex ( ) + rows == rowCount ) { return true ; } return false ; } try { int rowsToMove = table . getActiveRowIndex ( ) + rows ; if ( cursorPosition == Position . beforeFirst || rows < 0 ) { if ( cursorPosition == Position . afterLast ) { rowsToMove = rowCount + rows ; } else if ( cursorPosition == Position . beforeFirst ) { rowsToMove = rows - 1 ; } else { rowsToMove = table . getActiveRowIndex ( ) + rows ; } if ( rowsToMove < 0 ) { beforeFirst ( ) ; return false ; } table . resetRowPosition ( ) ; table . advanceToRow ( 0 ) ; } cursorPosition = Position . middle ; return table . advanceToRow ( rowsToMove ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
Moves the cursor a relative number of rows either positive or negative .
31,553
public void setFetchDirection ( int direction ) throws SQLException { if ( ( direction != FETCH_FORWARD ) && ( direction != FETCH_REVERSE ) && ( direction != FETCH_UNKNOWN ) ) throw SQLError . get ( SQLError . ILLEGAL_STATEMENT , direction ) ; this . fetchDirection = direction ; }
object will be processed .
31,554
public void updateAsciiStream ( String columnLabel , InputStream x , long length ) throws SQLException { throw SQLError . noSupport ( ) ; }
the specified number of bytes .
31,555
public void updateBlob ( String columnLabel , InputStream inputStream , long length ) throws SQLException { throw SQLError . noSupport ( ) ; }
have the specified number of bytes .
31,556
public void updateNClob ( String columnLabel , Reader reader , long length ) throws SQLException { throw SQLError . noSupport ( ) ; }
given number of characters long .
31,557
public void updateObject ( String columnLabel , Object x , int scaleOrLength ) throws SQLException { throw SQLError . noSupport ( ) ; }
Updates the designated column with an Object value .
31,558
public boolean wasNull ( ) throws SQLException { checkClosed ( ) ; try { return table . wasNull ( ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } }
Reports whether the last column read had a value of SQL NULL .
31,559
public Object [ ] getRowData ( ) throws SQLException { Object [ ] row = new Object [ columnCount ] ; for ( int i = 1 ; i < columnCount + 1 ; i ++ ) { row [ i - 1 ] = getObject ( i ) ; } return row ; }
Retrieve the raw row data as an array
31,560
void transformAndQueue ( T event , long systemCurrentTimeMillis ) { if ( rand . nextDouble ( ) < 0.05 ) { transformAndQueue ( event , systemCurrentTimeMillis ) ; } long delayms = nextZipfDelay ( ) ; delayed . add ( systemCurrentTimeMillis + delayms , event ) ; }
Possibly duplicate and delay by some random amount .
31,561
public T next ( long systemCurrentTimeMillis ) { while ( delayed . size ( ) < 10000 ) { T event = source . next ( systemCurrentTimeMillis ) ; if ( event == null ) { break ; } transformAndQueue ( event , systemCurrentTimeMillis ) ; } return delayed . nextReady ( systemCurrentTimeMillis ) ; }
Return the next event that is safe for delivery or null if there are no safe objects to deliver .
31,562
public int compareNames ( SchemaColumn that ) { String thatTbl ; String thisTbl ; if ( m_tableAlias != null && that . m_tableAlias != null ) { thisTbl = m_tableAlias ; thatTbl = that . m_tableAlias ; } else { thisTbl = m_tableName ; thatTbl = that . m_tableName ; } int tblCmp = nullSafeStringCompareTo ( thisTbl , thatTbl ) ; if ( tblCmp != 0 ) { return tblCmp ; } String thisCol ; String thatCol ; if ( m_columnName != null && that . m_columnName != null ) { thisCol = m_columnName ; thatCol = that . m_columnName ; } else { thisCol = m_columnAlias ; thatCol = that . m_columnAlias ; } int colCmp = nullSafeStringCompareTo ( thisCol , thatCol ) ; return colCmp ; }
Compare this schema column to the input .
31,563
public SchemaColumn copyAndReplaceWithTVE ( int colIndex ) { TupleValueExpression newTve ; if ( m_expression instanceof TupleValueExpression ) { newTve = ( TupleValueExpression ) m_expression . clone ( ) ; newTve . setColumnIndex ( colIndex ) ; } else { newTve = new TupleValueExpression ( m_tableName , m_tableAlias , m_columnName , m_columnAlias , m_expression , colIndex ) ; } return new SchemaColumn ( m_tableName , m_tableAlias , m_columnName , m_columnAlias , newTve , m_differentiator ) ; }
Return a copy of this SchemaColumn but with the input expression replaced by an appropriate TupleValueExpression .
31,564
synchronized void offer ( TransactionTask task ) { Iv2Trace . logTransactionTaskQueueOffer ( task ) ; m_backlog . addLast ( task ) ; taskQueueOffer ( ) ; }
Stick this task in the backlog . Many network threads may be racing to reach here synchronize to serialize queue order . Always returns true in this case side effect of extending TransactionTaskQueue .
31,565
private boolean aquireFileLock ( ) { final RandomAccessFile lraf = super . raf ; boolean success = false ; try { if ( this . fileLock != null ) { if ( this . fileLock . isValid ( ) ) { return true ; } else { this . releaseFileLock ( ) ; } } if ( isPosixManditoryFileLock ( ) ) { try { Runtime . getRuntime ( ) . exec ( new String [ ] { "chmod" , "g+s,g-x" , file . getPath ( ) } ) ; } catch ( Exception ex ) { } } this . fileLock = lraf . getChannel ( ) . tryLock ( 0 , MIN_LOCK_REGION , false ) ; success = ( this . fileLock != null && this . fileLock . isValid ( ) ) ; } catch ( Exception e ) { } if ( ! success ) { this . releaseFileLock ( ) ; } return success ; }
does the real work of aquiring the FileLock
31,566
private boolean releaseFileLock ( ) { boolean success = false ; if ( this . fileLock == null ) { success = true ; } else { try { this . fileLock . release ( ) ; success = true ; } catch ( Exception e ) { } finally { this . fileLock = null ; } } return success ; }
does the real work of releasing the FileLock
31,567
protected Object addOrRemove ( int intKey , Object objectValue , boolean remove ) { int hash = intKey ; int index = hashIndex . getHashIndex ( hash ) ; int lookup = hashIndex . hashTable [ index ] ; int lastLookup = - 1 ; Object returnValue = null ; for ( ; lookup >= 0 ; lastLookup = lookup , lookup = hashIndex . getNextLookup ( lookup ) ) { if ( intKey == intKeyTable [ lookup ] ) { break ; } } if ( lookup >= 0 ) { if ( remove ) { if ( intKey == 0 ) { hasZeroKey = false ; zeroKeyIndex = - 1 ; } intKeyTable [ lookup ] = 0 ; returnValue = objectValueTable [ lookup ] ; objectValueTable [ lookup ] = null ; hashIndex . unlinkNode ( index , lastLookup , lookup ) ; if ( accessTable != null ) { accessTable [ lookup ] = 0 ; } return returnValue ; } if ( isObjectValue ) { returnValue = objectValueTable [ lookup ] ; objectValueTable [ lookup ] = objectValue ; } if ( accessTable != null ) { accessTable [ lookup ] = accessCount ++ ; } return returnValue ; } if ( remove ) { return returnValue ; } if ( hashIndex . elementCount >= threshold ) { if ( reset ( ) ) { return addOrRemove ( intKey , objectValue , remove ) ; } else { return null ; } } lookup = hashIndex . linkNode ( index , lastLookup ) ; intKeyTable [ lookup ] = intKey ; if ( intKey == 0 ) { hasZeroKey = true ; zeroKeyIndex = lookup ; } objectValueTable [ lookup ] = objectValue ; if ( accessTable != null ) { accessTable [ lookup ] = accessCount ++ ; } return returnValue ; }
type - specific method for adding or removing keys in int - > Object maps
31,568
protected Object removeObject ( Object objectKey , boolean removeRow ) { if ( objectKey == null ) { return null ; } int hash = objectKey . hashCode ( ) ; int index = hashIndex . getHashIndex ( hash ) ; int lookup = hashIndex . hashTable [ index ] ; int lastLookup = - 1 ; Object returnValue = null ; for ( ; lookup >= 0 ; lastLookup = lookup , lookup = hashIndex . getNextLookup ( lookup ) ) { if ( objectKeyTable [ lookup ] . equals ( objectKey ) ) { objectKeyTable [ lookup ] = null ; hashIndex . unlinkNode ( index , lastLookup , lookup ) ; if ( isObjectValue ) { returnValue = objectValueTable [ lookup ] ; objectValueTable [ lookup ] = null ; } if ( removeRow ) { removeRow ( lookup ) ; } return returnValue ; } } return returnValue ; }
type specific method for Object sets or Object - > Object maps
31,569
public void clear ( ) { if ( hashIndex . modified ) { accessCount = 0 ; accessMin = accessCount ; hasZeroKey = false ; zeroKeyIndex = - 1 ; clearElementArrays ( 0 , hashIndex . linkTable . length ) ; hashIndex . clear ( ) ; if ( minimizeOnEmpty ) { rehash ( initialCapacity ) ; } } }
Clear the map completely .
31,570
public int getAccessCountCeiling ( int count , int margin ) { return ArrayCounter . rank ( accessTable , hashIndex . newNodePointer , count , accessMin + 1 , accessCount , margin ) ; }
Return the max accessCount value for count elements with the lowest access count . Always return at least accessMin + 1
31,571
protected void clear ( int count , int margin ) { if ( margin < 64 ) { margin = 64 ; } int maxlookup = hashIndex . newNodePointer ; int accessBase = getAccessCountCeiling ( count , margin ) ; for ( int lookup = 0 ; lookup < maxlookup ; lookup ++ ) { Object o = objectKeyTable [ lookup ] ; if ( o != null && accessTable [ lookup ] < accessBase ) { removeObject ( o , false ) ; } } accessMin = accessBase ; }
Clear approximately count elements from the map starting with those with low accessTable ranking .
31,572
public void materialise ( Session session ) { PersistentStore store ; if ( isDataExpression ) { store = session . sessionData . getSubqueryRowStore ( table ) ; dataExpression . insertValuesIntoSubqueryTable ( session , store ) ; return ; } Result result = queryExpression . getResult ( session , isExistsPredicate ? 1 : 0 ) ; RowSetNavigatorData navigator = ( ( RowSetNavigatorData ) result . getNavigator ( ) ) ; if ( uniqueRows ) { navigator . removeDuplicates ( ) ; } store = session . sessionData . getSubqueryRowStore ( table ) ; table . insertResult ( store , result ) ; result . getNavigator ( ) . close ( ) ; }
Fills the table with a result set
31,573
static public void encodeDecimal ( final FastSerializer fs , BigDecimal value ) throws IOException { fs . write ( ( byte ) VoltDecimalHelper . kDefaultScale ) ; fs . write ( ( byte ) 16 ) ; fs . write ( VoltDecimalHelper . serializeBigDecimal ( value ) ) ; }
Read a decimal according to the Export encoding specification .
31,574
static public void encodeGeographyPoint ( final FastSerializer fs , GeographyPointValue value ) throws IOException { final int length = GeographyPointValue . getLengthInBytes ( ) ; ByteBuffer bb = ByteBuffer . allocate ( length ) ; bb . order ( ByteOrder . nativeOrder ( ) ) ; value . flattenToBuffer ( bb ) ; byte [ ] array = bb . array ( ) ; assert ( array . length == length ) ; fs . write ( array ) ; }
Encode a GEOGRAPHY_POINT according to the Export encoding specification .
31,575
static public void encodeGeography ( final FastSerializer fs , GeographyValue value ) throws IOException { ByteBuffer bb = ByteBuffer . allocate ( value . getLengthInBytes ( ) ) ; bb . order ( ByteOrder . nativeOrder ( ) ) ; value . flattenToBuffer ( bb ) ; byte [ ] array = bb . array ( ) ; fs . writeInt ( array . length ) ; fs . write ( array ) ; }
Encode a GEOGRAPHY according to the Export encoding specification .
31,576
@ SuppressWarnings ( "unchecked" ) private ImmutableMap < String , ProcedureRunnerNTGenerator > loadSystemProcedures ( boolean startup ) { ImmutableMap . Builder < String , ProcedureRunnerNTGenerator > builder = ImmutableMap . < String , ProcedureRunnerNTGenerator > builder ( ) ; Set < Entry < String , Config > > entrySet = SystemProcedureCatalog . listing . entrySet ( ) ; for ( Entry < String , Config > entry : entrySet ) { String procName = entry . getKey ( ) ; Config sysProc = entry . getValue ( ) ; if ( sysProc . transactional ) { continue ; } final String className = sysProc . getClassname ( ) ; Class < ? extends VoltNonTransactionalProcedure > procClass = null ; if ( className != null ) { try { procClass = ( Class < ? extends VoltNonTransactionalProcedure > ) Class . forName ( className ) ; } catch ( final ClassNotFoundException e ) { if ( sysProc . commercial ) { continue ; } VoltDB . crashLocalVoltDB ( "Missing Java class for NT System Procedure: " + procName ) ; } if ( startup ) { try { if ( ( procClass . newInstance ( ) instanceof VoltNTSystemProcedure ) == false ) { VoltDB . crashLocalVoltDB ( "NT System Procedure is incorrect class type: " + procName ) ; } } catch ( InstantiationException | IllegalAccessException e ) { VoltDB . crashLocalVoltDB ( "Unable to instantiate NT System Procedure: " + procName ) ; } } ProcedureRunnerNTGenerator prntg = new ProcedureRunnerNTGenerator ( procClass ) ; builder . put ( procName , prntg ) ; } } return builder . build ( ) ; }
Load the system procedures . Optionally don t load UAC but use parameter instead .
31,577
@ SuppressWarnings ( "unchecked" ) synchronized void update ( CatalogContext catalogContext ) { CatalogMap < Procedure > procedures = catalogContext . database . getProcedures ( ) ; Map < String , ProcedureRunnerNTGenerator > runnerGeneratorMap = new TreeMap < > ( ) ; for ( Procedure procedure : procedures ) { if ( procedure . getTransactional ( ) ) { continue ; } String className = procedure . getClassname ( ) ; Class < ? extends VoltNonTransactionalProcedure > clz = null ; try { clz = ( Class < ? extends VoltNonTransactionalProcedure > ) catalogContext . classForProcedureOrUDF ( className ) ; } catch ( ClassNotFoundException e ) { if ( className . startsWith ( "org.voltdb." ) ) { String msg = String . format ( LoadedProcedureSet . ORGVOLTDB_PROCNAME_ERROR_FMT , className ) ; VoltDB . crashLocalVoltDB ( msg , false , null ) ; } else { String msg = String . format ( LoadedProcedureSet . UNABLETOLOAD_ERROR_FMT , className ) ; VoltDB . crashLocalVoltDB ( msg , false , null ) ; } } ProcedureRunnerNTGenerator prntg = new ProcedureRunnerNTGenerator ( clz ) ; runnerGeneratorMap . put ( procedure . getTypeName ( ) , prntg ) ; } m_procs = ImmutableMap . < String , ProcedureRunnerNTGenerator > builder ( ) . putAll ( runnerGeneratorMap ) . build ( ) ; loadSystemProcedures ( false ) ; m_paused = false ; m_pendingInvocations . forEach ( pi -> callProcedureNT ( pi . ciHandle , pi . user , pi . ccxn , pi . isAdmin , pi . ntPriority , pi . task ) ) ; m_pendingInvocations . clear ( ) ; }
Refresh the NT procedures when the catalog changes .
31,578
synchronized void callProcedureNT ( final long ciHandle , final AuthUser user , final Connection ccxn , final boolean isAdmin , final boolean ntPriority , final StoredProcedureInvocation task ) { if ( m_paused ) { PendingInvocation pi = new PendingInvocation ( ciHandle , user , ccxn , isAdmin , ntPriority , task ) ; m_pendingInvocations . add ( pi ) ; return ; } String procName = task . getProcName ( ) ; final ProcedureRunnerNTGenerator prntg ; if ( procName . startsWith ( "@" ) ) { prntg = m_sysProcs . get ( procName ) ; } else { prntg = m_procs . get ( procName ) ; } final ProcedureRunnerNT runner ; try { runner = prntg . generateProcedureRunnerNT ( user , ccxn , isAdmin , ciHandle , task . getClientHandle ( ) , task . getBatchTimeout ( ) ) ; } catch ( InstantiationException | IllegalAccessException e1 ) { ClientResponseImpl response = new ClientResponseImpl ( ClientResponseImpl . UNEXPECTED_FAILURE , new VoltTable [ 0 ] , "Could not create running context for " + procName + "." , task . getClientHandle ( ) ) ; InitiateResponseMessage irm = InitiateResponseMessage . messageForNTProcResponse ( ciHandle , ccxn . connectionId ( ) , response ) ; m_mailbox . deliver ( irm ) ; return ; } m_outstanding . put ( runner . m_id , runner ) ; Runnable invocationRunnable = new Runnable ( ) { public void run ( ) { try { runner . call ( task . getParams ( ) . toArray ( ) ) ; } catch ( Throwable ex ) { ex . printStackTrace ( ) ; throw ex ; } } } ; try { if ( ntPriority ) { m_priorityExecutorService . submit ( invocationRunnable ) ; } else { m_primaryExecutorService . submit ( invocationRunnable ) ; } } catch ( RejectedExecutionException e ) { handleNTProcEnd ( runner ) ; ClientResponseImpl response = new ClientResponseImpl ( ClientResponseImpl . UNEXPECTED_FAILURE , new VoltTable [ 0 ] , "Could not submit NT procedure " + procName + " to exec service for ." , task . getClientHandle ( ) ) ; InitiateResponseMessage irm = InitiateResponseMessage . messageForNTProcResponse ( ciHandle , ccxn . connectionId ( ) , response ) ; m_mailbox . deliver ( irm ) ; return ; } }
Invoke an NT procedure asynchronously on one of the exec services .
31,579
void handleCallbacksForFailedHosts ( final Set < Integer > failedHosts ) { for ( ProcedureRunnerNT runner : m_outstanding . values ( ) ) { runner . processAnyCallbacksFromFailedHosts ( failedHosts ) ; } }
For all - host NT procs use site failures to call callbacks for hosts that will obviously never respond .
31,580
private boolean isDefinedFunctionName ( String functionName ) { return FunctionForVoltDB . isFunctionNameDefined ( functionName ) || FunctionSQL . isFunction ( functionName ) || FunctionCustom . getFunctionId ( functionName ) != ID_NOT_DEFINED || ( null != m_schema . findChild ( "ud_function" , functionName ) ) ; }
Find out if the function is defined . It might be defined in the FunctionForVoltDB table . It also might be in the VoltXML .
31,581
public Object upper ( Session session , Object data ) { if ( data == null ) { return null ; } if ( typeCode == Types . SQL_CLOB ) { String result = ( ( ClobData ) data ) . getSubString ( session , 0 , ( int ) ( ( ClobData ) data ) . length ( session ) ) ; result = collation . toUpperCase ( result ) ; ClobData clob = session . createClob ( result . length ( ) ) ; clob . setString ( session , 0 , result ) ; return clob ; } return collation . toUpperCase ( ( String ) data ) ; }
Memory limits apply to Upper and Lower implementations with Clob data
31,582
public void outputStartTime ( final long startTimeMsec ) { log . format ( Locale . US , "#[StartTime: %.3f (seconds since epoch), %s]\n" , startTimeMsec / 1000.0 , ( new Date ( startTimeMsec ) ) . toString ( ) ) ; }
Log a start time in the log .
31,583
public String latencyHistoReport ( ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; PrintStream pw = null ; try { pw = new PrintStream ( baos , false , Charsets . UTF_8 . name ( ) ) ; } catch ( UnsupportedEncodingException e ) { Throwables . propagate ( e ) ; } m_latencyHistogram . outputPercentileDistributionVolt ( pw , 1 , 1000.0 ) ; return new String ( baos . toByteArray ( ) , Charsets . UTF_8 ) ; }
Generate a human - readable report of latencies in the form of a histogram . Latency is in milliseconds
31,584
public synchronized BBContainer getNextChunk ( ) throws IOException { if ( m_chunkReaderException != null ) { throw m_chunkReaderException ; } if ( ! m_hasMoreChunks . get ( ) ) { final Container c = m_availableChunks . poll ( ) ; return c ; } if ( m_chunkReader == null ) { m_chunkReader = new ChunkReader ( ) ; m_chunkReaderThread = new Thread ( m_chunkReader , "ChunkReader" ) ; m_chunkReaderThread . start ( ) ; } Container c = null ; while ( c == null && ( m_hasMoreChunks . get ( ) || ! m_availableChunks . isEmpty ( ) ) ) { c = m_availableChunks . poll ( ) ; if ( c == null ) { try { wait ( ) ; } catch ( InterruptedException e ) { throw new IOException ( e ) ; } } } if ( c != null ) { m_chunkReads . release ( ) ; } else { if ( m_chunkReaderException != null ) { throw m_chunkReaderException ; } } return c ; }
Will get the next chunk of the table that is just over the chunk size
31,585
protected void validateSpecifiedUserAndPassword ( String user , String password ) throws SQLException { String configuredUser = connProperties . getProperty ( "user" ) ; String configuredPassword = connProperties . getProperty ( "password" ) ; if ( ( ( user == null && configuredUser != null ) || ( user != null && configuredUser == null ) ) || ( user != null && ! user . equals ( configuredUser ) ) || ( ( password == null && configuredPassword != null ) || ( password != null && configuredPassword == null ) ) || ( password != null && ! password . equals ( configuredPassword ) ) ) { throw new SQLException ( "Given user name or password does not " + "match those configured for this object" ) ; } }
Throws a SQLException if given user name or password are not same as those configured for this object .
31,586
public Object setConnectionProperty ( String name , String value ) { return connProperties . setProperty ( name , value ) ; }
Sets JDBC Connection Properties to be used when physical connections are obtained for the pool .
31,587
public void start ( boolean block ) throws InterruptedException , ExecutionException { Future < ? > task = m_es . submit ( new ParentEvent ( null ) ) ; if ( block ) { task . get ( ) ; } }
Initialize and start watching the cache .
31,588
public Object getAggregatedValue ( Session session , Object currValue ) { if ( currValue == null ) { return opType == OpTypes . COUNT || opType == OpTypes . APPROX_COUNT_DISTINCT ? ValuePool . INTEGER_0 : null ; } return ( ( SetFunction ) currValue ) . getValue ( ) ; }
Get the result of a SetFunction or an ordinary value
31,589
private boolean tableListIncludesReadOnlyView ( List < Table > tableList ) { for ( Table table : tableList ) { if ( table . getMaterializer ( ) != null && ! TableType . isStream ( table . getMaterializer ( ) . getTabletype ( ) ) ) { return true ; } } return false ; }
Return true if tableList includes at least one matview .
31,590
private boolean tableListIncludesExportOnly ( List < Table > tableList ) { NavigableSet < String > exportTables = CatalogUtil . getExportTableNames ( m_catalogDb ) ; for ( Table table : tableList ) { if ( exportTables . contains ( table . getTypeName ( ) ) && TableType . isStream ( table . getTabletype ( ) ) ) { return true ; } } return false ; }
Return true if tableList includes at least one export table .
31,591
private ParsedResultAccumulator getBestCostPlanForEphemeralScans ( List < StmtEphemeralTableScan > scans ) { int nextPlanId = m_planSelector . m_planId ; boolean orderIsDeterministic = true ; boolean hasSignificantOffsetOrLimit = false ; String contentNonDeterminismMessage = null ; for ( StmtEphemeralTableScan scan : scans ) { if ( scan instanceof StmtSubqueryScan ) { nextPlanId = planForParsedSubquery ( ( StmtSubqueryScan ) scan , nextPlanId ) ; if ( ( ( StmtSubqueryScan ) scan ) . getBestCostPlan ( ) == null ) { return null ; } } else if ( scan instanceof StmtCommonTableScan ) { nextPlanId = planForCommonTableQuery ( ( StmtCommonTableScan ) scan , nextPlanId ) ; if ( ( ( StmtCommonTableScan ) scan ) . getBestCostBasePlan ( ) == null ) { return null ; } } else { throw new PlanningErrorException ( "Unknown scan plan type." ) ; } orderIsDeterministic = scan . isOrderDeterministic ( orderIsDeterministic ) ; contentNonDeterminismMessage = scan . contentNonDeterminismMessage ( contentNonDeterminismMessage ) ; hasSignificantOffsetOrLimit = scan . hasSignificantOffsetOrLimit ( hasSignificantOffsetOrLimit ) ; } m_planSelector . m_planId = nextPlanId ; return new ParsedResultAccumulator ( orderIsDeterministic , hasSignificantOffsetOrLimit , contentNonDeterminismMessage ) ; }
Generate best cost plans for a list of derived tables which we call FROM sub - queries and common table queries .
31,592
private boolean getBestCostPlanForExpressionSubQueries ( Set < AbstractExpression > subqueryExprs ) { int nextPlanId = m_planSelector . m_planId ; for ( AbstractExpression expr : subqueryExprs ) { assert ( expr instanceof SelectSubqueryExpression ) ; if ( ! ( expr instanceof SelectSubqueryExpression ) ) { continue ; } SelectSubqueryExpression subqueryExpr = ( SelectSubqueryExpression ) expr ; StmtSubqueryScan subqueryScan = subqueryExpr . getSubqueryScan ( ) ; nextPlanId = planForParsedSubquery ( subqueryScan , nextPlanId ) ; CompiledPlan bestPlan = subqueryScan . getBestCostPlan ( ) ; if ( bestPlan == null ) { return false ; } subqueryExpr . setSubqueryNode ( bestPlan . rootPlanGraph ) ; if ( bestPlan . rootPlanGraph . hasAnyNodeOfType ( PlanNodeType . SEND ) ) { m_recentErrorMsg = IN_EXISTS_SCALAR_ERROR_MESSAGE ; return false ; } } m_planSelector . m_planId = nextPlanId ; return true ; }
Generate best cost plans for each Subquery expression from the list
31,593
private CompiledPlan getNextPlan ( ) { CompiledPlan retval ; AbstractParsedStmt nextStmt = null ; if ( m_parsedSelect != null ) { nextStmt = m_parsedSelect ; retval = getNextSelectPlan ( ) ; } else if ( m_parsedInsert != null ) { nextStmt = m_parsedInsert ; retval = getNextInsertPlan ( ) ; } else if ( m_parsedDelete != null ) { nextStmt = m_parsedDelete ; retval = getNextDeletePlan ( ) ; } else if ( m_parsedUpdate != null ) { nextStmt = m_parsedUpdate ; retval = getNextUpdatePlan ( ) ; } else if ( m_parsedUnion != null ) { nextStmt = m_parsedUnion ; retval = getNextUnionPlan ( ) ; } else if ( m_parsedSwap != null ) { nextStmt = m_parsedSwap ; retval = getNextSwapPlan ( ) ; } else if ( m_parsedMigrate != null ) { nextStmt = m_parsedMigrate ; retval = getNextMigratePlan ( ) ; } else { throw new RuntimeException ( "setupForNewPlans encountered unsupported statement type." ) ; } if ( retval == null || retval . rootPlanGraph == null ) { return null ; } assert ( nextStmt != null ) ; retval . setParameters ( nextStmt . getParameters ( ) ) ; return retval ; }
Generate a unique and correct plan for the current SQL statement context . This method gets called repeatedly until it returns null meaning there are no more plans .
31,594
private void connectChildrenBestPlans ( AbstractPlanNode parentPlan ) { if ( parentPlan instanceof AbstractScanPlanNode ) { AbstractScanPlanNode scanNode = ( AbstractScanPlanNode ) parentPlan ; StmtTableScan tableScan = scanNode . getTableScan ( ) ; if ( tableScan instanceof StmtSubqueryScan ) { CompiledPlan bestCostPlan = ( ( StmtSubqueryScan ) tableScan ) . getBestCostPlan ( ) ; assert ( bestCostPlan != null ) ; AbstractPlanNode subQueryRoot = bestCostPlan . rootPlanGraph ; subQueryRoot . disconnectParents ( ) ; scanNode . clearChildren ( ) ; scanNode . addAndLinkChild ( subQueryRoot ) ; } else if ( tableScan instanceof StmtCommonTableScan ) { assert ( parentPlan instanceof SeqScanPlanNode ) ; SeqScanPlanNode scanPlanNode = ( SeqScanPlanNode ) parentPlan ; StmtCommonTableScan cteScan = ( StmtCommonTableScan ) tableScan ; CompiledPlan bestCostBasePlan = cteScan . getBestCostBasePlan ( ) ; CompiledPlan bestCostRecursivePlan = cteScan . getBestCostRecursivePlan ( ) ; assert ( bestCostBasePlan != null ) ; AbstractPlanNode basePlanRoot = bestCostBasePlan . rootPlanGraph ; scanPlanNode . setCTEBaseNode ( basePlanRoot ) ; if ( bestCostRecursivePlan != null ) { AbstractPlanNode recursePlanRoot = bestCostRecursivePlan . rootPlanGraph ; assert ( basePlanRoot instanceof CommonTablePlanNode ) ; CommonTablePlanNode ctePlanNode = ( CommonTablePlanNode ) basePlanRoot ; ctePlanNode . setRecursiveNode ( recursePlanRoot ) ; } } } else { for ( int i = 0 ; i < parentPlan . getChildCount ( ) ; ++ i ) { connectChildrenBestPlans ( parentPlan . getChild ( i ) ) ; } } }
For each sub - query or CTE node in the plan tree attach the corresponding plans to the parent node .
31,595
private boolean needProjectionNode ( AbstractPlanNode root ) { if ( ! root . planNodeClassNeedsProjectionNode ( ) ) { return false ; } if ( m_parsedSelect . hasComplexGroupby ( ) || m_parsedSelect . hasComplexAgg ( ) ) { return false ; } if ( root instanceof AbstractReceivePlanNode && m_parsedSelect . hasPartitionColumnInGroupby ( ) ) { return false ; } return true ; }
Return true if the plan referenced by root node needs a projection node appended to the top .
31,596
static private boolean deleteIsTruncate ( ParsedDeleteStmt stmt , AbstractPlanNode plan ) { if ( ! ( plan instanceof SeqScanPlanNode ) ) { return false ; } SeqScanPlanNode seqScanNode = ( SeqScanPlanNode ) plan ; if ( seqScanNode . getPredicate ( ) != null ) { return false ; } if ( stmt . hasLimitOrOffset ( ) ) { return false ; } return true ; }
Returns true if this DELETE can be executed in the EE as a truncate operation
31,597
private static AbstractPlanNode addCoordinatorToDMLNode ( AbstractPlanNode dmlRoot , boolean isReplicated ) { dmlRoot = SubPlanAssembler . addSendReceivePair ( dmlRoot ) ; AbstractPlanNode sumOrLimitNode ; if ( isReplicated ) { LimitPlanNode limitNode = new LimitPlanNode ( ) ; sumOrLimitNode = limitNode ; limitNode . setLimit ( 1 ) ; } else { AggregatePlanNode countNode = new AggregatePlanNode ( ) ; sumOrLimitNode = countNode ; TupleValueExpression count_tve = new TupleValueExpression ( AbstractParsedStmt . TEMP_TABLE_NAME , AbstractParsedStmt . TEMP_TABLE_NAME , "modified_tuples" , "modified_tuples" , 0 ) ; count_tve . setValueType ( VoltType . BIGINT ) ; count_tve . setValueSize ( VoltType . BIGINT . getLengthInBytesForFixedTypes ( ) ) ; countNode . addAggregate ( ExpressionType . AGGREGATE_SUM , false , 0 , count_tve ) ; TupleValueExpression tve = new TupleValueExpression ( AbstractParsedStmt . TEMP_TABLE_NAME , AbstractParsedStmt . TEMP_TABLE_NAME , "modified_tuples" , "modified_tuples" , 0 ) ; tve . setValueType ( VoltType . BIGINT ) ; tve . setValueSize ( VoltType . BIGINT . getLengthInBytesForFixedTypes ( ) ) ; NodeSchema count_schema = new NodeSchema ( ) ; count_schema . addColumn ( AbstractParsedStmt . TEMP_TABLE_NAME , AbstractParsedStmt . TEMP_TABLE_NAME , "modified_tuples" , "modified_tuples" , tve ) ; countNode . setOutputSchema ( count_schema ) ; } sumOrLimitNode . addAndLinkChild ( dmlRoot ) ; SendPlanNode sendNode = new SendPlanNode ( ) ; sendNode . addAndLinkChild ( sumOrLimitNode ) ; return sendNode ; }
Add a receive node a sum or limit node and a send node to the given DML node . If the DML target is a replicated table it will add a limit node otherwise it adds a sum node .
31,598
private static OrderByPlanNode buildOrderByPlanNode ( List < ParsedColInfo > cols ) { OrderByPlanNode n = new OrderByPlanNode ( ) ; for ( ParsedColInfo col : cols ) { n . addSortExpression ( col . m_expression , col . m_ascending ? SortDirectionType . ASC : SortDirectionType . DESC ) ; } return n ; }
Given a list of ORDER BY columns construct and return an OrderByPlanNode .
31,599
private static boolean isOrderByNodeRequired ( AbstractParsedStmt parsedStmt , AbstractPlanNode root ) { if ( ! parsedStmt . hasOrderByColumns ( ) ) { return false ; } int numberWindowFunctions = 0 ; int numberReceiveNodes = 0 ; int numberHashAggregates = 0 ; AbstractPlanNode probe ; for ( probe = root ; ! ( ( probe instanceof AbstractJoinPlanNode ) || ( probe instanceof AbstractScanPlanNode ) ) && ( probe != null ) ; probe = ( probe . getChildCount ( ) > 0 ) ? probe . getChild ( 0 ) : null ) { if ( probe . getPlanNodeType ( ) == PlanNodeType . WINDOWFUNCTION ) { numberWindowFunctions += 1 ; } if ( probe . getPlanNodeType ( ) == PlanNodeType . RECEIVE ) { numberReceiveNodes += 1 ; } if ( ( probe . getPlanNodeType ( ) == PlanNodeType . HASHAGGREGATE ) || ( probe . getPlanNodeType ( ) == PlanNodeType . PARTIALAGGREGATE ) ) { numberHashAggregates += 1 ; } } if ( probe == null ) { return true ; } if ( ! ( probe instanceof IndexSortablePlanNode ) ) { return true ; } IndexUseForOrderBy indexUse = ( ( IndexSortablePlanNode ) probe ) . indexUse ( ) ; if ( indexUse . getSortOrderFromIndexScan ( ) == SortDirectionType . INVALID ) { return true ; } if ( numberHashAggregates > 0 ) { return true ; } if ( numberWindowFunctions == 0 ) { if ( indexUse . getWindowFunctionUsesIndex ( ) == SubPlanAssembler . NO_INDEX_USE ) { return true ; } assert ( indexUse . getWindowFunctionUsesIndex ( ) == SubPlanAssembler . STATEMENT_LEVEL_ORDER_BY_INDEX ) ; return numberReceiveNodes > 0 ; } if ( numberWindowFunctions == 1 ) { if ( ( indexUse . getWindowFunctionUsesIndex ( ) != 0 ) || ( ! indexUse . isWindowFunctionCompatibleWithOrderBy ( ) ) ) { return true ; } return false ; } return true ; }
Determine if an OrderByPlanNode is needed . This may return false if the statement has no ORDER BY clause or if the subtree is already producing rows in the correct order . Note that a hash aggregate node will cause this to return true and a serial or partial aggregate node may cause this to return true .