sqlparser

package
v1.1.15 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2024 License: Apache-2.0, MIT Imports: 8 Imported by: 0

README

SQLParser

Go

A SQL parser.

Installation

go get github.com/longbridgeapp/sqlparser

Usage

TODO

SQL syntax supports

  • INSERT
  • UPDATE
  • SELECT
  • DELETE
  • WITH Clause for DELETE, INSERT, SELECT, UPDATE
  • WINDOW Clause for SELECT

Documentation

Overview

Package sqlparser fork from github.com/longbridgeapp/sqlparser@v0.3.1

Index

Constants

View Source
const (
	LowestPrec  = 0 // non-operators
	UnaryPrec   = 13
	HighestPrec = 14
)

Variables

View Source
var (
	// ErrNotImplemented not implemented
	ErrNotImplemented = errors.New("not implemented")
)

Functions

func ExprString

func ExprString(expr Expr) string

ExprString returns the string representation of expr. Returns a blank string if expr is nil.

func ForEachSource

func ForEachSource(src Source, fn func(Source) bool)

ForEachSource calls fn for every source within the current scope. Stops iteration if fn returns false.

func IdentName

func IdentName(ident *Ident) string

IdentName returns the name of ident. Returns a blank string if ident is nil.

func IsInteger

func IsInteger(s string) bool

IsInteger returns true if s only contains digits.

func SourceName

func SourceName(src Source) string

SourceName returns the name of the source. Only returns for TableName & ParenSource.

func Walk

func Walk(v Visitor, node Node) error

Walk traverses an AST in depth-first order: It starts by calling v.Visit(node); node must not be nil. If the visitor w returned by v.Visit(node) is not nil, Walk is invoked recursively with visitor w for each of the non-nil children of node, followed by a call of w.Visit(nil).

Types

type Assignment

type Assignment struct {
	Columns []*Ident // column list
	Expr    Expr     // assigned expression
}

Assignment is used within the UPDATE statement & upsert clause. It is similiar to an expression except that it must be an equality.

func (*Assignment) String

func (a *Assignment) String() string

String returns the string representation of the clause.

type BinaryExpr

type BinaryExpr struct {
	X  Expr  // lhs
	Op Token // operator
	Y  Expr  // rhs
}

func (*BinaryExpr) String

func (expr *BinaryExpr) String() string

String returns the string representation of the expression.

type BindExpr

type BindExpr struct {
	Name string // binding name
	Pos  int    // binding position
}

func (*BindExpr) String

func (expr *BindExpr) String() string

String returns the string representation of the expression.

type BlobLit

type BlobLit struct {
	Value string // literal value
}

func (*BlobLit) String

func (lit *BlobLit) String() string

String returns the string representation of the expression.

type BoolLit

type BoolLit struct {
	Value bool // literal value
}

func (*BoolLit) String

func (lit *BoolLit) String() string

String returns the string representation of the expression.

type Call

type Call struct {
	Name     *Ident // function name
	Star     bool
	Distinct bool
	Args     []Expr        // argument list
	Filter   *FilterClause // filter clause
}

func (*Call) String

func (c *Call) String() string

String returns the string representation of the expression.

type CaseBlock

type CaseBlock struct {
	Condition Expr // block condition
	Body      Expr // result expression
}

func (*CaseBlock) String

func (b *CaseBlock) String() string

String returns the string representation of the block.

type CaseExpr

type CaseExpr struct {
	Operand  Expr         // optional condition after the CASE keyword
	Blocks   []*CaseBlock // list of WHEN/THEN pairs
	ElseExpr Expr         // expression used by default case
}

func (*CaseExpr) String

func (expr *CaseExpr) String() string

String returns the string representation of the expression.

type ColumnArg

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

type Constraint

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

type DeleteStatement

type DeleteStatement struct {
	Only      bool
	TableName *TableName
	TableStar bool
	Alias     *Ident

	UsingList []*TableName

	Condition  Expr
	CursorName *Ident

	OutputExpressions *OutputNames
}

DeleteStatement see http://www.postgres.cn/docs/12/sql-delete.html

func (*DeleteStatement) String

func (s *DeleteStatement) String() string

String returns the string representation of the clause.

type Error

type Error struct {
	Pos Pos
	Msg string
}

Error represents a parse error.

func (Error) Error

func (e Error) Error() string

Error implements the error interface.

type Exists

type Exists struct {
	Not    bool
	Select *SelectStatement // select statement
}

func (*Exists) String

func (expr *Exists) String() string

String returns the string representation of the expression.

type Expr

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

func MustParseExprString

func MustParseExprString(s string) Expr

MustParseExprString parses s into an expression. Panic on error.

func ParseExprString

func ParseExprString(s string) (Expr, error)

ParseExprString parses s into an expression. Returns nil if s is blank.

