sql

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package sql provides SQL parsing and execution for XxSql.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AddColumnAction

type AddColumnAction struct {
	Column *ColumnDef
}

AddColumnAction represents ADD COLUMN action.

func (*AddColumnAction) String

func (a *AddColumnAction) String() string

type AddConstraintAction

type AddConstraintAction struct {
	Constraint *TableConstraint
}

AddConstraintAction represents ADD CONSTRAINT action.

func (*AddConstraintAction) String

func (a *AddConstraintAction) String() string

type AlterAction

type AlterAction interface {
	Node
	// contains filtered or unexported methods
}

AlterAction represents an action in ALTER TABLE.

type AlterTableStmt

type AlterTableStmt struct {
	TableName string
	Actions   []AlterAction
}

AlterTableStmt represents an ALTER TABLE statement.

func (*AlterTableStmt) String

func (s *AlterTableStmt) String() string

type AlterUserStmt

type AlterUserStmt struct {
	Username   string
	Host       string
	Identified string // new password
}

AlterUserStmt represents an ALTER USER statement.

func (*AlterUserStmt) String

func (s *AlterUserStmt) String() string

type AnalyzeStmt added in v0.0.5

type AnalyzeStmt struct {
	TableName string // Empty means analyze all tables
}

AnalyzeStmt represents an ANALYZE TABLE statement.

func (*AnalyzeStmt) String added in v0.0.5

func (s *AnalyzeStmt) String() string

type AnyAllExpr added in v0.0.5

type AnyAllExpr struct {
	Left     Expression // Left operand
	Op       BinaryOp   // Comparison operator (=, >, <, >=, <=, !=, <>)
	IsAny    bool       // true for ANY, false for ALL
	Subquery *SubqueryExpr
}

AnyAllExpr represents an ANY or ALL expression with a subquery. Examples: x > ANY (SELECT ...), x = ALL (SELECT ...)

func (*AnyAllExpr) String added in v0.0.5

func (e *AnyAllExpr) String() string

type Assignment

type Assignment struct {
	Column string
	Value  Expression
}

Assignment represents a SET assignment.

func (*Assignment) String

func (a *Assignment) String() string

type BackupStmt

type BackupStmt struct {
	Path        string // backup file path
	Compress    bool   // WITH COMPRESS option
	Incremental bool   // incremental backup
}

BackupStmt represents a BACKUP DATABASE statement.

func (*BackupStmt) String

func (s *BackupStmt) String() string

type BeginStmt added in v0.0.5

type BeginStmt struct {
	// TransactionType: "", "DEFERRED", "IMMEDIATE", or "EXCLUSIVE"
	TransactionType string
}

BeginStmt represents a BEGIN [TRANSACTION] statement.

func (*BeginStmt) String added in v0.0.5

func (s *BeginStmt) String() string

type BetweenExpr

type BetweenExpr struct {
	Expr  Expression
	Left  Expression
	Right Expression
	Not   bool
}

BetweenExpr represents a BETWEEN expression.

func (*BetweenExpr) String

func (e *BetweenExpr) String() string

type BinaryExpr

type BinaryExpr struct {
	Left       Expression
	Op         BinaryOp
	Right      Expression
	Alias      string // optional alias
	EscapeChar string // optional escape character for LIKE/NOT LIKE (default is '\')
}

BinaryExpr represents a binary expression.

func (*BinaryExpr) String

func (e *BinaryExpr) String() string

type BinaryOp

type BinaryOp int
const (
	OpEq BinaryOp = iota
	OpNe
	OpLt
	OpLe
	OpGt
	OpGe
	OpAdd
	OpSub
	OpMul
	OpDiv
	OpMod
	OpAnd
	OpOr
	OpLike
	OpNotLike
	OpGlob
	OpNotGlob
	OpIn
	OpNotIn
	OpConcat
)

func (BinaryOp) String added in v0.0.5

func (op BinaryOp) String() string

type BlockExpr added in v0.0.5

type BlockExpr struct {
	Expressions []Expression
}

BlockExpr represents a block of expressions. Syntax: BEGIN expr; expr; ... END or (expr, expr, ...) The result is the value of the last expression.

func (*BlockExpr) String added in v0.0.5

func (e *BlockExpr) String() string

type CTEDefinition added in v0.0.5

type CTEDefinition struct {
	Name      string    // CTE name
	Columns   []string  // Optional column names
	Query     Statement // The subquery defining the CTE
	Recursive bool      // Whether this is a recursive CTE
}

CTEDefinition represents a single CTE (Common Table Expression) definition.

func (*CTEDefinition) String added in v0.0.5

func (c *CTEDefinition) String() string

type CaseExpr

type CaseExpr struct {
	Expr  Expression // optional operand
	Whens []*CaseWhen
	Else  Expression
}

CaseExpr represents a CASE expression.

func (*CaseExpr) String

func (e *CaseExpr) String() string

type CaseWhen

type CaseWhen struct {
	Condition Expression
	Result    Expression
}

CaseWhen represents a WHEN clause in a CASE expression.

func (*CaseWhen) String

func (w *CaseWhen) String() string

type CastExpr

type CastExpr struct {
	Expr Expression
	Type *DataType
}

CastExpr represents a CAST expression.

func (*CastExpr) String

func (e *CastExpr) String() string

type CollateExpr added in v0.0.5

type CollateExpr struct {
	Expr    Expression
	Collate string
}

