parser

package
v0.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 19, 2026 License: MIT Imports: 15 Imported by: 0

README

SQL 解析适配器

概述

SQL 解析适配器是一个基于 TiDB Parser 的 SQL 解析和执行层,它能够:

  1. 解析各种 SQL 语句(SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER)
  2. 将 SQL 转换为结构化的中间表示
  3. 将解析后的语句转换为数据源操作
  4. 支持复杂的查询条件、JOIN、排序等

架构

SQL 字符串
    ↓
TiDB Parser (AST)
    ↓
SQLAdapter (适配器层)
    ↓
SQLStatement (中间表示)
    ↓
QueryBuilder (构建器)
    ↓
DataSource 操作

核心组件

1. SQLAdapter (adapter.go)

负责将 TiDB AST 转换为自定义的 SQLStatement 结构体。

adapter := parser.NewSQLAdapter()
result, err := adapter.Parse("SELECT * FROM users WHERE age > 25")

支持的功能

  • SELECT 语句:列选择、WHERE 条件、ORDER BY、LIMIT、JOIN、GROUP BY、HAVING
  • INSERT 语句:单行/多行插入
  • UPDATE 语句:单表更新、条件更新
  • DELETE 语句:条件删除
  • DDL 语句:CREATE TABLE、DROP TABLE、ALTER TABLE
2. QueryBuilder (builder.go)

负责将解析后的 SQLStatement 转换为数据源操作。

builder := parser.NewQueryBuilder(dataSource)
result, err := builder.BuildAndExecute(ctx, "SELECT * FROM users")
3. 数据结构 (types.go)

定义了 SQL 解析相关的所有数据结构。

使用示例

基本用法
package main

import (
    "context"
    "mysql-proxy/mysql/parser"
    "mysql-proxy/mysql/resource"
)

func main() {
    // 1. 创建数据源
    config := &resource.DataSourceConfig{
        Type: resource.DataSourceTypeMemory,
        Name: "test",
    }
    dataSource, _ := resource.CreateDataSource(config)
    dataSource.Connect(context.Background())

    // 2. 创建查询构建器
    builder := parser.NewQueryBuilder(dataSource)

    // 3. 执行 SQL
    result, err := builder.BuildAndExecute(
        context.Background(),
        "SELECT * FROM users WHERE age > 25",
    )

    // 4. 处理结果
    if err == nil {
        fmt.Printf("Found %d rows\n", len(result.Rows))
    }
}
直接使用适配器
// 创建适配器
adapter := parser.NewSQLAdapter()

// 解析 SQL
result, err := adapter.Parse("SELECT id, name FROM users WHERE age > 25")
if err != nil {
    log.Fatal(err)
}

// 访问解析后的数据
if result.Statement.Type == parser.SQLTypeSelect {
    selectStmt := result.Statement.Select
    fmt.Printf("Table: %s\n", selectStmt.From)
    fmt.Printf("Columns: %v\n", selectStmt.Columns)
    if selectStmt.Where != nil {
        fmt.Printf("Where: %v\n", selectStmt.Where)
    }
}
批量解析
// 解析多条 SQL 语句
results, err := adapter.ParseMulti(`
    CREATE TABLE users (id INT, name VARCHAR(255));
    INSERT INTO users (name) VALUES ('Alice');
    SELECT * FROM users;
`)

for _, result := range results {
    if result.Success {
        fmt.Printf("Statement type: %s\n", result.Statement.Type)
    }
}

SQL 语句支持

SELECT

