RuleGo RuleGo
🏠Home
  • Quick Start
  • Rule Chain
  • Standard Components
  • Extension Components
  • Custom Components
  • Visualization
  • RuleGo-Server
  • AOP
  • Trigger
  • Advanced Topics
  • Performance
  • Standard Components
  • Extension Components
  • Custom Components
  • Components Marketplace
  • Overview
  • Quick Start
  • Routing
  • DSL
  • API
  • Options
  • Components
🔥Editor (opens new window)
  • RuleGo Editor (opens new window)
  • RuleGo Server (opens new window)
  • StreamSQL
  • AI Agent Framework
  • TPCLAW Agent Platform (opens new window)
  • Github (opens new window)
  • Gitee (opens new window)
  • Changelog (opens new window)
  • English
  • 简体中文
🏠Home
  • Quick Start
  • Rule Chain
  • Standard Components
  • Extension Components
  • Custom Components
  • Visualization
  • RuleGo-Server
  • AOP
  • Trigger
  • Advanced Topics
  • Performance
  • Standard Components
  • Extension Components
  • Custom Components
  • Components Marketplace
  • Overview
  • Quick Start
  • Routing
  • DSL
  • API
  • Options
  • Components
🔥Editor (opens new window)
  • RuleGo Editor (opens new window)
  • RuleGo Server (opens new window)
  • StreamSQL
  • AI Agent Framework
  • TPCLAW Agent Platform (opens new window)
  • Github (opens new window)
  • Gitee (opens new window)
  • Changelog (opens new window)
  • English
  • 简体中文

广告采用随机轮播方式显示 ❤️成为赞助商
  • Quick Start

  • Rule Chain

  • Standard Components

  • Extension Components

  • Custom Components

  • Components marketplace

  • Visualization

  • AOP

  • Trigger

  • Advanced Topic

  • Agent Framework

  • RuleGo-Server

  • FAQ

  • Endpoint Module

  • Support

  • StreamSQL

    • Overview
    • Quick Start
    • Core Concepts
    • SQL Reference
    • API Reference
    • RuleGo Integration
    • Schema Validation
    • Advanced Examples
      • Custom Functions
      • Performance Modes
      • 📚 Related Docs
    • functions

    • case-studies

目录

Advanced Examples

# Advanced Examples

This page collects advanced usage such as custom functions and performance modes. For basic onboarding, see Quick Start.

# Custom Functions

StreamSQL supports registering custom functions (UDFs); once registered they can be used in SQL just like built-in functions.

package main

import (
    "fmt"
    "math"
    "time"

    "github.com/rulego/streamsql"
    "github.com/rulego/streamsql/functions"
    "github.com/rulego/streamsql/utils/cast"
)

func main() {
    registerCustomFunctions() // register the UDF first

    ssql := streamsql.New()
    defer ssql.Stop()

    sql := `SELECT
                device,
                square(value)         AS squared_value,
                f_to_c(temperature)   AS celsius,
                circle_area(radius)   AS area
            FROM stream
            WHERE value > 0`
    if err := ssql.Execute(sql); err != nil {
        panic(err)
    }

    ssql.AddSink(func(results []map[string]interface{}) {
        fmt.Printf("Custom function results: %v\n", results)
    })

    testData := []map[string]interface{}{
        {"device": "sensor1", "value": 5.0, "temperature": 68.0, "radius": 3.0},
        {"device": "sensor2", "value": 10.0, "temperature": 86.0, "radius": 2.5},
    }
    for _, data := range testData {
        ssql.Emit(data)
        time.Sleep(200 * time.Millisecond)
    }
    time.Sleep(500 * time.Millisecond)
}

// Register custom functions
func registerCustomFunctions() {
    // Math function: square
    functions.RegisterCustomFunction(
        "square", functions.TypeMath, "Math Function", "Calculate square", 1, 1,
        func(ctx *functions.FunctionContext, args []interface{}) (interface{}, error) {
            val := cast.ToFloat64(args[0])
            return val * val, nil
        },
    )
    // Fahrenheit to Celsius
    functions.RegisterCustomFunction(
        "f_to_c", functions.TypeConversion, "Temperature Conversion", "Fahrenheit to Celsius", 1, 1,
        func(ctx *functions.FunctionContext, args []interface{}) (interface{}, error) {
            fahrenheit := cast.ToFloat64(args[0])
            return (fahrenheit - 32) * 5 / 9, nil
        },
    )
    // Circle area
    functions.RegisterCustomFunction(
        "circle_area", functions.TypeMath, "Geometric Calculation", "Calculate circle area", 1, 1,
        func(ctx *functions.FunctionContext, args []interface{}) (interface{}, error) {
            radius := cast.ToFloat64(args[0])
            if radius < 0 {
                return nil, fmt.Errorf("radius must be positive")
            }
            return math.Pi * radius * radius, nil
        },
    )
}
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

Key points:

  • functions.RegisterCustomFunction(name, type, category, desc, minArgs, maxArgs, fn) registers a UDF; it returns (any, error).
  • Function types: TypeMath / TypeConversion / TypeString / TypeDateTime / TypeAggregation / TypeAnalytical / TypeCustom.
  • After registration, call them in SELECT/WHERE like built-in functions (e.g. square(value), f_to_c(temperature)).
  • Use cast.ToFloat64 and friends for tolerant argument conversion; registration must complete before Execute.

# Performance Modes

StreamSQL provides several preset performance modes; pick one per scenario:

package main

import (
    "fmt"

    "github.com/rulego/streamsql"
)

func main() {
    // High performance mode: large buffers + expand strategy, suited for high throughput
    ssqlHighPerf := streamsql.New(streamsql.WithHighPerformance())
    defer ssqlHighPerf.Stop()

    // Low latency mode: small buffers + fast response, suited for real-time alerts
    ssqlLowLatency := streamsql.New(streamsql.WithLowLatency())
    defer ssqlLowLatency.Stop()

    sql := "SELECT deviceId, AVG(temperature) FROM stream GROUP BY deviceId, TumblingWindow('5s')"
    ssqlHighPerf.Execute(sql)
    ssqlLowLatency.Execute(sql)

    fmt.Println("Different performance modes started")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Mode Suited Scenario Characteristics
Default New() General Balanced buffer and worker configuration
WithHighPerformance() High throughput Large buffers, expand overflow strategy
WithLowLatency() Real-time response Small buffers, block overflow, low latency

For finer control, use streamsql.NewStreamWithCustomPerformance(config) to customize buffer size, worker count, overflow strategy (drop/block/expand), etc.

# 📚 Related Docs

  • Quick Start
  • API Reference — performance config options, RegisterCustomFunction
Edit this page on GitHub (opens new window)
Last Updated: 2026/07/11, 04:40:00
Schema Validation
Aggregate Functions

← Schema Validation Aggregate Functions→

Theme by Vdoing | Copyright © 2023-2026 RuleGo Team | Apache 2.0 License

  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式