CollateExpr represents a COLLATE expression. Syntax: expr COLLATE collation_name

func (*CollateExpr) String added in v0.0.5

func (e *CollateExpr) String() string

type ColumnDef

type ColumnDef struct {
	Name            string
	Type            *DataType
	Nullable        bool // true if NULL allowed (default true)
	Default         Expression
	AutoIncr        bool
	PrimaryKey      bool
	Unique          bool
	Comment         string
	Collate         string     // COLLATE collation name
	GeneratedExpr   Expression // GENERATED ALWAYS AS expression
	GeneratedStored bool       // true if STORED, false if VIRTUAL
}

ColumnDef represents a column definition.

func (*ColumnDef) String

func (c *ColumnDef) String() string

type ColumnRef

type ColumnRef struct {
	Table string // optional table qualifier
	Name  string
	Alias string // optional alias
}

ColumnRef represents a column reference.

func (*ColumnRef) String

func (c *ColumnRef) String() string

type CommitStmt added in v0.0.5

type CommitStmt struct {
}

CommitStmt represents a COMMIT [TRANSACTION] statement.

func (*CommitStmt) String added in v0.0.5

func (s *CommitStmt) String() string

type ConstraintType

type ConstraintType int

ConstraintType represents the type of constraint.

const (
	ConstraintPrimaryKey ConstraintType = iota
	ConstraintUnique
	ConstraintForeignKey
	ConstraintCheck
)

type CopyStmt added in v0.0.5

type CopyStmt struct {
	TableName  string    // For COPY table FROM
	Query      Statement // For COPY (SELECT ...) TO
	FileName   string
	Direction  string // "FROM" or "TO"
	Format     string // csv, tsv, text (default: csv)
	Header     bool   // First row is header
	Delimiter  string // Field delimiter (default: comma)
	Quote      string // Quote character (default: ")
	NullString string // String representing NULL (default: \N)
	Encoding   string // File encoding (default: utf-8)
}

CopyStmt represents a COPY statement for bulk import/export. COPY table FROM 'file.csv' WITH (FORMAT csv, HEADER true, DELIMITER ',') COPY (SELECT ...) TO 'file.csv' WITH (FORMAT csv, HEADER true)

func (*CopyStmt) String added in v0.0.5

func (s *CopyStmt) String() string

type CreateFTSStmt added in v0.0.5

type CreateFTSStmt struct {
	IndexName   string   // Name of the FTS index
	TableName   string   // Table to index
	Columns     []string // Columns to include in the index
	Tokenizer   string   // Tokenizer type: "simple" (default), "porter"
	IfNotExists bool     // IF NOT EXISTS clause
}

CreateFTSStmt represents a CREATE FTS INDEX statement. Syntax: CREATE FTS INDEX name ON table(column1, column2, ...) [WITH TOKENIZER tokenizer]

func (*CreateFTSStmt) String added in v0.0.5

func (s *CreateFTSStmt) String() string

type CreateFunctionStmt added in v0.0.5

type CreateFunctionStmt struct {
	Name       string
	Parameters []*FunctionParameter
	ReturnType *DataType
	Body       Expression // Old style: SQL expression body
	Script     string     // New style: XxScript body
	Replace    bool       // CREATE OR REPLACE
}

CreateFunctionStmt represents a CREATE FUNCTION statement.

func (*CreateFunctionStmt) String added in v0.0.5

func (s *CreateFunctionStmt) String() string

type CreateIndexStmt

type CreateIndexStmt struct {
	Unique      bool
	IndexName   string
	TableName   string
	Columns     []string
	IfNotExists bool
}

CreateIndexStmt represents a CREATE INDEX statement.

func (*CreateIndexStmt) String

func (s *CreateIndexStmt) String() string

type CreateTableStmt

type CreateTableStmt struct {
	IfNotExists bool
	Temp        bool // TEMP or TEMPORARY keyword
	TableName   string
	Columns     []*ColumnDef
	Constraints []*TableConstraint
	Options     map[string]string
}

CreateTableStmt represents a CREATE TABLE statement.

func (*CreateTableStmt) String

func (s *CreateTableStmt) String() string

type CreateTriggerStmt added in v0.0.5

type CreateTriggerStmt struct {
	TriggerName string
	Timing      TriggerTiming
	Event       TriggerEvent
	TableName   string
	Granularity TriggerGranularity
	WhenClause  Expression  // optional WHEN condition
	Body        []Statement // trigger body statements
	IfNotExists bool
}

CreateTriggerStmt represents a CREATE TRIGGER statement. Syntax: CREATE TRIGGER name {BEFORE|AFTER|INSTEAD OF} {INSERT|UPDATE|DELETE} ON table [FOR EACH ROW] BEGIN statements END

func (*CreateTriggerStmt) String added in v0.0.5

func (s *CreateTriggerStmt) String() string

type CreateUserStmt

type CreateUserStmt struct {
	IfNotExists bool
	Username    string
	Host        string // default: '%'
	Identified  string // password or auth string
	Role        string // optional: admin, user
}

CreateUserStmt represents a CREATE USER statement.

func (*CreateUserStmt) String

func (s *CreateUserStmt) String() string

type CreateViewStmt added in v0.0.5

type CreateViewStmt struct {
	ViewName    string
	Columns     []string // Optional column names
	SelectStmt  Statement
	OrReplace   bool
	CheckOption string // "CASCADED", "LOCAL", or "" (empty for no check)
}