func SplitExprTree

func SplitExprTree(expr Expr) []Expr

SplitExprTree splits apart expr so it is a list of all AND joined expressions. For example, the expression "A AND B AND (C OR (D AND E))" would be split into a list of "A", "B", "C OR (D AND E)".

type Exprs

type Exprs struct {
	Exprs []Expr // list of expressions
}

func (*Exprs) String

func (l *Exprs) String() string

String returns the string representation of the expression.

type FilterClause

type FilterClause struct {
	X Expr // filter expression
}

func (*FilterClause) String

func (c *FilterClause) String() string

String returns the string representation of the clause.

type Hint

type Hint struct {
	Value string
}

func (*Hint) String

func (h *Hint) String() string

String returns the string representation of the expression.

type Ident

type Ident struct {
	Name      string // identifier name
	Quoted    bool   // true if double quoted
	QuoteChar string // " for postgresql, ` for mysql, etc
}

func (*Ident) String

func (i *Ident) String() string

String returns the string representation of the expression.

type IndexedColumn

type IndexedColumn struct {
	X    Expr // column expression
	Asc  bool
	Desc bool
}

func (*IndexedColumn) String

func (c *IndexedColumn) String() string

String returns the string representation of the column.

type InsertStatement

type InsertStatement struct {
	TableName *TableName

	ColumnNames []*Ident
	Overriding  string

	DefaultValues bool
	Expressions   []*Exprs
	Query         *SelectStatement

	UpsertClause *UpsertClause

	OutputExpressions *OutputNames
}

InsertStatement see http://www.postgres.cn/docs/12/sql-insert.html

func (*InsertStatement) String

func (s *InsertStatement) String() string

String returns the string representation of the statement.

type JoinClause

type JoinClause struct {
	X          Source         // lhs source
	Operator   *JoinOperator  // join operator
	Y          Source         // rhs source
	Constraint JoinConstraint // join constraint
}

func (*JoinClause) String

func (c *JoinClause) String() string

String returns the string representation of the clause.

type JoinConstraint

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

JoinConstraint represents either an ON or USING join constraint.

type JoinOperator

type JoinOperator struct {
	Comma   bool
	Natural bool
	Left    bool
	Outer   bool
	Inner   bool
	Cross   bool
}

func (*JoinOperator) String

func (op *JoinOperator) String() string

String returns the string representation of the operator.

type Lexer

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

func NewLexer

func NewLexer(r io.Reader) *Lexer

func (*Lexer) Lex

func (l *Lexer) Lex() (pos Pos, token Token, lit string)

type Node

type Node interface {
	fmt.Stringer
	// contains filtered or unexported methods
}

type NullLit

type NullLit struct {
}

func (*NullLit) String

func (lit *NullLit) String() string

String returns the string representation of the expression.

type NumberLit

type NumberLit struct {
	Value string // literal value
}

func (*NumberLit) String

func (lit *NumberLit) String() string

String returns the string representation of the expression.

type OnConstraint

type OnConstraint struct {
	X Expr // constraint expression
}

func (*OnConstraint) String

func (c *OnConstraint) String() string

String returns the string representation of the constraint.

type OrderingTerm

type OrderingTerm struct {
	X Expr // ordering expression

	Asc  bool
	Desc bool

	NullsFirst bool
	NullsLast  bool
}

func (*OrderingTerm) String

func (t *OrderingTerm) String() string

String returns the string representation of the term.

type OutputNames

type OutputNames []*ResultColumn

func (OutputNames) String

func (on OutputNames) String() string

type ParenExpr

type ParenExpr struct {
	X Expr // parenthesized expression
}

func (*ParenExpr) String

func (expr *ParenExpr) String() string

String returns the string representation of the expression.

type ParenSource

type ParenSource struct {
	X     Source // nested source
	Alias *Ident // optional table alias (select source only)
}

func (*ParenSource) String

func (s *ParenSource) String() string

String returns the string representation of the source.

type Parser

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

Parser represents a SQL parser.

func NewParser

func NewParser(r io.Reader) *Parser

NewParser returns a new instance of Parser that reads from r.

func (*Parser) ParseExpr

func (p *Parser) ParseExpr() (expr Expr, err error)

func (*Parser) ParseStatement

func (p *Parser) ParseStatement() (stmt Statement, err error)

type Pos

type Pos struct {
	Offset int // offset, starting at 0
	Line   int // line number, starting at 1
	Column int // column number, starting at 1 (byte count)
}

func (Pos) IsValid

func (p Pos) IsValid() bool

IsValid returns true if p is non-zero.

func (Pos) String

func (p Pos) String() string

String returns a string representation of the position.

type QualifiedRef

type QualifiedRef struct {
	Table  *Ident // table name
	Star   bool
	Column *Ident // column name
}

func (*QualifiedRef) String

