sqlscope

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sqlscope analyzes and rewrites SQL with scope awareness.

Transpile      convert Trino SQL to StarRocks or MySQL
ApplyRowFilter      filter every in-scope table by a predicate
InjectCTEs          prepend CTE definitions to a query's root WITH
RewriteTables       replace table references with other tables or derived tables
ColumnOrigins       source columns whose values reach the result (lineage)
OutputLineage       sources for each query output in projection order
OutputColumns       names of the columns a statement outputs
ReferencedColumns   columns referenced anywhere, per table
ColumnUsages        column references with the clause they appear in

Analysis and scoped rewriting functions share the functional [Option]s.

The SQL engine is the sqlscope FFI shared library (libsqlscope_ffi.so, libsqlscope_ffi.dylib or sqlscope_ffi.dll) published with each sqlscope release. The package loads it at runtime without cgo, so CGO_ENABLED=0 builds work; it neither bundles nor downloads the library. See Load for how the library is located. All functions are safe for concurrent use.

Index

Examples

Constants

View Source
const LibraryPathEnv = "SQLSCOPE_LIBRARY_PATH"

LibraryPathEnv names the environment variable that locates the sqlscope FFI library when Load is not given a path.

Variables

View Source
var (
	ErrInvalidArgument = errors.New("sqlscope: invalid argument")
	ErrParse           = errors.New("sqlscope: parse error")
	ErrUnsupported     = errors.New("sqlscope: unsupported")
	ErrInternal        = errors.New("sqlscope: internal error")
)

Sentinel errors for errors.Is.

Functions

func ApplyRowFilter

func ApplyRowFilter(sql, predicate string, opts ...Option) (string, error)

ApplyRowFilter wraps every in-scope physical table of a query in a derived table filtered by predicate:

SELECT * FROM a  ->  SELECT * FROM (SELECT * FROM a WHERE <predicate>) AS a

Filtering each table before it is joined keeps the filter correct across outer joins, CTEs, subqueries and set operations. The input must be one SELECT or set operation. predicate is parsed as one boolean expression and inserted into the AST; bind or escape its values before calling.

By default every physical table is filtered; WithTableNames, WithTableRegexp and WithDefaultDB restrict the scope. CTE references, table functions and the DUAL dummy table (Oracle, the MySQL family, Snowflake) are never wrapped. Output is regenerated (normalized, comments dropped) and verified to parse. When no table is in scope the input is returned unchanged.

Example
sql, err := sqlscope.ApplyRowFilter(
	`SELECT "uid" FROM accounts`,
	`"user" = 'alice'`,
	sqlscope.WithDialect("postgres"),
)
if err != nil {
	panic(err)
}
fmt.Println(sql)
Output:
SELECT "uid" FROM (SELECT * FROM accounts WHERE "user" = 'alice') AS accounts

func ColumnOrigins

func ColumnOrigins(sql string, opts ...Option) (map[string][]string, error)

ColumnOrigins returns the source columns whose values flow into the statement's result, keyed by root physical table, with sorted columns. Filter-only positions (WHERE, JOIN ON, GROUP BY, HAVING, ORDER BY) and the right side of INTERSECT / EXCEPT are excluded. Every table read is present, possibly with no columns. UPDATE and MERGE report their assigned values.

Example
cols, _ := sqlscope.ColumnOrigins(
	`SELECT o.id, p.amount FROM orders o JOIN payments p ON o.id = p.order_id WHERE o.status = 'PAID'`,
	sqlscope.WithSchema(map[string][]string{"orders": {"id", "status"}, "payments": {"order_id", "amount"}}),
)
fmt.Println(cols)
Output:
map[orders:[id] payments:[amount]]

func InjectCTEs

func InjectCTEs(sql string, ctes []CTEDef, opts ...Option) (string, error)

InjectCTEs adds CTE definitions to the root WITH clause of a query, before the CTEs it already declares. Definitions keep their order, so each may use earlier ones. A name that repeats another definition or an existing root CTE is rejected. An empty ctes slice returns sql unchanged.

Example
sql, _ := sqlscope.InjectCTEs(
	"SELECT id FROM recent_orders",
	[]sqlscope.CTEDef{{Name: "recent_orders", Query: "SELECT id FROM orders WHERE created_at >= DATE '2026-01-01'"}},
)
fmt.Println(sql)
Output:
WITH recent_orders AS (SELECT id FROM orders WHERE created_at >= CAST('2026-01-01' AS DATE)) SELECT id FROM recent_orders

func LibraryFileName added in v0.2.0

func LibraryFileName() string