CreateViewStmt represents a CREATE VIEW statement.

func (*CreateViewStmt) String added in v0.0.5

func (s *CreateViewStmt) String() string

type DataType

type DataType struct {
	Name      string
	Size      int // for CHAR, VARCHAR
	Precision int // for DECIMAL, NUMERIC
	Scale     int // for DECIMAL, NUMERIC
	Unsigned  bool
}

DataType represents a data type.

func (*DataType) String

func (d *DataType) String() string

type DeleteStmt

type DeleteStmt struct {
	Table      string
	Where      Expression
	OrderBy    []*OrderByItem
	Limit      *int
	Returning  *ReturningClause // RETURNING clause
	WithClause *WithClause      // Optional WITH clause
}

DeleteStmt represents a DELETE statement.

func (*DeleteStmt) String

func (s *DeleteStmt) String() string

type DescribeStmt

type DescribeStmt struct {
	TableName string
}

DescribeStmt represents a DESCRIBE/DESC table statement.

func (*DescribeStmt) String

func (s *DescribeStmt) String() string

type DropColumnAction

type DropColumnAction struct {
	ColumnName string
}

DropColumnAction represents DROP COLUMN action.

func (*DropColumnAction) String

func (a *DropColumnAction) String() string

type DropConstraintAction

type DropConstraintAction struct {
	ConstraintName string
}

DropConstraintAction represents DROP CONSTRAINT action.

func (*DropConstraintAction) String

func (a *DropConstraintAction) String() string

type DropFTSStmt added in v0.0.5

type DropFTSStmt struct {
	IndexName string
	IfExists  bool
}

DropFTSStmt represents a DROP FTS INDEX statement. Syntax: DROP FTS INDEX name

func (*DropFTSStmt) String added in v0.0.5

func (s *DropFTSStmt) String() string

type DropFunctionStmt added in v0.0.5

type DropFunctionStmt struct {
	Name     string
	IfExists bool
}

DropFunctionStmt represents a DROP FUNCTION statement.

func (*DropFunctionStmt) String added in v0.0.5

func (s *DropFunctionStmt) String() string

type DropIndexStmt

type DropIndexStmt struct {
	IndexName string
	TableName string
	IfExists  bool
}

DropIndexStmt represents a DROP INDEX statement.

func (*DropIndexStmt) String

func (s *DropIndexStmt) String() string

type DropTableStmt

type DropTableStmt struct {
	IfExists  bool
	TableName string
}

DropTableStmt represents a DROP TABLE statement.

func (*DropTableStmt) String

func (s *DropTableStmt) String() string

type DropTriggerStmt added in v0.0.5

type DropTriggerStmt struct {
	TriggerName string
	TableName   string // optional, for MySQL compatibility
	IfExists    bool
}

DropTriggerStmt represents a DROP TRIGGER statement.

func (*DropTriggerStmt) String added in v0.0.5

func (s *DropTriggerStmt) String() string

type DropUserStmt

type DropUserStmt struct {
	IfExists bool
	Username string
	Host     string
}

DropUserStmt represents a DROP USER statement.

func (*DropUserStmt) String

func (s *DropUserStmt) String() string

type DropViewStmt added in v0.0.5

type DropViewStmt struct {
	ViewName string
	IfExists bool
}

DropViewStmt represents a DROP VIEW statement.

func (*DropViewStmt) String added in v0.0.5

func (s *DropViewStmt) String() string

type ExistsExpr added in v0.0.5

type ExistsExpr struct {
	Subquery *SubqueryExpr
	Not      bool // true for NOT EXISTS
}

ExistsExpr represents an EXISTS subquery expression.

func (*ExistsExpr) String added in v0.0.5

func (e *ExistsExpr) String() string

type ExplainStmt added in v0.0.5

type ExplainStmt struct {
	Statement Statement // The statement to explain
	QueryPlan bool      // EXPLAIN QUERY PLAN
}

ExplainStmt represents an EXPLAIN statement.

func (*ExplainStmt) String added in v0.0.5

func (s *ExplainStmt) String() string

type Expression

type Expression interface {
	Node
	// contains filtered or unexported methods
}

Expression represents an expression.

type FrameBound added in v0.0.5

type FrameBound struct {
	Type   string // "UNBOUNDED PRECEDING", "PRECEDING", "CURRENT ROW", "FOLLOWING", "UNBOUNDED FOLLOWING"
	Offset int    // Offset for PRECEDING/FOLLOWING (0 for CURRENT ROW, UNBOUNDED)
}

FrameBound represents one side of a window frame.

func (FrameBound) String added in v0.0.5

func (f FrameBound) String() string

type FrameSpec added in v0.0.5

type FrameSpec struct {
	Mode  string     // "ROWS" or "RANGE"
	Start FrameBound // Start bound
	End   FrameBound // End bound (optional, defaults to CURRENT ROW)
}

FrameSpec represents a window frame clause (ROWS/RANGE BETWEEN ... AND ...).

func (*FrameSpec) String added in v0.0.5

func (f *FrameSpec) String() string

type FromClause

type FromClause struct {
	Table *TableRef
	Joins []*JoinClause
}

FromClause represents a FROM clause.

func (*FromClause) String

func (c *FromClause) String() string

type FunctionCall

type FunctionCall struct {
	Name     string
	Args     []Expression
	Distinct bool
	Filter   Expression // FILTER (WHERE ...) clause for aggregates
}

FunctionCall represents a function call.