func (r *QualifiedRef) String() string

String returns the string representation of the expression.

type Range

type Range struct {
	X Expr // lhs expression
	Y Expr // rhs expression
}

func (*Range) String

func (r *Range) String() string

String returns the string representation of the expression.

type ResultColumn

type ResultColumn struct {
	Star  bool
	Expr  Expr   // column expression (may be "tbl.*")
	Alias *Ident // alias name
}

func (*ResultColumn) String

func (c *ResultColumn) String() string

String returns the string representation of the column.

type Scope

type Scope struct {
	Parent *Scope
	Source Source
}

Scope represents a context for name resolution. Names can be resolved at the current source or in parent scopes.

type SelectStatement

type SelectStatement struct {
	All      bool
	Distinct bool
	Columns  *OutputNames // list of result columns in the SELECT clause

	FromItems Source

	Condition Expr

	GroupingElements []Expr
	HavingCondition  Expr

	Union     bool
	UnionAll  bool
	Intersect bool
	Except    bool
	Compound  *SelectStatement // compounded SELECT statement

	OrderBy []*OrderingTerm // terms of ORDER BY clause

	Limit  Expr
	Fetch  Expr
	Offset Expr // offset expression

	Hint *Hint
}

SelectStatement see http://www.postgres.cn/docs/12/sql-select.html

func (*SelectStatement) String

func (s *SelectStatement) String() string

String returns the string representation of the statement.

type Source

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

Source represents a table or subquery.

func ResolveSource

func ResolveSource(root Source, name string) Source

ResolveSource returns a source with the given name. This can either be the table name or the alias for a source.

func SourceList

func SourceList(src Source) []Source

SourceList returns a list of scopes in the current scope.

func StatementSource

func StatementSource(stmt Statement) Source

StatementSource returns the root statement for a statement.

type Statement

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

type StringLit

type StringLit struct {
	Value string // literal value (without quotes)
}

func (*StringLit) String

func (lit *StringLit) String() string

String returns the string representation of the expression.

type TableName

type TableName struct {
	Name  *Ident // table name
	Alias *Ident // optional table alias
}

func (*TableName) String

func (n *TableName) String() string

String returns the string representation of the table name.

func (*TableName) TableName

func (n *TableName) TableName() string

TableName returns the name used to identify n. Returns the alias, if one is specified. Otherwise returns the name.

type Token

type Token int

Token is the set of lexical tokens of the Go programming language.

const (
	// Special tokens
	ILLEGAL Token = iota
	EOF
	COMMENT
	SPACE

	IDENT     // IDENT
	QIDENT    // "IDENT" or `IDENT`
	STRING    // 'string'
	BLOB      // ???
	FLOAT     // 123.45
	INTEGER   // 123
	MLCOMMENT // multiline comment
	NULL      // NULL
	TRUE      // true
	FALSE     // false
	BIND      //? or ?NNN or :VVV or @VVV or $VVV

	SEMI   // ;
	LP     // (
	RP     // )
	COMMA  // ,
	NE     // !=
	EQ     // =
	LE     // <=
	LG     // <>
	LT     // <
	GT     // >
	GE     // >=
	BITAND // &
	BITOR  // |
	BITNOT // !
	LSHIFT // <<
	RSHIFT // >>
	PLUS   // +
	MINUS  // -
	STAR   // *
	SLASH  // /
	REM    // %
	CONCAT // ||
	DOT    // .

	ABORT
	ACTION
	ADD
	AFTER
	AGG_COLUMN
	AGG_FUNCTION
	ALL
	ALTER
	ANALYZE
	AND
	AS
	ASC
	ASTERISK
	ATTACH
	AUTOINCREMENT
	BEFORE
	BEGIN
	BETWEEN
	BY
	CASCADE
	CASE
	CAST
	CHECK
	COLUMN
	COLUMNKW
	COMMIT
	CONFLICT
	CONSTRAINT
	CREATE
	CROSS
	CTIME_KW
	CURRENT
	CURRENT_TIME
	CURRENT_DATE
	CURRENT_TIMESTAMP
	DATABASE
	DEFAULT
	DEFERRABLE
	DEFERRED
	DELETE
	DESC
	DETACH
	DISTINCT
	DO
	DROP
	EACH
	ELSE
	END
	ESCAPE
	EXCEPT
	EXCLUDE
	EXCLUSIVE
	EXISTS
	EXPLAIN
	FAIL
	FILTER
	FIRST
	FOLLOWING
	FOR
	FOREIGN
	FROM
	FUNCTION
	GLOB
	GROUP
	GROUPS
	HAVING
	IF
	IF_NULL_ROW
	IGNORE
	IMMEDIATE
	IN
	INDEX
	INDEXED
	INITIALLY
	INNER
	INSERT
	INSTEAD
	INTERSECT
	INTO
	IS
	ISNOT
	ISNULL // TODO: REMOVE?
	JOIN
	KEY
	LAST
	LEFT
	LIKE
	LIMIT
	MATCH
	NATURAL
	NO
	NOT
	NOTBETWEEN
	NOTEXISTS
	NOTGLOB
	NOTHING
	NOTIN
	NOTLIKE
	NOTMATCH
	NOTNULL
	NOTREGEXP
	NULLS
	OF
	OFFSET
	ON
	ONLY
	OR
	ORDER
	OTHERS
	OUTER
	OVER
	OVERRIDING
	PARTITION
	PLAN
	PRAGMA
	PRECEDING
	PRIMARY
	QUERY
	RAISE
	RANGE
	RECURSIVE
	REFERENCES
	REGEXP
	REGISTER
	REINDEX
	RELEASE
	RENAME
	RESTRICT
	RETURNING
	ROLLBACK
	ROW
	ROWS
	SELECT
	SELECT_COLUMN
	SET
	SPAN
	SYSTEM
	TABLE
	TEMP
	THEN
	TIES
	TO
	TRANSACTION
	TRIGGER
	TRUTH
	UNBOUNDED
	UNION
	UNIQUE
	UPDATE
	USER
	USING
	VACUUM
	VALUE
	VALUES
	VARIABLE
	VECTOR
	VIEW
	VIRTUAL
	WHEN
	WHERE
	WINDOW
	WITH
	WITHOUT
	FETCH
	NEXT

	ANY // ???

)

