idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
31,600 | private static AbstractPlanNode handleOrderBy ( AbstractParsedStmt parsedStmt , AbstractPlanNode root ) { assert ( parsedStmt instanceof ParsedSelectStmt || parsedStmt instanceof ParsedUnionStmt || parsedStmt instanceof ParsedDeleteStmt ) ; if ( ! isOrderByNodeRequired ( parsedStmt , root ) ) { return root ; } OrderByPlanNode orderByNode = buildOrderByPlanNode ( parsedStmt . orderByColumns ( ) ) ; orderByNode . addAndLinkChild ( root ) ; return orderByNode ; } | Create an order by node as required by the statement and make it a parent of root . |
31,601 | private AbstractPlanNode handleSelectLimitOperator ( AbstractPlanNode root ) { LimitPlanNode topLimit = m_parsedSelect . getLimitNodeTop ( ) ; assert ( topLimit != null ) ; AbstractPlanNode sendNode = null ; boolean canPushDown = ! m_parsedSelect . hasDistinctWithGroupBy ( ) ; if ( canPushDown ) { sendNode = checkLimitPushDownViability ( root ) ; if ( sendNode == null ) { canPushDown = false ; } else { canPushDown = m_parsedSelect . getCanPushdownLimit ( ) ; } } if ( m_parsedSelect . m_mvFixInfo . needed ( ) ) { canPushDown = false ; } if ( canPushDown ) { LimitPlanNode distLimit = m_parsedSelect . getLimitNodeDist ( ) ; AbstractPlanNode distributedPlan = sendNode . getChild ( 0 ) ; distributedPlan . clearParents ( ) ; sendNode . clearChildren ( ) ; if ( m_parsedSelect . hasOrderByColumns ( ) ) { distributedPlan = handleOrderBy ( m_parsedSelect , distributedPlan ) ; } if ( isInlineLimitPlanNodePossible ( distributedPlan ) ) { distributedPlan . addInlinePlanNode ( distLimit ) ; sendNode . addAndLinkChild ( distributedPlan ) ; } else { distLimit . addAndLinkChild ( distributedPlan ) ; sendNode . addAndLinkChild ( distLimit ) ; } } return inlineLimitOperator ( root , topLimit ) ; } | Add a limit pushed - down if possible and return the new root . |
31,602 | private AbstractPlanNode handleUnionLimitOperator ( AbstractPlanNode root ) { LimitPlanNode topLimit = m_parsedUnion . getLimitNodeTop ( ) ; assert ( topLimit != null ) ; return inlineLimitOperator ( root , topLimit ) ; } | Add a limit and return the new root . |
31,603 | private AbstractPlanNode inlineLimitOperator ( AbstractPlanNode root , LimitPlanNode topLimit ) { if ( isInlineLimitPlanNodePossible ( root ) ) { root . addInlinePlanNode ( topLimit ) ; } else if ( root instanceof ProjectionPlanNode && isInlineLimitPlanNodePossible ( root . getChild ( 0 ) ) ) { root . getChild ( 0 ) . addInlinePlanNode ( topLimit ) ; } else { topLimit . addAndLinkChild ( root ) ; root = topLimit ; } return root ; } | Inline Limit plan node if possible |
31,604 | static private boolean isInlineLimitPlanNodePossible ( AbstractPlanNode pn ) { if ( pn instanceof OrderByPlanNode || pn . getPlanNodeType ( ) == PlanNodeType . AGGREGATE ) { return true ; } return false ; } | Inline limit plan node can be applied with ORDER BY node and serial aggregation node |
31,605 | private boolean switchToIndexScanForGroupBy ( AbstractPlanNode candidate , IndexGroupByInfo gbInfo ) { if ( ! m_parsedSelect . isGrouped ( ) ) { return false ; } if ( candidate instanceof IndexScanPlanNode ) { calculateIndexGroupByInfo ( ( IndexScanPlanNode ) candidate , gbInfo ) ; if ( gbInfo . m_coveredGroupByColumns != null && ! gbInfo . m_coveredGroupByColumns . isEmpty ( ) ) { gbInfo . m_indexAccess = candidate ; return true ; } return false ; } AbstractPlanNode sourceSeqScan = findSeqScanCandidateForGroupBy ( candidate ) ; if ( sourceSeqScan == null ) { return false ; } assert ( sourceSeqScan instanceof SeqScanPlanNode ) ; AbstractPlanNode parent = null ; if ( sourceSeqScan . getParentCount ( ) > 0 ) { parent = sourceSeqScan . getParent ( 0 ) ; } AbstractPlanNode indexAccess = indexAccessForGroupByExprs ( ( SeqScanPlanNode ) sourceSeqScan , gbInfo ) ; if ( indexAccess . getPlanNodeType ( ) != PlanNodeType . INDEXSCAN ) { return false ; } gbInfo . m_indexAccess = indexAccess ; if ( parent != null ) { indexAccess . clearParents ( ) ; parent . replaceChild ( 0 , indexAccess ) ; return false ; } return true ; } | For a seqscan feeding a GROUP BY consider substituting an IndexScan that pre - sorts by the GROUP BY keys . If a candidate is already an indexscan simply calculate GROUP BY column coverage |
31,606 | private AbstractPlanNode handleWindowedOperators ( AbstractPlanNode root ) { WindowFunctionExpression winExpr = m_parsedSelect . getWindowFunctionExpressions ( ) . get ( 0 ) ; assert ( winExpr != null ) ; WindowFunctionPlanNode pnode = new WindowFunctionPlanNode ( ) ; pnode . setWindowFunctionExpression ( winExpr ) ; IndexUseForOrderBy scanNode = findScanNodeForWindowFunction ( root ) ; AbstractPlanNode cnode = null ; int winfunc = ( scanNode == null ) ? SubPlanAssembler . NO_INDEX_USE : scanNode . getWindowFunctionUsesIndex ( ) ; if ( ( SubPlanAssembler . STATEMENT_LEVEL_ORDER_BY_INDEX == winfunc ) || ( SubPlanAssembler . NO_INDEX_USE == winfunc ) ) { List < AbstractExpression > partitionByExpressions = winExpr . getPartitionByExpressions ( ) ; boolean dontsort [ ] = new boolean [ winExpr . getOrderbySize ( ) ] ; List < AbstractExpression > orderByExpressions = winExpr . getOrderByExpressions ( ) ; List < SortDirectionType > orderByDirections = winExpr . getOrderByDirections ( ) ; OrderByPlanNode onode = new OrderByPlanNode ( ) ; for ( int idx = 0 ; idx < winExpr . getPartitionbySize ( ) ; ++ idx ) { SortDirectionType pdir = SortDirectionType . ASC ; AbstractExpression partitionByExpression = partitionByExpressions . get ( idx ) ; int sidx = winExpr . getSortIndexOfOrderByExpression ( partitionByExpression ) ; if ( 0 <= sidx ) { pdir = orderByDirections . get ( sidx ) ; dontsort [ sidx ] = true ; } onode . addSortExpression ( partitionByExpression , pdir ) ; } for ( int idx = 0 ; idx < winExpr . getOrderbySize ( ) ; ++ idx ) { if ( ! dontsort [ idx ] ) { AbstractExpression orderByExpr = orderByExpressions . get ( idx ) ; SortDirectionType orderByDir = orderByDirections . get ( idx ) ; onode . addSortExpression ( orderByExpr , orderByDir ) ; } } onode . addAndLinkChild ( root ) ; cnode = onode ; } else { assert ( scanNode != null ) ; assert ( 0 == scanNode . getWindowFunctionUsesIndex ( ) ) ; if ( m_partitioning . requiresTwoFragments ( ) ) { OrderByPlanNode onode = new OrderByPlanNode ( ) ; SortDirectionType dir = scanNode . getSortOrderFromIndexScan ( ) ; assert ( dir != SortDirectionType . INVALID ) ; List < AbstractExpression > orderExprs = scanNode . getFinalExpressionOrderFromIndexScan ( ) ; assert ( orderExprs != null ) ; for ( AbstractExpression ae : orderExprs ) { onode . addSortExpression ( ae , dir ) ; } onode . addAndLinkChild ( root ) ; cnode = onode ; } else { cnode = root ; } } pnode . addAndLinkChild ( cnode ) ; return pnode ; } | Create nodes for windowed operations . |
31,607 | private static void updatePartialIndex ( IndexScanPlanNode scan ) { if ( scan . getPredicate ( ) == null && scan . getPartialIndexPredicate ( ) != null ) { if ( scan . isForSortOrderOnly ( ) ) { scan . setPredicate ( Collections . singletonList ( scan . getPartialIndexPredicate ( ) ) ) ; } scan . setForPartialIndexOnly ( ) ; } } | Check if the index for the scan node is a partial index and if so make sure that the scan contains index predicate and update index reason as needed for |
31,608 | private void calculateIndexGroupByInfo ( IndexScanPlanNode root , IndexGroupByInfo gbInfo ) { String fromTableAlias = root . getTargetTableAlias ( ) ; assert ( fromTableAlias != null ) ; Index index = root . getCatalogIndex ( ) ; if ( ! IndexType . isScannable ( index . getType ( ) ) ) { return ; } ArrayList < AbstractExpression > bindings = new ArrayList < > ( ) ; gbInfo . m_coveredGroupByColumns = calculateGroupbyColumnsCovered ( index , fromTableAlias , bindings ) ; gbInfo . m_canBeFullySerialized = ( gbInfo . m_coveredGroupByColumns . size ( ) == m_parsedSelect . groupByColumns ( ) . size ( ) ) ; } | Sets IndexGroupByInfo for an IndexScan |
31,609 | private AbstractPlanNode indexAccessForGroupByExprs ( SeqScanPlanNode root , IndexGroupByInfo gbInfo ) { if ( ! root . isPersistentTableScan ( ) ) { return root ; } String fromTableAlias = root . getTargetTableAlias ( ) ; assert ( fromTableAlias != null ) ; List < ParsedColInfo > groupBys = m_parsedSelect . groupByColumns ( ) ; Table targetTable = m_catalogDb . getTables ( ) . get ( root . getTargetTableName ( ) ) ; assert ( targetTable != null ) ; CatalogMap < Index > allIndexes = targetTable . getIndexes ( ) ; List < Integer > maxCoveredGroupByColumns = new ArrayList < > ( ) ; ArrayList < AbstractExpression > maxCoveredBindings = null ; Index pickedUpIndex = null ; boolean foundAllGroupByCoveredIndex = false ; for ( Index index : allIndexes ) { if ( ! IndexType . isScannable ( index . getType ( ) ) ) { continue ; } if ( ! index . getPredicatejson ( ) . isEmpty ( ) ) { continue ; } ArrayList < AbstractExpression > bindings = new ArrayList < > ( ) ; List < Integer > coveredGroupByColumns = calculateGroupbyColumnsCovered ( index , fromTableAlias , bindings ) ; if ( coveredGroupByColumns . size ( ) > maxCoveredGroupByColumns . size ( ) ) { maxCoveredGroupByColumns = coveredGroupByColumns ; pickedUpIndex = index ; maxCoveredBindings = bindings ; if ( maxCoveredGroupByColumns . size ( ) == groupBys . size ( ) ) { foundAllGroupByCoveredIndex = true ; break ; } } } if ( pickedUpIndex == null ) { return root ; } IndexScanPlanNode indexScanNode = new IndexScanPlanNode ( root , null , pickedUpIndex , SortDirectionType . INVALID ) ; indexScanNode . setForGroupingOnly ( ) ; indexScanNode . setBindings ( maxCoveredBindings ) ; gbInfo . m_coveredGroupByColumns = maxCoveredGroupByColumns ; gbInfo . m_canBeFullySerialized = foundAllGroupByCoveredIndex ; return indexScanNode ; } | Turn sequential scan to index scan for group by if possible |
31,610 | private static void fixDistributedApproxCountDistinct ( AggregatePlanNode distNode , AggregatePlanNode coordNode ) { assert ( distNode != null ) ; assert ( coordNode != null ) ; List < ExpressionType > distAggTypes = distNode . getAggregateTypes ( ) ; boolean hasApproxCountDistinct = false ; for ( int i = 0 ; i < distAggTypes . size ( ) ; ++ i ) { ExpressionType et = distAggTypes . get ( i ) ; if ( et == ExpressionType . AGGREGATE_APPROX_COUNT_DISTINCT ) { hasApproxCountDistinct = true ; distNode . updateAggregate ( i , ExpressionType . AGGREGATE_VALS_TO_HYPERLOGLOG ) ; } } if ( hasApproxCountDistinct ) { List < ExpressionType > coordAggTypes = coordNode . getAggregateTypes ( ) ; for ( int i = 0 ; i < coordAggTypes . size ( ) ; ++ i ) { ExpressionType et = coordAggTypes . get ( i ) ; if ( et == ExpressionType . AGGREGATE_APPROX_COUNT_DISTINCT ) { coordNode . updateAggregate ( i , ExpressionType . AGGREGATE_HYPERLOGLOGS_TO_CARD ) ; } } } } | This function is called once it s been determined that we can push down an aggregation plan node . |
31,611 | protected AbstractPlanNode checkLimitPushDownViability ( AbstractPlanNode root ) { AbstractPlanNode receiveNode = root ; List < ParsedColInfo > orderBys = m_parsedSelect . orderByColumns ( ) ; boolean orderByCoversAllGroupBy = m_parsedSelect . groupByIsAnOrderByPermutation ( ) ; while ( ! ( receiveNode instanceof ReceivePlanNode ) ) { if ( ! ( receiveNode instanceof OrderByPlanNode ) && ! ( receiveNode instanceof ProjectionPlanNode ) && ! isValidAggregateNodeForLimitPushdown ( receiveNode , orderBys , orderByCoversAllGroupBy ) ) { return null ; } if ( receiveNode instanceof OrderByPlanNode ) { if ( ! m_parsedSelect . hasPartitionColumnInGroupby ( ) && isOrderByAggregationValue ( m_parsedSelect . orderByColumns ( ) ) ) { return null ; } } if ( receiveNode . getChildCount ( ) == 0 ) { return null ; } assert ( receiveNode . getChildCount ( ) == 1 ) ; receiveNode = receiveNode . getChild ( 0 ) ; } return receiveNode . getChild ( 0 ) ; } | Check if we can push the limit node down . |
31,612 | private static Set < String > getIndexedColumnSetForTable ( Table table ) { HashSet < String > columns = new HashSet < > ( ) ; for ( Index index : table . getIndexes ( ) ) { for ( ColumnRef colRef : index . getColumns ( ) ) { columns . add ( colRef . getColumn ( ) . getTypeName ( ) ) ; } } return columns ; } | Get the unique set of names of all columns that are part of an index on the given table . |
31,613 | private static boolean isNullRejecting ( Collection < String > tableAliases , List < AbstractExpression > exprs ) { for ( AbstractExpression expr : exprs ) { for ( String tableAlias : tableAliases ) { if ( ExpressionUtil . isNullRejectingExpression ( expr , tableAlias ) ) { return true ; } } } return false ; } | Verify if an expression from the input list is NULL - rejecting for any of the tables from the list |
31,614 | private int determineIndexOrdering ( StmtTableScan tableScan , int keyComponentCount , List < AbstractExpression > indexedExprs , List < ColumnRef > indexedColRefs , AccessPath retval , int [ ] orderSpoilers , List < AbstractExpression > bindingsForOrder ) { ParsedSelectStmt pss = ( m_parsedStmt instanceof ParsedSelectStmt ) ? ( ( ParsedSelectStmt ) m_parsedStmt ) : null ; boolean hasOrderBy = ( m_parsedStmt . hasOrderByColumns ( ) && ( ! m_parsedStmt . orderByColumns ( ) . isEmpty ( ) ) ) ; boolean hasWindowFunctions = ( pss != null && pss . hasWindowFunctionExpression ( ) ) ; if ( ! hasOrderBy && ! hasWindowFunctions ) { return 0 ; } WindowFunctionScoreboard windowFunctionScores = new WindowFunctionScoreboard ( m_parsedStmt , tableScan ) ; for ( int indexCtr = 0 ; ! windowFunctionScores . isDone ( ) && indexCtr < keyComponentCount ; indexCtr += 1 ) { AbstractExpression indexExpr = ( indexedExprs == null ) ? null : indexedExprs . get ( indexCtr ) ; ColumnRef indexColRef = ( indexedColRefs == null ) ? null : indexedColRefs . get ( indexCtr ) ; windowFunctionScores . matchIndexEntry ( new ExpressionOrColumn ( indexCtr , tableScan , indexExpr , SortDirectionType . INVALID , indexColRef ) ) ; } return windowFunctionScores . getResult ( retval , orderSpoilers , bindingsForOrder ) ; } | Determine if an index which is in the AccessPath argument retval can satisfy a parsed select statement s order by or window function ordering requirements . |
31,615 | private static List < AbstractExpression > findBindingsForOneIndexedExpression ( ExpressionOrColumn nextStatementEOC , ExpressionOrColumn indexEntry ) { assert ( nextStatementEOC . m_expr != null ) ; AbstractExpression nextStatementExpr = nextStatementEOC . m_expr ; if ( indexEntry . m_colRef != null ) { ColumnRef indexColRef = indexEntry . m_colRef ; if ( matchExpressionAndColumnRef ( nextStatementExpr , indexColRef , indexEntry . m_tableScan ) ) { return s_reusableImmutableEmptyBinding ; } return null ; } List < AbstractExpression > moreBindings = nextStatementEOC . m_expr . bindingToIndexedExpression ( indexEntry . m_expr ) ; if ( moreBindings != null ) { return moreBindings ; } return null ; } | Match the indexEntry which is from an index with a statement expression or column . The nextStatementEOC must be an expression not a column reference . |
31,616 | private static boolean removeExactMatchCoveredExpressions ( AbstractExpression coveringExpr , List < AbstractExpression > exprsToCover ) { boolean hasMatch = false ; Iterator < AbstractExpression > iter = exprsToCover . iterator ( ) ; while ( iter . hasNext ( ) ) { AbstractExpression exprToCover = iter . next ( ) ; if ( coveringExpr . bindingToIndexedExpression ( exprToCover ) != null ) { iter . remove ( ) ; hasMatch = true ; } } return hasMatch ; } | Loop over the expressions to cover to find ones that exactly match the covering expression and remove them from the original list . Returns true if there is at least one match . False otherwise . |
31,617 | private static List < AbstractExpression > removeNotNullCoveredExpressions ( StmtTableScan tableScan , List < AbstractExpression > coveringExprs , List < AbstractExpression > exprsToCover ) { Set < TupleValueExpression > coveringTves = new HashSet < > ( ) ; for ( AbstractExpression coveringExpr : coveringExprs ) { if ( ExpressionUtil . isNullRejectingExpression ( coveringExpr , tableScan . getTableAlias ( ) ) ) { coveringTves . addAll ( ExpressionUtil . getTupleValueExpressions ( coveringExpr ) ) ; } } Iterator < AbstractExpression > iter = exprsToCover . iterator ( ) ; while ( iter . hasNext ( ) ) { AbstractExpression filter = iter . next ( ) ; if ( ExpressionType . OPERATOR_NOT == filter . getExpressionType ( ) ) { assert ( filter . getLeft ( ) != null ) ; if ( ExpressionType . OPERATOR_IS_NULL == filter . getLeft ( ) . getExpressionType ( ) ) { assert ( filter . getLeft ( ) . getLeft ( ) != null ) ; List < TupleValueExpression > tves = ExpressionUtil . getTupleValueExpressions ( filter . getLeft ( ) . getLeft ( ) ) ; if ( coveringTves . containsAll ( tves ) ) { iter . remove ( ) ; } } } } return exprsToCover ; } | Remove NOT NULL expressions that are covered by the NULL - rejecting expressions . For example COL IS NOT NULL is covered by the COL > 0 NULL - rejecting comparison expression . |
31,618 | protected static AbstractPlanNode addSendReceivePair ( AbstractPlanNode scanNode ) { SendPlanNode sendNode = new SendPlanNode ( ) ; sendNode . addAndLinkChild ( scanNode ) ; ReceivePlanNode recvNode = new ReceivePlanNode ( ) ; recvNode . addAndLinkChild ( sendNode ) ; return recvNode ; } | Insert a send receive pair above the supplied scanNode . |
31,619 | protected static AbstractPlanNode getAccessPlanForTable ( JoinNode tableNode ) { StmtTableScan tableScan = tableNode . getTableScan ( ) ; AccessPath path = tableNode . m_currentAccessPath ; assert ( path != null ) ; if ( path . index == null ) { return getScanAccessPlanForTable ( tableScan , path ) ; } return getIndexAccessPlanForTable ( tableScan , path ) ; } | Given an access path build the single - site or distributed plan that will assess the data from the table according to the path . |
31,620 | private static AbstractPlanNode getIndexAccessPlanForTable ( StmtTableScan tableScan , AccessPath path ) { Index index = path . index ; IndexScanPlanNode scanNode = new IndexScanPlanNode ( tableScan , index ) ; AbstractPlanNode resultNode = scanNode ; scanNode . setSortDirection ( path . sortDirection ) ; for ( AbstractExpression expr : path . indexExprs ) { if ( path . lookupType == IndexLookupType . GEO_CONTAINS ) { scanNode . addSearchKeyExpression ( expr ) ; scanNode . addCompareNotDistinctFlag ( false ) ; continue ; } AbstractExpression exprRightChild = expr . getRight ( ) ; assert ( exprRightChild != null ) ; if ( expr . getExpressionType ( ) == ExpressionType . COMPARE_IN ) { resultNode = injectIndexedJoinWithMaterializedScan ( exprRightChild , scanNode ) ; MaterializedScanPlanNode matscan = ( MaterializedScanPlanNode ) resultNode . getChild ( 0 ) ; AbstractExpression elemExpr = matscan . getOutputExpression ( ) ; assert ( elemExpr != null ) ; replaceInListFilterWithEqualityFilter ( path . endExprs , exprRightChild , elemExpr ) ; exprRightChild = elemExpr ; } if ( exprRightChild instanceof AbstractSubqueryExpression ) { assert ( false ) ; } scanNode . addSearchKeyExpression ( exprRightChild ) ; scanNode . addCompareNotDistinctFlag ( expr . getExpressionType ( ) == ExpressionType . COMPARE_NOTDISTINCT ) ; } scanNode . setLookupType ( path . lookupType ) ; scanNode . setBindings ( path . bindings ) ; scanNode . setEndExpression ( ExpressionUtil . combinePredicates ( path . endExprs ) ) ; if ( ! path . index . getPredicatejson ( ) . isEmpty ( ) ) { try { scanNode . setPartialIndexPredicate ( AbstractExpression . fromJSONString ( path . index . getPredicatejson ( ) , tableScan ) ) ; } catch ( JSONException e ) { throw new PlanningErrorException ( e . getMessage ( ) , 0 ) ; } } scanNode . setPredicate ( path . otherExprs ) ; scanNode . setInitialExpression ( ExpressionUtil . combinePredicates ( path . initialExpr ) ) ; scanNode . setSkipNullPredicate ( ) ; scanNode . setEliminatedPostFilters ( path . eliminatedPostExprs ) ; final IndexUseForOrderBy indexUse = scanNode . indexUse ( ) ; indexUse . setWindowFunctionUsesIndex ( path . m_windowFunctionUsesIndex ) ; indexUse . setSortOrderFromIndexScan ( path . sortDirection ) ; indexUse . setWindowFunctionIsCompatibleWithOrderBy ( path . m_stmtOrderByIsCompatible ) ; indexUse . setFinalExpressionOrderFromIndexScan ( path . m_finalExpressionOrder ) ; return resultNode ; } | Get an index scan access plan for a table . |
31,621 | private static AbstractPlanNode injectIndexedJoinWithMaterializedScan ( AbstractExpression listElements , IndexScanPlanNode scanNode ) { MaterializedScanPlanNode matScan = new MaterializedScanPlanNode ( ) ; assert ( listElements instanceof VectorValueExpression || listElements instanceof ParameterValueExpression ) ; matScan . setRowData ( listElements ) ; matScan . setSortDirection ( scanNode . getSortDirection ( ) ) ; NestLoopIndexPlanNode nlijNode = new NestLoopIndexPlanNode ( ) ; nlijNode . setJoinType ( JoinType . INNER ) ; nlijNode . addInlinePlanNode ( scanNode ) ; nlijNode . addAndLinkChild ( matScan ) ; nlijNode . resolveSortDirection ( ) ; return nlijNode ; } | Generate a plan for an IN - LIST - driven index scan |
31,622 | private static void replaceInListFilterWithEqualityFilter ( List < AbstractExpression > endExprs , AbstractExpression inListRhs , AbstractExpression equalityRhs ) { for ( AbstractExpression comparator : endExprs ) { AbstractExpression otherExpr = comparator . getRight ( ) ; if ( otherExpr == inListRhs ) { endExprs . remove ( comparator ) ; AbstractExpression replacement = new ComparisonExpression ( ExpressionType . COMPARE_EQUAL , comparator . getLeft ( ) , equalityRhs ) ; endExprs . add ( replacement ) ; break ; } } } | with an equality filter referencing the second given rhs . |
31,623 | CallEvent [ ] makeRandomEvent ( ) { long callId = ++ lastCallIdUsed ; Integer agentId = agentsAvailable . poll ( ) ; if ( agentId == null ) { return null ; } Long phoneNo = phoneNumbersAvailable . poll ( ) ; assert ( phoneNo != null ) ; Date startTS = new Date ( currentSystemMilliTimestamp ) ; long durationms = - 1 ; long meancalldurationms = config . meancalldurationseconds * 1000 ; long maxcalldurationms = config . maxcalldurationseconds * 1000 ; double stddev = meancalldurationms / 2.0 ; while ( ( durationms <= 0 ) || ( durationms > maxcalldurationms ) ) { durationms = ( long ) ( rand . nextGaussian ( ) * stddev ) + meancalldurationms ; } Date endTS = new Date ( startTS . getTime ( ) + durationms ) ; CallEvent [ ] event = new CallEvent [ 2 ] ; event [ 0 ] = new CallEvent ( callId , agentId , phoneNo , startTS , null ) ; event [ 1 ] = new CallEvent ( callId , agentId , phoneNo , null , endTS ) ; return event ; } | Generate a random call event with a duration . |
31,624 | public CallEvent next ( long systemCurrentTimeMillis ) { if ( systemCurrentTimeMillis > currentSystemMilliTimestamp ) { long eventBacklog = targetEventsThisMillisecond - eventsSoFarThisMillisecond ; targetEventsThisMillisecond = ( long ) Math . floor ( targetEventsPerMillisecond ) ; double targetFraction = targetEventsPerMillisecond - targetEventsThisMillisecond ; targetEventsThisMillisecond += ( rand . nextDouble ( ) <= targetFraction ) ? 1 : 0 ; targetEventsThisMillisecond += eventBacklog ; eventsSoFarThisMillisecond = 0 ; currentSystemMilliTimestamp = systemCurrentTimeMillis ; } CallEvent callEvent = delayedEvents . nextReady ( systemCurrentTimeMillis ) ; if ( callEvent != null ) { assert ( callEvent . startTS == null ) ; assert ( callEvent . endTS != null ) ; agentsAvailable . add ( callEvent . agentId ) ; phoneNumbersAvailable . add ( callEvent . phoneNo ) ; validate ( ) ; return callEvent ; } if ( targetEventsThisMillisecond == eventsSoFarThisMillisecond ) { validate ( ) ; return null ; } CallEvent [ ] event = makeRandomEvent ( ) ; if ( event == null ) { validate ( ) ; return null ; } long endTimeKey = event [ 1 ] . endTS . getTime ( ) ; assert ( ( endTimeKey - systemCurrentTimeMillis ) < ( config . maxcalldurationseconds * 1000 ) ) ; delayedEvents . add ( endTimeKey , event [ 1 ] ) ; eventsSoFarThisMillisecond ++ ; validate ( ) ; return event [ 0 ] ; } | Return the next call event that is safe for delivery or null if there are no safe objects to deliver . |
31,625 | private void validate ( ) { long delayedEventCount = delayedEvents . size ( ) ; long outstandingAgents = config . agents - agentsAvailable . size ( ) ; long outstandingPhones = config . numbers - phoneNumbersAvailable . size ( ) ; if ( outstandingAgents != outstandingPhones ) { throw new RuntimeException ( String . format ( "outstandingAgents (%d) != outstandingPhones (%d)" , outstandingAgents , outstandingPhones ) ) ; } if ( outstandingAgents != delayedEventCount ) { throw new RuntimeException ( String . format ( "outstandingAgents (%d) != delayedEventCount (%d)" , outstandingAgents , delayedEventCount ) ) ; } } | Smoke check on validity of data structures . This was useful while getting the code right for this class but it doesn t do much now unless the code needs changes . |
31,626 | void printSummary ( ) { System . out . printf ( "There are %d agents outstanding and %d phones. %d entries waiting to go.\n" , agentsAvailable . size ( ) , phoneNumbersAvailable . size ( ) , delayedEvents . size ( ) ) ; } | Debug statement to help users verify there are no lost or delayed events . |
31,627 | private boolean isNegativeNumber ( String token ) { try { Double . parseDouble ( token ) ; return true ; } catch ( NumberFormatException e ) { return false ; } } | Check if the token is a negative number . |
31,628 | private boolean isLongOption ( String token ) { if ( ! token . startsWith ( "-" ) || token . length ( ) == 1 ) { return false ; } int pos = token . indexOf ( "=" ) ; String t = pos == - 1 ? token : token . substring ( 0 , pos ) ; if ( ! options . getMatchingOptions ( t ) . isEmpty ( ) ) { return true ; } else if ( getLongPrefix ( token ) != null && ! token . startsWith ( "--" ) ) { return true ; } return false ; } | Tells if the token looks like a long option . |
31,629 | private void handleUnknownToken ( String token ) throws ParseException { if ( token . startsWith ( "-" ) && token . length ( ) > 1 && ! stopAtNonOption ) { throw new UnrecognizedOptionException ( "Unrecognized option: " + token , token ) ; } cmd . addArg ( token ) ; if ( stopAtNonOption ) { skipParsing = true ; } } | Handles an unknown token . If the token starts with a dash an UnrecognizedOptionException is thrown . Otherwise the token is added to the arguments of the command line . If the stopAtNonOption flag is set this stops the parsing and the remaining tokens are added as - is in the arguments of the command line . |
31,630 | public String getText ( ) { if ( sqlTextStr == null ) { sqlTextStr = new String ( sqlText , Constants . UTF8ENCODING ) ; } return sqlTextStr ; } | Get the text of the SQL statement represented . |
31,631 | public static String canonicalizeStmt ( String stmtStr ) { stmtStr = stmtStr . replaceAll ( "\n" , " " ) ; stmtStr = stmtStr . trim ( ) ; if ( ! stmtStr . endsWith ( ";" ) ) { stmtStr += ";" ; } return stmtStr ; } | use the same statement to compute crc . |
31,632 | private static boolean [ ] createSafeOctets ( String safeChars ) { int maxChar = - 1 ; char [ ] safeCharArray = safeChars . toCharArray ( ) ; for ( char c : safeCharArray ) { maxChar = Math . max ( c , maxChar ) ; } boolean [ ] octets = new boolean [ maxChar + 1 ] ; for ( char c : safeCharArray ) { octets [ c ] = true ; } return octets ; } | Creates a boolean array with entries corresponding to the character values specified in safeChars set to true . The array is as small as is required to hold the given character information . |
31,633 | String getTableName ( ) { if ( opType == OpTypes . MULTICOLUMN ) { return tableName ; } if ( opType == OpTypes . COLUMN ) { if ( rangeVariable == null ) { return tableName ; } return rangeVariable . getTable ( ) . getName ( ) . name ; } return "" ; } | Returns the table name for a column expression as a string |
31,634 | VoltXMLElement voltAnnotateColumnXML ( VoltXMLElement exp ) { if ( tableName != null ) { if ( rangeVariable != null && rangeVariable . rangeTable != null && rangeVariable . tableAlias != null && rangeVariable . rangeTable . tableType == TableBase . SYSTEM_SUBQUERY ) { exp . attributes . put ( "table" , rangeVariable . tableAlias . name . toUpperCase ( ) ) ; } else { exp . attributes . put ( "table" , tableName . toUpperCase ( ) ) ; } } exp . attributes . put ( "column" , columnName . toUpperCase ( ) ) ; if ( ( alias == null ) || ( getAlias ( ) . length ( ) == 0 ) ) { exp . attributes . put ( "alias" , columnName . toUpperCase ( ) ) ; } if ( rangeVariable != null && rangeVariable . tableAlias != null ) { exp . attributes . put ( "tablealias" , rangeVariable . tableAlias . name . toUpperCase ( ) ) ; } exp . attributes . put ( "index" , Integer . toString ( columnIndex ) ) ; return exp ; } | VoltDB added method to provide detail for a non - catalog - dependent representation of this HSQLDB object . |
31,635 | void parseTablesAndParams ( VoltXMLElement root ) { parseParameters ( root ) ; parseCommonTableExpressions ( root ) ; for ( VoltXMLElement node : root . children ) { if ( node . name . equalsIgnoreCase ( "tablescan" ) ) { parseTable ( node ) ; } else if ( node . name . equalsIgnoreCase ( "tablescans" ) ) { parseTables ( node ) ; } } } | Parse tables and parameters . |
31,636 | private AbstractExpression parseExpressionNode ( VoltXMLElement exprNode ) { String elementName = exprNode . name . toLowerCase ( ) ; XMLElementExpressionParser parser = m_exprParsers . get ( elementName ) ; if ( parser == null ) { throw new PlanningErrorException ( "Unsupported expression node '" + elementName + "'" ) ; } AbstractExpression retval = parser . parse ( this , exprNode ) ; assert ( "asterisk" . equals ( elementName ) || retval != null ) ; return retval ; } | Given a VoltXMLElement expression node translate it into an AbstractExpression . This is mostly a lookup in the table m_exprParsers . |
31,637 | private AbstractExpression parseVectorExpression ( VoltXMLElement exprNode ) { ArrayList < AbstractExpression > args = new ArrayList < > ( ) ; for ( VoltXMLElement argNode : exprNode . children ) { assert ( argNode != null ) ; AbstractExpression argExpr = parseExpressionNode ( argNode ) ; assert ( argExpr != null ) ; args . add ( argExpr ) ; } VectorValueExpression vve = new VectorValueExpression ( ) ; vve . setValueType ( VoltType . VOLTTABLE ) ; vve . setArgs ( args ) ; return vve ; } | Parse a Vector value for SQL - IN |
31,638 | private SelectSubqueryExpression parseSubqueryExpression ( VoltXMLElement exprNode ) { assert ( exprNode . children . size ( ) == 1 ) ; VoltXMLElement subqueryElmt = exprNode . children . get ( 0 ) ; AbstractParsedStmt subqueryStmt = parseSubquery ( subqueryElmt ) ; String withoutAlias = null ; StmtSubqueryScan stmtSubqueryScan = addSubqueryToStmtCache ( subqueryStmt , withoutAlias ) ; return new SelectSubqueryExpression ( ExpressionType . SELECT_SUBQUERY , stmtSubqueryScan ) ; } | Parse an expression subquery |
31,639 | private StmtTableScan resolveStmtTableScanByAlias ( String tableAlias ) { StmtTableScan tableScan = getStmtTableScanByAlias ( tableAlias ) ; if ( tableScan != null ) { return tableScan ; } if ( m_parentStmt != null ) { return m_parentStmt . resolveStmtTableScanByAlias ( tableAlias ) ; } return null ; } | Return StmtTableScan by table alias . In case of correlated queries may need to walk up the statement tree . |
31,640 | protected StmtTableScan addTableToStmtCache ( Table table , String tableAlias ) { StmtTableScan tableScan = m_tableAliasMap . get ( tableAlias ) ; if ( tableScan == null ) { tableScan = new StmtTargetTableScan ( table , tableAlias , m_stmtId ) ; m_tableAliasMap . put ( tableAlias , tableScan ) ; } return tableScan ; } | Add a table to the statement cache . |
31,641 | protected StmtSubqueryScan addSubqueryToStmtCache ( AbstractParsedStmt subquery , String tableAlias ) { assert ( subquery != null ) ; if ( tableAlias == null ) { tableAlias = AbstractParsedStmt . TEMP_TABLE_NAME + "_" + subquery . m_stmtId ; } StmtSubqueryScan subqueryScan = new StmtSubqueryScan ( subquery , tableAlias , m_stmtId ) ; StmtTableScan prior = m_tableAliasMap . put ( tableAlias , subqueryScan ) ; assert ( prior == null ) ; return subqueryScan ; } | Add a sub - query to the statement cache . |
31,642 | private StmtTargetTableScan addSimplifiedSubqueryToStmtCache ( StmtSubqueryScan subqueryScan , StmtTargetTableScan tableScan ) { String tableAlias = subqueryScan . getTableAlias ( ) ; assert ( tableAlias != null ) ; Table promotedTable = tableScan . getTargetTable ( ) ; StmtTargetTableScan promotedScan = new StmtTargetTableScan ( promotedTable , tableAlias , m_stmtId ) ; promotedScan . setOriginalSubqueryScan ( subqueryScan ) ; StmtTableScan prior = m_tableAliasMap . put ( tableAlias , promotedScan ) ; assert ( prior == subqueryScan ) ; m_tableList . add ( promotedTable ) ; return promotedScan ; } | Replace an existing subquery scan with its underlying table scan . The subquery has already passed all the checks from the canSimplifySubquery method . Subquery ORDER BY clause is ignored if such exists . |
31,643 | protected AbstractExpression replaceExpressionsWithPve ( AbstractExpression expr ) { assert ( expr != null ) ; if ( expr instanceof TupleValueExpression ) { int paramIdx = ParameterizationInfo . getNextParamIndex ( ) ; ParameterValueExpression pve = new ParameterValueExpression ( paramIdx , expr ) ; m_parameterTveMap . put ( paramIdx , expr ) ; return pve ; } if ( expr instanceof AggregateExpression ) { int paramIdx = ParameterizationInfo . getNextParamIndex ( ) ; ParameterValueExpression pve = new ParameterValueExpression ( paramIdx , expr ) ; List < TupleValueExpression > tves = ExpressionUtil . getTupleValueExpressions ( expr ) ; assert ( m_parentStmt != null ) ; for ( TupleValueExpression tve : tves ) { int origId = tve . getOrigStmtId ( ) ; if ( m_stmtId != origId && m_parentStmt . m_stmtId != origId ) { throw new PlanningErrorException ( "Subqueries do not support aggregation of parent statement columns" ) ; } } m_parameterTveMap . put ( paramIdx , expr ) ; return pve ; } if ( expr . getLeft ( ) != null ) { expr . setLeft ( replaceExpressionsWithPve ( expr . getLeft ( ) ) ) ; } if ( expr . getRight ( ) != null ) { expr . setRight ( replaceExpressionsWithPve ( expr . getRight ( ) ) ) ; } if ( expr . getArgs ( ) != null ) { List < AbstractExpression > newArgs = new ArrayList < > ( ) ; for ( AbstractExpression argument : expr . getArgs ( ) ) { newArgs . add ( replaceExpressionsWithPve ( argument ) ) ; } expr . setArgs ( newArgs ) ; } return expr ; } | Helper method to replace all TVEs and aggregated expressions with the corresponding PVEs . The original expressions are placed into the map to be propagated to the EE . The key to the map is the parameter index . |
31,644 | private StmtCommonTableScan resolveCommonTableByName ( String tableName , String tableAlias ) { StmtCommonTableScan answer = null ; StmtCommonTableScanShared scan = null ; for ( AbstractParsedStmt scope = this ; scope != null && scan == null ; scope = scope . getParentStmt ( ) ) { scan = scope . getCommonTableByName ( tableName ) ; } if ( scan != null ) { answer = new StmtCommonTableScan ( tableName , tableAlias , scan ) ; } return answer ; } | Look for a common table by name possibly in parent scopes . This is different from resolveStmtTableByAlias in that it looks for common tables and only by name not by alias . Of course a name and an alias are both strings so this is kind of a stylized distinction . |
31,645 | protected void parseParameters ( VoltXMLElement root ) { VoltXMLElement paramsNode = null ; for ( VoltXMLElement node : root . children ) { if ( node . name . equalsIgnoreCase ( "parameters" ) ) { paramsNode = node ; break ; } } if ( paramsNode == null ) { return ; } for ( VoltXMLElement node : paramsNode . children ) { if ( node . name . equalsIgnoreCase ( "parameter" ) ) { long id = Long . parseLong ( node . attributes . get ( "id" ) ) ; String typeName = node . attributes . get ( "valuetype" ) ; String isVectorParam = node . attributes . get ( "isvector" ) ; String indexAttr = node . attributes . get ( "index" ) ; assert ( indexAttr != null ) ; int index = Integer . parseInt ( indexAttr ) ; VoltType type = VoltType . typeFromString ( typeName ) ; ParameterValueExpression pve = new ParameterValueExpression ( ) ; pve . setParameterIndex ( index ) ; pve . setValueType ( type ) ; if ( isVectorParam != null && isVectorParam . equalsIgnoreCase ( "true" ) ) { pve . setParamIsVector ( ) ; } m_paramsById . put ( id , pve ) ; getParamsByIndex ( ) . put ( index , pve ) ; } } } | Populate the statement s paramList from the parameters element . Each parameter has an id and an index both of which are numeric . It also has a type and an indication of whether it s a vector parameter . For each parameter we create a ParameterValueExpression named pve which holds the type and vector parameter indication . We add the pve to two maps m_paramsById and m_paramsByIndex . |
31,646 | protected void promoteUnionParametersFromChild ( AbstractParsedStmt childStmt ) { getParamsByIndex ( ) . putAll ( childStmt . getParamsByIndex ( ) ) ; m_parameterTveMap . putAll ( childStmt . m_parameterTveMap ) ; } | in the EE . |
31,647 | HashMap < AbstractExpression , Set < AbstractExpression > > analyzeValueEquivalence ( ) { m_joinTree . analyzeJoinExpressions ( m_noTableSelectionList ) ; return m_joinTree . getAllEquivalenceFilters ( ) ; } | Collect value equivalence expressions across the entire SQL statement |
31,648 | protected Table getTableFromDB ( String tableName ) { Table table = m_db . getTables ( ) . getExact ( tableName ) ; return table ; } | Look up a table by name . This table may be stored in the local catalog or else the global catalog . |
31,649 | private AbstractExpression parseTableCondition ( VoltXMLElement tableScan , String joinOrWhere ) { AbstractExpression condExpr = null ; for ( VoltXMLElement childNode : tableScan . children ) { if ( ! childNode . name . equalsIgnoreCase ( joinOrWhere ) ) { continue ; } assert ( childNode . children . size ( ) == 1 ) ; assert ( condExpr == null ) ; condExpr = parseConditionTree ( childNode . children . get ( 0 ) ) ; assert ( condExpr != null ) ; ExpressionUtil . finalizeValueTypes ( condExpr ) ; condExpr = ExpressionUtil . evaluateExpression ( condExpr ) ; if ( ConstantValueExpression . isBooleanTrue ( condExpr ) ) { condExpr = null ; } } return condExpr ; } | Parse a where or join clause . This behavior is common to all kinds of statements . |
31,650 | LimitPlanNode limitPlanNodeFromXml ( VoltXMLElement limitXml , VoltXMLElement offsetXml ) { if ( limitXml == null && offsetXml == null ) { return null ; } String node ; long limitParameterId = - 1 ; long offsetParameterId = - 1 ; long limit = - 1 ; long offset = 0 ; if ( limitXml != null ) { if ( ( node = limitXml . attributes . get ( "limit_paramid" ) ) != null ) { limitParameterId = Long . parseLong ( node ) ; } else { assert ( limitXml . children . size ( ) == 1 ) ; VoltXMLElement valueNode = limitXml . children . get ( 0 ) ; String isParam = valueNode . attributes . get ( "isparam" ) ; if ( ( isParam != null ) && ( isParam . equalsIgnoreCase ( "true" ) ) ) { limitParameterId = Long . parseLong ( valueNode . attributes . get ( "id" ) ) ; } else { node = limitXml . attributes . get ( "limit" ) ; assert ( node != null ) ; limit = Long . parseLong ( node ) ; } } } if ( offsetXml != null ) { if ( ( node = offsetXml . attributes . get ( "offset_paramid" ) ) != null ) { offsetParameterId = Long . parseLong ( node ) ; } else { if ( offsetXml . children . size ( ) == 1 ) { VoltXMLElement valueNode = offsetXml . children . get ( 0 ) ; String isParam = valueNode . attributes . get ( "isparam" ) ; if ( ( isParam != null ) && ( isParam . equalsIgnoreCase ( "true" ) ) ) { offsetParameterId = Long . parseLong ( valueNode . attributes . get ( "id" ) ) ; } else { node = offsetXml . attributes . get ( "offset" ) ; assert ( node != null ) ; offset = Long . parseLong ( node ) ; } } } } if ( limit != - 1 ) assert limitParameterId == - 1 : "Parsed value and param. limit." ; if ( offset != 0 ) assert offsetParameterId == - 1 : "Parsed value and param. offset." ; LimitPlanNode limitPlanNode = new LimitPlanNode ( ) ; limitPlanNode . setLimit ( ( int ) limit ) ; limitPlanNode . setOffset ( ( int ) offset ) ; limitPlanNode . setLimitParameterIndex ( parameterCountIndexById ( limitParameterId ) ) ; limitPlanNode . setOffsetParameterIndex ( parameterCountIndexById ( offsetParameterId ) ) ; return limitPlanNode ; } | Produce a LimitPlanNode from the given XML |
31,651 | protected boolean orderByColumnsCoverUniqueKeys ( ) { HashMap < String , List < AbstractExpression > > baseTableAliases = new HashMap < > ( ) ; for ( ParsedColInfo col : orderByColumns ( ) ) { AbstractExpression expr = col . m_expression ; List < TupleValueExpression > baseTVEExpressions = expr . findAllTupleValueSubexpressions ( ) ; Set < String > baseTableNames = new HashSet < > ( ) ; for ( TupleValueExpression tve : baseTVEExpressions ) { String tableAlias = tve . getTableAlias ( ) ; assert ( tableAlias != null ) ; baseTableNames . add ( tableAlias ) ; } if ( baseTableNames . size ( ) != 1 ) { continue ; } AbstractExpression baseTVE = baseTVEExpressions . get ( 0 ) ; String nextTableAlias = ( ( TupleValueExpression ) baseTVE ) . getTableAlias ( ) ; assert ( nextTableAlias != null ) ; List < AbstractExpression > perTable = baseTableAliases . get ( nextTableAlias ) ; if ( perTable == null ) { perTable = new ArrayList < > ( ) ; baseTableAliases . put ( nextTableAlias , perTable ) ; } perTable . add ( expr ) ; } if ( m_tableAliasMap . size ( ) > baseTableAliases . size ( ) ) { return false ; } boolean allScansAreDeterministic = true ; for ( Entry < String , List < AbstractExpression > > orderedAlias : baseTableAliases . entrySet ( ) ) { List < AbstractExpression > orderedAliasExprs = orderedAlias . getValue ( ) ; StmtTableScan tableScan = getStmtTableScanByAlias ( orderedAlias . getKey ( ) ) ; if ( tableScan == null ) { assert ( false ) ; return false ; } if ( tableScan instanceof StmtSubqueryScan ) { return false ; } Table table = ( ( StmtTargetTableScan ) tableScan ) . getTargetTable ( ) ; allScansAreDeterministic = false ; for ( Index index : table . getIndexes ( ) ) { if ( ! index . getUnique ( ) ) { continue ; } List < AbstractExpression > indexExpressions = new ArrayList < > ( ) ; String jsonExpr = index . getExpressionsjson ( ) ; if ( jsonExpr . isEmpty ( ) ) { for ( ColumnRef cref : index . getColumns ( ) ) { Column col = cref . getColumn ( ) ; TupleValueExpression tve = new TupleValueExpression ( table . getTypeName ( ) , orderedAlias . getKey ( ) , col . getName ( ) , col . getName ( ) , col . getIndex ( ) ) ; indexExpressions . add ( tve ) ; } } else { try { indexExpressions = AbstractExpression . fromJSONArrayString ( jsonExpr , tableScan ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; assert ( false ) ; continue ; } } if ( orderedAliasExprs . containsAll ( indexExpressions ) ) { allScansAreDeterministic = true ; break ; } } if ( ! allScansAreDeterministic ) { return false ; } } return true ; } | Order by Columns or expressions has to operate on the display columns or expressions . |
31,652 | protected void addHonoraryOrderByExpressions ( HashSet < AbstractExpression > orderByExprs , List < ParsedColInfo > candidateColumns ) { if ( m_tableAliasMap . size ( ) != 1 ) { return ; } HashMap < AbstractExpression , Set < AbstractExpression > > valueEquivalence = analyzeValueEquivalence ( ) ; for ( ParsedColInfo colInfo : candidateColumns ) { AbstractExpression colExpr = colInfo . m_expression ; if ( colExpr instanceof TupleValueExpression ) { Set < AbstractExpression > tveEquivs = valueEquivalence . get ( colExpr ) ; if ( tveEquivs != null ) { for ( AbstractExpression expr : tveEquivs ) { if ( expr instanceof ParameterValueExpression || expr instanceof ConstantValueExpression ) { orderByExprs . add ( colExpr ) ; } } } } } StmtTableScan scan = m_tableAliasMap . values ( ) . iterator ( ) . next ( ) ; Table table = getTableFromDB ( scan . getTableName ( ) ) ; if ( table == null ) { return ; } Set < Column > orderByColumns = new HashSet < > ( ) ; for ( AbstractExpression expr : orderByExprs ) { if ( expr instanceof TupleValueExpression ) { TupleValueExpression tve = ( TupleValueExpression ) expr ; Column col = table . getColumns ( ) . get ( tve . getColumnName ( ) ) ; orderByColumns . add ( col ) ; } } CatalogMap < Constraint > constraints = table . getConstraints ( ) ; if ( constraints == null ) { return ; } Set < Index > indices = new HashSet < > ( ) ; for ( Constraint constraint : constraints ) { Index index = constraint . getIndex ( ) ; if ( index != null && index . getUnique ( ) && index . getExpressionsjson ( ) . isEmpty ( ) ) { indices . add ( index ) ; } } for ( ParsedColInfo colInfo : candidateColumns ) { AbstractExpression expr = colInfo . m_expression ; if ( expr instanceof TupleValueExpression ) { TupleValueExpression tve = ( TupleValueExpression ) expr ; for ( Index index : indices ) { CatalogMap < ColumnRef > columns = index . getColumns ( ) ; boolean addAllColumns = true ; for ( ColumnRef cr : columns ) { Column col = cr . getColumn ( ) ; if ( orderByColumns . contains ( col ) == false ) { addAllColumns = false ; break ; } } if ( addAllColumns ) { for ( Column addCol : table . getColumns ( ) ) { TupleValueExpression ntve = new TupleValueExpression ( tve . getTableName ( ) , tve . getTableAlias ( ) , addCol . getName ( ) , null , - 1 ) ; orderByExprs . add ( ntve ) ; } break ; } } } } } | Given a set of order - by expressions and a select list which is a list of columns each with an expression and an alias expand the order - by list with new expressions which could be on the order - by list without changing the sort order and which are otherwise helpful . |
31,653 | protected boolean producesOneRowOutput ( ) { if ( m_tableAliasMap . size ( ) != 1 ) { return false ; } StmtTableScan scan = m_tableAliasMap . values ( ) . iterator ( ) . next ( ) ; Table table = getTableFromDB ( scan . getTableName ( ) ) ; if ( table == null ) { return false ; } CatalogMap < Index > indexes = table . getIndexes ( ) ; if ( indexes == null || indexes . size ( ) == 0 ) { return false ; } HashMap < AbstractExpression , Set < AbstractExpression > > valueEquivalence = analyzeValueEquivalence ( ) ; if ( valueEquivalence . isEmpty ( ) ) { return false ; } Set < AbstractExpression > parameterizedConstantKeys = new HashSet < > ( ) ; Set < AbstractExpression > valueEquivalenceKeys = valueEquivalence . keySet ( ) ; for ( AbstractExpression key : valueEquivalenceKeys ) { if ( key instanceof TupleValueExpression ) { Set < AbstractExpression > values = valueEquivalence . get ( key ) ; for ( AbstractExpression value : values ) { if ( ( value instanceof ParameterValueExpression ) || ( value instanceof ConstantValueExpression ) ) { TupleValueExpression tve = ( TupleValueExpression ) key ; parameterizedConstantKeys . add ( tve ) ; } } } } for ( Index index : indexes ) { if ( ! index . getUnique ( ) || ! index . getExpressionsjson ( ) . isEmpty ( ) ) { continue ; } Set < AbstractExpression > indexExpressions = new HashSet < > ( ) ; CatalogMap < ColumnRef > indexColRefs = index . getColumns ( ) ; for ( ColumnRef indexColRef : indexColRefs ) { Column col = indexColRef . getColumn ( ) ; TupleValueExpression tve = new TupleValueExpression ( scan . getTableName ( ) , scan . getTableAlias ( ) , col . getName ( ) , col . getName ( ) , col . getIndex ( ) ) ; indexExpressions . add ( tve ) ; } if ( parameterizedConstantKeys . containsAll ( indexExpressions ) ) { return true ; } } return false ; } | row else false |
31,654 | public Collection < String > calculateUDFDependees ( ) { List < String > answer = new ArrayList < > ( ) ; Collection < AbstractExpression > fCalls = findAllSubexpressionsOfClass ( FunctionExpression . class ) ; for ( AbstractExpression fCall : fCalls ) { FunctionExpression fexpr = ( FunctionExpression ) fCall ; if ( fexpr . isUserDefined ( ) ) { answer . add ( fexpr . getFunctionName ( ) ) ; } } return answer ; } | Calculate the UDF dependees . These are the UDFs called in an expression in this procedure . |
31,655 | public void statementGuaranteesDeterminism ( boolean hasLimitOrOffset , boolean order , String contentDeterminismDetail ) { m_statementHasLimitOrOffset = hasLimitOrOffset ; m_statementIsOrderDeterministic = order ; if ( contentDeterminismDetail != null ) { m_contentDeterminismDetail = contentDeterminismDetail ; } } | Mark the level of result determinism imposed by the statement which can save us from a difficult determination based on the plan graph . |
31,656 | private static void setParamIndexes ( BitSet ints , List < AbstractExpression > params ) { for ( AbstractExpression ae : params ) { assert ( ae instanceof ParameterValueExpression ) ; ParameterValueExpression pve = ( ParameterValueExpression ) ae ; int param = pve . getParameterIndex ( ) ; ints . set ( param ) ; } } | sources of bindings IndexScans and IndexCounts . |
31,657 | private static int [ ] bitSetToIntVector ( BitSet ints ) { int intCount = ints . cardinality ( ) ; if ( intCount == 0 ) { return null ; } int [ ] result = new int [ intCount ] ; int nextBit = ints . nextSetBit ( 0 ) ; for ( int ii = 0 ; ii < intCount ; ii ++ ) { assert ( nextBit != - 1 ) ; result [ ii ] = nextBit ; nextBit = ints . nextSetBit ( nextBit + 1 ) ; } assert ( nextBit == - 1 ) ; return result ; } | to convert the set bits to their integer indexes . |
31,658 | public VoltType [ ] parameterTypes ( ) { if ( m_parameterTypes == null ) { m_parameterTypes = new VoltType [ getParameters ( ) . length ] ; int ii = 0 ; for ( ParameterValueExpression param : getParameters ( ) ) { m_parameterTypes [ ii ++ ] = param . getValueType ( ) ; } } return m_parameterTypes ; } | This is assumed to be called only after parameters has been fully initialized . |
31,659 | public static Session newSession ( int dbID , String user , String password , int timeZoneSeconds ) { Database db = ( Database ) databaseIDMap . get ( dbID ) ; if ( db == null ) { return null ; } Session session = db . connect ( user , password , timeZoneSeconds ) ; session . isNetwork = true ; return session ; } | Used by server to open a new session |
31,660 | public static Session newSession ( String type , String path , String user , String password , HsqlProperties props , int timeZoneSeconds ) { Database db = getDatabase ( type , path , props ) ; if ( db == null ) { return null ; } return db . connect ( user , password , timeZoneSeconds ) ; } | Used by in - process connections and by Servlet |
31,661 | public static synchronized Database lookupDatabaseObject ( String type , String path ) { assert ( type == DatabaseURL . S_MEM ) ; java . util . HashMap < String , Database > databaseMap = memDatabaseMap ; String key = path ; return ( Database ) databaseMap . get ( key ) ; } | Looks up database of a given type and path in the registry . Returns null if there is none . |
31,662 | private static synchronized void addDatabaseObject ( String type , String path , Database db ) { assert ( type == DatabaseURL . S_MEM ) ; java . util . HashMap < String , Database > databaseMap = memDatabaseMap ; String key = path ; databaseIDMap . put ( db . databaseID , db ) ; databaseMap . put ( key , db ) ; } | Adds a database to the registry . Returns null if there is none . |
31,663 | static void removeDatabase ( Database database ) { int dbID = database . databaseID ; String type = database . getType ( ) ; String path = database . getPath ( ) ; notifyServers ( database ) ; assert ( type == DatabaseURL . S_MEM ) ; java . util . HashMap < String , Database > databaseMap = memDatabaseMap ; String key = path ; databaseIDMap . remove ( dbID ) ; databaseMap . remove ( key ) ; if ( databaseIDMap . isEmpty ( ) ) { ValuePool . resetPool ( ) ; } } | Removes the database from registry . |
31,664 | private static void deRegisterServer ( Server server , Database db ) { Iterator it = serverMap . values ( ) . iterator ( ) ; for ( ; it . hasNext ( ) ; ) { HashSet databases = ( HashSet ) it . next ( ) ; databases . remove ( db ) ; if ( databases . isEmpty ( ) ) { it . remove ( ) ; } } } | Deregisters a server as serving a given database . Not yet used . |
31,665 | private static void registerServer ( Server server , Database db ) { if ( ! serverMap . containsKey ( server ) ) { serverMap . put ( server , new HashSet ( ) ) ; } HashSet databases = ( HashSet ) serverMap . get ( server ) ; databases . add ( db ) ; } | Registers a server as serving a given database . |
31,666 | private static void notifyServers ( Database db ) { Iterator it = serverMap . keySet ( ) . iterator ( ) ; for ( ; it . hasNext ( ) ; ) { Server server = ( Server ) it . next ( ) ; HashSet databases = ( HashSet ) serverMap . get ( server ) ; if ( databases . contains ( db ) ) { } } } | Notifies all servers that serve the database that the database has been shutdown . |
31,667 | private static String filePathToKey ( String path ) { try { return FileUtil . getDefaultInstance ( ) . canonicalPath ( path ) ; } catch ( Exception e ) { return path ; } } | thrown exception to an HsqlException in the process |
31,668 | public static boolean isComment ( String sql ) { Matcher commentMatcher = PAT_SINGLE_LINE_COMMENT . matcher ( sql ) ; return commentMatcher . matches ( ) ; } | Check if a SQL string is a comment . |
31,669 | public static String extractDDLToken ( String sql ) { String ddlToken = null ; Matcher ddlMatcher = PAT_ANY_DDL_FIRST_TOKEN . matcher ( sql ) ; if ( ddlMatcher . find ( ) ) { ddlToken = ddlMatcher . group ( 1 ) . toLowerCase ( ) ; } return ddlToken ; } | Get the DDL token if any at the start of this statement . |
31,670 | public static String extractDDLTableName ( String sql ) { Matcher matcher = PAT_TABLE_DDL_PREAMBLE . matcher ( sql ) ; if ( matcher . find ( ) ) { return matcher . group ( 2 ) . toLowerCase ( ) ; } return null ; } | Get the table name for a CREATE or DROP DDL statement . |
31,671 | public static String checkPermitted ( String sql ) { for ( CheckedPattern cp : BLACKLISTS ) { CheckedPattern . Result result = cp . check ( sql ) ; if ( result . matcher != null ) { return String . format ( "%s, in statement: %s" , result . explanation , sql ) ; } } boolean hadWLMatch = false ; for ( CheckedPattern cp : WHITELISTS ) { if ( cp . matches ( sql ) ) { hadWLMatch = true ; break ; } } if ( ! hadWLMatch ) { return String . format ( "AdHoc DDL contains an unsupported statement: %s" , sql ) ; } return null ; } | Naive filtering for stuff we haven t implemented yet . Hopefully this gets whittled away and eventually disappears . |
31,672 | static private boolean matchesStringAtIndex ( char [ ] buf , int index , String str ) { int strLength = str . length ( ) ; if ( index + strLength > buf . length ) { return false ; } for ( int i = 0 ; i < strLength ; ++ i ) { if ( buf [ index + i ] != str . charAt ( i ) ) { return false ; } } return true ; } | Determine if a character buffer contains the specified string a the specified index . Avoids an array index exception if the buffer is too short . |
31,673 | private static String removeCStyleComments ( String ddl ) { StringBuilder sb = new StringBuilder ( ) ; for ( String part : PAT_STRIP_CSTYLE_COMMENTS . split ( ddl ) ) { sb . append ( part ) ; } return sb . toString ( ) ; } | Remove c - style comments from a string aggressively |
31,674 | private static ObjectToken findObjectToken ( String objectTypeName ) { if ( objectTypeName != null ) { for ( ObjectToken ot : OBJECT_TOKENS ) { if ( ot . token . equalsIgnoreCase ( objectTypeName ) ) { return ot ; } } } return null ; } | Find information about an object type token if it s a known object type . |
31,675 | synchronized void pushPair ( Session session , Object [ ] row1 , Object [ ] row2 ) { if ( maxRowsQueued == 0 ) { trigger . fire ( triggerType , name . name , table . getName ( ) . name , row1 , row2 ) ; return ; } if ( rowsQueued >= maxRowsQueued ) { if ( nowait ) { pendingQueue . removeLast ( ) ; } else { try { wait ( ) ; } catch ( InterruptedException e ) { } rowsQueued ++ ; } } else { rowsQueued ++ ; } pendingQueue . add ( new TriggerData ( session , row1 , row2 ) ) ; notify ( ) ; } | The main thread tells the trigger thread to fire by this call . If this Trigger is not threaded then the fire method is caled immediately and executed by the main thread . Otherwise the row data objects are added to the queue to be used by the Trigger thread . |
31,676 | public synchronized CompiledPlan planSqlCore ( String sql , StatementPartitioning partitioning ) { TrivialCostModel costModel = new TrivialCostModel ( ) ; DatabaseEstimates estimates = new DatabaseEstimates ( ) ; CompiledPlan plan = null ; try ( QueryPlanner planner = new QueryPlanner ( sql , "PlannerTool" , "PlannerToolProc" , m_database , partitioning , m_hsql , estimates , ! VoltCompiler . DEBUG_MODE , costModel , null , null , DeterminismMode . FASTER , false ) ) { planner . parse ( ) ; plan = planner . plan ( ) ; assert ( plan != null ) ; } catch ( Exception e ) { String loggedMsg = "" ; if ( ! ( e instanceof PlanningErrorException || e instanceof HSQLParseException ) ) { logException ( e , "Error compiling query" ) ; loggedMsg = " (Stack trace has been written to the log.)" ; } if ( e . getMessage ( ) != null ) { throw new RuntimeException ( "SQL error while compiling query: " + e . getMessage ( ) + loggedMsg , e ) ; } throw new RuntimeException ( "SQL error while compiling query: " + e . toString ( ) + loggedMsg , e ) ; } if ( plan == null ) { throw new RuntimeException ( "Null plan received in PlannerTool.planSql" ) ; } return plan ; } | Stripped down compile that is ONLY used to plan default procedures . |
31,677 | private boolean isReadOnlyProcedure ( String pname ) { final Boolean b = m_procedureInfo . get ( ) . get ( pname ) ; if ( b == null ) { return false ; } return b ; } | Check if procedure is readonly? |
31,678 | private VoltTable [ ] aggregateProcedureProfileStats ( VoltTable [ ] baseStats ) { if ( baseStats == null || baseStats . length != 1 ) { return baseStats ; } StatsProcProfTable timeTable = new StatsProcProfTable ( ) ; baseStats [ 0 ] . resetRowPosition ( ) ; while ( baseStats [ 0 ] . advanceRow ( ) ) { boolean transactional = baseStats [ 0 ] . getLong ( "TRANSACTIONAL" ) == 1 ; if ( ! transactional ) { continue ; } if ( ! baseStats [ 0 ] . getString ( "STATEMENT" ) . equalsIgnoreCase ( "<ALL>" ) ) { continue ; } String pname = baseStats [ 0 ] . getString ( "PROCEDURE" ) ; timeTable . updateTable ( ! isReadOnlyProcedure ( pname ) , baseStats [ 0 ] . getLong ( "TIMESTAMP" ) , pname , baseStats [ 0 ] . getLong ( "PARTITION_ID" ) , baseStats [ 0 ] . getLong ( "INVOCATIONS" ) , baseStats [ 0 ] . getLong ( "MIN_EXECUTION_TIME" ) , baseStats [ 0 ] . getLong ( "MAX_EXECUTION_TIME" ) , baseStats [ 0 ] . getLong ( "AVG_EXECUTION_TIME" ) , baseStats [ 0 ] . getLong ( "FAILURES" ) , baseStats [ 0 ] . getLong ( "ABORTS" ) ) ; } return new VoltTable [ ] { timeTable . sortByAverage ( "EXECUTION_TIME" ) } ; } | Produce PROCEDUREPROFILE aggregation of PROCEDURE subselector |
31,679 | private VoltTable [ ] aggregateProcedureInputStats ( VoltTable [ ] baseStats ) { if ( baseStats == null || baseStats . length != 1 ) { return baseStats ; } StatsProcInputTable timeTable = new StatsProcInputTable ( ) ; baseStats [ 0 ] . resetRowPosition ( ) ; while ( baseStats [ 0 ] . advanceRow ( ) ) { boolean transactional = baseStats [ 0 ] . getLong ( "TRANSACTIONAL" ) == 1 ; if ( ! transactional ) { continue ; } if ( ! baseStats [ 0 ] . getString ( "STATEMENT" ) . equalsIgnoreCase ( "<ALL>" ) ) { continue ; } String pname = baseStats [ 0 ] . getString ( "PROCEDURE" ) ; timeTable . updateTable ( ! isReadOnlyProcedure ( pname ) , pname , baseStats [ 0 ] . getLong ( "PARTITION_ID" ) , baseStats [ 0 ] . getLong ( "TIMESTAMP" ) , baseStats [ 0 ] . getLong ( "INVOCATIONS" ) , baseStats [ 0 ] . getLong ( "MIN_PARAMETER_SET_SIZE" ) , baseStats [ 0 ] . getLong ( "MAX_PARAMETER_SET_SIZE" ) , baseStats [ 0 ] . getLong ( "AVG_PARAMETER_SET_SIZE" ) ) ; } return new VoltTable [ ] { timeTable . sortByInput ( "PROCEDURE_INPUT" ) } ; } | Produce PROCEDUREINPUT aggregation of PROCEDURE subselector |
31,680 | private VoltTable [ ] aggregateProcedureOutputStats ( VoltTable [ ] baseStats ) { if ( baseStats == null || baseStats . length != 1 ) { return baseStats ; } StatsProcOutputTable timeTable = new StatsProcOutputTable ( ) ; baseStats [ 0 ] . resetRowPosition ( ) ; while ( baseStats [ 0 ] . advanceRow ( ) ) { boolean transactional = baseStats [ 0 ] . getLong ( "TRANSACTIONAL" ) == 1 ; if ( ! transactional ) { continue ; } if ( ! baseStats [ 0 ] . getString ( "STATEMENT" ) . equalsIgnoreCase ( "<ALL>" ) ) { continue ; } String pname = baseStats [ 0 ] . getString ( "PROCEDURE" ) ; timeTable . updateTable ( ! isReadOnlyProcedure ( pname ) , pname , baseStats [ 0 ] . getLong ( "PARTITION_ID" ) , baseStats [ 0 ] . getLong ( "TIMESTAMP" ) , baseStats [ 0 ] . getLong ( "INVOCATIONS" ) , baseStats [ 0 ] . getLong ( "MIN_RESULT_SIZE" ) , baseStats [ 0 ] . getLong ( "MAX_RESULT_SIZE" ) , baseStats [ 0 ] . getLong ( "AVG_RESULT_SIZE" ) ) ; } return new VoltTable [ ] { timeTable . sortByOutput ( "PROCEDURE_OUTPUT" ) } ; } | Produce PROCEDUREOUTPUT aggregation of PROCEDURE subselector |
31,681 | public void notifyOfCatalogUpdate ( ) { m_procedureInfo = getProcedureInformationfoSupplier ( ) ; m_registeredStatsSources . put ( StatsSelector . PROCEDURE , new NonBlockingHashMap < Long , NonBlockingHashSet < StatsSource > > ( ) ) ; } | Please be noted that this function will be called from Site thread where most other functions in the class are from StatsAgent thread . |
31,682 | public void addState ( long agreementHSId ) { SiteState ss = m_stateBySite . get ( agreementHSId ) ; if ( ss != null ) return ; ss = new SiteState ( ) ; ss . hsId = agreementHSId ; ss . newestConfirmedTxnId = m_newestConfirmedTxnId ; m_stateBySite . put ( agreementHSId , ss ) ; } | Once a failed node is rejoined put it s sites back into all of the data structures here . |
31,683 | public Pair < CompleteTransactionTask , Boolean > pollFirstCompletionTask ( CompletionCounter nextTaskCounter ) { Pair < CompleteTransactionTask , Boolean > pair = m_compTasks . pollFirstEntry ( ) . getValue ( ) ; if ( m_compTasks . isEmpty ( ) ) { return pair ; } Pair < CompleteTransactionTask , Boolean > next = peekFirst ( ) ; if ( nextTaskCounter . txnId == 0L ) { nextTaskCounter . txnId = next . getFirst ( ) . getMsgTxnId ( ) ; nextTaskCounter . completionCount ++ ; nextTaskCounter . timestamp = next . getFirst ( ) . getTimestamp ( ) ; } else if ( nextTaskCounter . txnId == next . getFirst ( ) . getMsgTxnId ( ) && nextTaskCounter . timestamp == next . getFirst ( ) . getTimestamp ( ) ) { nextTaskCounter . completionCount ++ ; } return pair ; } | Remove the CompleteTransactionTask from the head and count the next CompleteTransactionTask |
31,684 | private static boolean isComparable ( CompleteTransactionTask c1 , CompleteTransactionTask c2 ) { return c1 . getMsgTxnId ( ) == c2 . getMsgTxnId ( ) && MpRestartSequenceGenerator . isForRestart ( c1 . getTimestamp ( ) ) == MpRestartSequenceGenerator . isForRestart ( c2 . getTimestamp ( ) ) ; } | 4 ) restart completion and repair completion can t overwrite each other |
31,685 | public boolean matchCompleteTransactionTask ( long txnId , long timestamp ) { if ( ! m_compTasks . isEmpty ( ) ) { long lowestTxnId = m_compTasks . firstKey ( ) ; if ( txnId == lowestTxnId ) { Pair < CompleteTransactionTask , Boolean > pair = m_compTasks . get ( lowestTxnId ) ; return timestamp == pair . getFirst ( ) . getTimestamp ( ) ; } } return false ; } | Only match CompleteTransactionTask at head of the queue |
31,686 | public static VoltTable aggregateStats ( VoltTable stats ) throws IllegalArgumentException { stats . resetRowPosition ( ) ; if ( stats . getRowCount ( ) == 0 ) { return stats ; } String role = null ; Map < Byte , State > states = new TreeMap < > ( ) ; while ( stats . advanceRow ( ) ) { final byte clusterId = ( byte ) stats . getLong ( CN_REMOTE_CLUSTER_ID ) ; final String curRole = stats . getString ( CN_ROLE ) ; if ( role == null ) { role = curRole ; } else if ( ! role . equals ( curRole ) ) { throw new IllegalArgumentException ( "Inconsistent DR role across cluster nodes: " + stats . toFormattedString ( false ) ) ; } final State state = State . valueOf ( stats . getString ( CN_STATE ) ) ; states . put ( clusterId , state . and ( states . get ( clusterId ) ) ) ; } if ( states . size ( ) > 1 ) { states . remove ( ( byte ) - 1 ) ; } assert role != null ; stats . clearRowData ( ) ; for ( Map . Entry < Byte , State > e : states . entrySet ( ) ) { stats . addRow ( role , e . getValue ( ) . name ( ) , e . getKey ( ) ) ; } return stats ; } | Aggregates DRROLE statistics reported by multiple nodes into a single cluster - wide row . The role column should be the same across all nodes . The state column may defer slightly and it uses the same logical AND - ish operation to combine the states . |
31,687 | public static String getString ( String key ) { if ( RESOURCE_BUNDLE == null ) throw new RuntimeException ( "Localized messages from resource bundle '" + BUNDLE_NAME + "' not loaded during initialization of driver." ) ; try { if ( key == null ) throw new IllegalArgumentException ( "Message key can not be null" ) ; String message = RESOURCE_BUNDLE . getString ( key ) ; if ( message == null ) message = "Missing error message for key '" + key + "'" ; return message ; } catch ( MissingResourceException e ) { return '!' + key + '!' ; } } | Returns the localized message for the given message key |
31,688 | public void createAllDevNullTargets ( Exception lastWriteException ) { Map < Integer , SnapshotDataTarget > targets = Maps . newHashMap ( ) ; final AtomicInteger numTargets = new AtomicInteger ( ) ; for ( Deque < SnapshotTableTask > tasksForSite : m_taskListsForHSIds . values ( ) ) { for ( SnapshotTableTask task : tasksForSite ) { if ( task . getTarget ( true ) != null ) { try { task . getTarget ( ) . close ( ) ; } catch ( Exception e ) { SNAP_LOG . error ( "Failed closing data target after error" , e ) ; } } SnapshotDataTarget target = targets . get ( task . m_table . getRelativeIndex ( ) ) ; if ( target == null ) { target = new DevNullSnapshotTarget ( lastWriteException ) ; final Runnable onClose = new TargetStatsClosure ( target , task . m_table . getTypeName ( ) , numTargets , m_snapshotRecord ) ; target . setOnCloseHandler ( onClose ) ; targets . put ( task . m_table . getRelativeIndex ( ) , target ) ; m_targets . add ( target ) ; numTargets . incrementAndGet ( ) ; } task . setTarget ( target ) ; } } } | In case the deferred setup phase fails some data targets may have not been created yet . This method will close all existing data targets and replace all with DevNullDataTargets so that snapshot can be drained . |
31,689 | private Map < String , Boolean > collapseSets ( List < List < String > > allTableSets ) { Map < String , Boolean > answer = new TreeMap < > ( ) ; for ( List < String > tables : allTableSets ) { for ( String table : tables ) { answer . put ( table , false ) ; } } return answer ; } | Take a list of list of table names and collapse into a map which maps all table names to false . We will set the correct values later on . We just want to get the structure right now . Note that tables may be named multiple time in the lists of lists of tables . Everything gets mapped to false so we don t care . |
31,690 | private List < List < String > > decodeTables ( String [ ] tablesThatMustBeEmpty ) { List < List < String > > answer = new ArrayList < > ( ) ; for ( String tableSet : tablesThatMustBeEmpty ) { String tableNames [ ] = tableSet . split ( "\\+" ) ; answer . add ( Arrays . asList ( tableNames ) ) ; } return answer ; } | Decode sets of names encoded as by concatenation with plus signs into lists of lists of strings . Preserve the order since we need it to match to error messages later on . |
31,691 | public VoltTable [ ] run ( SystemProcedureExecutionContext ctx ) { createAndExecuteSysProcPlan ( SysProcFragmentId . PF_shutdownSync , SysProcFragmentId . PF_shutdownSyncDone ) ; SynthesizedPlanFragment pfs [ ] = new SynthesizedPlanFragment [ ] { new SynthesizedPlanFragment ( SysProcFragmentId . PF_shutdownCommand , true ) } ; executeSysProcPlanFragments ( pfs , SysProcFragmentId . PF_procedureDone ) ; return new VoltTable [ 0 ] ; } | Begin an un - graceful shutdown . |
31,692 | public void drain ( ) throws InterruptedException , IOException { ClientImpl currentClient = this . getClient ( ) ; if ( currentClient == null ) { throw new IOException ( "Client is unavailable for drain()." ) ; } currentClient . drain ( ) ; } | Block the current thread until all queued stored procedure invocations have received responses or there are no more connections to the cluster |
31,693 | public void backpressureBarrier ( ) throws InterruptedException , IOException { ClientImpl currentClient = this . getClient ( ) ; if ( currentClient == null ) { throw new IOException ( "Client is unavailable for backpressureBarrier()." ) ; } currentClient . backpressureBarrier ( ) ; } | Blocks the current thread until there is no more backpressure or there are no more connections to the database |
31,694 | public boolean absolute ( int position ) { if ( position < 0 ) { position += size ; } if ( position < 0 ) { beforeFirst ( ) ; return false ; } if ( position > size ) { afterLast ( ) ; return false ; } if ( size == 0 ) { return false ; } if ( position < currentPos ) { beforeFirst ( ) ; } while ( position > currentPos ) { next ( ) ; } return true ; } | Uses similar semantics to java . sql . ResultSet except this is 0 based . When position is 0 or positive it is from the start ; when negative it is from end |
31,695 | private void printErrorAndQuit ( String message ) { System . out . println ( message + "\n-------------------------------------------------------------------------------------\n" ) ; printUsage ( ) ; System . exit ( - 1 ) ; } | Prints out an error message and the application usage print - out then terminates the application . |
31,696 | public AppHelper printActualUsage ( ) { System . out . println ( "-------------------------------------------------------------------------------------" ) ; int maxLength = 24 ; for ( Argument a : Arguments ) if ( maxLength < a . Name . length ( ) ) maxLength = a . Name . length ( ) ; for ( Argument a : Arguments ) { String template = "%1$" + String . valueOf ( maxLength - 1 ) + "s : " ; System . out . printf ( template , a . Name ) ; System . out . println ( a . Value ) ; } System . out . println ( "-------------------------------------------------------------------------------------" ) ; return this ; } | Prints a full list of actual arguments that will be used by the application after interpretation of defaults and actual argument values as passed by the user on the command line . |
31,697 | public byte byteValue ( String name ) { try { return Byte . valueOf ( this . getArgumentByName ( name ) . Value ) ; } catch ( NullPointerException npe ) { printErrorAndQuit ( String . format ( "Argument '%s' was not provided." , name ) ) ; } catch ( Exception x ) { printErrorAndQuit ( String . format ( "Argument '%s' could not be cast to type: 'byte'." , name ) ) ; } return - 1 ; } | Retrieves the value of an argument as a byte . |
31,698 | public short shortValue ( String name ) { try { return Short . valueOf ( this . getArgumentByName ( name ) . Value ) ; } catch ( NullPointerException npe ) { printErrorAndQuit ( String . format ( "Argument '%s' was not provided." , name ) ) ; } catch ( Exception x ) { printErrorAndQuit ( String . format ( "Argument '%s' could not be cast to type: 'short'." , name ) ) ; } return - 1 ; } | Retrieves the value of an argument as a short . |
31,699 | public int intValue ( String name ) { try { return Integer . valueOf ( this . getArgumentByName ( name ) . Value ) ; } catch ( NullPointerException npe ) { printErrorAndQuit ( String . format ( "Argument '%s' was not provided." , name ) ) ; } catch ( Exception x ) { printErrorAndQuit ( String . format ( "Argument '%s' could not be cast to type: 'int'." , name ) ) ; } return - 1 ; } | Retrieves the value of an argument as a int . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.