func (*FunctionCall) String

func (f *FunctionCall) String() string

type FunctionParameter added in v0.0.5

type FunctionParameter struct {
	Name         string
	Type         *DataType
	DefaultValue Expression // optional default value
}

FunctionParameter represents a parameter in a UDF.

func (*FunctionParameter) String added in v0.0.5

func (p *FunctionParameter) String() string

type GrantOn

type GrantOn int

GrantOn represents the object type for GRANT/REVOKE.

const (
	GrantOnAll GrantOn = iota
	GrantOnDatabase
	GrantOnTable
)

type GrantStmt

type GrantStmt struct {
	Privileges []*Privilege
	On         GrantOn
	Database   string
	Table      string
	To         string // username
	Host       string
	WithGrant  bool // WITH GRANT OPTION
}

GrantStmt represents a GRANT statement.

func (*GrantStmt) String

func (s *GrantStmt) String() string

type IfExpr added in v0.0.5

type IfExpr struct {
	Condition Expression
	ThenExpr  Expression
	ElseExpr  Expression // may be nil
}

IfExpr represents an IF expression. Syntax: IF condition THEN expr [ELSE expr] END

func (*IfExpr) String added in v0.0.5

func (e *IfExpr) String() string

type InExpr

type InExpr struct {
	Expr   Expression
	List   []Expression
	Select Statement
	Not    bool
}

InExpr represents an IN expression.

func (*InExpr) String

func (e *InExpr) String() string

type InsertStmt

type InsertStmt struct {
	Table                string
	Columns              []string
	Values               [][]Expression
	OnDuplicateKeyUpdate []*Assignment    // MySQL-style ON DUPLICATE KEY UPDATE
	OnConflict           *UpsertClause    // SQLite-style ON CONFLICT
	Returning            *ReturningClause // RETURNING clause
	WithClause           *WithClause      // Optional WITH clause
}

InsertStmt represents an INSERT statement.

func (*InsertStmt) String

func (s *InsertStmt) String() string

type IsNullExpr

type IsNullExpr struct {
	Expr Expression
	Not  bool
}

IsNullExpr represents an IS NULL expression.

func (*IsNullExpr) String

func (e *IsNullExpr) String() string

type JoinClause

type JoinClause struct {
	Type  JoinType
	Table *TableRef
	On    Expression
	Using []string
}

JoinClause represents a JOIN clause.

func (*JoinClause) String

func (c *JoinClause) String() string

type JoinType

type JoinType int

JoinType represents the type of JOIN.

const (
	JoinInner JoinType = iota
	JoinLeft
	JoinRight
	JoinCross
	JoinFull
)

type LetExpr added in v0.0.5

type LetExpr struct {
	Name  string
	Value Expression
}

LetExpr represents a LET variable assignment. Syntax: LET name = expr

func (*LetExpr) String added in v0.0.5

func (e *LetExpr) String() string

type Lexer

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

Lexer tokenizes SQL input.

func NewLexer

func NewLexer(input string) *Lexer

NewLexer creates a new lexer for the given input.

func (*Lexer) Column

func (l *Lexer) Column() int

Column returns the current column number.

func (*Lexer) Line

func (l *Lexer) Line() int

Line returns the current line number.

func (*Lexer) NextToken

func (l *Lexer) NextToken() Token

NextToken returns the next token from the input.

func (*Lexer) Pos

func (l *Lexer) Pos() int

Pos returns the current position.

type Literal

type Literal struct {
	Value interface{}
	Type  LiteralType
	Alias string // optional alias
}

Literal represents a literal value.

func (*Literal) String

func (l *Literal) String() string

type LiteralType

type LiteralType int
const (
	LiteralNull LiteralType = iota
	LiteralString
	LiteralNumber
	LiteralBool
	LiteralBlob
)

type LoadDataStmt added in v0.0.5

type LoadDataStmt struct {
	FileName         string
	TableName        string
	FieldsTerminated string // default: '\t'
	FieldsEnclosed   string // default: ”
	FieldsEscaped    string // default: '\\'
	LinesTerminated  string // default: '\n'
	LinesStarting    string // default: ”
	IgnoreRows       int
	ColumnList       []string // Optional column list
}

LoadDataStmt represents a LOAD DATA INFILE statement (MySQL style). LOAD DATA INFILE 'file.csv' INTO TABLE table_name

FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'
IGNORE 1 ROWS;

func (*LoadDataStmt) String added in v0.0.5

func (s *LoadDataStmt) String() string

type MatchExpr added in v0.0.5

type MatchExpr struct {
	Table   string   // Table name (or alias)
	Query   string   // Search query string
	Columns []string // Optional: specific columns to search
}

MatchExpr represents a MATCH expression for full-text search. Syntax: table_name MATCH 'search query' Used in WHERE clause for FTS queries.

func (*MatchExpr) String added in v0.0.5

func (e *MatchExpr) String() string

type ModifyColumnAction

type ModifyColumnAction struct {
	Column *ColumnDef
}

ModifyColumnAction represents MODIFY COLUMN action.

func (*ModifyColumnAction) String

func (a *ModifyColumnAction) String() string

type Node

type Node interface {
	String() string
	// contains filtered or unexported methods
}

Node represents an AST node.

type OrderByItem

type OrderByItem struct {
	Expr       Expression
	Ascending  bool
	NullsFirst bool   // NULLS FIRST specified
	NullsLast  bool   // NULLS LAST specified
	Collate    string // COLLATE collation name
}

