sqlparse

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package sqlparse lexes, parses, and validates the incoming SQL (SQLite syntax) and reports the external tables a query references, so the engine knows which data sources to fetch. It performs syntactic validation only; authoritative semantic validation happens when the query runs against the per-request SQLite database (see internal/localdb).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

type Error struct {
	Pos *Position
	Msg string
}

Error describes why a query failed to parse or validate. Pos points at the offending location when one is known (syntax errors and most validation errors), and is nil otherwise (e.g. an empty query).

func (*Error) Error

func (e *Error) Error() string

type Join

type Join struct {
	Type    JoinType
	Natural bool
	On      []Predicate // ON conjuncts (structured where possible); nil for USING/none
	Using   []string    // USING (col, …) columns; nil for ON/none
}

Join describes a join operator and its constraint.

type JoinType

type JoinType int

JoinType identifies the kind of join connecting two sources. It is an enum so downstream consumers switch on the named constants exhaustively rather than matching strings. The zero value is JoinInner.

const (
	JoinInner JoinType = iota // INNER / plain JOIN
	JoinLeft                  // LEFT [OUTER] JOIN
	JoinRight                 // RIGHT [OUTER] JOIN
	JoinFull                  // FULL [OUTER] JOIN
	JoinCross                 // CROSS JOIN
	JoinComma                 // implicit comma join
)

func (JoinType) String

func (j JoinType) String() string

type Limit

type Limit struct {
	Count  *Value
	Offset *Value
}

Limit is a LIMIT clause with an optional OFFSET. Count and Offset are the literal or bind values as written (use Count.Literal.AsInt() for the number).

type Literal

type Literal struct {
	Kind LiteralKind
	Raw  string // original source text (e.g. 21, 'paid', X'4142', CURRENT_TIMESTAMP)
	// Value is the parsed Go value matching Kind:
	//   LiteralInteger -> int64    LiteralFloat   -> float64
	//   LiteralString  -> string   LiteralBool    -> bool
	//   LiteralBlob    -> []byte   LiteralNull    -> nil
	//   LiteralKeyword -> string (the upper-cased keyword)
	//
	// Prefer the typed accessors (AsInt, AsString, …) over asserting Value.
	Value any
}

Literal is a typed SQL literal value.

func (*Literal) AsBlob

func (l *Literal) AsBlob() ([]byte, bool)

AsBlob returns the bytes when the literal is a blob.

func (*Literal) AsBool

func (l *Literal) AsBool() (bool, bool)

AsBool returns the value when the literal is a boolean.

func (*Literal) AsFloat

func (l *Literal) AsFloat() (float64, bool)

AsFloat returns the value when the literal is a float.

func (*Literal) AsInt

func (l *Literal) AsInt() (int64, bool)

AsInt returns the value when the literal is an integer.

func (*Literal) AsKeyword

func (l *Literal) AsKeyword() (string, bool)

AsKeyword returns the keyword when the literal is one of CURRENT_TIME, CURRENT_DATE, or CURRENT_TIMESTAMP.

func (*Literal) AsString

func (l *Literal) AsString() (string, bool)

AsString returns the value when the literal is a string.

func (*Literal) IsNull

func (l *Literal) IsNull() bool

IsNull reports whether the literal is SQL NULL.

type LiteralKind

type LiteralKind int

LiteralKind classifies a SQL literal so consumers switch on its type rather than reparsing text.

const (
	LiteralNull    LiteralKind = iota // NULL
	LiteralInteger                    // integer (incl. hex 0x…)
	LiteralFloat                      // floating point
	LiteralString                     // 'text'
	LiteralBool                       // TRUE / FALSE
	LiteralBlob                       // X'4142'
	LiteralKeyword                    // CURRENT_TIME / CURRENT_DATE / CURRENT_TIMESTAMP
)

func (LiteralKind) String

func (l LiteralKind) String() string

type Operator

type Operator int

Operator is a comparison operator in a structured predicate. It is an enum so downstream consumers (e.g. a push-down planner) handle the full closed set via an exhaustive switch rather than matching operator strings. The zero value, OpNone, means the predicate is not a structured comparison (only Raw applies).

const (
	OpNone Operator = iota // not a structured comparison

	OpEq    // =
	OpNotEq // <>
	OpLt    // <
	OpLte   // <=
	OpGt    // >
	OpGte   // >=

	OpLike      // LIKE
	OpNotLike   // NOT LIKE
	OpGlob      // GLOB
	OpNotGlob   // NOT GLOB
	OpRegexp    // REGEXP
	OpNotRegexp // NOT REGEXP
	OpMatch     // MATCH
	OpNotMatch  // NOT MATCH

	OpIs                // IS
	OpIsNot             // IS NOT
	OpIsDistinctFrom    // IS DISTINCT FROM
	OpIsNotDistinctFrom // IS NOT DISTINCT FROM
	OpIsNull            // IS NULL
	OpIsNotNull         // IS NOT NULL

	OpBetween    // BETWEEN (Values = [low, high])
	OpNotBetween // NOT BETWEEN (Values = [low, high])
	OpIn         // IN (Values = list)
	OpNotIn      // NOT IN (Values = list)
)

func (Operator) String

func (o Operator) String() string

String returns the SQL form of the operator (empty for OpNone).

type OrderTerm

type OrderTerm struct {
	Table  string
	Column string
	Expr   string
	Desc   bool
}

OrderTerm is one ORDER BY term. Column (with optional Table qualifier) is set for a simple column; otherwise Expr holds the raw text of the ordering expression. Desc is true for DESC, false for ASC/unspecified.

