-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathprocessor_data.go
More file actions
586 lines (510 loc) · 18.7 KB
/
processor_data.go
File metadata and controls
586 lines (510 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
/*
* Copyright 2025 The RuleGo Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package stream
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/rulego/streamsql/aggregator"
"github.com/rulego/streamsql/condition"
"github.com/rulego/streamsql/expr"
"github.com/rulego/streamsql/functions"
"github.com/rulego/streamsql/logger"
"github.com/rulego/streamsql/types"
)
// DataProcessor data processor responsible for processing data streams
type DataProcessor struct {
stream *Stream
}
// NewDataProcessor creates a data processor
func NewDataProcessor(stream *Stream) *DataProcessor {
return &DataProcessor{stream: stream}
}
// Process main processing loop
func (dp *DataProcessor) Process() {
// Initialize aggregator for window mode
if dp.stream.config.NeedWindow {
dp.initializeAggregator()
dp.startWindowProcessing()
}
// Create a timer to avoid creating multiple temporary timers causing resource leaks
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop() // Ensure timer is stopped when function exits
// Main processing loop
for {
// Safely access dataChan using read lock
dp.stream.dataChanMux.RLock()
currentDataChan := dp.stream.dataChan
dp.stream.dataChanMux.RUnlock()
select {
case data, ok := <-currentDataChan:
if !ok {
// Channel is closed
return
}
// Apply filter conditions
if dp.stream.filter == nil || dp.stream.filter.Evaluate(data) {
if dp.stream.config.NeedWindow {
// Window mode, add data to window
dp.stream.Window.Add(data)
} else {
// Non-window mode, process data directly and output
dp.processDirectData(data)
}
}
case <-dp.stream.done:
// Received close signal
return
case <-ticker.C:
// Timer triggered, do nothing, just prevent CPU spinning
}
}
}
// initializeAggregator initializes the aggregator
func (dp *DataProcessor) initializeAggregator() {
// Convert to new AggregationField format
aggregationFields := convertToAggregationFields(dp.stream.config.SelectFields, dp.stream.config.FieldAlias)
// Check if we have post-aggregation expressions
if len(dp.stream.config.PostAggExpressions) > 0 {
// Use enhanced aggregator for post-aggregation support
enhancedAgg := aggregator.NewEnhancedGroupAggregator(dp.stream.config.GroupFields, aggregationFields)
// Add post-aggregation expressions
for _, postExpr := range dp.stream.config.PostAggExpressions {
err := enhancedAgg.AddPostAggregationExpression(
postExpr.OutputField,
postExpr.OriginalExpr,
convertToAggregationFieldInfos(postExpr.RequiredFields),
)
if err != nil {
// Log error but continue
fmt.Printf("Error adding post-aggregation expression %s: %v\n", postExpr.OriginalExpr, err)
}
}
dp.stream.aggregator = enhancedAgg
} else {
// Use regular aggregator
dp.stream.aggregator = aggregator.NewGroupAggregator(dp.stream.config.GroupFields, aggregationFields)
}
// Register expression calculators
for field, fieldExpr := range dp.stream.config.FieldExpressions {
dp.registerExpressionCalculator(field, fieldExpr)
}
}
// convertToAggregationFieldInfos converts types.AggregationFieldInfo to aggregator.AggregationFieldInfo
func convertToAggregationFieldInfos(fields []types.AggregationFieldInfo) []aggregator.AggregationFieldInfo {
result := make([]aggregator.AggregationFieldInfo, len(fields))
for i, field := range fields {
result[i] = aggregator.AggregationFieldInfo{
FuncName: field.FuncName,
InputField: field.InputField,
Placeholder: field.Placeholder,
AggType: field.AggType,
FullCall: field.FullCall, // 保持FullCall字段
}
}
return result
}
// registerExpressionCalculator registers expression calculator
func (dp *DataProcessor) registerExpressionCalculator(field string, fieldExpr types.FieldExpression) {
// Create local variables to avoid closure issues
currentField := field
currentFieldExpr := fieldExpr
// Register expression calculator
dp.stream.aggregator.RegisterExpression(
currentField,
currentFieldExpr.Expression,
currentFieldExpr.Fields,
func(data interface{}) (interface{}, error) {
// Ensure data is map[string]interface{} type
if dataMap, ok := data.(map[string]interface{}); ok {
return dp.evaluateExpressionForAggregation(currentFieldExpr, dataMap)
}
return nil, fmt.Errorf("unsupported data type: %T, expected map[string]interface{}", data)
},
)
}
// evaluateExpressionForAggregation evaluates expression for aggregation
// Parameters:
// - fieldExpr: field expression
// - data: data to process, must be map[string]interface{} type
func (dp *DataProcessor) evaluateExpressionForAggregation(fieldExpr types.FieldExpression, data map[string]interface{}) (interface{}, error) {
// Directly use the passed map data
dataMap := data
// Check if expression contains nested fields, if so use custom expression engine directly
hasNestedFields := strings.Contains(fieldExpr.Expression, ".")
if hasNestedFields {
return dp.evaluateNestedFieldExpression(fieldExpr.Expression, dataMap)
}
// Check if it's a CASE expression
trimmedExpr := strings.TrimSpace(fieldExpr.Expression)
upperExpr := strings.ToUpper(trimmedExpr)
if strings.HasPrefix(upperExpr, SQLKeywordCase) {
return dp.evaluateCaseExpression(fieldExpr.Expression, dataMap)
}
// Use bridge to evaluate expression, supporting string concatenation and IS NULL syntax
bridge := functions.GetExprBridge()
// Preprocess IS NULL and LIKE syntax in expression
processedExpr := fieldExpr.Expression
if bridge.ContainsIsNullOperator(processedExpr) {
if processed, err := bridge.PreprocessIsNullExpression(processedExpr); err == nil {
processedExpr = processed
}
}
if bridge.ContainsLikeOperator(processedExpr) {
if processed, err := bridge.PreprocessLikeExpression(processedExpr); err == nil {
processedExpr = processed
}
}
result, err := bridge.EvaluateExpression(processedExpr, dataMap)
if err != nil {
// If bridge fails, fallback to original expression engine
return dp.fallbackExpressionEvaluation(fieldExpr.Expression, dataMap)
}
return result, nil
}
// convertToDataMap converts data to map format
// convertToDataMap method has been removed, please use github.com/rulego/streamsql/utils/converter.ToDataMap function instead
// evaluateNestedFieldExpression evaluates nested field expression
func (dp *DataProcessor) evaluateNestedFieldExpression(expression string, dataMap map[string]interface{}) (interface{}, error) {
// Directly use custom expression engine to handle nested fields, supporting NULL values
// Preprocess backtick identifiers
exprToUse := expression
bridge := functions.GetExprBridge()
if bridge.ContainsBacktickIdentifiers(exprToUse) {
if processed, err := bridge.PreprocessBacktickIdentifiers(exprToUse); err == nil {
exprToUse = processed
}
}
expr, parseErr := expr.NewExpression(exprToUse)
if parseErr != nil {
return nil, fmt.Errorf("expression parse failed: %w", parseErr)
}
// Use EvaluateValueWithNull to get actual values (including strings)
result, isNull, err := expr.EvaluateValueWithNull(dataMap)
if err != nil {
return nil, fmt.Errorf("expression evaluation failed: %w", err)
}
if isNull {
return nil, nil // Return nil to represent NULL value
}
return result, nil
}
// evaluateCaseExpression evaluates CASE expression
func (dp *DataProcessor) evaluateCaseExpression(expression string, dataMap map[string]interface{}) (interface{}, error) {
// CASE expression uses NULL-supporting evaluation method
// Preprocess backtick identifiers
exprToUse := expression
bridge := functions.GetExprBridge()
if bridge.ContainsBacktickIdentifiers(exprToUse) {
if processed, err := bridge.PreprocessBacktickIdentifiers(exprToUse); err == nil {
exprToUse = processed
}
}
expr, parseErr := expr.NewExpression(exprToUse)
if parseErr != nil {
return nil, fmt.Errorf("CASE expression parse failed: %w", parseErr)
}
// Use EvaluateValueWithNull to get actual value (including strings)
result, isNull, err := expr.EvaluateValueWithNull(dataMap)
if err != nil {
return nil, fmt.Errorf("CASE expression evaluation failed: %w", err)
}
if isNull {
return nil, nil // Return nil to indicate NULL value
}
return result, nil
}
// fallbackExpressionEvaluation fallback expression evaluation
func (dp *DataProcessor) fallbackExpressionEvaluation(expression string, dataMap map[string]interface{}) (interface{}, error) {
// Preprocess backtick identifiers
exprToUse := expression
bridge := functions.GetExprBridge()
if bridge.ContainsBacktickIdentifiers(exprToUse) {
if processed, err := bridge.PreprocessBacktickIdentifiers(exprToUse); err == nil {
exprToUse = processed
}
}
// First try using bridge processor (supports string concatenation etc.)
if result, err := bridge.EvaluateExpression(exprToUse, dataMap); err == nil {
return result, nil
}
// If bridge fails, fallback to custom expression engine
expr, parseErr := expr.NewExpression(exprToUse)
if parseErr != nil {
return nil, fmt.Errorf("expression parse failed: %w", parseErr)
}
// Use EvaluateValueWithNull to get actual value (including strings)
result, isNull, err := expr.EvaluateValueWithNull(dataMap)
if err != nil {
return nil, fmt.Errorf("expression evaluation failed: %w", err)
}
if isNull {
return nil, nil // Return nil to indicate NULL value
}
return result, nil
}
// startWindowProcessing starts window processing
func (dp *DataProcessor) startWindowProcessing() {
// Start window processing goroutine
dp.stream.Window.Start()
// Process window mode
go func() {
defer func() {
if r := recover(); r != nil {
logger.Error("Window processing goroutine panic recovered: %v", r)
}
}()
outputChan := dp.stream.Window.OutputChan()
for {
select {
case batch, ok := <-outputChan:
if !ok {
// Channel closed, exit
return
}
dp.processWindowBatch(batch)
case <-dp.stream.done:
// Stream stopped, exit
return
}
}
}()
}
// processWindowBatch processes window batch data
func (dp *DataProcessor) processWindowBatch(batch []types.Row) {
// Process window batch data
for _, item := range batch {
if err := dp.stream.aggregator.Put(WindowStartField, item.Slot.WindowStart()); err != nil {
logger.Error("failed to put window start: %v", err)
}
if err := dp.stream.aggregator.Put(WindowEndField, item.Slot.WindowEnd()); err != nil {
logger.Error("failed to put window end: %v", err)
}
if err := dp.stream.aggregator.Add(item.Data); err != nil {
logger.Error("aggregate error: %v", err)
}
}
// Get and send aggregation results
if results, err := dp.stream.aggregator.GetResults(); err == nil {
dp.processAggregationResults(results)
dp.stream.aggregator.Reset()
}
}
// processAggregationResults processes aggregation results
func (dp *DataProcessor) processAggregationResults(results []map[string]interface{}) {
var finalResults []map[string]interface{}
// Process DISTINCT
if dp.stream.config.Distinct {
finalResults = dp.applyDistinct(results)
} else {
finalResults = results
}
// Apply HAVING filter condition
if dp.stream.config.Having != "" {
finalResults = dp.applyHavingFilter(finalResults)
}
// Apply LIMIT restriction
if dp.stream.config.Limit > 0 && len(finalResults) > dp.stream.config.Limit {
finalResults = finalResults[:dp.stream.config.Limit]
}
// Send results to result channel and Sink functions
if len(finalResults) > 0 {
// Non-blocking send to result channel
dp.stream.sendResultNonBlocking(finalResults)
// Asynchronously call all sinks
dp.stream.callSinksAsync(finalResults)
}
}
// applyDistinct applies DISTINCT deduplication
func (dp *DataProcessor) applyDistinct(results []map[string]interface{}) []map[string]interface{} {
seenResults := make(map[string]bool)
var finalResults []map[string]interface{}
for _, result := range results {
serializedResult, jsonErr := json.Marshal(result)
if jsonErr != nil {
logger.Error("Error serializing result for distinct check: %v", jsonErr)
finalResults = append(finalResults, result)
continue
}
if !seenResults[string(serializedResult)] {
finalResults = append(finalResults, result)
seenResults[string(serializedResult)] = true
}
}
return finalResults
}
// applyHavingFilter applies HAVING filter
func (dp *DataProcessor) applyHavingFilter(results []map[string]interface{}) []map[string]interface{} {
// Check if HAVING condition contains CASE expression
hasCaseExpression := strings.Contains(strings.ToUpper(dp.stream.config.Having), SQLKeywordCase)
var filteredResults []map[string]interface{}
if hasCaseExpression {
filteredResults = dp.applyHavingWithCaseExpression(results)
} else {
filteredResults = dp.applyHavingWithCondition(results)
}
return filteredResults
}
// applyHavingWithCaseExpression applies HAVING filter using CASE expression
func (dp *DataProcessor) applyHavingWithCaseExpression(results []map[string]interface{}) []map[string]interface{} {
// HAVING condition contains CASE expression, use our expression parser
// Preprocess backtick identifiers
exprToUse := dp.stream.config.Having
bridge := functions.GetExprBridge()
if bridge.ContainsBacktickIdentifiers(exprToUse) {
if processed, err := bridge.PreprocessBacktickIdentifiers(exprToUse); err == nil {
exprToUse = processed
}
}
expression, err := expr.NewExpression(exprToUse)
if err != nil {
logger.Error("having filter error (CASE expression): %v", err)
return results
}
var filteredResults []map[string]interface{}
// Apply HAVING filter using CASE expression calculator
for _, result := range results {
// Use EvaluateValueWithNull method to support NULL value processing
havingResult, isNull, err := expression.EvaluateValueWithNull(result)
if err != nil {
logger.Error("having filter evaluation error: %v", err)
continue
}
// If result is NULL, condition is not satisfied (SQL standard behavior)
if isNull {
continue
}
// For numeric results, greater than 0 is considered true (satisfies HAVING condition)
// For string results, non-empty is considered true
if havingResult != nil {
if numResult, ok := havingResult.(float64); ok {
if numResult > 0 {
filteredResults = append(filteredResults, result)
}
} else if strResult, ok := havingResult.(string); ok {
if strResult != "" {
filteredResults = append(filteredResults, result)
}
} else {
// Other types, non-nil is considered true
filteredResults = append(filteredResults, result)
}
}
}
return filteredResults
}
// applyHavingWithCondition applies HAVING filter using condition expression
func (dp *DataProcessor) applyHavingWithCondition(results []map[string]interface{}) []map[string]interface{} {
// HAVING condition doesn't contain CASE expression, use original expr-lang processing
// Preprocess LIKE syntax in HAVING condition, convert to expr-lang understandable form
processedHaving := dp.stream.config.Having
bridge := functions.GetExprBridge()
if bridge.ContainsLikeOperator(dp.stream.config.Having) {
if processed, err := bridge.PreprocessLikeExpression(dp.stream.config.Having); err == nil {
processedHaving = processed
}
}
// Preprocess IS NULL syntax in HAVING condition
if bridge.ContainsIsNullOperator(processedHaving) {
if processed, err := bridge.PreprocessIsNullExpression(processedHaving); err == nil {
processedHaving = processed
}
}
// Create HAVING condition
havingFilter, err := condition.NewExprCondition(processedHaving)
if err != nil {
logger.Error("having filter error: %v", err)
return results
}
var filteredResults []map[string]interface{}
// Apply HAVING filter
for _, result := range results {
if havingFilter.Evaluate(result) {
filteredResults = append(filteredResults, result)
}
}
return filteredResults
}
// processDirectData directly processes non-window data
// Parameters:
// - data: data to be processed, must be map[string]interface{} type
func (dp *DataProcessor) processDirectData(data map[string]interface{}) {
// Directly use the passed map data
dataMap := data
// Create result map, pre-allocate appropriate capacity
estimatedSize := len(dp.stream.config.FieldExpressions) + len(dp.stream.config.SimpleFields)
if estimatedSize < 8 {
estimatedSize = 8 // Minimum capacity
}
result := make(map[string]interface{}, estimatedSize)
// Process expression fields (using pre-compiled information)
for fieldName := range dp.stream.config.FieldExpressions {
dp.stream.processExpressionField(fieldName, dataMap, result)
}
// Use pre-compiled field information to process SimpleFields
if len(dp.stream.config.SimpleFields) > 0 {
for _, fieldSpec := range dp.stream.config.SimpleFields {
dp.stream.processSimpleField(fieldSpec, dataMap, dataMap, result)
}
} else if len(dp.stream.config.FieldExpressions) == 0 {
// If no fields specified and no expression fields, keep all fields
for k, v := range dataMap {
result[k] = v
}
}
// Check if any field contains unnest function result and expand to multiple rows
results := dp.expandUnnestResults(result, dataMap)
// Non-blocking send result to resultChan
dp.stream.sendResultNonBlocking(results)
// Asynchronously call all sinks, avoid blocking
dp.stream.callSinksAsync(results)
}
// expandUnnestResults 检查结果是否包含 unnest 函数输出并展开为多行
func (dp *DataProcessor) expandUnnestResults(result map[string]interface{}, originalData map[string]interface{}) []map[string]interface{} {
// Early return if no unnest function is used in the query
// This optimization significantly improves performance for queries without unnest functions
if !dp.stream.hasUnnestFunction {
return []map[string]interface{}{result}
}
if len(result) == 0 {
return []map[string]interface{}{result}
}
for fieldName, fieldValue := range result {
if functions.IsUnnestResult(fieldValue) {
expandedRows := functions.ProcessUnnestResultWithFieldName(fieldValue, fieldName)
// 如果unnest结果为空,返回空结果数组
if len(expandedRows) == 0 {
return []map[string]interface{}{}
}
results := make([]map[string]interface{}, len(expandedRows))
for i, unnestRow := range expandedRows {
newRow := make(map[string]interface{}, len(result)+len(unnestRow))
for k, v := range result {
if k != fieldName {
newRow[k] = v
}
}
for k, v := range unnestRow {
newRow[k] = v
}
results[i] = newRow
}
return results
}
}
return []map[string]interface{}{result}
}