OrderByItem represents an ORDER BY item.

func (*OrderByItem) String

func (o *OrderByItem) String() string

type ParenExpr

type ParenExpr struct {
	Expr Expression
}

ParenExpr represents a parenthesized expression.

func (*ParenExpr) String

func (e *ParenExpr) String() string

type Parser

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

Parser parses SQL statements.

func NewParser

func NewParser(input string) *Parser

NewParser creates a new parser for the given input.

func (*Parser) Error added in v0.0.5

func (p *Parser) Error() error

Error returns any parse error that occurred.

func (*Parser) Parse

func (p *Parser) Parse() (Statement, error)

Parse parses the input and returns a statement.

func (*Parser) ParseExpression added in v0.0.5

func (p *Parser) ParseExpression() Expression

ParseExpression parses a single expression and returns it. This is useful for parsing generated column expressions.

type PragmaStmt added in v0.0.5

type PragmaStmt struct {
	Name     string      // pragma name
	Value    interface{} // optional value (can be string, int, bool, or nil for query)
	Argument string      // optional argument for function-style pragmas like table_info(table)
}

PragmaStmt represents a PRAGMA statement. Syntax: PRAGMA name [= value] or PRAGMA name(argument)

func (*PragmaStmt) String added in v0.0.5

func (s *PragmaStmt) String() string

type Privilege

type Privilege struct {
	Type    PrivilegeType
	Columns []string // For column-level privileges
}

Privilege represents a privilege with optional columns.

func (*Privilege) String

func (p *Privilege) String() string

type PrivilegeType

type PrivilegeType int

PrivilegeType represents a SQL privilege type.

const (
	PrivAll PrivilegeType = iota
	PrivSelect
	PrivInsert
	PrivUpdate
	PrivDelete
	PrivCreate
	PrivDrop
	PrivIndex
	PrivAlter
	PrivUsage
)

func (PrivilegeType) String

func (p PrivilegeType) String() string

String returns the string representation of the privilege.

type RankExpr added in v0.0.5

type RankExpr struct {
	IndexName string // Optional: specific index name
}

RankExpr represents a RANK expression for FTS result ordering. Returns the relevance score of the FTS match.

func (*RankExpr) String added in v0.0.5

func (e *RankExpr) String() string

type ReleaseSavepointStmt added in v0.0.5

type ReleaseSavepointStmt struct {
	Name string
}

ReleaseSavepointStmt represents a RELEASE SAVEPOINT name statement.

func (*ReleaseSavepointStmt) String added in v0.0.5

func (s *ReleaseSavepointStmt) String() string

type RenameColumnAction

type RenameColumnAction struct {
	OldName string
	NewName string
}

RenameColumnAction represents RENAME COLUMN action.

func (*RenameColumnAction) String

func (a *RenameColumnAction) String() string

type RenameTableAction

type RenameTableAction struct {
	NewName string
}

RenameTableAction represents RENAME TO action.

func (*RenameTableAction) String

func (a *RenameTableAction) String() string

type RestoreStmt

type RestoreStmt struct {
	Path string // backup file path
}

RestoreStmt represents a RESTORE DATABASE statement.

func (*RestoreStmt) String

func (s *RestoreStmt) String() string

type ReturningClause added in v0.0.5

type ReturningClause struct {
	Columns []Expression // Columns to return, nil or empty means *
	All     bool         // RETURNING *
}

ReturningClause represents a RETURNING clause.

func (*ReturningClause) String added in v0.0.5

func (r *ReturningClause) String() string

type RevokeStmt

type RevokeStmt struct {
	Privileges []*Privilege
	On         GrantOn
	Database   string
	Table      string
	From       string // username
	Host       string
}

RevokeStmt represents a REVOKE statement.

func (*RevokeStmt) String

func (s *RevokeStmt) String() string

type RollbackStmt added in v0.0.5

type RollbackStmt struct {
	ToSavepoint string // if non-empty, rollback to this savepoint
}

RollbackStmt represents a ROLLBACK [TRANSACTION] [TO SAVEPOINT name] statement.

func (*RollbackStmt) String added in v0.0.5

func (s *RollbackStmt) String() string

type SavepointStmt added in v0.0.5

type SavepointStmt struct {
	Name string
}

SavepointStmt represents a SAVEPOINT name statement.

func (*SavepointStmt) String added in v0.0.5

func (s *SavepointStmt) String() string

type ScalarSubquery added in v0.0.5

type ScalarSubquery struct {
	Subquery *SubqueryExpr
}

ScalarSubquery represents a scalar subquery that returns a single value. Example: SELECT (SELECT COUNT(*) FROM users)

func (*ScalarSubquery) String added in v0.0.5

func (e *ScalarSubquery) String() string

type SelectStmt

type SelectStmt struct {
	Distinct bool
	Columns  []Expression // SELECT columns
	From     *FromClause  // FROM clause
	Where    Expression   // WHERE condition
	GroupBy  []Expression // GROUP BY columns
	Having   Expression   // HAVING condition
	OrderBy  []*OrderByItem
	Limit    *int
	Offset   *int
}

SelectStmt represents a SELECT statement.

func (*SelectStmt) String

func (s *SelectStmt) String() string

type SetOperation added in v0.0.5

type SetOperation int

SetOperation represents a set operation type.

const (
	SetUnion SetOperation = iota
	SetIntersect
	SetExcept
)