支持以下特性:

  • 列选择(SELECT id, name FROM users
  • 通配符(SELECT * FROM users
  • WHERE 条件(WHERE age > 25 AND status = 'active'
  • ORDER BY(ORDER BY created_at DESC
  • LIMIT/OFFSET(LIMIT 10 OFFSET 20
  • JOIN(JOIN orders ON users.id = orders.user_id
  • GROUP BY(GROUP BY category
  • HAVING(HAVING COUNT(*) > 5
  • 聚合函数(COUNT, SUM, AVG, MAX, MIN
  • DISTINCT(SELECT DISTINCT name FROM users
INSERT

支持以下特性:

  • 单行插入(INSERT INTO users (name) VALUES ('Alice')
  • 批量插入(INSERT INTO users (name) VALUES ('Alice'), ('Bob')
  • 指定列(INSERT INTO users (name, age) VALUES ('Alice', 25)
UPDATE

支持以下特性:

  • 单字段更新(UPDATE users SET age = 26
  • 多字段更新(UPDATE users SET age = 26, status = 'active'
  • 条件更新(WHERE id = 1
  • ORDER BY(ORDER BY created_at DESC
  • LIMIT(LIMIT 10
DELETE

支持以下特性:

  • 条件删除(DELETE FROM users WHERE age < 18
  • ORDER BY(ORDER BY created_at DESC
  • LIMIT(LIMIT 10
DDL

支持以下特性:

  • CREATE TABLE(CREATE TABLE users (id INT, name VARCHAR(255))
  • DROP TABLE(DROP TABLE users
  • DROP TABLE IF EXISTS(DROP TABLE IF EXISTS users
  • ALTER TABLE(基础支持)

测试

运行单元测试
go test -v ./mysql/parser/...
运行集成示例
go run example_sql_adapter.go
运行性能测试
go test -bench=. -benchmem ./mysql/parser/...

数据结构

SQLStatement

所有 SQL 语句的通用结构。

type SQLStatement struct {
    Type      SQLType
    RawSQL    string
    Select    *SelectStatement
    Insert    *InsertStatement
    Update    *UpdateStatement
    Delete    *DeleteStatement
    Create    *CreateStatement
    Drop      *DropStatement
    Alter     *AlterStatement
}
SelectStatement
type SelectStatement struct {
    Distinct   bool
    Columns    []SelectColumn
    From       string
    Joins      []JoinInfo
    Where      *Expression
    GroupBy    []string
    Having     *Expression
    OrderBy    []OrderByItem
    Limit      *int64
    Offset     *int64
}
Expression

表达式树结构,支持复杂的条件表达式。

type Expression struct {
    Type      ExprType
    Column    string
    Value     interface{}
    Operator  string
    Left      *Expression
    Right     *Expression
    Args      []Expression
    Function  string
}

性能特性

  • 基于 TiDB Parser,性能优异
  • 零内存分配的解析过程(大部分)
  • 支持批量解析
  • 解析结果可序列化为 JSON

扩展性

添加新的 SQL 类型支持
  1. types.go 中定义新的 SQLType
  2. adapter.go 中实现对应的转换函数
  3. builder.go 中实现执行逻辑
  4. 添加测试用例
添加新的表达式类型

convertExpression 函数中添加新的 case 分支:

case *ast.YourExprType:
    expr.Type = "YOUR_TYPE"
    // 处理逻辑

限制

当前版本的限制:

  1. 子查询支持有限(仅能解析,不能完全执行)
  2. 窗口函数支持有限(仅能解析)
  3. CTE (WITH 子句) 支持有限(仅能解析)
  4. 存储过程不支持
  5. 复杂的 ALTER TABLE 操作支持有限

后续计划

  • 完善子查询执行
  • 添加窗口函数支持
  • 实现 CTE 支持
  • 优化表达式求值
  • 添加查询优化器
  • 支持更多数据类型

参考资料

Documentation

Index

Constants

View Source
const (
	SortAsc  = "ASC"
	SortDesc = "DESC"
)

排序方向

View Source
const (
	SetNames   = "SET NAMES"
	SetCharset = "SET CHARSET"
)

Variables

View Source
var SupportedWindowFunctions = map[string]bool{

	"ROW_NUMBER":   true,
	"RANK":         true,
	"DENSE_RANK":   true,
	"PERCENT_RANK": true,
	"CUME_DIST":    true,
	"NTILE":        true,

	"LAG":         true,
	"LEAD":        true,
	"FIRST_VALUE": true,
	"LAST_VALUE":  true,
	"NTH_VALUE":   true,

	"COUNT":  true,
	"SUM":    true,
	"AVG":    true,
	"MIN":    true,
	"MAX":    true,
	"STDDEV": true,
	"VAR":    true,
}

支持的窗口函数

Functions

func ExtractColumnNames

func ExtractColumnNames(stmt ast.StmtNode) []string

ExtractColumnNames 提取列名

func ExtractDatabaseNames

func ExtractDatabaseNames(stmt ast.StmtNode) []string

ExtractDatabaseNames 提取数据库名

func ExtractTableNames

func ExtractTableNames(stmt ast.StmtNode) []string

ExtractTableNames 提取表名

func GetStmtType

func GetStmtType(stmt ast.StmtNode) string

GetStmtType 获取 SQL 语句类型

func IsReadOperation

func IsReadOperation(stmt ast.StmtNode) bool

IsReadOperation 判断是否为读操作

func IsRecommendIndexStatement

func IsRecommendIndexStatement(sql string) bool

IsRecommendIndexStatement 检查是否为 RECOMMEND INDEX 语句

func IsTransactionOperation

func IsTransactionOperation(stmt ast.StmtNode) bool

IsTransactionOperation 判断是否为事务操作

func IsWindowFunction

func IsWindowFunction(funcName string) bool

IsWindowFunction 检查是否为窗口函数

func IsWriteOperation

func IsWriteOperation(stmt ast.StmtNode) bool

IsWriteOperation 判断是否为写操作

func ParseVariableName

func ParseVariableName(name string) (string, error)

ParseVariableName 解析变量名 支持格式: @var_name, @@var_name(系统变量), :var_name(绑定变量)

func ValidateFunction

func ValidateFunction(fn *FunctionStmt) error

ValidateFunction 验证函数

func ValidateProcedure

func ValidateProcedure(proc *ProcedureStmt) error

ValidateProcedure 验证存储过程

func ValidateWindowExpression

func ValidateWindowExpression(we *WindowExpression) error

ValidateWindowExpression 验证窗口函数表达式

Types

type AlterAction

type AlterAction struct {
	Type    string      `json:"type"` // ADD, DROP, MODIFY, CHANGE, etc.
	Column  *ColumnInfo `json:"column,omitempty"`
	OldName string      `json:"old_name,omitempty"`
	NewName string      `json:"new_name,omitempty"`
}

AlterAction ALTER 操作

type AlterStatement

type AlterStatement struct {
	Type    string        `json:"type"` // TABLE, etc.
	Name    string        `json:"name"`
	Actions []AlterAction `json:"actions,omitempty"`
}

AlterStatement ALTER 语句

type BlockStmt

type BlockStmt struct {
	Declarations []Declaration
	Statements   []Statement
}

BlockStmt 语句块

func NewBlock

func NewBlock(decls []Declaration, stmts []Statement) *BlockStmt

NewBlock 创建语句块

type BoundType

type BoundType int

BoundType 边界类型

const (
	BoundUnboundedPreceding BoundType = iota // UNBOUNDED PRECEDING
	BoundPreceding                           // n PRECEDING
	BoundCurrentRow                          // CURRENT ROW
	BoundFollowing                           // n FOLLOWING
	BoundUnboundedFollowing                  // UNBOUNDED FOLLOWING
)

type CTEContext

type CTEContext struct {
	// CTE缓存
	CTEResults map[string][]map[string]interface{}

	// CTE是否已物化
	CTEMaterialized map[string]bool
}

CTEContext CTE执行上下文

func NewCTEContext

func NewCTEContext() *CTEContext

NewCTEContext 创建CTE执行上下文

func (*CTEContext) ClearAll

func (ctx *CTEContext) ClearAll()

ClearAll 清除所有CTE缓存

func (*CTEContext) ClearCTE

func (ctx *CTEContext) ClearCTE(cteName string)

ClearCTE 清除指定CTE的缓存

func (*CTEContext) GetCTEResult

func (ctx *CTEContext) GetCTEResult(cteName string) ([]map[string]interface{}, bool)

GetCTEResult 获取CTE结果

func (*CTEContext) IsCTEMaterialized

func (ctx *CTEContext) IsCTEMaterialized(cteName string) bool

IsCTEMaterialized 检查CTE是否已物化

func (*CTEContext) SetCTEResult

func (ctx *CTEContext) SetCTEResult(cteName string, result []map[string]interface{})

SetCTEResult 设置CTE结果

type CTEInfo

type CTEInfo struct {
	Name      string           // CTE名称
	Alias     string           // CTE别名
	Subquery  *SelectStatement // CTE子查询
	Columns   []string         // 列别名(可选)
	Recursive bool             // 是否为递归CTE
}

CTEInfo CTE(公用表表达式)信息

type CTEOptimizer

type CTEOptimizer struct {
	// 优化配置
	InlineThreshold int  // 内联阈值(行数)
	CacheEnabled    bool // 是否启用缓存
}

CTEOptimizer CTE优化器

func NewCTEOptimizer

func NewCTEOptimizer() *CTEOptimizer

NewCTEOptimizer 创建CTE优化器

func (*CTEOptimizer) Optimize

func (opt *CTEOptimizer) Optimize(withClause *WithClause, selectStmt *SelectStatement) (*SelectStatement, error)

Optimize 优化CTE 策略: 1. CTE只引用一次: 内联(Inline) 2. CTE多次引用: 物化(Materialize)并缓存 3. 递归CTE: 强制物化

type CallStmt

type CallStmt struct {
	ProcedureName string
	Args          []Expression // 参数
}

CallStmt CALL语句

func NewCall

func NewCall(procedureName string, args ...Expression) *CallStmt

NewCall 创建CALL语句

type CaseStmt

type CaseStmt struct {
	Expression Expression // 可选的表达式
	Cases      []CaseWhen
	Else       *BlockStmt
}

CaseStmt CASE语句

func NewCase

func NewCase(expr Expression) *CaseStmt

NewCase 创建CASE语句

func (*CaseStmt) AddElse

func (cs *CaseStmt) AddElse(elseBlock *BlockStmt)

AddElse 添加ELSE

func (*CaseStmt) AddWhen

func (cs *CaseStmt) AddWhen(condition Expression, thenBlock *BlockStmt)

AddWhen 添加WHEN

type CaseWhen

type CaseWhen struct {
	Condition Expression
	Then      *BlockStmt
}

CaseWhen CASE WHEN

type CheckOptionValidator

type CheckOptionValidator struct {
	// contains filtered or unexported fields
}

CheckOptionValidator validates INSERT/UPDATE operations against WITH CHECK OPTION

func NewCheckOptionValidator

func NewCheckOptionValidator(viewInfo *domain.ViewInfo) *CheckOptionValidator

NewCheckOptionValidator creates a new CHECK OPTION validator

func (*CheckOptionValidator) ValidateInsert

func (cv *CheckOptionValidator) ValidateInsert(row domain.Row) error

ValidateInsert validates an INSERT operation against view's CHECK OPTION

func (*CheckOptionValidator) ValidateUpdate

func (cv *CheckOptionValidator) ValidateUpdate(row domain.Row, updates domain.Row) error

ValidateUpdate validates an UPDATE operation against view's CHECK OPTION

type ColumnInfo

type ColumnInfo struct {
	Name       string          `json:"name"`
	Type       string          `json:"type"`
	Nullable   bool            `json:"nullable"`
	Primary    bool            `json:"primary"`
	Default    interface{}     `json:"default,omitempty"`
	Unique     bool            `json:"unique,omitempty"`
	AutoInc    bool            `json:"auto_increment,omitempty"`
	ForeignKey *ForeignKeyInfo `json:"foreign_key,omitempty"`
	Comment    string          `json:"comment,omitempty"`

	// Generated Columns 支持
	IsGenerated      bool     `json:"is_generated,omitempty"`      // 是否为生成列
	GeneratedType    string   `json:"generated_type,omitempty"`    // "STORED" (第一阶段) 或 "VIRTUAL" (第二阶段)
	GeneratedExpr    string   `json:"generated_expr,omitempty"`    // 表达式字符串
	GeneratedDepends []string `json:"generated_depends,omitempty"` // 依赖的列名

	// Vector Columns 支持
	VectorDim  int    `json:"vector_dim,omitempty"`  // 向量维度
	VectorType string `json:"vector_type,omitempty"` // 向量类型(如 "float32")
}

ColumnInfo 列信息(用于 DDL)

func (ColumnInfo) IsVectorType

func (c ColumnInfo) IsVectorType() bool

IsVectorType 检查是否为向量类型

type ColumnVisitor

type ColumnVisitor struct {
	// contains filtered or unexported fields
}

ColumnVisitor 列名访问器

func NewColumnVisitor

func NewColumnVisitor() *ColumnVisitor

NewColumnVisitor 创建列名访问器

func (*ColumnVisitor) Enter

func (v *ColumnVisitor) Enter(n ast.Node) (ast.Node, bool)

Enter 进入节点

func (*ColumnVisitor) GetColumns

func (v *ColumnVisitor) GetColumns() []string

GetColumns 获取列名列表

func (*ColumnVisitor) Leave

func (v *ColumnVisitor) Leave(n ast.Node) (ast.Node, bool)

Leave 离开节点

type CreateIndexStatement

type CreateIndexStatement struct {
	IndexName string   `json:"index_name"`
	TableName string   `json:"table_name"`
	Columns   []string `json:"columns"`    // Support composite index (multi-column)
	IndexType string   `json:"index_type"` // BTREE, HASH, FULLTEXT, VECTOR
	Unique    bool     `json:"unique"`
	IfExists  bool     `json:"if_exists"`

	// Vector Index 配置
	IsVectorIndex   bool                   `json:"is_vector_index,omitempty"`
	VectorIndexType string                 `json:"vector_index_type,omitempty"` // hnsw, ivf_flat, flat
	VectorMetric    string                 `json:"vector_metric,omitempty"`     // cosine, l2, inner_product
	VectorDim       int                    `json:"vector_dim,omitempty"`
	VectorParams    map[string]interface{} `json:"vector_params,omitempty"`
}

CreateIndexStatement CREATE INDEX 语句

type CreateStatement

type CreateStatement struct {
	Type       string                 `json:"type"` // TABLE, DATABASE, INDEX, etc.
	Name       string                 `json:"name"`
	Columns    []ColumnInfo           `json:"columns,omitempty"`
	Options    map[string]interface{} `json:"options,omitempty"`
	Persistent bool                   `json:"persistent,omitempty"` // PERSISTENT=1 for hybrid storage
}

CreateStatement CREATE 语句

type CreateUserStatement

type CreateUserStatement struct {
	Username    string `json:"username"`
	Host        string `json:"host,omitempty"`     // Default is '%'
	Password    string `json:"password,omitempty"` // IDENTIFIED BY
	IfNotExists bool   `json:"if_not_exists"`
}

CreateUserStatement CREATE USER 语句

type CreateViewStatement

type CreateViewStatement struct {
	OrReplace   bool             `json:"or_replace"`
	Algorithm   string           `json:"algorithm,omitempty"` // UNDEFINED, MERGE, TEMPTABLE
	Definer     string           `json:"definer,omitempty"`   // 'user'@'host'
	Security    string           `json:"security,omitempty"`  // DEFINER, INVOKER
	Name        string           `json:"name"`
	ColumnList  []string         `json:"column_list,omitempty"`
	Select      *SelectStatement `json:"select"`
	CheckOption string           `json:"check_option,omitempty"` // NONE, CASCADED, LOCAL
}

CreateViewStatement CREATE VIEW 语句

type DDLHandler

type DDLHandler struct{}

DDLHandler DDL 语句处理器(CREATE/DROP/ALTER)

func NewDDLHandler

func NewDDLHandler() *DDLHandler

NewDDLHandler 创建 DDL 处理器

func (*DDLHandler) Handle

func (h *DDLHandler) Handle(stmt ast.StmtNode) (interface{}, error)

Handle 处理 DDL 语句

type DDLResult

type DDLResult struct {
	Type      string
	Tables    []string
	Databases []string
}

DDL 结果

type DMLHandler

type DMLHandler struct{}

DMLHandler DML 语句处理器(INSERT/UPDATE/DELETE)

func NewDMLHandler

func NewDMLHandler() *DMLHandler

NewDMLHandler 创建 DML 处理器

func (*DMLHandler) Handle

func (h *DMLHandler) Handle(stmt ast.StmtNode) (interface{}, error)

Handle 处理 DML 语句

type DMLResult

type DMLResult struct {
	Type     string
	Tables   []string
	Columns  []string
	Affected int64
}

DML 结果

type Declaration

type Declaration struct {
	Name     string
	DataType string
	Initial  interface{} // 初始值(可选)
}

Declaration 变量声明

type DeclareStmt

type DeclareStmt struct {
	Variables []Declaration
}

DeclareStmt DECLARE语句

func NewDeclare

func NewDeclare(decls ...Declaration) *DeclareStmt

NewDeclare 创建DECLARE语句

type DefaultHandler

type DefaultHandler struct{}

DefaultHandler 默认处理器

func NewDefaultHandler

func NewDefaultHandler() *DefaultHandler

NewDefaultHandler 创建默认处理器

func (*DefaultHandler) Handle

func (h *DefaultHandler) Handle(stmt ast.StmtNode) (interface{}, error)

Handle 处理未知类型语句

type DefaultResult

type DefaultResult struct {
	Type string
	Stmt ast.StmtNode
}

默认结果

type DeleteStatement

type DeleteStatement struct {
	Table   string        `json:"table"`
	Where   *Expression   `json:"where,omitempty"`
	OrderBy []OrderByItem `json:"order_by,omitempty"`
	Limit   *int64        `json:"limit,omitempty"`
}

DeleteStatement DELETE 语句

type DescribeStatement

type DescribeStatement struct {
	Table  string `json:"table"`
	Column string `json:"column,omitempty"`
}

DescribeStatement DESCRIBE 语句

type DropIndexStatement

type DropIndexStatement struct {
	IndexName string `json:"index_name"`
	TableName string `json:"table_name"`
	IfExists  bool   `json:"if_exists"`
}

DropIndexStatement DROP INDEX 语句

type DropStatement

type DropStatement struct {
	Type     string `json:"type"` // TABLE, DATABASE, INDEX, etc.
	Name     string `json:"name"`
	IfExists bool   `json:"if_exists"`
}

DropStatement DROP 语句

type DropUserStatement

type DropUserStatement struct {
	Username string `json:"username"`
	Host     string `json:"host,omitempty"` // Default is '%'
	IfExists bool   `json:"if_exists"`
}

DropUserStatement DROP USER 语句

type DropViewStatement

type DropViewStatement struct {
	Views    []string `json:"views"`     // 视图名称列表
	IfExists bool     `json:"if_exists"` // IF EXISTS
	Restrict bool     `json:"restrict"`  // RESTRICT (TiDB 不支持,保留用于兼容性)
	Cascade  bool     `json:"cascade"`   // CASCADE (TiDB 不支持,保留用于兼容性)
}

DropViewStatement DROP VIEW 语句

type ElseIfStmt

type ElseIfStmt struct {
	Condition Expression
	Then      *BlockStmt
}

ElseIfStmt ELSE IF语句

type ExplainStatement

type ExplainStatement struct {
	Query     *SelectStatement `json:"query,omitempty"`      // The query to explain
	TargetSQL string           `json:"target_sql,omitempty"` // Raw SQL string
	Format    string           `json:"format,omitempty"`     // Format type (e.g., "TREE", "JSON")
	Analyze   bool             `json:"analyze,omitempty"`    // EXPLAIN ANALYZE
}

ExplainStatement EXPLAIN 语句

type ExprConverter

type ExprConverter struct{}

ExprConverter AST 表达式转换器 用于将 TiDB AST 表达式转换为内部表达式格式

func NewExprConverter

func NewExprConverter() *ExprConverter

NewExprConverter 创建表达式转换器

func (*ExprConverter) Convert

func (c *ExprConverter) Convert(astExpr ast.ExprNode) (string, error)

Convert 转换 AST 表达式到内部表达式 第二阶段基础版本:保留字符串表达式,扩展复杂表达式的解析能力

func (*ExprConverter) ConvertBinaryOp

func (c *ExprConverter) ConvertBinaryOp(op *ast.BinaryOperationExpr) (string, error)

ConvertBinaryOp 转换二元运算表达式

func (*ExprConverter) ConvertColumnRef

func (c *ExprConverter) ConvertColumnRef(colRef *ast.ColumnNameExpr) (string, error)

ConvertColumnRef 转换列引用表达式

func (*ExprConverter) ConvertFunctionCall

func (c *ExprConverter) ConvertFunctionCall(funcCall *ast.FuncCallExpr) (string, error)

ConvertFunctionCall 转换函数调用表达式

func (*ExprConverter) ExtractDependencies

func (c *ExprConverter) ExtractDependencies(expr ast.ExprNode) []string

ExtractDependencies 从表达式中提取依赖的列名 这个方法已经在 adapter.go 中实现,这里提供统一的接口

func (*ExprConverter) ValidateExpression

func (c *ExprConverter) ValidateExpression(expr ast.ExprNode) error

ValidateExpression 验证表达式语法

type ExprType

type ExprType string

ExprType 表达式类型

const (
	ExprTypeColumn   ExprType = "COLUMN"
	ExprTypeValue    ExprType = "VALUE"
	ExprTypeOperator ExprType = "OPERATOR"
	ExprTypeFunction ExprType = "FUNCTION"
	ExprTypeList     ExprType = "LIST"
)

type Expression

type Expression struct {
	Type     ExprType     `json:"type"`
	Column   string       `json:"column,omitempty"`
	Value    interface{}  `json:"value,omitempty"`
	Operator string       `json:"operator,omitempty"`
	Left     *Expression  `json:"left,omitempty"`
	Right    *Expression  `json:"right,omitempty"`
	Args     []Expression `json:"args,omitempty"`
	Function string       `json:"function,omitempty"`
}

Expression 表达式

type ForeignKeyInfo

type ForeignKeyInfo struct {
	RefTable  string `json:"ref_table"`
	RefColumn string `json:"ref_column"`
	OnDelete  string `json:"on_delete,omitempty"`
	OnUpdate  string `json:"on_update,omitempty"`
}

ForeignKeyInfo 外键信息

type FrameBound

type FrameBound struct {
	Type  BoundType
	Value Expression // 帧偏移值(可为空)
}

FrameBound 帧边界

type FrameMode

type FrameMode int

FrameMode 帧模式

const (
	FrameModeRows   FrameMode = iota // ROWS
	FrameModeRange                   // RANGE
	FrameModeGroups                  // GROUPS(暂不支持)
)

type FunctionInfo

type FunctionInfo struct {
	Name       string
	Params     []ProcedureParam
	ReturnType string
	Body       *BlockStmt
}

FunctionInfo 函数信息

type FunctionStmt

type FunctionStmt struct {
	Name       string
	Params     []ProcedureParam
	ReturnType string
	Body       *BlockStmt
}

FunctionStmt 函数语句

func NewFunction

func NewFunction(name string, returnType string, body *BlockStmt, params ...ProcedureParam) *FunctionStmt

NewFunction 创建函数

type GrantStatement

type GrantStatement struct {
	Privileges      []string `json:"privileges"`
	On              string   `json:"on"` // e.g., "db.*", "db.table"
	To              string   `json:"to"` // e.g., "'user'@'host'"
	WithGrantOption bool     `json:"with_grant_option"`
}

GrantStatement GRANT 语句

type HandlerChain

type HandlerChain struct {
	// contains filtered or unexported fields
}

HandlerChain 处理器链

func NewHandlerChain

func NewHandlerChain() *HandlerChain

NewHandlerChain 创建新的处理器链

func (*HandlerChain) Handle

func (c *HandlerChain) Handle(stmt ast.StmtNode) (interface{}, error)

Handle 处理 SQL 语句

func (*HandlerChain) RegisterHandler

func (c *HandlerChain) RegisterHandler(stmtType string, handler StmtHandler)

RegisterHandler 注册处理器

func (*HandlerChain) SetDefaultHandler

func (c *HandlerChain) SetDefaultHandler(handler StmtHandler)

SetDefaultHandler 设置默认处理器

type HintsParser

type HintsParser struct {
	// contains filtered or unexported fields
}

HintsParser hints 解析器

func NewHintsParser

func NewHintsParser() *HintsParser

NewHintsParser 创建 hints 解析器

func (*HintsParser) ExtractHintsFromSQL

func (hp *HintsParser) ExtractHintsFromSQL(sql string) (*ParsedHints, string, error)

ExtractHintsFromSQL 从 SQL 中提取 hints

func (*HintsParser) NewParsedHints

func (hp *HintsParser) NewParsedHints() *ParsedHints

NewParsedHints 创建空的 ParsedHints

func (*HintsParser) ParseFromComment

func (hp *HintsParser) ParseFromComment(comment string) (*ParsedHints, error)

ParseFromComment 从注释中解析 hints

type IfStmt

type IfStmt struct {
	Condition Expression
	Then      *BlockStmt
	ElseIfs   []*ElseIfStmt
	Else      *BlockStmt
}

IfStmt IF语句

func NewIf

func NewIf(condition Expression, thenBlock *BlockStmt) *IfStmt

NewIf 创建IF语句

func (*IfStmt) AddElse

func (is *IfStmt) AddElse(elseBlock *BlockStmt)

AddElse 添加ELSE

func (*IfStmt) AddElseIf

func (is *IfStmt) AddElseIf(condition Expression, thenBlock *BlockStmt)

AddElseIf 添加ELSE IF

type InsertStatement

type InsertStatement struct {
	Table       string           `json:"table"`
	Columns     []string         `json:"columns,omitempty"`
	Values      [][]interface{}  `json:"values"`
	OnDuplicate *UpdateStatement `json:"on_duplicate,omitempty"`
}

InsertStatement INSERT 语句

type JoinInfo

type JoinInfo struct {
	Type      JoinType    `json:"type"`
	Table     string      `json:"table"`
	Alias     string      `json:"alias,omitempty"`
	Condition *Expression `json:"condition,omitempty"`
}

JoinInfo JOIN 信息

type JoinType

type JoinType string

JoinType JOIN 类型

const (
	JoinTypeInner JoinType = "INNER"
	JoinTypeLeft  JoinType = "LEFT"
	JoinTypeRight JoinType = "RIGHT"
	JoinTypeFull  JoinType = "FULL"
	JoinTypeCross JoinType = "CROSS"
)

type OrderByItem

type OrderByItem struct {
	Column    string `json:"column"`
	Direction string `json:"direction"`           // ASC, DESC
	Collation string `json:"collation,omitempty"` // COLLATE clause (optional)
}

OrderByItem 排序项

type OrderItem

type OrderItem struct {
	Expr      Expression
	Direction string
	Collation string // COLLATE clause (optional)
}

OrderItem 排序项

type ParamType

type ParamType int

ParamType 参数类型

const (
	ParamTypeIn    ParamType = iota // IN参数
	ParamTypeOut                    // OUT参数
	ParamTypeInOut                  // INOUT参数
)

func ToProcedureParamType

func ToProcedureParamType(mode string) (ParamType, error)

ToProcedureParamType 转换参数类型字符串为ParamType

func (ParamType) ToString

func (pt ParamType) ToString() string

ToString 返回参数类型的字符串表示

type ParseResult

type ParseResult struct {
	Statement *SQLStatement `json:"statement"`
	Success   bool          `json:"success"`
	Error     string        `json:"error,omitempty"`
}

ParseResult 解析结果

type ParsedHints

type ParsedHints struct {
	// JOIN hints
	HashJoinTables     []string
	MergeJoinTables    []string
	INLJoinTables      []string
	INLHashJoinTables  []string
	INLMergeJoinTables []string
	NoHashJoinTables   []string
	NoMergeJoinTables  []string
	NoIndexJoinTables  []string
	LeadingOrder       []string
	StraightJoin       bool

	// INDEX hints
	UseIndex     map[string][]string
	ForceIndex   map[string][]string
	IgnoreIndex  map[string][]string
	OrderIndex   map[string]string
	NoOrderIndex map[string]string

	// AGG hints
	HashAgg      bool
	StreamAgg    bool
	MPP1PhaseAgg bool
	MPP2PhaseAgg bool

	// Subquery hints
	SemiJoinRewrite bool
	NoDecorrelate   bool
	UseTOJA         bool

	// Global hints
	QBName                string
	MaxExecutionTime      time.Duration
	MemoryQuota           int64
	ReadConsistentReplica bool
	ResourceGroup         string
}

ParsedHints 解析后的 hints

func (*ParsedHints) String

func (h *ParsedHints) String() string

String 返回 hints 的字符串表示

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

Parser SQL 解析器,封装 TiDB parser

func NewParser

func NewParser() *Parser

NewParser 创建新的 SQL 解析器

func (*Parser) ParseCreateDatabaseStmt

func (p *Parser) ParseCreateDatabaseStmt(sql string) (*ast.CreateDatabaseStmt, error)

ParseCreateDatabaseStmt 解析 CREATE DATABASE 语句

func (*Parser) ParseCreateTableStmt

func (p *Parser) ParseCreateTableStmt(sql string) (*ast.CreateTableStmt, error)

ParseCreateTableStmt 解析 CREATE TABLE 语句

func (*Parser) ParseCreateUserStmt

func (p *Parser) ParseCreateUserStmt(sql string) (*ast.CreateUserStmt, error)

ParseCreateUserStmt 解析 CREATE USER 语句

func (*Parser) ParseDeleteStmt

func (p *Parser) ParseDeleteStmt(sql string) (*ast.DeleteStmt, error)

ParseDeleteStmt 解析 DELETE 语句

func (*Parser) ParseDropDatabaseStmt

func (p *Parser) ParseDropDatabaseStmt(sql string) (*ast.DropDatabaseStmt, error)

ParseDropDatabaseStmt 解析 DROP DATABASE 语句

func (*Parser) ParseDropTableStmt

func (p *Parser) ParseDropTableStmt(sql string) (*ast.DropTableStmt, error)

ParseDropTableStmt 解析 DROP TABLE 语句

func (*Parser) ParseDropUserStmt

func (p *Parser) ParseDropUserStmt(sql string) (*ast.DropUserStmt, error)

ParseDropUserStmt 解析 DROP USER 语句

func (*Parser) ParseGrantStmt

func (p *Parser) ParseGrantStmt(sql string) (*ast.GrantStmt, error)

ParseGrantStmt 解析 GRANT 语句

func (*Parser) ParseInsertStmt

func (p *Parser) ParseInsertStmt(sql string) (*ast.InsertStmt, error)

ParseInsertStmt 解析 INSERT 语句

func (*Parser) ParseOneStmt

func (p *Parser) ParseOneStmt(sql string) (ast.StmtNode, error)

ParseOneStmt 解析单条 SQL 语句

func (*Parser) ParseOneStmtText

func (p *Parser) ParseOneStmtText(sql string) (ast.StmtNode, error)

ParseOneStmtText 解析 SQL 文本(去除注释和空白)

func (*Parser) ParseRevokeStmt

func (p *Parser) ParseRevokeStmt(sql string) (*ast.RevokeStmt, error)

ParseRevokeStmt 解析 REVOKE 语句

func (*Parser) ParseSQL

func (p *Parser) ParseSQL(sql string) ([]ast.StmtNode, error)

ParseSQL 解析 SQL 语句,返回 AST 节点列表

func (*Parser) ParseSelectStmt

func (p *Parser) ParseSelectStmt(sql string) (*ast.SelectStmt, error)

ParseSelectStmt 解析 SELECT 语句

func (*Parser) ParseSetStmt

func (p *Parser) ParseSetStmt(sql string) (*ast.SetStmt, error)

ParseSetStmt 解析 SET 语句

func (*Parser) ParseShowStmt

func (p *Parser) ParseShowStmt(sql string) (*ast.ShowStmt, error)

ParseShowStmt 解析 SHOW 语句

func (*Parser) ParseUpdateStmt

func (p *Parser) ParseUpdateStmt(sql string) (*ast.UpdateStmt, error)

ParseUpdateStmt 解析 UPDATE 语句

func (*Parser) ParseUseStmt

func (p *Parser) ParseUseStmt(sql string) (*ast.UseStmt, error)

ParseUseStmt 解析 USE 语句

type ParserError

type ParserError struct {
	SQL     string `json:"sql"`
	Message string `json:"message"`
	Pos     int    `json:"pos"`
}

ParserError 解析错误

func (*ParserError) Error

func (e *ParserError) Error() string

type ProcedureInfo

type ProcedureInfo struct {
	Name    string
	Params  []ProcedureParam
	Body    *BlockStmt
	Returns []ColumnInfo // 返回值(用于函数)
}

ProcedureInfo 存储过程信息

type ProcedureParam

type ProcedureParam struct {
	Name      string
	ParamType ParamType
	DataType  string
}

ProcedureParam 参数定义

func NewParam

func NewParam(name string, paramType ParamType, dataType string) ProcedureParam

NewParam 创建参数

type ProcedureStmt

type ProcedureStmt struct {
	Name   string
	Params []ProcedureParam
	Body   *BlockStmt
}

ProcedureStmt 存储过程语句

func NewProcedure

func NewProcedure(name string, body *BlockStmt, params ...ProcedureParam) *ProcedureStmt

NewProcedure 创建存储过程

type QueryBuilder

type QueryBuilder struct {
	// contains filtered or unexported fields
}

QueryBuilder 查询构建器

func NewQueryBuilder

func NewQueryBuilder(dataSource domain.DataSource) *QueryBuilder

NewQueryBuilder 创建查询构建器

func (*QueryBuilder) BuildAndExecute

func (b *QueryBuilder) BuildAndExecute(ctx context.Context, sql string) (*domain.QueryResult, error)

BuildAndExecute 构建并执行 SQL 语句

func (*QueryBuilder) ExecuteStatement

func (b *QueryBuilder) ExecuteStatement(ctx context.Context, stmt *SQLStatement) (*domain.QueryResult, error)

ExecuteStatement 执行解析后的语句

type QueryHandler

type QueryHandler struct{}

QueryHandler SELECT 查询处理器

func NewQueryHandler

func NewQueryHandler() *QueryHandler

NewQueryHandler 创建查询处理器

func (*QueryHandler) Handle

func (h *QueryHandler) Handle(stmt ast.StmtNode) (interface{}, error)

Handle 处理 SELECT 语句

type QueryResult

type QueryResult struct {
	Type    string
	Tables  []string
	Columns []string
	Stmt    *ast.SelectStmt
}

查询结果

type RecommendIndexConfig

type RecommendIndexConfig struct {
	MaxNumIndexes   int
	MaxIndexColumns int
	MaxNumQuery     int
	Timeout         int // 秒
}

RecommendIndexConfig 索引推荐配置

func DefaultRecommendIndexConfig

func DefaultRecommendIndexConfig() *RecommendIndexConfig

DefaultRecommendIndexConfig 默认配置

func (*RecommendIndexConfig) ApplyConfig

func (cfg *RecommendIndexConfig) ApplyConfig(optionName, optionValue string) error

ApplyConfig 应用配置更改

func (*RecommendIndexConfig) GetConfigString

func (cfg *RecommendIndexConfig) GetConfigString() string

GetConfigString 获取配置字符串

type RecommendIndexParser

type RecommendIndexParser struct{}

RecommendIndexParser RECOMMEND INDEX 语句解析器

func NewRecommendIndexParser

func NewRecommendIndexParser() *RecommendIndexParser

NewRecommendIndexParser 创建 RECOMMEND INDEX 解析器

func (*RecommendIndexParser) Parse

Parse 解析 RECOMMEND INDEX 语句

type RecommendIndexStatement

type RecommendIndexStatement struct {
	Action string // "RUN", "SHOW", "SET"

	// RUN 参数
	Query    string // SQL 查询字符串
	ForQuery bool   // 是否指定了 FOR 子句

	// SET 参数
	OptionName  string // 选项名称
	OptionValue string // 选项值
}

RecommendIndexStatement RECOMMEND INDEX 语句

type ReturnStmt

type ReturnStmt struct {
	Expression Expression // 返回值(可选)
}

ReturnStmt RETURN语句

func NewReturn

func NewReturn(expr Expression) *ReturnStmt

NewReturn 创建RETURN语句

type RevokeStatement

type RevokeStatement struct {
	Privileges []string `json:"privileges"`
	On         string   `json:"on"`   // e.g., "db.*", "db.table"
	From       string   `json:"from"` // e.g., "'user'@'host'"
}

RevokeStatement REVOKE 语句

type Row

type Row map[string]interface{}

Row 行数据的类型别名,与 resource.Row 保持一致 为了避免循环导入,这里使用 map[string]interface{} 表示行数据

type SQLAdapter

type SQLAdapter struct {
	// contains filtered or unexported fields
}

SQLAdapter SQL 解析适配器

func NewSQLAdapter

func NewSQLAdapter() *SQLAdapter

NewSQLAdapter 创建 SQL 适配器

func (*SQLAdapter) Parse

func (a *SQLAdapter) Parse(sql string) (*ParseResult, error)

Parse 解析 SQL 语句

func (*SQLAdapter) ParseMulti

func (a *SQLAdapter) ParseMulti(sql string) ([]*ParseResult, error)

ParseMulti 解析多条 SQL 语句

type SQLInfo

type SQLInfo struct {
	Tables       []string      // 涉及的表名
	Columns      []string      // 涉及的列名
	Databases    []string      // 涉及的数据库名
	WhereExpr    ast.ExprNode  // WHERE 条件表达式
	LimitExpr    *ast.Limit    // LIMIT 表达式
	OrderByItems []*ast.ByItem // ORDER BY 子句
	GroupByItems []*ast.ByItem // GROUP BY 子句
	Having       ast.ExprNode  // HAVING 子句
	IsSelect     bool
	IsInsert     bool
	IsUpdate     bool
	IsDelete     bool
	IsDDL        bool
}

SQLInfo 提取的 SQL 信息

func ExtractSQLInfo

func ExtractSQLInfo(stmt ast.StmtNode) *SQLInfo

ExtractSQLInfo 提取 SQL 信息

type SQLStatement

type SQLStatement struct {
	Type       SQLType              `json:"type"`
	RawSQL     string               `json:"raw_sql"`
	Select     *SelectStatement     `json:"select,omitempty"`
	Insert     *InsertStatement     `json:"insert,omitempty"`
	Update     *UpdateStatement     `json:"update,omitempty"`
	Delete     *DeleteStatement     `json:"delete,omitempty"`
	Create     *CreateStatement     `json:"create,omitempty"`
	CreateView *CreateViewStatement `json:"create_view,omitempty"`
	Drop       *DropStatement       `json:"drop,omitempty"`
	DropView   *DropViewStatement   `json:"drop_view,omitempty"`
	Alter      *AlterStatement      `json:"alter,omitempty"`
	// Note: TiDB does not support ALTER VIEW, so AlterView field is deprecated
	// AlterView    *AlterViewStatement    `json:"alter_view,omitempty"`
	CreateIndex *CreateIndexStatement `json:"create_index,omitempty"`
	DropIndex   *DropIndexStatement   `json:"drop_index,omitempty"`
	Show        *ShowStatement        `json:"show,omitempty"`
	Describe    *DescribeStatement    `json:"describe,omitempty"`
	Explain     *ExplainStatement     `json:"explain,omitempty"`
	Begin       *TransactionStatement `json:"begin,omitempty"`
	Commit      *TransactionStatement `json:"commit,omitempty"`
	Rollback    *TransactionStatement `json:"rollback,omitempty"`
	Use         *UseStatement         `json:"use,omitempty"`
	CreateUser  *CreateUserStatement  `json:"create_user,omitempty"`
	DropUser    *DropUserStatement    `json:"drop_user,omitempty"`
	Grant       *GrantStatement       `json:"grant,omitempty"`
	Revoke      *RevokeStatement      `json:"revoke,omitempty"`
	SetPassword *SetPasswordStatement `json:"set_password,omitempty"`
}

SQLStatement SQL 语句

type SQLType

type SQLType string

SQLType SQL 语句类型

const (
	SQLTypeSelect     SQLType = "SELECT"
	SQLTypeInsert     SQLType = "INSERT"
	SQLTypeUpdate     SQLType = "UPDATE"
	SQLTypeDelete     SQLType = "DELETE"
	SQLTypeCreate     SQLType = "CREATE"
	SQLTypeCreateView SQLType = "CREATE VIEW"
	SQLTypeDrop       SQLType = "DROP"
	SQLTypeDropView   SQLType = "DROP VIEW"
	SQLTypeAlter      SQLType = "ALTER"
	// Note: TiDB does not support ALTER VIEW, so SQLTypeAlterView is deprecated
	// SQLTypeAlterView   SQLType = "ALTER VIEW"
	SQLTypeTruncate   SQLType = "TRUNCATE"
	SQLTypeShow       SQLType = "SHOW"
	SQLTypeDescribe   SQLType = "DESCRIBE"
	SQLTypeExplain    SQLType = "EXPLAIN"
	SQLTypeBegin      SQLType = "BEGIN"
	SQLTypeCommit     SQLType = "COMMIT"
	SQLTypeRollback   SQLType = "ROLLBACK"
	SQLTypeUse        SQLType = "USE"
	SQLTypeCreateUser SQLType = "CREATE USER"
	SQLTypeDropUser   SQLType = "DROP USER"
	SQLTypeGrant      SQLType = "GRANT"
	SQLTypeRevoke     SQLType = "REVOKE"
	SQLTypeSetPasswd  SQLType = "SET PASSWORD"
	SQLTypeUnknown    SQLType = "UNKNOWN"
)

type SQLVisitor

type SQLVisitor struct {
	// contains filtered or unexported fields
}

SQLVisitor AST 访问器,用于提取 SQL 信息

func NewSQLVisitor

func NewSQLVisitor() *SQLVisitor

NewSQLVisitor 创建新的 SQL 访问器

func (*SQLVisitor) Enter

func (v *SQLVisitor) Enter(n ast.Node) (ast.Node, bool)

Enter 进入节点

func (*SQLVisitor) GetInfo

func (v *SQLVisitor) GetInfo() *SQLInfo

GetInfo 获取提取的 SQL 信息

func (*SQLVisitor) Leave

func (v *SQLVisitor) Leave(n ast.Node) (ast.Node, bool)

Leave 离开节点

type SelectColumn

type SelectColumn struct {
	Name       string      `json:"name"`
	Alias      string      `json:"alias,omitempty"`
	Table      string      `json:"table,omitempty"`
	Expr       *Expression `json:"expr,omitempty"`
	IsWildcard bool        `json:"is_wildcard"` // 是否是 *
}

SelectColumn SELECT 列

type SelectStatement

type SelectStatement struct {
	Distinct bool           `json:"distinct"`
	Columns  []SelectColumn `json:"columns"`
	From     string         `json:"from"`
	Joins    []JoinInfo     `json:"joins,omitempty"`
	Where    *Expression    `json:"where,omitempty"`
	GroupBy  []string       `json:"group_by,omitempty"`
	Having   *Expression    `json:"having,omitempty"`
	OrderBy  []OrderByItem  `json:"order_by,omitempty"`
	Limit    *int64         `json:"limit,omitempty"`
	Offset   *int64         `json:"offset,omitempty"`
	Hints    string         `json:"hints,omitempty"` // Raw hints string from SQL comment
}

SelectStatement SELECT 语句

type SetHandler

type SetHandler struct{}

SetHandler SET 语句处理器

func NewSetHandler

func NewSetHandler() *SetHandler

NewSetHandler 创建 SET 处理器

func (*SetHandler) Handle

func (h *SetHandler) Handle(stmt ast.StmtNode) (interface{}, error)

Handle 处理 SET 语句

type SetPasswordStatement

type SetPasswordStatement struct {
	Username    string `json:"username"`
	Host        string `json:"host,omitempty"` // Default is '%'
	NewPassword string `json:"new_password"`   // PASSWORD('password')
}

SetPasswordStatement SET PASSWORD 语句

type SetResult

type SetResult struct {
	Type  string
	Vars  map[string]interface{}
	Count int
}

SET 结果

type SetStmt

type SetStmt struct {
	Variable string
	Value    Expression
}

SetStmt SET语句

func NewSet

func NewSet(variable string, value Expression) *SetStmt

NewSet 创建SET语句

type ShowHandler

type ShowHandler struct{}

ShowHandler SHOW 语句处理器

func NewShowHandler

func NewShowHandler() *ShowHandler

NewShowHandler 创建 SHOW 处理器

func (*ShowHandler) Handle

func (h *ShowHandler) Handle(stmt ast.StmtNode) (interface{}, error)

Handle 处理 SHOW 语句

type ShowResult

type ShowResult struct {
	Type   string
	ShowTp string
	Tables []string
}

SHOW 结果

type ShowStatement

type ShowStatement struct {
	Type  string `json:"type"` // TABLES, DATABASES, COLUMNS, PROCESSLIST, etc.
	Table string `json:"table,omitempty"`
	Where string `json:"where,omitempty"`
	Like  string `json:"like,omitempty"`
	Full  bool   `json:"full,omitempty"` // SHOW FULL PROCESSLIST
}

ShowStatement SHOW 语句

type Statement

type Statement interface{}

Statement 语句

type StmtHandler

type StmtHandler interface {
	Handle(stmt ast.StmtNode) (result interface{}, err error)
}

StmtHandler SQL 语句处理器接口

type TableVisitor

type TableVisitor struct {
	// contains filtered or unexported fields
}

TableVisitor 表名访问器

func NewTableVisitor

func NewTableVisitor() *TableVisitor

NewTableVisitor 创建表名访问器

func (*TableVisitor) Enter

func (v *TableVisitor) Enter(n ast.Node) (ast.Node, bool)

Enter 进入节点

func (*TableVisitor) GetTables

func (v *TableVisitor) GetTables() []string

GetTables 获取表名列表

func (*TableVisitor) Leave

func (v *TableVisitor) Leave(n ast.Node) (ast.Node, bool)

Leave 离开节点

type TransactionStatement

type TransactionStatement struct {
	Level string `json:"level,omitempty"` // 隔离级别:READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE
}

TransactionStatement 事务语句

type UpdateStatement

type UpdateStatement struct {
	Table   string                 `json:"table"`
	Set     map[string]interface{} `json:"set"`
	Where   *Expression            `json:"where,omitempty"`
	OrderBy []OrderByItem          `json:"order_by,omitempty"`
	Limit   *int64                 `json:"limit,omitempty"`
}

UpdateStatement UPDATE 语句

type UseHandler

type UseHandler struct{}

UseHandler USE 语句处理器

func NewUseHandler

func NewUseHandler() *UseHandler

NewUseHandler 创建 USE 处理器

func (*UseHandler) Handle

func (h *UseHandler) Handle(stmt ast.StmtNode) (interface{}, error)

Handle 处理 USE 语句

type UseResult

type UseResult struct {
	Type     string
	Database string
}

USE 结果

type UseStatement

type UseStatement struct {
	Database string `json:"database"` // 数据库名
}

UseStatement USE 语句

type WhileStmt

type WhileStmt struct {
	Condition Expression
	Body      *BlockStmt
}

WhileStmt WHILE语句

func NewWhile

func NewWhile(condition Expression, body *BlockStmt) *WhileStmt

NewWhile 创建WHILE语句

type WindowExpression

type WindowExpression struct {
	FuncName string       // 函数名
	Args     []Expression // 函数参数
	Spec     *WindowSpec  // 窗口规范
	Distinct bool         // DISTINCT标记
}

WindowExpression 窗口函数表达式

func CreateAggregateWindow

func CreateAggregateWindow(funcName string, args []Expression, partitionBy []Expression, orderBy []OrderItem, frame *WindowFrame) *WindowExpression

CreateAggregateWindow 创建聚合窗口

func CreateOffsetWindow

func CreateOffsetWindow(funcName string, args []Expression, partitionBy []Expression, orderBy []OrderItem) *WindowExpression

CreateOffsetWindow 创建偏移窗口

func CreateRankingWindow

func CreateRankingWindow(funcName string, partitionBy []Expression, orderBy []OrderItem) *WindowExpression

CreateRankingWindow 创建排名窗口

func NewWindowExpression

func NewWindowExpression(funcName string, args []Expression, spec *WindowSpec) (*WindowExpression, error)

NewWindowExpression 创建窗口函数表达式

func (*WindowExpression) Clone

func (we *WindowExpression) Clone() *WindowExpression

Clone 克隆窗口表达式

func (*WindowExpression) GetWindowType

func (we *WindowExpression) GetWindowType() WindowType

GetWindowType 获取窗口函数类型

func (*WindowExpression) IsAggregateFunction

func (we *WindowExpression) IsAggregateFunction() bool

IsAggregateFunction 检查是否为聚合函数

func (*WindowExpression) IsOffsetFunction

func (we *WindowExpression) IsOffsetFunction() bool

IsOffsetFunction 检查是否为偏移函数

func (*WindowExpression) IsRankingFunction

func (we *WindowExpression) IsRankingFunction() bool

IsRankingFunction 检查是否为排名函数

func (*WindowExpression) IsValueFunction

func (we *WindowExpression) IsValueFunction() bool

IsValueFunction 检查是否为值函数

type WindowFrame

type WindowFrame struct {
	Mode  FrameMode   // 帧模式(ROWS/RANGE)
	Start FrameBound  // 起始边界
	End   *FrameBound // 结束边界(可为空)
}

WindowFrame 窗口帧

func ParseWindowFrame

func ParseWindowFrame(mode FrameMode, start BoundType, startValue Expression, end BoundType, endValue Expression) *WindowFrame

ParseWindowFrame 解析窗口帧

type WindowSpec

type WindowSpec struct {
	Name        string       // 窗口名称(如果有)
	PartitionBy []Expression // PARTITION BY表达式
	OrderBy     []OrderItem  // ORDER BY表达式
	Frame       *WindowFrame // 窗口帧定义
}

WindowSpec 窗口规范

func ParseWindowSpec

func ParseWindowSpec(windowName string, partitionBy []Expression, orderBy []OrderItem, frame *WindowFrame) *WindowSpec

ParseWindowSpec 解析窗口规范

type WindowType

type WindowType int

WindowType 窗口函数类型

const (
	WindowTypeRanking   WindowType = iota // 排名函数
	WindowTypeOffset                      // 偏移函数
	WindowTypeAggregate                   // 聚合函数
	WindowTypeValue                       // 值函数
)

type WithClause

type WithClause struct {
	CTEs        []*CTEInfo // CTE列表
	IsRecursive bool       // 是否递归
}

WithClause WITH子句(CTE定义)

func NewWithClause

func NewWithClause(isRecursive bool) *WithClause

NewWithClause 创建WITH子句

func ParseCTEFromTiDB

func ParseCTEFromTiDB(astNode interface{}) (*WithClause, error)

ParseCTEFromTiDB 从TiDB Parser的AST解析CTE 注意: TiDB Parser不完全支持CTE解析,这里提供手动构建接口

func (*WithClause) AddCTE

func (wc *WithClause) AddCTE(name string, subquery *SelectStatement, columns ...string)

AddCTE 添加CTE

func (*WithClause) GetCTE

func (wc *WithClause) GetCTE(name string) *CTEInfo

GetCTE 获取CTE

func (*WithClause) GetCTENames

func (wc *WithClause) GetCTENames() []string

GetCTENames 获取所有CTE名称

func (*WithClause) HasCTE

func (wc *WithClause) HasCTE(name string) bool

HasCTE 检查是否存在CTE

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL