Documentation
¶
Overview ¶
Package sqlscope analyzes and rewrites SQL with scope awareness.
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) OutputColumns names of the columns a statement outputs ReferencedColumns columns referenced anywhere, per table ColumnUsages column references with the clause they appear in
Every function takes the same functional [Option]s; options that do not apply to a function are ignored.
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 ¶
- Constants
- Variables
- func ApplyRowFilter(sql, predicate string, opts ...Option) (string, error)
- func ColumnOrigins(sql string, opts ...Option) (map[string][]string, error)
- func InjectCTEs(sql string, ctes []CTEDef, opts ...Option) (string, error)
- func LibraryFileName() string
- func LibraryVersion() (string, error)
- func Load(path string) (err error)
- func OutputColumns(sql string, opts ...Option) ([]string, error)
- func ReferencedColumns(sql string, opts ...Option) (map[string][]string, error)
- func RewriteTables(sql string, rewrites []TableRewrite, opts ...Option) (string, error)
- type CTEDef
- type ColumnClause
- type ColumnUsage
- type Error
- type Kind
- type Option
- type TableRef
- type TableRewrite
- type UnionRewrite
Examples ¶
Constants ¶
const LibraryPathEnv = "SQLSCOPE_LIBRARY_PATH"
LibraryPathEnv names the environment variable that locates the sqlscope FFI library when Load is not given a path.
Variables ¶
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 ¶
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 ¶
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 ¶
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
LibraryVersion returns the version of the loaded sqlscope FFI library, loading it if needed.
func Load ¶ added in v0.2.0
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 ¶
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 ¶
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.
Types ¶
type CTEDef ¶
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 ¶
Error is returned by every sqlscope function. Use errors.Is with the sentinel errors, or inspect Kind.
func (*Error) UnmarshalJSON ¶
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 ¶
WithDefaultDB sets the schema used to resolve unqualified table references against schema-qualified WithTableNames entries (ApplyRowFilter).
func WithDialect ¶
WithDialect selects the SQL dialect ("trino", "postgres", "mysql", "starrocks", "spark", "hive", "snowflake", ...). The default is trino.
func WithSchema ¶
WithSchema supplies table schemas: table name -> ordered column names. Keys may be bare, schema- or catalog-qualified. 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 ¶
WithStripCatalogs makes RewriteTables treat the catalogs as transparent while matching: with WithStripCatalogs("hive"), hive.sales.orders matches the match key "sales.orders".
func WithTableNames ¶
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 ¶
WithTableRegexp restricts ApplyRowFilter to tables whose bare or fully qualified name matches any of the regular expressions.
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 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.