func (*SetOperation) String added in v0.0.5

func (s *SetOperation) String() string

type SetPasswordStmt

type SetPasswordStmt struct {
	ForUser  string // optional: FOR user
	ForHost  string
	Password string
}

SetPasswordStmt represents a SET PASSWORD statement.

func (*SetPasswordStmt) String

func (s *SetPasswordStmt) String() string

type ShowCreateTableStmt

type ShowCreateTableStmt struct {
	TableName string
}

ShowCreateTableStmt represents a SHOW CREATE TABLE statement.

func (*ShowCreateTableStmt) String

func (s *ShowCreateTableStmt) String() string

type ShowGrantsStmt

type ShowGrantsStmt struct {
	ForUser string // optional: SHOW GRANTS FOR user
	ForHost string
}

ShowGrantsStmt represents a SHOW GRANTS statement.

func (*ShowGrantsStmt) String

func (s *ShowGrantsStmt) String() string

type ShowStmt

type ShowStmt struct {
	Type string // TABLES, DATABASES, COLUMNS, etc.
	Like string
	From string // table name for SHOW COLUMNS
}

ShowStmt represents a SHOW statement.

func (*ShowStmt) String

func (s *ShowStmt) String() string

type StarExpr

type StarExpr struct {
	Table string // optional table qualifier
}

StarExpr represents a * or table.* expression.

func (*StarExpr) String

func (s *StarExpr) String() string

type Statement

type Statement interface {
	Node
	// contains filtered or unexported methods
}

Statement represents a SQL statement.

func Parse

func Parse(input string) (Statement, error)

Parse parses a single SQL statement from the input string.

func ParseAll

func ParseAll(input string) ([]Statement, error)

ParseAll parses all statements in the input.

type SubqueryExpr added in v0.0.4

type SubqueryExpr struct {
	Select *SelectStmt
}

SubqueryExpr represents a subquery expression (e.g., in IN clause).

func (*SubqueryExpr) String added in v0.0.4

func (e *SubqueryExpr) String() string

type TableConstraint

type TableConstraint struct {
	Name       string
	Type       ConstraintType
	Columns    []string
	RefTable   string
	RefColumns []string
	CheckExpr  Expression // For CHECK constraint
	OnDelete   string     // For FK: CASCADE, SET NULL, RESTRICT, NO ACTION
	OnUpdate   string     // For FK: CASCADE, SET NULL, RESTRICT, NO ACTION
}

TableConstraint represents a table-level constraint.

func (*TableConstraint) String

func (c *TableConstraint) String() string

type TableRef

type TableRef struct {
	Name     string        // Table name (if referencing a real table)
	Alias    string        // Optional alias
	Subquery *SubqueryExpr // Subquery (if this is a derived table)
	Lateral  bool          // LATERAL keyword for correlated subqueries
	Values   *ValuesExpr   // VALUES constructor (if this is a values table)
}

TableRef represents a table reference (either a named table or a subquery).

func (*TableRef) String

func (t *TableRef) String() string

type Token

type Token struct {
	Type   TokenType
	Value  string
	Line   int // 1-based line number
	Column int // 1-based column number
}

Token represents a lexical token.

func Tokenize

func Tokenize(input string) ([]Token, error)

Tokenize returns all tokens from the input.

type TokenType

type TokenType int

TokenType represents the type of a token.

