Help us shape the future of Go! Take the 2026 Go Developer Survey

sqlparser

package
v0.55.0 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package sqlparser contains SQL parsing functionality for SQLite.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyEdits

func ApplyEdits(input string, edits []Edit) (string, error)

ApplyEdits returns input with each edit's [Start:End) range replaced by its Replacement. Edits may be supplied in any order; they are applied in reverse start order so pre-edit offsets remain valid throughout.

Returns an error if any edit has End < Start, any range falls outside [0, len(input)], two edits overlap, or two edits share the same Start (which would make the relative apply order ambiguous when one or both is an insertion, since sort.Slice is not stable on equal Start values).

func BuildTrigger added in v0.55.0

func BuildTrigger(name, tblName, ddl string) (*metadata.Trigger, error)

BuildTrigger constructs a metadata.Trigger from its raw parts, shared by the sqlite3 and rqlite drivers (rqlite mirrors the sqlite3 inspect path). ddl is parsed via ExtractTriggerTimingEvents for timing (BEFORE/AFTER/INSTEAD OF) and firing events (INSERT/UPDATE/DELETE).

The returned trigger is always populated with the raw ddl as its Definition, even on parse failure: a non-nil error means the structured Timing/Events could not be derived and were left empty, but the caller should still surface the trigger (with its raw definition) rather than drop it. Trigger.Enabled stays nil; SQLite has no enabled/disabled concept. Callers log the error at debug with their own driver prefix.

func ExtractColumnDDLInfo added in v0.55.0

func ExtractColumnDDLInfo(stmt string) (map[string]ColumnDDLInfo, error)

ExtractColumnDDLInfo parses a CREATE TABLE statement and returns a map keyed by unquoted column name carrying the best-effort, DDL-only column attributes (AUTOINCREMENT and generated-column expression). Columns with no such attributes are omitted from the map.

Returns an error if stmt cannot be parsed; callers should fall back to leaving these fields at their zero values.

func ExtractTriggerTimingEvents added in v0.55.0

func ExtractTriggerTimingEvents(stmt string) (timing string, events []string, err error)

ExtractTriggerTimingEvents parses a CREATE TRIGGER statement and returns its timing ("BEFORE", "AFTER", or "INSTEAD OF"; empty if none was declared) and its firing events (a subset of "INSERT", "UPDATE", "DELETE"). A SQLite trigger fires on exactly one event, so events usually has a single element, but the slice form matches the cross-driver metadata model.

Returns an error if stmt cannot be parsed as a CREATE TRIGGER statement; callers should fall back to leaving Timing/Events empty and keeping the raw trigger DDL.

func RewriteCreateIndexStmt

func RewriteCreateIndexStmt(stmt, newIndexIdent, newTableIdent string) (string, error)

RewriteCreateIndexStmt rewrites a CREATE INDEX statement (as read from sqlite_master) so that it applies to a different table. The index's own identifier, including any schema qualifier, is replaced with newIndexIdent, and the ON <table> target is replaced with newTableIdent.

Both replacement arguments must be pre-rendered SQL identifier text (i.e. already quoted as needed). newIndexIdent may carry a schema qualifier (`"sch"."idx_copy"`); newTableIdent must be a bare table identifier because SQLite's CREATE INDEX ... ON clause does not accept a schema qualifier (the table is resolved in the index's own schema).

Column references in the indexed-column list and in a partial index's WHERE clause are left untouched: SQLite does not permit table-qualified references there, so they cannot name the source table.

func RewriteCreateTriggerStmt

func RewriteCreateTriggerStmt(stmt, newTriggerIdent, newTableIdent string) (string, error)

RewriteCreateTriggerStmt rewrites a CREATE TRIGGER statement (as read from sqlite_master) so that it applies to a different table. The trigger's own identifier, including any schema qualifier, is replaced with newTriggerIdent. The ON <table> target, and every table-name position in the trigger body that names the same table (case-insensitively), are replaced with newTableIdent; body references to other tables are left untouched. This mirrors the self-FK rewrite semantics of CopyTable: the copied trigger operates on the copied table, while cross-table references (e.g. inserts into an audit table) continue to point at their original targets.

Both replacement arguments must be pre-rendered SQL identifier text (i.e. already quoted as needed). newTriggerIdent may carry a schema qualifier (`"sch"."trg_copy"`); newTableIdent must be a bare table identifier because SQLite's CREATE TRIGGER ... ON clause does not accept a schema qualifier (the table is resolved in the trigger's own schema).

Types

type CheckClause added in v0.55.0

type CheckClause struct {
	// Name is the constraint name, or empty if the CHECK was declared
	// without a CONSTRAINT <name> prefix (the common case in SQLite).
	Name string

	// Clause is the raw CHECK expression text, with quotes/whitespace
	// preserved as in the source DDL. It does not include the enclosing
	// parentheses or the CHECK keyword.
	Clause string
}

CheckClause is a single CHECK constraint extracted from a CREATE TABLE statement. SQLite rarely names CHECK constraints, so Name is usually empty (it is only set when the DDL uses the CONSTRAINT <name> CHECK form). Clause is the raw expression text as it appeared between the CHECK parentheses, e.g. "price > 0".

func ExtractCheckConstraints added in v0.55.0

func ExtractCheckConstraints(stmt string) ([]CheckClause, error)

ExtractCheckConstraints returns one CheckClause per CHECK constraint declared in a CREATE TABLE statement, in source order. Both column-level (`price INTEGER CHECK (price > 0)`) and table-level (`CHECK (price > discount)`) forms are returned. A nil slice (and nil error) is returned when the statement has no CHECK constraints.

Returns an error if stmt cannot be parsed as a CREATE TABLE statement; callers should fall back to leaving the structured Clause empty and keeping any raw DDL.

type ColDef

type ColDef struct {
	// DefCtx is the antlr context for the column definition.
	DefCtx *sqlite.Column_defContext

	// Raw is the raw text of the entire column definition.
	Raw string

	// RawName is the raw text of the column name as it appeared in the input.
	// It may be quoted using any of SQLite's four legal identifier-quoting
	// styles: double-quote, single-quote, backtick, or square brackets.
	RawName string

	// Name is the column name, stripped of any of SQLite's four legal
	// identifier-quoting styles: double-quote ("name"), single-quote ('name'),
	// backtick (`name`), and square brackets ([name]).
	Name string

	// RawType is the raw text of the column type as it appeared in the input.
	RawType string

	// Type is the canonicalized column type.
	Type string

	// InputOffset is the byte offset of the column definition (Raw) in the
	// input. The def ends at InputOffset+len(Raw).
	InputOffset int

	// RawNameOffset is the byte offset of RawName in the input. The name
	// token ends at RawNameOffset+len(RawName). Used by drivers to splice
	// rewrites at exact positions without relying on substring matching.
	RawNameOffset int

	// RawTypeOffset is the byte offset of RawType in the input. The type
	// token ends at RawTypeOffset+len(RawType). Used by drivers to splice
	// rewrites at exact positions without relying on substring matching.
	RawTypeOffset int
}

ColDef represents a column definition in a CREATE TABLE statement.

func ExtractCreateTableStmtColDefs

func ExtractCreateTableStmtColDefs(stmt string) ([]*ColDef, error)

ExtractCreateTableStmtColDefs extracts the column definitions from a CREATE TABLE statement.

func (*ColDef) String

func (cd *ColDef) String() string

String returns the raw text of the column definition.

type ColumnDDLInfo added in v0.55.0

type ColumnDDLInfo struct {
	// GeneratedExpr is the raw expression text of a GENERATED ALWAYS AS
	// (expr) / AS (expr) column, without the enclosing parentheses. Empty
	// for non-generated columns.
	GeneratedExpr string

	// AutoIncrement reports whether the column carries the AUTOINCREMENT
	// keyword (only legal on an INTEGER PRIMARY KEY column).
	AutoIncrement bool
}

ColumnDDLInfo carries the best-effort, DDL-only column attributes that SQLite does not expose via pragma: whether a column is declared INTEGER PRIMARY KEY AUTOINCREMENT, and the generated-column expression text. The generated flag itself is sourced from pragma_table_xinfo by the driver; only the expression requires the DDL.

type Edit

type Edit struct {
	// Replacement is the text to splice in place of input[Start:End].
	Replacement string

	// Start is the byte offset where the replacement begins (inclusive).
	Start int

	// End is the byte offset where the replacement ends (exclusive).
	// End must be >= Start.
	End int
}

Edit describes a single non-overlapping byte-range replacement within an input string. Used by ApplyEdits to splice multiple parser-derived rewrites into a CREATE TABLE statement.

type ForeignTableRef

type ForeignTableRef struct {
	// RawTable is the raw text of the referenced table token as it appeared
	// in the input, preserving any of SQLite's four legal identifier-quote
	// styles (double-quote, single-quote, backtick, square brackets).
	RawTable string

	// Table is the referenced table name with quotes stripped. Always
	// non-empty.
	Table string

	// TableOffset is the byte offset of RawTable in the input. The token
	// ends at TableOffset+len(RawTable).
	TableOffset int
}

ForeignTableRef describes a single REFERENCES <table> occurrence inside a CREATE TABLE statement's foreign-key clauses, with the byte offset of the table token in the original input. Both the column-constraint form (`col INTEGER REFERENCES other(id)`) and the table-constraint form (`FOREIGN KEY(col) REFERENCES other(id)`) funnel through the same foreign_table grammar rule, so both produce ForeignTableRef entries.

Returned by value (not pointer) because the struct is small, logically immutable after extraction, and used read-only by callers.

func ExtractForeignTableRefsFromCreateTableStmt

func ExtractForeignTableRefsFromCreateTableStmt(stmt string) ([]ForeignTableRef, error)

ExtractForeignTableRefsFromCreateTableStmt returns one ForeignTableRef per REFERENCES <table> occurrence in a CREATE TABLE statement. Refs are returned in source order. A nil slice (and nil error) is returned when the statement has no foreign-key clauses.

func (ForeignTableRef) String

func (r ForeignTableRef) String() string

String returns the raw text of the foreign-table reference.

type TableIdent

type TableIdent struct {
	// Schema is the table's schema, with any of SQLite's four legal
	// identifier-quoting styles (double-quote, single-quote, backtick,
	// square brackets) stripped. Empty if no schema part was present.
	Schema string

	// Table is the table name, with any of SQLite's four legal
	// identifier-quoting styles stripped. Always non-empty.
	Table string

	// RawSchema is the raw text of the schema token as it appeared in the
	// input, preserving any surrounding quotes. Empty if no schema part was
	// present.
	RawSchema string

	// RawTable is the raw text of the table token as it appeared in the
	// input, preserving any surrounding quotes.
	RawTable string

	// SchemaOffset is the byte offset of RawSchema in the input.
	// -1 if no schema part was present.
	SchemaOffset int

	// TableOffset is the byte offset of RawTable in the input.
	TableOffset int
}

TableIdent holds an extracted table identifier from a CREATE TABLE statement, including the byte offsets of the schema and table tokens in the original input.

func ExtractTableIdentFromCreateTableStmt

func ExtractTableIdentFromCreateTableStmt(stmt string) (*TableIdent, error)

ExtractTableIdentFromCreateTableStmt extracts the table identifier (schema, table, and the byte offsets of each token in the input) from a CREATE TABLE statement.

CREATE TABLE "sakila"."actor" ( actor_id INTEGER NOT NULL)
--> &TableIdent{Schema:"sakila", Table:"actor", RawSchema:`"sakila"`,
                RawTable:`"actor"`, SchemaOffset:13, TableOffset:22}

Returns an error if no table identifier can be extracted.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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