The list of tokens.

func Lookup

func Lookup(ident string) Token

func (Token) IsBinaryOp

func (tok Token) IsBinaryOp() bool

func (Token) IsLiteral

func (tok Token) IsLiteral() bool

func (Token) Precedence

func (op Token) Precedence() int

func (Token) String

func (tok Token) String() string

type Type

type Type struct {
	Name      *Ident     // type name
	Lparen    Pos        // position of left paren (optional)
	Precision *NumberLit // precision (optional)
	Scale     *NumberLit // scale (optional)
	Rparen    Pos        // position of right paren (optional)
}

func (*Type) String

func (t *Type) String() string

String returns the string representation of the type.

type UnaryExpr

type UnaryExpr struct {
	Op Token // operation
	X  Expr  // target expression
}

func (*UnaryExpr) String

func (expr *UnaryExpr) String() string

String returns the string representation of the expression.

type UpdateStatement

type UpdateStatement struct {
	Only      bool
	TableName *TableName
	TableStar bool
	Alias     *Ident

	Assignments []*Assignment

	FromList []*TableName

	Condition  Expr
	CursorName *Ident

	OutputExpressions *OutputNames
}

UpdateStatement see http://www.postgres.cn/docs/12/sql-update.html

func (*UpdateStatement) String

func (s *UpdateStatement) String() string

String returns the string representation of the clause.

type UpsertClause

type UpsertClause struct {
	Columns   []*IndexedColumn // optional indexed column list
	WhereExpr Expr             // optional conditional expression

	DoNothing       bool          // position of NOTHING keyword after DO
	DoUpdate        bool          // position of UPDATE keyword after DO
	Assignments     []*Assignment // list of column assignments
	UpdateWhereExpr Expr          // optional conditional expression for DO UPDATE SET
}

func (*UpsertClause) String

func (c *UpsertClause) String() string

String returns the string representation of the clause.

type UsingConstraint

type UsingConstraint struct {
	Columns []*Ident // column list
}

func (*UsingConstraint) String

func (c *UsingConstraint) String() string

String returns the string representation of the constraint.

type VisitEndFunc

type VisitEndFunc func(Node) error

VisitEndFunc represents a function type that implements Visitor. Only executes on node exit.

func (VisitEndFunc) Visit

func (fn VisitEndFunc) Visit(node Node) (Visitor, error)

Visit is a no-op.

func (VisitEndFunc) VisitEnd

func (fn VisitEndFunc) VisitEnd(node Node) error

VisitEnd executes fn.

type VisitFunc

type VisitFunc func(Node) error

VisitFunc represents a function type that implements Visitor. Only executes on node entry.

func (VisitFunc) Visit

func (fn VisitFunc) Visit(node Node) (Visitor, error)

Visit executes fn. Walk visits node children if fn returns true.

func (VisitFunc) VisitEnd

func (fn VisitFunc) VisitEnd(node Node) error

VisitEnd is a no-op.

type Visitor

type Visitor interface {
	Visit(node Node) (w Visitor, err error)
	VisitEnd(node Node) error
}

A Visitor's Visit method is invoked for each node encountered by Walk. If the result visitor w is not nil, Walk visits each of the children of node with the visitor w, followed by a call of w.Visit(nil).

Jump to

Keyboard shortcuts

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