LibraryFileName is the platform's file name of the sqlscope shared library: libsqlscope_ffi.so, libsqlscope_ffi.dylib or sqlscope_ffi.dll.

func LibraryVersion added in v0.2.0

func LibraryVersion() (string, error)

LibraryVersion returns the version of the loaded sqlscope FFI library, loading it if needed.

func Load added in v0.2.0

func Load(path string) (err error)

Load loads the sqlscope FFI library, the shared library published with each sqlscope release. With an empty path it tries, in order, the path in $SQLSCOPE_LIBRARY_PATH, LibraryFileName next to the executable, and LibraryFileName on the system library search path.

Load is optional: the first operation loads the library the same way. Calling it at startup selects the library explicitly and reports a missing library early. Once a library is loaded it stays loaded; loading a different path afterwards is an error.

func OutputColumns

func OutputColumns(sql string, opts ...Option) ([]string, error)

OutputColumns returns the names of the columns a statement outputs, in order. Unaliased expressions are named _col{i}; * expands from WithSchema or stays "*". An explicit column list on CREATE VIEW, CREATE TABLE or INSERT wins. It returns nil for statements without columns (DROP TABLE).

Example
cols, _ := sqlscope.OutputColumns("SELECT id, amount AS total FROM orders")
fmt.Println(cols)
Output:
[id total]

func ReferencedColumns

func ReferencedColumns(sql string, opts ...Option) (map[string][]string, error)

ReferencedColumns returns the columns referenced anywhere in a statement, filters included, keyed by root physical table, with sorted columns. It is a superset of ColumnOrigins and also accepts DELETE, UPDATE and MERGE. References that cannot be resolved precisely are attributed to every candidate table rather than dropped.

func RewriteTables

func RewriteTables(sql string, rewrites []TableRewrite, opts ...Option) (string, error)

RewriteTables replaces physical table references in a query according to rewrites. Matched references keep their alias, or their bare name when unaliased (disambiguated on collisions); qualified column and star references are rebound onto it. CTE references are never replaced. Catalogs given to WithStripCatalogs are transparent while matching. When nothing matches the input is returned unchanged.

func Transpile added in v0.7.0

func Transpile(sql, source, target string, mode TranspileMode) ([]string, error)

Transpile converts Trino SQL to starrocks or mysql, returning one string per statement.

Types

type CTEDef

type CTEDef struct {
	Name  string `json:"name"`
	Query string `json:"query"`
}

CTEDef is a common table expression "Name AS (Query)". Name is an identifier value, not SQL text; it is quoted as needed.

type ColumnClause

type ColumnClause string

ColumnClause is the SQL clause that contains a column reference.

const (
	ColumnClauseSelect          ColumnClause = "SELECT"
	ColumnClauseFrom            ColumnClause = "FROM"
	ColumnClauseJoinOn          ColumnClause = "JOIN_ON"
	ColumnClauseJoinUsing       ColumnClause = "JOIN_USING"
	ColumnClauseWhere           ColumnClause = "WHERE"
	ColumnClauseGroupBy         ColumnClause = "GROUP_BY"
	ColumnClauseHaving          ColumnClause = "HAVING"
	ColumnClauseQualify         ColumnClause = "QUALIFY"
	ColumnClauseWindow          ColumnClause = "WINDOW"
	ColumnClauseOrderBy         ColumnClause = "ORDER_BY"
	ColumnClauseSortBy          ColumnClause = "SORT_BY"
	ColumnClauseDistributeBy    ColumnClause = "DISTRIBUTE_BY"
	ColumnClauseClusterBy       ColumnClause = "CLUSTER_BY"
	ColumnClauseConnectBy       ColumnClause = "CONNECT_BY"
	ColumnClauseLateralView     ColumnClause = "LATERAL_VIEW"
	ColumnClauseUpdateSetTarget ColumnClause = "UPDATE_SET_TARGET"
	ColumnClauseUpdateSetValue  ColumnClause = "UPDATE_SET_VALUE"
	ColumnClauseMergeOn         ColumnClause = "MERGE_ON"
	ColumnClauseMergeWhen       ColumnClause = "MERGE_WHEN"
	ColumnClauseReturning       ColumnClause = "RETURNING"
)

type ColumnUsage

type ColumnUsage struct {
	Table  string       `json:"table"`
	Column string       `json:"column"`
	Clause ColumnClause `json:"clause"`
}

ColumnUsage is one distinct use of a root table column in a clause.

func ColumnUsages

func ColumnUsages(sql string, opts ...Option) ([]ColumnUsage, error)

ColumnUsages returns every distinct (table, column, clause) use in a statement, sorted by table, column and clause.

