idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
16,200
public void parse ( final InsertStatement insertStatement ) { if ( ! lexerEngine . skipIfEqual ( getCustomizedInsertKeywords ( ) ) ) { return ; } removeUnnecessaryToken ( insertStatement ) ; Optional < InsertValuesToken > insertValuesToken = insertStatement . findSQLToken ( InsertValuesToken . class ) ; Preconditions . checkState ( insertValuesToken . isPresent ( ) ) ; insertStatement . getSQLTokens ( ) . remove ( insertValuesToken . get ( ) ) ; insertStatement . addSQLToken ( new InsertSetToken ( insertValuesToken . get ( ) . getStartIndex ( ) ) ) ; do { SQLExpression left = basicExpressionParser . parse ( insertStatement ) ; Column column = null ; if ( left instanceof SQLPropertyExpression ) { column = new Column ( SQLUtil . getExactlyValue ( ( ( SQLPropertyExpression ) left ) . getName ( ) ) , insertStatement . getTables ( ) . getSingleTableName ( ) ) ; } if ( left instanceof SQLIdentifierExpression ) { column = new Column ( SQLUtil . getExactlyValue ( ( ( SQLIdentifierExpression ) left ) . getName ( ) ) , insertStatement . getTables ( ) . getSingleTableName ( ) ) ; } if ( left instanceof SQLIgnoreExpression ) { column = new Column ( SQLUtil . getExactlyValue ( ( ( SQLIgnoreExpression ) left ) . getExpression ( ) ) , insertStatement . getTables ( ) . getSingleTableName ( ) ) ; } Preconditions . checkNotNull ( column ) ; lexerEngine . accept ( Symbol . EQ ) ; SQLExpression right = basicExpressionParser . parse ( insertStatement ) ; if ( shardingRule . isShardingColumn ( column . getName ( ) , column . getTableName ( ) ) && ( right instanceof SQLNumberExpression || right instanceof SQLTextExpression || right instanceof SQLParameterMarkerExpression ) ) { insertStatement . getRouteConditions ( ) . add ( new Condition ( column , right ) ) ; } } while ( lexerEngine . skipIfEqual ( Symbol . COMMA ) ) ; InsertValue insertValue = new InsertValue ( new LinkedList < SQLExpression > ( ) ) ; insertStatement . getValues ( ) . add ( insertValue ) ; }
Parse insert set .
16,201
public Optional < SQLStatementRule > findSQLStatementRule ( final DatabaseType databaseType , final String contextClassName ) { return Optional . fromNullable ( parserRuleDefinitions . get ( DatabaseType . H2 == databaseType ? DatabaseType . MySQL : databaseType ) . getSqlStatementRuleDefinition ( ) . getRules ( ) . get ( contextClassName ) ) ; }
Find SQL statement rule .
16,202
public Optional < SQLSegmentFiller > findSQLSegmentFiller ( final DatabaseType databaseType , final Class < ? extends SQLSegment > sqlSegmentClass ) { return Optional . fromNullable ( parserRuleDefinitions . get ( DatabaseType . H2 == databaseType ? DatabaseType . MySQL : databaseType ) . getFillerRuleDefinition ( ) . getRules ( ) . get ( sqlSegmentClass ) ) ; }
Find SQL segment rule .
16,203
public String readStringNul ( ) { byte [ ] result = new byte [ byteBuf . bytesBefore ( ( byte ) 0 ) ] ; byteBuf . readBytes ( result ) ; byteBuf . skipBytes ( 1 ) ; return new String ( result ) ; }
Read null terminated string from byte buffers .
16,204
public static TextProtocolBackendHandler newInstance ( final String sql , final BackendConnection backendConnection ) { if ( sql . toUpperCase ( ) . startsWith ( SCTL_SET ) ) { return new ShardingCTLSetBackendHandler ( sql , backendConnection ) ; } if ( sql . toUpperCase ( ) . startsWith ( SCTL_SHOW ) ) { return new ShardingCTLShowBackendHandler ( sql , backendConnection ) ; } if ( sql . toUpperCase ( ) . startsWith ( SCTL_EXPLAIN ) ) { return new ShardingCTLExplainBackendHandler ( sql , backendConnection ) ; } throw new IllegalArgumentException ( sql ) ; }
Create new instance of sharding CTL backend handler .
16,205
public void optimize ( final SQLStatementRule rule , final SQLStatement sqlStatement ) { Optional < SQLStatementOptimizer > optimizer = rule . getOptimizer ( ) ; if ( optimizer . isPresent ( ) ) { optimizer . get ( ) . optimize ( sqlStatement , shardingTableMetaData ) ; } }
Optimize SQL statement .
16,206
public static ParserRuleContext getFirstChildNode ( final ParserRuleContext node , final RuleName ruleName ) { Optional < ParserRuleContext > result = findFirstChildNode ( node , ruleName ) ; Preconditions . checkState ( result . isPresent ( ) ) ; return result . get ( ) ; }
Get first child node .
16,207
public static Optional < ParserRuleContext > findFirstChildNode ( final ParserRuleContext node , final RuleName ruleName ) { Queue < ParserRuleContext > parserRuleContexts = new LinkedList < > ( ) ; parserRuleContexts . add ( node ) ; ParserRuleContext parserRuleContext ; while ( null != ( parserRuleContext = parserRuleContexts . poll ( ) ) ) { if ( isMatchedNode ( parserRuleContext , ruleName ) ) { return Optional . of ( parserRuleContext ) ; } for ( int i = 0 ; i < parserRuleContext . getChildCount ( ) ; i ++ ) { if ( parserRuleContext . getChild ( i ) instanceof ParserRuleContext ) { parserRuleContexts . add ( ( ParserRuleContext ) parserRuleContext . getChild ( i ) ) ; } } } return Optional . absent ( ) ; }
Find first child node .
16,208
public static Optional < ParserRuleContext > findFirstChildNodeNoneRecursive ( final ParserRuleContext node , final RuleName ruleName ) { if ( isMatchedNode ( node , ruleName ) ) { return Optional . of ( node ) ; } for ( int i = 0 ; i < node . getChildCount ( ) ; i ++ ) { if ( node . getChild ( i ) instanceof ParserRuleContext ) { ParserRuleContext child = ( ParserRuleContext ) node . getChild ( i ) ; if ( isMatchedNode ( child , ruleName ) ) { return Optional . of ( child ) ; } } } return Optional . absent ( ) ; }
Find first child node none recursive .
16,209
public static Optional < ParserRuleContext > findSingleNodeFromFirstDescendant ( final ParserRuleContext node , final RuleName ruleName ) { ParserRuleContext nextNode = node ; do { if ( isMatchedNode ( nextNode , ruleName ) ) { return Optional . of ( nextNode ) ; } if ( 1 != nextNode . getChildCount ( ) || ! ( nextNode . getChild ( 0 ) instanceof ParserRuleContext ) ) { return Optional . absent ( ) ; } nextNode = ( ParserRuleContext ) nextNode . getChild ( 0 ) ; } while ( null != nextNode ) ; return Optional . absent ( ) ; }
Find single node from first descendant which only has one child .
16,210
public static Collection < ParserRuleContext > getAllDescendantNodes ( final ParserRuleContext node , final RuleName ruleName ) { Collection < ParserRuleContext > result = new LinkedList < > ( ) ; if ( isMatchedNode ( node , ruleName ) ) { result . add ( node ) ; } for ( ParserRuleContext each : getChildrenNodes ( node ) ) { result . addAll ( getAllDescendantNodes ( each , ruleName ) ) ; } return result ; }
Get all descendant nodes .
16,211
public boolean containsColumn ( final String tableName , final String column ) { return containsTable ( tableName ) && tables . get ( tableName ) . getColumns ( ) . keySet ( ) . contains ( column . toLowerCase ( ) ) ; }
Judge contains column from table meta data or not .
16,212
public Collection < String > getAllColumnNames ( final String tableName ) { return tables . containsKey ( tableName ) ? tables . get ( tableName ) . getColumns ( ) . keySet ( ) : Collections . < String > emptyList ( ) ; }
Get all column names via table .
16,213
public static AggregationUnit create ( final AggregationType type ) { switch ( type ) { case MAX : return new ComparableAggregationUnit ( false ) ; case MIN : return new ComparableAggregationUnit ( true ) ; case SUM : case COUNT : return new AccumulationAggregationUnit ( ) ; case AVG : return new AverageAggregationUnit ( ) ; default : throw new UnsupportedOperationException ( type . name ( ) ) ; } }
Create aggregation unit instance .
16,214
public void execute ( final Collection < T > targets , final ForceExecuteCallback < T > callback ) throws SQLException { Collection < SQLException > exceptions = new LinkedList < > ( ) ; for ( T each : targets ) { try { callback . execute ( each ) ; } catch ( final SQLException ex ) { exceptions . add ( ex ) ; } } throwSQLExceptionIfNecessary ( exceptions ) ; }
Force execute .
16,215
public final T newService ( final String type , final Properties props ) { Collection < T > typeBasedServices = loadTypeBasedServices ( type ) ; if ( typeBasedServices . isEmpty ( ) ) { throw new ShardingConfigurationException ( "Invalid `%s` SPI type `%s`." , classType . getName ( ) , type ) ; } T result = typeBasedServices . iterator ( ) . next ( ) ; result . setProperties ( props ) ; return result ; }
Create new instance for type based SPI .
16,216
public static void setError ( final Span span , final Exception cause ) { span . setTag ( Tags . ERROR . getKey ( ) , true ) . log ( System . currentTimeMillis ( ) , getReason ( cause ) ) ; }
Set error .
16,217
public static ShardingRouter newInstance ( final ShardingRule shardingRule , final ShardingMetaData shardingMetaData , final DatabaseType databaseType , final ParsingResultCache parsingResultCache ) { return HintManager . isDatabaseShardingOnly ( ) ? new DatabaseHintSQLRouter ( shardingRule ) : new ParsingSQLRouter ( shardingRule , shardingMetaData , databaseType , parsingResultCache ) ; }
Create new instance of sharding router .
16,218
public static SQLExecuteCallback < Integer > getPreparedUpdateSQLExecuteCallback ( final DatabaseType databaseType , final boolean isExceptionThrown ) { return new SQLExecuteCallback < Integer > ( databaseType , isExceptionThrown ) { protected Integer executeSQL ( final RouteUnit routeUnit , final Statement statement , final ConnectionMode connectionMode ) throws SQLException { return ( ( PreparedStatement ) statement ) . executeUpdate ( ) ; } } ; }
Get update callback .
16,219
public static SQLExecuteCallback < Boolean > getPreparedSQLExecuteCallback ( final DatabaseType databaseType , final boolean isExceptionThrown ) { return new SQLExecuteCallback < Boolean > ( databaseType , isExceptionThrown ) { protected Boolean executeSQL ( final RouteUnit routeUnit , final Statement statement , final ConnectionMode connectionMode ) throws SQLException { return ( ( PreparedStatement ) statement ) . execute ( ) ; } } ; }
Get execute callback .
16,220
public boolean hasLogicTable ( final String logicTableName ) { for ( TableRule each : tableRules ) { if ( each . getLogicTable ( ) . equals ( logicTableName . toLowerCase ( ) ) ) { return true ; } } return false ; }
Judge contains this logic table in this rule .
16,221
public String getBindingActualTable ( final String dataSource , final String logicTable , final String otherActualTable ) { int index = - 1 ; for ( TableRule each : tableRules ) { index = each . findActualTableIndex ( dataSource , otherActualTable ) ; if ( - 1 != index ) { break ; } } if ( - 1 == index ) { throw new ShardingConfigurationException ( "Actual table [%s].[%s] is not in table config" , dataSource , otherActualTable ) ; } for ( TableRule each : tableRules ) { if ( each . getLogicTable ( ) . equals ( logicTable . toLowerCase ( ) ) ) { return each . getActualDataNodes ( ) . get ( index ) . getTableName ( ) . toLowerCase ( ) ; } } throw new ShardingConfigurationException ( "Cannot find binding actual table, data source: %s, logic table: %s, other actual table: %s" , dataSource , logicTable , otherActualTable ) ; }
Deduce actual table name from other actual table name in same binding table rule .
16,222
public final void parse ( final SelectStatement selectStatement ) { if ( ! lexerEngine . skipIfEqual ( DefaultKeyword . GROUP ) ) { return ; } lexerEngine . accept ( DefaultKeyword . BY ) ; while ( true ) { addGroupByItem ( basicExpressionParser . parse ( selectStatement ) , selectStatement ) ; if ( ! lexerEngine . equalAny ( Symbol . COMMA ) ) { break ; } lexerEngine . nextToken ( ) ; } lexerEngine . skipAll ( getSkippedKeywordAfterGroupBy ( ) ) ; selectStatement . setGroupByLastIndex ( lexerEngine . getCurrentToken ( ) . getEndPosition ( ) - lexerEngine . getCurrentToken ( ) . getLiterals ( ) . length ( ) - 1 ) ; }
Parse group by .
16,223
public static AbstractUseParser newInstance ( final DatabaseType dbType , final ShardingRule shardingRule , final LexerEngine lexerEngine ) { switch ( dbType ) { case H2 : case MySQL : return new MySQLUseParser ( lexerEngine ) ; default : throw new UnsupportedOperationException ( String . format ( "Cannot support database [%s]." , dbType ) ) ; } }
Create use parser instance .
16,224
public long readIntLenenc ( ) { int firstByte = readInt1 ( ) ; if ( firstByte < 0xfb ) { return firstByte ; } if ( 0xfb == firstByte ) { return 0 ; } if ( 0xfc == firstByte ) { return byteBuf . readShortLE ( ) ; } if ( 0xfd == firstByte ) { return byteBuf . readMediumLE ( ) ; } return byteBuf . readLongLE ( ) ; }
Read lenenc integer from byte buffers .
16,225
public void writeIntLenenc ( final long value ) { if ( value < 0xfb ) { byteBuf . writeByte ( ( int ) value ) ; return ; } if ( value < Math . pow ( 2 , 16 ) ) { byteBuf . writeByte ( 0xfc ) ; byteBuf . writeShortLE ( ( int ) value ) ; return ; } if ( value < Math . pow ( 2 , 24 ) ) { byteBuf . writeByte ( 0xfd ) ; byteBuf . writeMediumLE ( ( int ) value ) ; return ; } byteBuf . writeByte ( 0xfe ) ; byteBuf . writeLongLE ( value ) ; }
Write lenenc integer to byte buffers .
16,226
public String readStringLenenc ( ) { int length = ( int ) readIntLenenc ( ) ; byte [ ] result = new byte [ length ] ; byteBuf . readBytes ( result ) ; return new String ( result ) ; }
Read lenenc string from byte buffers .
16,227
public void writeStringLenenc ( final String value ) { if ( Strings . isNullOrEmpty ( value ) ) { byteBuf . writeByte ( 0 ) ; return ; } writeIntLenenc ( value . getBytes ( ) . length ) ; byteBuf . writeBytes ( value . getBytes ( ) ) ; }
Write lenenc string to byte buffers .
16,228
public void writeBytesLenenc ( final byte [ ] value ) { if ( 0 == value . length ) { byteBuf . writeByte ( 0 ) ; return ; } writeIntLenenc ( value . length ) ; byteBuf . writeBytes ( value ) ; }
Write lenenc bytes to byte buffers .
16,229
public String readStringFix ( final int length ) { byte [ ] result = new byte [ length ] ; byteBuf . readBytes ( result ) ; return new String ( result ) ; }
Read fixed length string from byte buffers .
16,230
public byte [ ] readStringNulByBytes ( ) { byte [ ] result = new byte [ byteBuf . bytesBefore ( ( byte ) 0 ) ] ; byteBuf . readBytes ( result ) ; byteBuf . skipBytes ( 1 ) ; return result ; }
Read null terminated string from byte buffers and return bytes .
16,231
public String readStringEOF ( ) { byte [ ] result = new byte [ byteBuf . readableBytes ( ) ] ; byteBuf . readBytes ( result ) ; return new String ( result ) ; }
Read rest of packet string from byte buffers .
16,232
public Map < Column , List < Condition > > getConditionsMap ( ) { Map < Column , List < Condition > > result = new LinkedHashMap < > ( conditions . size ( ) , 1 ) ; for ( Condition each : conditions ) { if ( ! result . containsKey ( each . getColumn ( ) ) ) { result . put ( each . getColumn ( ) , new LinkedList < Condition > ( ) ) ; } result . get ( each . getColumn ( ) ) . add ( each ) ; } return result ; }
Get conditions map .
16,233
public AndCondition optimize ( ) { AndCondition result = new AndCondition ( ) ; for ( Condition each : conditions ) { if ( Condition . class . equals ( each . getClass ( ) ) ) { result . getConditions ( ) . add ( each ) ; } } if ( result . getConditions ( ) . isEmpty ( ) ) { result . getConditions ( ) . add ( new NullCondition ( ) ) ; } return result ; }
Optimize and condition .
16,234
@ SuppressWarnings ( "unchecked" ) public void init ( final SQLStatementRuleDefinitionEntity dialectRuleDefinitionEntity , final ExtractorRuleDefinition extractorRuleDefinition ) { for ( SQLStatementRuleEntity each : dialectRuleDefinitionEntity . getRules ( ) ) { SQLStatementRule sqlStatementRule = new SQLStatementRule ( each . getContext ( ) , ( Class < ? extends SQLStatement > ) Class . forName ( each . getSqlStatementClass ( ) ) , ( SQLStatementOptimizer ) newClassInstance ( each . getOptimizerClass ( ) ) ) ; sqlStatementRule . getExtractors ( ) . addAll ( createExtractors ( each . getExtractorRuleRefs ( ) , extractorRuleDefinition ) ) ; rules . put ( getContextClassName ( each . getContext ( ) ) , sqlStatementRule ) ; } }
Initialize SQL statement rule definition .
16,235
public void start ( final int port ) { try { ServerBootstrap bootstrap = new ServerBootstrap ( ) ; bossGroup = createEventLoopGroup ( ) ; if ( bossGroup instanceof EpollEventLoopGroup ) { groupsEpoll ( bootstrap ) ; } else { groupsNio ( bootstrap ) ; } ChannelFuture future = bootstrap . bind ( port ) . sync ( ) ; future . channel ( ) . closeFuture ( ) . sync ( ) ; } finally { workerGroup . shutdownGracefully ( ) ; bossGroup . shutdownGracefully ( ) ; BackendExecutorContext . getInstance ( ) . getExecuteEngine ( ) . close ( ) ; } }
Start Sharding - Proxy .
16,236
public void initListeners ( ) { schemaChangedListener . watch ( ChangedType . UPDATED , ChangedType . DELETED ) ; propertiesChangedListener . watch ( ChangedType . UPDATED ) ; authenticationChangedListener . watch ( ChangedType . UPDATED ) ; }
Initialize all configuration changed listeners .
16,237
public final synchronized void renew ( final DataSourceChangedEvent dataSourceChangedEvent ) { dataSource . close ( ) ; dataSource = new MasterSlaveDataSource ( DataSourceConverter . getDataSourceMap ( dataSourceChangedEvent . getDataSourceConfigurations ( ) ) , dataSource . getMasterSlaveRule ( ) , dataSource . getShardingProperties ( ) . getProps ( ) ) ; }
Renew master - slave data source .
16,238
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public static int compareTo ( final Comparable thisValue , final Comparable otherValue , final OrderDirection orderDirection , final OrderDirection nullOrderDirection ) { if ( null == thisValue && null == otherValue ) { return 0 ; } if ( null == thisValue ) { return orderDirection == nullOrderDirection ? - 1 : 1 ; } if ( null == otherValue ) { return orderDirection == nullOrderDirection ? 1 : - 1 ; } return OrderDirection . ASC == orderDirection ? thisValue . compareTo ( otherValue ) : - thisValue . compareTo ( otherValue ) ; }
Compare two object with order type .
16,239
public static XAProperties createXAProperties ( final DatabaseType databaseType ) { switch ( databaseType ) { case H2 : return new H2XAProperties ( ) ; case MySQL : return new MySQLXAProperties ( ) ; case PostgreSQL : return new PostgreSQLXAProperties ( ) ; case Oracle : return new OracleXAProperties ( ) ; case SQLServer : return new SQLServerXAProperties ( ) ; default : throw new UnsupportedOperationException ( String . format ( "Cannot support database type: `%s`" , databaseType ) ) ; } }
Create XA properties .
16,240
public void add ( final Condition condition ) { if ( andConditions . isEmpty ( ) ) { andConditions . add ( new AndCondition ( ) ) ; } andConditions . get ( 0 ) . getConditions ( ) . add ( condition ) ; }
Add condition .
16,241
public OrCondition optimize ( ) { for ( AndCondition each : andConditions ) { if ( each . getConditions ( ) . get ( 0 ) instanceof NullCondition ) { OrCondition result = new OrCondition ( ) ; result . add ( new NullCondition ( ) ) ; return result ; } } return this ; }
Optimize or condition .
16,242
public List < Condition > findConditions ( final Column column ) { List < Condition > result = new LinkedList < > ( ) ; for ( AndCondition each : andConditions ) { result . addAll ( Collections2 . filter ( each . getConditions ( ) , new Predicate < Condition > ( ) { public boolean apply ( final Condition input ) { return input . getColumn ( ) . equals ( column ) ; } } ) ) ; } return result ; }
Find conditions by column .
16,243
public void resetColumnLabel ( final String schema ) { Map < String , Integer > labelAndIndexMap = new HashMap < > ( 1 , 1 ) ; labelAndIndexMap . put ( schema , 1 ) ; resetLabelAndIndexMap ( labelAndIndexMap ) ; }
Reset column label .
16,244
public Optional < ColumnDefinitionSegment > findColumnDefinition ( final String columnName , final ShardingTableMetaData shardingTableMetaData ) { Optional < ColumnDefinitionSegment > result = findColumnDefinitionFromMetaData ( columnName , shardingTableMetaData ) ; return result . isPresent ( ) ? result : findColumnDefinitionFromCurrentAddClause ( columnName ) ; }
Find column definition .
16,245
public Optional < ColumnDefinitionSegment > findColumnDefinitionFromMetaData ( final String columnName , final ShardingTableMetaData shardingTableMetaData ) { if ( ! shardingTableMetaData . containsTable ( getTables ( ) . getSingleTableName ( ) ) ) { return Optional . absent ( ) ; } for ( ColumnMetaData each : shardingTableMetaData . get ( getTables ( ) . getSingleTableName ( ) ) . getColumns ( ) . values ( ) ) { if ( columnName . equalsIgnoreCase ( each . getColumnName ( ) ) ) { return Optional . of ( new ColumnDefinitionSegment ( columnName , each . getDataType ( ) , each . isPrimaryKey ( ) ) ) ; } } return Optional . absent ( ) ; }
Find column definition from meta data .
16,246
public Collection < SQLSegment > extract ( final SQLAST ast ) { Collection < SQLSegment > result = new LinkedList < > ( ) ; Preconditions . checkState ( ast . getSQLStatementRule ( ) . isPresent ( ) ) ; Map < ParserRuleContext , Integer > parameterMarkerIndexes = getParameterMarkerIndexes ( ast . getParserRuleContext ( ) ) ; for ( SQLSegmentExtractor each : ast . getSQLStatementRule ( ) . get ( ) . getExtractors ( ) ) { if ( each instanceof OptionalSQLSegmentExtractor ) { Optional < ? extends SQLSegment > sqlSegment = ( ( OptionalSQLSegmentExtractor ) each ) . extract ( ast . getParserRuleContext ( ) , parameterMarkerIndexes ) ; if ( sqlSegment . isPresent ( ) ) { result . add ( sqlSegment . get ( ) ) ; } } else if ( each instanceof CollectionSQLSegmentExtractor ) { result . addAll ( ( ( CollectionSQLSegmentExtractor ) each ) . extract ( ast . getParserRuleContext ( ) , parameterMarkerIndexes ) ) ; } } return result ; }
Extract SQL segments .
16,247
public static AbstractSelectParser newInstance ( final DatabaseType dbType , final ShardingRule shardingRule , final LexerEngine lexerEngine , final ShardingTableMetaData shardingTableMetaData ) { switch ( dbType ) { case H2 : case MySQL : return new MySQLSelectParser ( shardingRule , lexerEngine , shardingTableMetaData ) ; case Oracle : return new OracleSelectParser ( shardingRule , lexerEngine , shardingTableMetaData ) ; case SQLServer : return new SQLServerSelectParser ( shardingRule , lexerEngine , shardingTableMetaData ) ; case PostgreSQL : return new PostgreSQLSelectParser ( shardingRule , lexerEngine , shardingTableMetaData ) ; default : throw new UnsupportedOperationException ( String . format ( "Cannot support database [%s]." , dbType ) ) ; } }
Create select parser instance .
16,248
public Collection < String > getSlaveDataSourceNames ( ) { if ( disabledDataSourceNames . isEmpty ( ) ) { return super . getSlaveDataSourceNames ( ) ; } Collection < String > result = new LinkedList < > ( super . getSlaveDataSourceNames ( ) ) ; result . removeAll ( disabledDataSourceNames ) ; return result ; }
Get slave data source names .
16,249
public void updateDisabledDataSourceNames ( final String dataSourceName , final boolean isDisabled ) { if ( isDisabled ) { disabledDataSourceNames . add ( dataSourceName ) ; } else { disabledDataSourceNames . remove ( dataSourceName ) ; } }
Update disabled data source names .
16,250
public Optional < String > getAlias ( final String name ) { if ( containStar ) { return Optional . absent ( ) ; } String rawName = SQLUtil . getExactlyValue ( name ) ; for ( SelectItem each : items ) { if ( SQLUtil . getExactlyExpression ( rawName ) . equalsIgnoreCase ( SQLUtil . getExactlyExpression ( SQLUtil . getExactlyValue ( each . getExpression ( ) ) ) ) ) { return each . getAlias ( ) ; } if ( rawName . equalsIgnoreCase ( each . getAlias ( ) . orNull ( ) ) ) { return Optional . of ( rawName ) ; } } return Optional . absent ( ) ; }
Get alias .
16,251
public List < AggregationSelectItem > getAggregationSelectItems ( ) { List < AggregationSelectItem > result = new LinkedList < > ( ) ; for ( SelectItem each : items ) { if ( each instanceof AggregationSelectItem ) { AggregationSelectItem aggregationSelectItem = ( AggregationSelectItem ) each ; result . add ( aggregationSelectItem ) ; result . addAll ( aggregationSelectItem . getDerivedAggregationSelectItems ( ) ) ; } } return result ; }
Get aggregation select items .
16,252
public Optional < DistinctSelectItem > getDistinctSelectItem ( ) { for ( SelectItem each : items ) { if ( each instanceof DistinctSelectItem ) { return Optional . of ( ( DistinctSelectItem ) each ) ; } } return Optional . absent ( ) ; }
Get distinct select item optional .
16,253
public List < AggregationDistinctSelectItem > getAggregationDistinctSelectItems ( ) { List < AggregationDistinctSelectItem > result = new LinkedList < > ( ) ; for ( SelectItem each : items ) { if ( each instanceof AggregationDistinctSelectItem ) { result . add ( ( AggregationDistinctSelectItem ) each ) ; } } return result ; }
Get aggregation distinct select items .
16,254
public boolean hasUnqualifiedStarSelectItem ( ) { for ( SelectItem each : items ) { if ( each instanceof StarSelectItem && ! ( ( StarSelectItem ) each ) . getOwner ( ) . isPresent ( ) ) { return true ; } } return false ; }
Judge has unqualified star select item .
16,255
public Collection < StarSelectItem > getQualifiedStarSelectItems ( ) { Collection < StarSelectItem > result = new LinkedList < > ( ) ; for ( SelectItem each : items ) { if ( each instanceof StarSelectItem && ( ( StarSelectItem ) each ) . getOwner ( ) . isPresent ( ) ) { result . add ( ( StarSelectItem ) each ) ; } } return result ; }
Get qualified star select items .
16,256
public Optional < StarSelectItem > findStarSelectItem ( final String tableNameOrAlias ) { Optional < Table > table = getTables ( ) . find ( tableNameOrAlias ) ; if ( ! table . isPresent ( ) ) { return Optional . absent ( ) ; } for ( SelectItem each : items ) { if ( ! ( each instanceof StarSelectItem ) ) { continue ; } StarSelectItem starSelectItem = ( StarSelectItem ) each ; if ( starSelectItem . getOwner ( ) . isPresent ( ) && getTables ( ) . find ( starSelectItem . getOwner ( ) . get ( ) ) . equals ( table ) ) { return Optional . of ( starSelectItem ) ; } } return Optional . absent ( ) ; }
Find star select item via table name or alias .
16,257
public void setIndexForItems ( final Map < String , Integer > columnLabelIndexMap ) { setIndexForAggregationItem ( columnLabelIndexMap ) ; setIndexForOrderItem ( columnLabelIndexMap , orderByItems ) ; setIndexForOrderItem ( columnLabelIndexMap , groupByItems ) ; }
Set index for select items .
16,258
public SelectStatement mergeSubqueryStatement ( ) { SelectStatement result = processLimitForSubquery ( ) ; processItems ( result ) ; processOrderByItems ( result ) ; result . setParametersIndex ( getParametersIndex ( ) ) ; return result ; }
Merge subquery statement if contains .
16,259
public static void logSQL ( final String logicSQL , final Collection < String > dataSourceNames ) { log ( "Rule Type: master-slave" ) ; log ( "SQL: {} ::: DataSources: {}" , logicSQL , Joiner . on ( "," ) . join ( dataSourceNames ) ) ; }
Print SQL log for master slave rule .
16,260
public static void logSQL ( final String logicSQL , final boolean showSimple , final SQLStatement sqlStatement , final Collection < RouteUnit > routeUnits ) { log ( "Rule Type: sharding" ) ; log ( "Logic SQL: {}" , logicSQL ) ; log ( "SQLStatement: {}" , sqlStatement ) ; if ( showSimple ) { logSimpleMode ( routeUnits ) ; } else { logNormalMode ( routeUnits ) ; } }
Print SQL log for sharding rule .
16,261
public static DataSource createDataSource ( final File yamlFile ) { YamlRootEncryptRuleConfiguration config = YamlEngine . unmarshal ( yamlFile , YamlRootEncryptRuleConfiguration . class ) ; return EncryptDataSourceFactory . createDataSource ( config . getDataSource ( ) , new EncryptRuleConfigurationYamlSwapper ( ) . swap ( config . getEncryptRule ( ) ) ) ; }
Create encrypt data source .
16,262
public Token getMatchedToken ( final int tokenType ) throws RecognitionException { Token result = parser . getCurrentToken ( ) ; boolean isIdentifierCompatible = false ; if ( identifierTokenIndex == tokenType && identifierTokenIndex > result . getType ( ) ) { isIdentifierCompatible = true ; } if ( result . getType ( ) == tokenType || isIdentifierCompatible ) { if ( Token . EOF != tokenType && isIdentifierCompatible && result instanceof CommonToken ) { ( ( CommonToken ) result ) . setType ( identifierTokenIndex ) ; } parser . getErrorHandler ( ) . reportMatch ( parser ) ; parser . consume ( ) ; } else { result = parser . getErrorHandler ( ) . recoverInline ( parser ) ; if ( parser . getBuildParseTree ( ) && - 1 == result . getTokenIndex ( ) ) { parser . getContext ( ) . addErrorNode ( parser . createErrorNode ( parser . getContext ( ) , result ) ) ; } } return result ; }
Get matched token by token type .
16,263
@ SuppressWarnings ( "unchecked" ) public static < T > T handle ( final Environment environment , final String prefix , final Class < T > targetClass ) { switch ( springBootVersion ) { case 1 : return ( T ) v1 ( environment , prefix ) ; default : return ( T ) v2 ( environment , prefix , targetClass ) ; } }
Spring Boot 1 . x is compatible with Spring Boot 2 . x by Using Java Reflect .
16,264
public void addUnit ( final SQLExpression [ ] columnValues , final Object [ ] columnParameters ) { if ( type == InsertType . VALUES ) { this . units . add ( new ColumnValueOptimizeResult ( columnNames , columnValues , columnParameters ) ) ; } else { this . units . add ( new SetAssignmentOptimizeResult ( columnNames , columnValues , columnParameters ) ) ; } }
Add insert optimize result uint .
16,265
public static MergeEngine newInstance ( final DatabaseType databaseType , final ShardingRule shardingRule , final SQLRouteResult routeResult , final ShardingTableMetaData shardingTableMetaData , final List < QueryResult > queryResults ) throws SQLException { if ( routeResult . getSqlStatement ( ) instanceof SelectStatement ) { return new DQLMergeEngine ( databaseType , routeResult , queryResults ) ; } if ( routeResult . getSqlStatement ( ) instanceof DALStatement ) { return new DALMergeEngine ( shardingRule , queryResults , ( DALStatement ) routeResult . getSqlStatement ( ) , shardingTableMetaData ) ; } throw new UnsupportedOperationException ( String . format ( "Cannot support type '%s'" , routeResult . getSqlStatement ( ) . getType ( ) ) ) ; }
Create merge engine instance .
16,266
public Optional < TableRule > findTableRule ( final String logicTableName ) { for ( TableRule each : tableRules ) { if ( each . getLogicTable ( ) . equalsIgnoreCase ( logicTableName ) ) { return Optional . of ( each ) ; } } return Optional . absent ( ) ; }
Find table rule .
16,267
public Optional < TableRule > findTableRuleByActualTable ( final String actualTableName ) { for ( TableRule each : tableRules ) { if ( each . isExisted ( actualTableName ) ) { return Optional . of ( each ) ; } } return Optional . absent ( ) ; }
Find table rule via actual table name .
16,268
public TableRule getTableRule ( final String logicTableName ) { Optional < TableRule > tableRule = findTableRule ( logicTableName ) ; if ( tableRule . isPresent ( ) ) { return tableRule . get ( ) ; } if ( isBroadcastTable ( logicTableName ) ) { return new TableRule ( shardingDataSourceNames . getDataSourceNames ( ) , logicTableName ) ; } if ( ! Strings . isNullOrEmpty ( shardingDataSourceNames . getDefaultDataSourceName ( ) ) ) { return new TableRule ( shardingDataSourceNames . getDefaultDataSourceName ( ) , logicTableName ) ; } throw new ShardingConfigurationException ( "Cannot find table rule and default data source with logic table: '%s'" , logicTableName ) ; }
Get table rule .
16,269
public ShardingStrategy getDatabaseShardingStrategy ( final TableRule tableRule ) { return null == tableRule . getDatabaseShardingStrategy ( ) ? defaultDatabaseShardingStrategy : tableRule . getDatabaseShardingStrategy ( ) ; }
Get database sharding strategy .
16,270
public ShardingStrategy getTableShardingStrategy ( final TableRule tableRule ) { return null == tableRule . getTableShardingStrategy ( ) ? defaultTableShardingStrategy : tableRule . getTableShardingStrategy ( ) ; }
Get table sharding strategy .
16,271
public boolean isAllBindingTables ( final Collection < String > logicTableNames ) { if ( logicTableNames . isEmpty ( ) ) { return false ; } Optional < BindingTableRule > bindingTableRule = findBindingTableRule ( logicTableNames ) ; if ( ! bindingTableRule . isPresent ( ) ) { return false ; } Collection < String > result = new TreeSet < > ( String . CASE_INSENSITIVE_ORDER ) ; result . addAll ( bindingTableRule . get ( ) . getAllLogicTables ( ) ) ; return ! result . isEmpty ( ) && result . containsAll ( logicTableNames ) ; }
Judge logic tables is all belong to binding encryptors .
16,272
public Optional < BindingTableRule > findBindingTableRule ( final String logicTableName ) { for ( BindingTableRule each : bindingTableRules ) { if ( each . hasLogicTable ( logicTableName ) ) { return Optional . of ( each ) ; } } return Optional . absent ( ) ; }
Find binding table rule via logic table name .
16,273
public boolean isAllBroadcastTables ( final Collection < String > logicTableNames ) { if ( logicTableNames . isEmpty ( ) ) { return false ; } for ( String each : logicTableNames ) { if ( ! isBroadcastTable ( each ) ) { return false ; } } return true ; }
Judge logic tables is all belong to broadcast encryptors .
16,274
public boolean isBroadcastTable ( final String logicTableName ) { for ( String each : broadcastTables ) { if ( each . equalsIgnoreCase ( logicTableName ) ) { return true ; } } return false ; }
Judge logic table is belong to broadcast tables .
16,275
public boolean isAllInDefaultDataSource ( final Collection < String > logicTableNames ) { for ( String each : logicTableNames ) { if ( findTableRule ( each ) . isPresent ( ) || isBroadcastTable ( each ) ) { return false ; } } return ! logicTableNames . isEmpty ( ) ; }
Judge logic tables is all belong to default data source .
16,276
public boolean isShardingColumn ( final String columnName , final String tableName ) { for ( TableRule each : tableRules ) { if ( each . getLogicTable ( ) . equalsIgnoreCase ( tableName ) && isShardingColumn ( each , columnName ) ) { return true ; } } return false ; }
Judge is sharding column or not .
16,277
public Optional < String > findGenerateKeyColumnName ( final String logicTableName ) { for ( TableRule each : tableRules ) { if ( each . getLogicTable ( ) . equalsIgnoreCase ( logicTableName ) && null != each . getGenerateKeyColumn ( ) ) { return Optional . of ( each . getGenerateKeyColumn ( ) ) ; } } return Optional . absent ( ) ; }
Find column name of generated key .
16,278
public String getLogicTableName ( final String logicIndexName ) { for ( TableRule each : tableRules ) { if ( logicIndexName . equals ( each . getLogicIndex ( ) ) ) { return each . getLogicTable ( ) ; } } throw new ShardingConfigurationException ( "Cannot find logic table name with logic index name: '%s'" , logicIndexName ) ; }
Get logic table name base on logic index name .
16,279
public Collection < String > getLogicTableNames ( final String actualTableName ) { Collection < String > result = new LinkedList < > ( ) ; for ( TableRule each : tableRules ) { if ( each . isExisted ( actualTableName ) ) { result . add ( each . getLogicTable ( ) ) ; } } return result ; }
Get logic table names base on actual table name .
16,280
public DataNode getDataNode ( final String logicTableName ) { TableRule tableRule = getTableRule ( logicTableName ) ; return tableRule . getActualDataNodes ( ) . get ( 0 ) ; }
Find data node by logic table name .
16,281
public DataNode getDataNode ( final String dataSourceName , final String logicTableName ) { TableRule tableRule = getTableRule ( logicTableName ) ; for ( DataNode each : tableRule . getActualDataNodes ( ) ) { if ( shardingDataSourceNames . getDataSourceNames ( ) . contains ( each . getDataSourceName ( ) ) && each . getDataSourceName ( ) . equals ( dataSourceName ) ) { return each ; } } throw new ShardingConfigurationException ( "Cannot find actual data node for data source name: '%s' and logic table name: '%s'" , dataSourceName , logicTableName ) ; }
Find data node by data source and logic table .
16,282
public Optional < String > findActualDefaultDataSourceName ( ) { String defaultDataSourceName = shardingDataSourceNames . getDefaultDataSourceName ( ) ; if ( Strings . isNullOrEmpty ( defaultDataSourceName ) ) { return Optional . absent ( ) ; } Optional < String > masterDefaultDataSourceName = findMasterDataSourceName ( defaultDataSourceName ) ; return masterDefaultDataSourceName . isPresent ( ) ? masterDefaultDataSourceName : Optional . of ( defaultDataSourceName ) ; }
Find actual default data source name .
16,283
public Optional < MasterSlaveRule > findMasterSlaveRule ( final String dataSourceName ) { for ( MasterSlaveRule each : masterSlaveRules ) { if ( each . containDataSourceName ( dataSourceName ) ) { return Optional . of ( each ) ; } } return Optional . absent ( ) ; }
Find master slave rule .
16,284
public String getActualDataSourceName ( final String actualTableName ) { Optional < TableRule > tableRule = findTableRuleByActualTable ( actualTableName ) ; if ( tableRule . isPresent ( ) ) { return tableRule . get ( ) . getActualDatasourceNames ( ) . iterator ( ) . next ( ) ; } if ( ! Strings . isNullOrEmpty ( shardingDataSourceNames . getDefaultDataSourceName ( ) ) ) { return shardingDataSourceNames . getDefaultDataSourceName ( ) ; } throw new ShardingException ( "Cannot found actual data source name of '%s' in sharding rule." , actualTableName ) ; }
Get actual data source name .
16,285
public boolean contains ( final String logicTableName ) { return findTableRule ( logicTableName ) . isPresent ( ) || findBindingTableRule ( logicTableName ) . isPresent ( ) || isBroadcastTable ( logicTableName ) ; }
Judge contains table in sharding rule .
16,286
public Collection < String > getShardingLogicTableNames ( final Collection < String > logicTableNames ) { Collection < String > result = new LinkedList < > ( ) ; for ( String each : logicTableNames ) { Optional < TableRule > tableRule = findTableRule ( each ) ; if ( tableRule . isPresent ( ) ) { result . add ( each ) ; } } return result ; }
Get sharding logic table names .
16,287
void doAwaitUntil ( ) throws InterruptedException { lock . lock ( ) ; try { condition . await ( DEFAULT_TIMEOUT_MILLISECONDS , TimeUnit . MILLISECONDS ) ; } finally { lock . unlock ( ) ; } }
Do await until default timeout milliseconds .
16,288
public static RoutingEngine newInstance ( final ShardingRule shardingRule , final ShardingDataSourceMetaData shardingDataSourceMetaData , final SQLStatement sqlStatement , final OptimizeResult optimizeResult ) { Collection < String > tableNames = sqlStatement . getTables ( ) . getTableNames ( ) ; if ( SQLType . TCL == sqlStatement . getType ( ) ) { return new DatabaseBroadcastRoutingEngine ( shardingRule ) ; } if ( SQLType . DDL == sqlStatement . getType ( ) ) { return new TableBroadcastRoutingEngine ( shardingRule , sqlStatement ) ; } if ( SQLType . DAL == sqlStatement . getType ( ) ) { return getDALRoutingEngine ( shardingRule , sqlStatement , tableNames ) ; } if ( SQLType . DCL == sqlStatement . getType ( ) ) { return getDCLRoutingEngine ( shardingRule , sqlStatement , shardingDataSourceMetaData ) ; } if ( shardingRule . isAllInDefaultDataSource ( tableNames ) ) { return new DefaultDatabaseRoutingEngine ( shardingRule , tableNames ) ; } if ( shardingRule . isAllBroadcastTables ( tableNames ) ) { return SQLType . DQL == sqlStatement . getType ( ) ? new UnicastRoutingEngine ( shardingRule , tableNames ) : new DatabaseBroadcastRoutingEngine ( shardingRule ) ; } if ( optimizeResult . getShardingConditions ( ) . isAlwaysFalse ( ) || tableNames . isEmpty ( ) ) { return new UnicastRoutingEngine ( shardingRule , tableNames ) ; } Collection < String > shardingTableNames = shardingRule . getShardingLogicTableNames ( tableNames ) ; if ( 1 == shardingTableNames . size ( ) || shardingRule . isAllBindingTables ( shardingTableNames ) ) { return new StandardRoutingEngine ( sqlStatement , shardingRule , shardingTableNames . iterator ( ) . next ( ) , optimizeResult ) ; } return new ComplexRoutingEngine ( sqlStatement , shardingRule , tableNames , optimizeResult ) ; }
Create new instance of routing engine .
16,289
public DatabaseAccessConfiguration swap ( final DataSource dataSource ) { DataSourcePropertyProvider provider = DataSourcePropertyProviderLoader . getProvider ( dataSource ) ; try { String url = ( String ) findGetterMethod ( dataSource , provider . getURLPropertyName ( ) ) . invoke ( dataSource ) ; String username = ( String ) findGetterMethod ( dataSource , provider . getUsernamePropertyName ( ) ) . invoke ( dataSource ) ; String password = ( String ) findGetterMethod ( dataSource , provider . getPasswordPropertyName ( ) ) . invoke ( dataSource ) ; return new DatabaseAccessConfiguration ( url , username , password ) ; } catch ( final ReflectiveOperationException ex ) { throw new ShardingException ( "Cannot swap data source type: `%s`, please provide an implementation from SPI `%s`" , dataSource . getClass ( ) . getName ( ) , DataSourcePropertyProvider . class . getName ( ) ) ; } }
Swap data source to database access configuration .
16,290
public static AbstractDescribeParser newInstance ( final DatabaseType dbType , final ShardingRule shardingRule , final LexerEngine lexerEngine ) { switch ( dbType ) { case H2 : case MySQL : return new MySQLDescribeParser ( shardingRule , lexerEngine ) ; default : throw new UnsupportedOperationException ( String . format ( "Cannot support database [%s]." , dbType ) ) ; } }
Create describe parser instance .
16,291
public String getRawMasterDataSourceName ( final String dataSourceName ) { for ( MasterSlaveRuleConfiguration each : shardingRuleConfig . getMasterSlaveRuleConfigs ( ) ) { if ( each . getName ( ) . equals ( dataSourceName ) ) { return each . getMasterDataSourceName ( ) ; } } return dataSourceName ; }
Get raw master data source name .
16,292
public String getRandomDataSourceName ( final Collection < String > dataSourceNames ) { Random random = new Random ( ) ; int index = random . nextInt ( dataSourceNames . size ( ) ) ; Iterator < String > iterator = dataSourceNames . iterator ( ) ; for ( int i = 0 ; i < index ; i ++ ) { iterator . next ( ) ; } return iterator . next ( ) ; }
Get random data source name .
16,293
public SQLRouteResult route ( final SQLRouteResult sqlRouteResult ) { for ( MasterSlaveRule each : masterSlaveRules ) { route ( each , sqlRouteResult ) ; } return sqlRouteResult ; }
Route Master slave after sharding .
16,294
public void persistConfiguration ( final String shardingSchemaName , final Map < String , DataSourceConfiguration > dataSourceConfigs , final RuleConfiguration ruleConfig , final Authentication authentication , final Properties props , final boolean isOverwrite ) { persistDataSourceConfiguration ( shardingSchemaName , dataSourceConfigs , isOverwrite ) ; persistRuleConfiguration ( shardingSchemaName , ruleConfig , isOverwrite ) ; persistAuthentication ( authentication , isOverwrite ) ; persistProperties ( props , isOverwrite ) ; }
Persist rule configuration .
16,295
public boolean hasDataSourceConfiguration ( final String shardingSchemaName ) { return ! Strings . isNullOrEmpty ( regCenter . get ( configNode . getDataSourcePath ( shardingSchemaName ) ) ) ; }
Judge whether schema has data source configuration .
16,296
public boolean hasRuleConfiguration ( final String shardingSchemaName ) { return ! Strings . isNullOrEmpty ( regCenter . get ( configNode . getRulePath ( shardingSchemaName ) ) ) ; }
Judge whether schema has rule configuration .
16,297
@ SuppressWarnings ( "unchecked" ) public Map < String , DataSourceConfiguration > loadDataSourceConfigurations ( final String shardingSchemaName ) { Map < String , YamlDataSourceConfiguration > result = ( Map ) YamlEngine . unmarshal ( regCenter . getDirectly ( configNode . getDataSourcePath ( shardingSchemaName ) ) ) ; Preconditions . checkState ( null != result && ! result . isEmpty ( ) , "No available data sources to load for orchestration." ) ; return Maps . transformValues ( result , new Function < YamlDataSourceConfiguration , DataSourceConfiguration > ( ) { public DataSourceConfiguration apply ( final YamlDataSourceConfiguration input ) { return new DataSourceConfigurationYamlSwapper ( ) . swap ( input ) ; } } ) ; }
Load data source configurations .
16,298
public ShardingRuleConfiguration loadShardingRuleConfiguration ( final String shardingSchemaName ) { return new ShardingRuleConfigurationYamlSwapper ( ) . swap ( YamlEngine . unmarshal ( regCenter . getDirectly ( configNode . getRulePath ( shardingSchemaName ) ) , YamlShardingRuleConfiguration . class ) ) ; }
Load sharding rule configuration .
16,299
public MasterSlaveRuleConfiguration loadMasterSlaveRuleConfiguration ( final String shardingSchemaName ) { return new MasterSlaveRuleConfigurationYamlSwapper ( ) . swap ( YamlEngine . unmarshal ( regCenter . getDirectly ( configNode . getRulePath ( shardingSchemaName ) ) , YamlMasterSlaveRuleConfiguration . class ) ) ; }
Load master - slave rule configuration .