const (
	// Special tokens
	TokEOF TokenType = iota
	TokError

	// Keywords - DDL
	TokCreate
	TokTable
	TokView
	TokDrop
	TokIndex
	TokPrimary
	TokKey
	TokUnique
	TokConstraint
	TokForeign
	TokReferences
	TokAlter
	TokAdd
	TokColumn
	TokRename
	TokModify
	TokDatabase
	TokSchema
	TokTemp // TEMP/TEMPORARY keyword

	// Keywords - Bulk Import/Export
	TokCopy
	TokLoad
	TokData
	TokInfile
	TokFields
	TokTerminated
	TokLines
	TokEnclosed
	TokEscaped
	TokEscape // ESCAPE for LIKE
	TokOptionally

	// Keywords - DML
	TokSelect
	TokFrom
	TokWhere
	TokInsert
	TokInto
	TokValues
	TokUpdate
	TokSet
	TokDelete

	// Keywords - Clauses
	TokAnd
	TokOr
	TokNot
	TokIn
	TokLike
	TokGlob
	TokBetween
	TokIs
	TokNull
	TokDefault
	TokAs
	TokOn
	TokUsing
	TokDistinct

	// Keywords - JOIN
	TokJoin
	TokInner
	TokLeft
	TokRight
	TokCross
	TokOuter
	TokFull
	TokNatural

	// Keywords - Set operations
	TokUnion
	TokAll
	TokIntersect
	TokExcept

	// Keywords - GROUP BY / HAVING / ORDER BY
	TokGroup
	TokBy
	TokHaving
	TokOrder
	TokAsc
	TokDesc
	TokLimit
	TokOffset
	TokOf
	TokNulls  // NULLS FIRST/LAST
	TokFirst  // NULLS FIRST
	TokLast   // NULLS LAST
	TokFilter // FILTER (WHERE ...)

	// Keywords - Data types
	TokSeq // Auto-increment integer
	TokInt
	TokInteger
	TokBigInt
	TokSmallInt
	TokTinyInt
	TokFloat
	TokDouble
	TokDecimal
	TokNumeric
	TokChar
	TokVarchar
	TokText
	TokDate
	TokTime
	TokDateTime
	TokTimestamp
	TokBoolean
	TokBool
	TokBlob

	// Keywords - Functions
	TokCount
	TokSum
	TokAvg
	TokMin
	TokMax
	TokCoalesce
	TokNullIf
	TokCast
	TokCase
	TokWhen
	TokThen
	TokElse
	TokEnd

	// Keywords - JSON Functions
	TokJsonExtract
	TokJsonArray
	TokJsonObject
	TokJsonType
	TokJsonValid
	TokJsonQuote
	TokJsonUnquote
	TokJsonContains
	TokJsonKeys
	TokJsonLength

	// Keywords - Other
	TokIf
	TokExists
	TokAny
	TokAutoIncrement
	TokUnsigned
	TokZerofill
	TokCollate
	TokEngine
	TokCharset
	TokComment
	TokCheck
	TokCascade
	TokCascaded // CASCADED for VIEW CHECK OPTION
	TokRestrict
	TokAction
	TokLocal // LOCAL for VIEW CHECK OPTION
	TokDescribe
	TokBackup
	TokRestore

	// Keywords - Privileges
	TokGrant
	TokRevoke
	TokPrivileges
	TokTo
	TokUse
	TokShow
	TokTruncate
	TokVacuum
	TokPragma
	TokAnalyze
	TokUser
	TokPassword
	TokIdentified
	TokRole
	TokGrants
	TokOption
	TokWith
	TokRecursive
	TokAt
	TokFor

	// Keywords - Window Functions
	TokOver
	TokPartition
	TokWindow
	TokRows
	TokRange
	TokPreceding
	TokFollowing
	TokCurrent
	TokLead        // LEAD window function
	TokLag         // LAG window function
	TokNtile       // NTILE window function
	TokFirstValue  // FIRST_VALUE window function
	TokLastValue   // LAST_VALUE window function
	TokNthValue    // NTH_VALUE window function
	TokPercentRank // PERCENT_RANK window function
	TokCumeDist    // CUME_DIST window function
	TokIgnore      // IGNORE NULLS
	TokRespect     // RESPECT NULLS
	TokUnbounded   // UNBOUNDED PRECEDING/FOLLOWING
	TokFromFirst   // FROM FIRST (for NTH_VALUE)
	TokFromLast    // FROM LAST (for NTH_VALUE)

	// Keywords - LATERAL
	TokLateral // LATERAL for correlated subqueries

	// Keywords - UDF
	TokFunction
	TokReturns
	TokReturn
	TokReplace
	TokLet
	TokBegin

	// Keywords - Transaction
	TokCommit
	TokRollback
	TokTransaction
	TokSavepoint
	TokRelease
	TokWork      // optional keyword in COMMIT/ROLLBACK
	TokDeferred  // DEFERRED transaction
	TokImmediate // IMMEDIATE transaction
	TokExclusive // EXCLUSIVE transaction

	// Keywords - Trigger
	TokTrigger
	TokBefore
	TokAfter
	TokInstead
	TokEach
	TokRow
	TokStatement

	// Keywords - UPSERT and RETURNING
	TokConflict
	TokDo
	TokNothing
	TokReturning

	// Keywords - EXPLAIN
	TokExplain
	TokQuery
	TokPlan

	// Keywords - Generated Columns
	TokGenerated
	TokAlways
	TokVirtual
	TokStored

	// Keywords - Full-Text Search
	TokMatch     // MATCH
	TokFts       // FTS
	TokRank      // RANK
	TokTokenizer // TOKENIZER

	// Identifiers and literals
	TokIdent   // identifier
	TokNumber  // numeric literal
	TokString  // string literal
	TokBoolLit // boolean literal (TRUE/FALSE)

	// Operators
	TokEq      // =
	TokNe      // != or <>
	TokLt      // <
	TokLe      // <=
	TokGt      // >
	TokGe      // >=
	TokPlus    // +
	TokMinus   // -
	TokStar    // *
	TokSlash   // /
	TokPercent // %
	TokCaret   // ^
	TokConcat  // ||

	// Punctuation
	TokLParen    // (
	TokRParen    // )
	TokLBracket  // [
	TokRBracket  // ]
	TokLBrace    // {
	TokRBrace    // }
	TokComma     // ,
	TokSemi      // ;
	TokDot       // .
	TokColon     // :
	TokArrow     // ->
	TokDoubleCol // ::
	TokDollar    // $

	// Special
	TokParameter // ? or $1 for prepared statements
	TokAssign    // :=
)

func LookupKeyword

func LookupKeyword(s string) TokenType

LookupKeyword looks up a keyword and returns its token type. Returns TokIdent if not a keyword.

func (TokenType) String

func (t TokenType) String() string

String returns a string representation of the token type.

type TriggerEvent added in v0.0.5

type TriggerEvent int

TriggerEvent represents the event that fires a trigger.

const (
	TriggerInsert TriggerEvent = iota
	TriggerUpdate
	TriggerDelete
)

func (TriggerEvent) String added in v0.0.5

func (e TriggerEvent) String() string

type TriggerGranularity added in v0.0.5

type TriggerGranularity int

TriggerGranularity represents FOR EACH ROW or FOR EACH STATEMENT.

const (
	TriggerForEachRow TriggerGranularity = iota
	TriggerForEachStatement
)

func (TriggerGranularity) String added in v0.0.5

func (g TriggerGranularity) String() string