Example
usages, _ := sqlscope.ColumnUsages("SELECT id FROM orders WHERE status = 'PAID'")
for _, u := range usages {
	fmt.Println(u.Table, u.Column, u.Clause)
}
Output:
orders id SELECT
orders status WHERE

type Error

type Error struct {
	Kind    Kind
	Message string
}

Error is returned by every sqlscope function. Use errors.Is with the sentinel errors, or inspect Kind.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Is reports whether target is the sentinel for e's kind.

func (*Error) UnmarshalJSON

func (e *Error) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the library's error object.

type Kind

type Kind string

Kind classifies an Error.

const (
	// KindInvalidArgument: an option or argument is invalid.
	KindInvalidArgument Kind = "invalid_argument"
	// KindParse: the SQL text could not be parsed.
	KindParse Kind = "parse"
	// KindUnsupported: the statement shape is not supported, or the input
	// exceeded a safety limit.
	KindUnsupported Kind = "unsupported"
	// KindInternal: sqlscope produced an invalid result, or its library
	// could not be loaded.
	KindInternal Kind = "internal"
)

type Option

type Option func(*options)

Option configures a sqlscope call.

func WithDefaultDB

func WithDefaultDB(db string) Option

WithDefaultDB sets the schema used to resolve unqualified table references against schema-qualified WithTableNames entries (ApplyRowFilter).

func WithDialect

func WithDialect(dialect string) Option

WithDialect selects the SQL dialect ("trino", "postgres", "mysql", "starrocks", "spark", "hive", "snowflake", ...). The default is trino.

func WithSchema

func WithSchema(schema map[string][]string) Option

WithSchema supplies table schemas: table name -> ordered column names. Keys may be bare, schema- or catalog-qualified. Supply catalog names without SQL quote delimiters. Matching follows the dialect's case rules, so Trino matches S.A to s.a. The schema expands wildcards and attributes unqualified columns. A table listed with no columns has zero columns; an absent table is unknown.

Read by ColumnOrigins, OutputColumns, ReferencedColumns and ColumnUsages.

func WithStripCatalogs

func WithStripCatalogs(catalogs ...string) Option

WithStripCatalogs makes RewriteTables treat the catalogs as transparent while matching: with WithStripCatalogs("hive"), hive.sales.orders matches the match key "sales.orders".

func WithTableNames

func WithTableNames(names ...string) Option

WithTableNames restricts ApplyRowFilter to the named tables: bare ("orders"), schema-qualified ("sales.orders") or catalog-qualified ("iceberg.sales.orders"), matched case-insensitively. Composes additively with WithTableRegexp.

func WithTableRegexp

func WithTableRegexp(patterns ...string) Option

WithTableRegexp restricts ApplyRowFilter to tables whose bare or fully qualified name matches any of the regular expressions.

type OutputColumnLineage added in v0.8.0

type OutputColumnLineage struct {
	Name    string              `json:"name"`
	Sources map[string][]string `json:"sources"`
}

OutputColumnLineage groups one projected column's value sources by physical table.

func OutputLineage added in v0.8.0

func OutputLineage(sql string, opts ...Option) ([]OutputColumnLineage, error)

OutputLineage returns one entry per projection in order, or nil for statements without a query.

type TableRef

type TableRef struct {
	Catalog string `json:"catalog,omitempty"`
	Schema  string `json:"schema,omitempty"`
	Table   string `json:"table"`
}

TableRef is a table name, optionally schema- and catalog-qualified.

type TableRewrite

type TableRewrite struct {
	MatchKey string        `json:"matchKey"`
	Inline   *TableRef     `json:"inline,omitempty"`
	Union    *UnionRewrite `json:"union,omitempty"`
	Columns  []string      `json:"columns,omitempty"`
	Rename   *TableRef     `json:"rename,omitempty"`
}

TableRewrite replaces references to MatchKey ("schema.table"). Set exactly one of Inline, Union, or Rename. Columns lists identifier values for Inline; omitted or empty Columns selects *. Rename changes the table name directly.

type TranspileMode added in v0.7.0

type TranspileMode string

TranspileMode controls handling of recognized unsupported Trino constructs.

const (
	Strict     TranspileMode = "strict"
	BestEffort TranspileMode = "best_effort"
)

type UnionRewrite

type UnionRewrite struct {
	TableAlias string     `json:"tableAlias"`
	Columns    []string   `json:"columns"`
	Branches   []TableRef `json:"branches"`
}

UnionRewrite is a derived table backed by UNION DISTINCT over Branches. TableAlias is used for references without an alias of their own.

Jump to

Keyboard shortcuts

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