type Position

type Position struct {
	Line   int
	Column int
}

Position is a location in the source SQL. Line is 1-based and Column is 0-based, following ANTLR's convention.

type Predicate

type Predicate struct {
	Table  string // column's table qualifier ("" if unqualified)
	Column string
	Op     Operator
	Value  *Value  // single right-hand value (see above)
	Values []Value // multiple right-hand values: IN list, or BETWEEN [low, high]
	// RefTable/RefColumn hold the right-hand column when the comparison is
	// column-to-column (both Value and Values are nil).
	RefTable  string
	RefColumn string
	Raw       string // always set: original text of the conjunct
}

Predicate is one conjunct of a WHERE or ON clause. When Op != OpNone it is a structured comparison on "<Table>.<Column>" that may be pushable to a source. Otherwise only Raw is meaningful (the original text of the conjunct).

The right-hand side depends on Op:

  • single-value ops (=, <>, <, <=, >, >=, LIKE, GLOB, REGEXP, MATCH and their NOT forms, IS, IS NOT, IS [NOT] DISTINCT FROM): Value is set, Values nil.
  • IN / NOT IN: Values holds the list, Value nil.
  • BETWEEN / NOT BETWEEN: Values holds [low, high], Value nil.
  • IS NULL / IS NOT NULL: both Value and Values are nil.
  • column-to-column comparison (e.g. a join key "a.x = b.y"): RefTable/ RefColumn hold the right-hand column and Value/Values are nil.

type Projection

type Projection struct {
	Star   bool   // SELECT * (Table=="") or SELECT t.* (Table set)
	Table  string // qualifier for t.* or for a qualified column
	Column string // column name for a simple column projection
	Alias  string // AS alias, if any
	Expr   string // raw text for non-column expressions (e.g. COUNT(*))
}

Projection is one entry of the SELECT list.

type Query

type Query struct {
	// Raw is the original SQL, run verbatim against the local database later.
	Raw string
	// Tables are the external base tables the query references: referenced
	// tables minus CTE names and table-valued functions, deduped and sorted,
	// with identifiers unquoted.
	Tables []string
	// Columns are the column names the query references, deduped and sorted,
	// with identifiers unquoted. This is a flat set across the whole query;
	// mapping each column to a specific table is future work. SELECT * yields
	// no columns (the set of columns is not known syntactically).
	Columns []string
	// Stmt is the structured AST of the query, built for planning what to fetch
	// per source and which filters/projections can be pushed down. Tables and
	// Columns above are exhaustive flat views; Stmt models the query structure
	// (see ast.go for what is and isn't yet represented).
	Stmt *Select
}

Query is the validated result of parsing an incoming SQL statement.

func Parse

func Parse(raw string) (*Query, error)

Parse lexes, parses, and validates a single read-only SELECT statement and returns the external tables it references. Syntax errors, non-SELECT statements, and multiple statements yield an error.

func (*Query) SQL

func (q *Query) SQL() string

SQL renders the query back into a SQL string.

type Select

type Select struct {
	// Complete reports whether the AST fully represents the source query. It is
	// false when the parser dropped clauses the AST does not model (ORDER BY,
	// LIMIT, GROUP BY/HAVING, WINDOW, WITH/CTE, or a compound UNION/EXCEPT tail),
	// meaning SQL() reconstructs only part of the query and must not be treated
	// as an equivalent rewrite. The zero value (false) is the safe default.
	Complete    bool
	Distinct    bool
	Projections []Projection
	// From holds the FROM/JOIN sources in order. From[0] is the first source;
	// each later source From[i] is connected by Joins[i-1].
	From []Source
	// Joins[i] describes how From[i+1] joins the preceding sources.
	Joins []Join
	// Where holds the top-level AND-ed conjuncts of the WHERE clause.
	Where []Predicate
	// OrderBy holds the ORDER BY terms in order, empty if none.
	OrderBy []OrderTerm
	// Limit holds the LIMIT/OFFSET clause, nil if none.
	Limit *Limit
}

Select is the structured form of a single SELECT query.

func (*Select) SQL

func (s *Select) SQL() string

SQL renders the Select back into a SQL string. It reproduces only the modeled clauses; when Complete is false the result omits clauses that were present in the source query (see Select.Complete) and must not be treated as equivalent.

type Source

type Source struct {
	Schema   string  // optional schema qualifier (base tables only)
	Name     string  // base table name; empty for subquery / Raw sources
	Subquery *Select // non-nil when the source is a (SELECT …) subquery
	Alias    string  // empty when unaliased
	Raw      string  // original text for unmodeled sources (table functions, paren joins)
}

Source is a single FROM/JOIN source: a base table, a subquery, or a form dfetch does not model (table-valued function, parenthesized join), preserved in Raw.

func (Source) IsSubquery

func (s Source) IsSubquery() bool

IsSubquery reports whether the source is a derived table (subquery).

type Value

type Value struct {
	Kind    ValueKind
	Literal *Literal // set when Kind == ValueLiteral
	Bind    string   // bind parameter token (e.g. ?, :id, @x, $y) when Kind == ValueBind
}

Value is the right-hand side of a simple comparison predicate: either a typed literal or a bind parameter.

type ValueKind

type ValueKind int

ValueKind distinguishes a literal from a bind parameter. It is an enum so consumers switch on the named constants rather than matching strings.

const (
	ValueLiteral ValueKind = iota // a literal value (e.g. 5, 'abc')
	ValueBind                     // a bind parameter (e.g. ?, :id)
)

func (ValueKind) String

func (v ValueKind) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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