type TriggerInfo added in v0.0.5

type TriggerInfo struct {
	Name        string
	Timing      TriggerTiming
	Event       TriggerEvent
	TableName   string
	Granularity TriggerGranularity
	WhenClause  string // serialized WHEN expression
	Body        string // serialized body statements
}

TriggerInfo represents stored trigger information.

type TriggerTiming added in v0.0.5

type TriggerTiming int

TriggerTiming represents when a trigger fires.

const (
	TriggerBefore TriggerTiming = iota
	TriggerAfter
	TriggerInsteadOf
)

func (TriggerTiming) String added in v0.0.5

func (t TriggerTiming) String() string

type TruncateTableStmt

type TruncateTableStmt struct {
	TableName string
}

TruncateTableStmt represents a TRUNCATE TABLE statement.

func (*TruncateTableStmt) String

func (s *TruncateTableStmt) String() string

type UnaryExpr

type UnaryExpr struct {
	Op    UnaryOp
	Right Expression
}

UnaryExpr represents a unary expression.

func (*UnaryExpr) String

func (e *UnaryExpr) String() string

type UnaryOp

type UnaryOp int
const (
	OpNot UnaryOp = iota
	OpNeg
)

type UnionStmt

type UnionStmt struct {
	Left  Statement
	Right Statement
	All   bool
	Op    SetOperation // UNION, INTERSECT, or EXCEPT
}

UnionStmt represents a UNION statement.

func (*UnionStmt) String

func (s *UnionStmt) String() string

type UpdateStmt

type UpdateStmt struct {
	Table       string
	Assignments []*Assignment
	Where       Expression
	OrderBy     []*OrderByItem
	Limit       *int
	Returning   *ReturningClause // RETURNING clause
	WithClause  *WithClause      // Optional WITH clause
}

UpdateStmt represents an UPDATE statement.

func (*UpdateStmt) String

func (s *UpdateStmt) String() string

type UpsertClause added in v0.0.5

type UpsertClause struct {
	ConflictColumns []string      // ON CONFLICT(column1, column2)
	DoNothing       bool          // DO NOTHING
	DoUpdate        bool          // DO UPDATE
	Assignments     []*Assignment // SET assignments for DO UPDATE
	Where           Expression    // Optional WHERE for DO UPDATE
}

UpsertClause represents an ON CONFLICT clause (SQLite-style UPSERT).

func (*UpsertClause) String added in v0.0.5

func (u *UpsertClause) String() string

type UseStmt

type UseStmt struct {
	Database string
}

UseStmt represents a USE DATABASE statement.

func (*UseStmt) String

func (s *UseStmt) String() string

type UserFunction added in v0.0.5

type UserFunction struct {
	Name       string
	Parameters []*FunctionParameter
	ReturnType *DataType
	Body       Expression
}

UserFunction represents a stored user-defined function.

type VacuumStmt added in v0.0.5

type VacuumStmt struct {
	Table    string // optional table name, empty means vacuum entire database
	IntoPath string // optional INTO path for vacuum into a different file
}

VacuumStmt represents a VACUUM statement. Syntax: VACUUM [table_name] [INTO 'filename']

func (*VacuumStmt) String added in v0.0.5

func (s *VacuumStmt) String() string

type ValuesExpr added in v0.0.5

type ValuesExpr struct {
	Rows    [][]Expression // Each row is a list of expressions
	Alias   string         // Optional table alias
	Columns []string       // Optional column aliases
}

ValuesExpr represents a VALUES table constructor. Example: VALUES (1, 'a'), (2, 'b')

func (*ValuesExpr) String added in v0.0.5

func (e *ValuesExpr) String() string

type WindowFuncCall added in v0.0.5

type WindowFuncCall struct {
	Func         *FunctionCall // The function being called
	Window       *WindowSpec   // The window specification
	Alias        string        // optional alias
	IgnoreNulls  bool          // IGNORE NULLS (for LEAD/LAG/FIRST_VALUE/LAST_VALUE)
	RespectNulls bool          // RESPECT NULLS (default behavior, explicitly stated)
}

WindowFuncCall represents a window function call with OVER clause.

func (*WindowFuncCall) String added in v0.0.5

func (w *WindowFuncCall) String() string

type WindowSpec added in v0.0.5

type WindowSpec struct {
	PartitionBy []Expression   // PARTITION BY expressions
	OrderBy     []*OrderByItem // ORDER BY items
	Name        string         // Named window reference (optional)
	Frame       *FrameSpec     // Window frame clause (optional)
}

WindowSpec represents the window specification for window functions.

func (*WindowSpec) String added in v0.0.5

func (w *WindowSpec) String() string

type WithClause added in v0.0.5

type WithClause struct {
	CTEs      []CTEDefinition
	Recursive bool
}

WithClause represents a WITH clause that can be attached to DML statements. It allows CTEs to be used with INSERT, UPDATE, DELETE.

func (*WithClause) String added in v0.0.5

func (w *WithClause) String() string

type WithStmt added in v0.0.5

type WithStmt struct {
	CTEs      []CTEDefinition // List of CTE definitions
	MainQuery Statement       // The main query that uses the CTEs
}

WithStmt represents a WITH clause (CTE) statement. WITH cte_name AS (SELECT ...) SELECT * FROM cte_name

func (*WithStmt) String added in v0.0.5

func (s *WithStmt) String() string

Jump to

Keyboard shortcuts

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