polyglot

package module
v0.5.4 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2026 License: MIT Imports: 9 Imported by: 0

README

Polyglot Go SDK

Official Go SDK for Polyglot SQL.

The SDK uses PureGo to call the polyglot-sql-ffi shared library without cgo. It does not download or bundle native libraries at runtime. Build or download the matching FFI library yourself and point the SDK at it.

Important: go get github.com/tobilg/polyglot/packages/go installs only the Go module. Runtime calls such as Transpile, Parse, ParseDataType, Validate, lineage, and OpenLineage generation require a separate polyglot-sql-ffi shared library (.so, .dylib, or .dll) that matches the SDK release version. Provide that library with Open(path) or POLYGLOT_SQL_FFI_PATH plus OpenDefault().

Install

go get github.com/tobilg/polyglot/packages/go

Go module releases use nested tags that match the root Polyglot release, for example packages/go/v0.5.0.

Native Library Setup

Build the shared library from this repository, or download the matching FFI artifact from the same Polyglot release as the Go SDK tag:

cargo build -p polyglot-sql-ffi --profile ffi_release

Then either open it explicitly:

client, err := polyglot.Open("../../target/ffi_release/libpolyglot_sql_ffi.so")

or set POLYGLOT_SQL_FFI_PATH and use OpenDefault:

export POLYGLOT_SQL_FFI_PATH="$PWD/target/ffi_release/libpolyglot_sql_ffi.so"

OpenDefault checks POLYGLOT_SQL_FFI_PATH first, then common local build locations relative to the current working directory, its parent, two levels up, and the executable directory. As a final fallback it asks the system loader to resolve the platform library name.

Library names by platform:

  • Linux: libpolyglot_sql_ffi.so
  • macOS: libpolyglot_sql_ffi.dylib
  • Windows: polyglot_sql_ffi.dll

Basic Usage

package main

import (
	"fmt"
	"log"

	polyglot "github.com/tobilg/polyglot/packages/go"
)

func main() {
	client, err := polyglot.OpenDefault()
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	sql, err := client.Transpile(
		"SELECT IFNULL(a, b) FROM t",
		"mysql",
		"postgres",
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(sql[0])
}

API Reference

The primary API is client-scoped. Package-level convenience functions mirror the operational calls and require an explicitly configured default client, as shown in Default Client.

Lifecycle and Versions
API Description
Open(path string) (*Client, error) Load a specific native FFI library.
OpenDefault() (*Client, error) Resolve and load the native FFI library from POLYGLOT_SQL_FFI_PATH, local candidates, or system loader lookup.
client.Close() error Release the loaded native library handle. Safe to call more than once.
Version() string Return the Go SDK version.
client.Version() string Return the Go SDK version.
client.RuntimeVersion() (string, error) Return the version reported by the loaded native FFI library.
RuntimeVersion() (string, error) Default-client wrapper for client.RuntimeVersion.
LibraryPathEnv Exported constant for the POLYGLOT_SQL_FFI_PATH environment variable name.
SQL Operations

These methods are available on *Client and as package-level wrappers:

API Description
Transpile(sql, fromDialect, toDialect string, options ...TranspileOptions) ([]string, error) Parse SQL in one dialect and generate SQL in another.
Format(sql, dialect string, options ...FormatOptions) ([]string, error) Format SQL for a dialect, with optional formatting guards.
Optimize(sql, dialect string, options ...OptimizeOptions) ([]string, error) Apply optimizer rewrites and return SQL.
Generate(ast json.RawMessage, dialect string, options ...GenerateOptions) ([]string, error) Generate SQL from a JSON AST returned by Parse or related APIs.
GenerateDataType(dataType json.RawMessage, dialect string) (string, error) Generate SQL from a JSON DataType returned by ParseDataType.
Validate(sql, dialect string) (ValidationResult, error) Validate SQL and return diagnostics as data when validation fails.
Dialects() ([]string, error) Return supported dialect names.
DialectCount() (int, error) Return the number of supported dialects.

An empty dialect string defaults to generic.

dialects, err := client.Dialects()
if err != nil {
	log.Fatal(err)
}

formatted, err := client.Format("SELECT a,b FROM t", "postgres")
if err != nil {
	log.Fatal(err)
}

optimized, err := client.Optimize("SELECT a FROM t WHERE NOT (NOT (b = 1))", "generic")
if err != nil {
	log.Fatal(err)
}

fmt.Println(len(dialects), formatted[0], optimized[0])
JSON AST APIs

These methods return json.RawMessage so applications can decode only the parts they need:

API Description
Parse(sql, dialect string) (json.RawMessage, error) Parse one or more SQL statements into a JSON AST array.
ParseOne(sql, dialect string) (json.RawMessage, error) Parse one SQL statement into a single JSON AST node.
ParseDataType(sql, dialect string) (json.RawMessage, error) Parse exactly one standalone SQL data type into a JSON DataType.
Tokenize(sql, dialect string) (json.RawMessage, error) Tokenize SQL and return token JSON.
AnnotateTypes(sql, dialect string, schema *ValidationSchema) (json.RawMessage, error) Parse SQL and annotate expression types, optionally using schema metadata.
Diff(sql1, sql2, dialect string) (json.RawMessage, error) Return an AST diff between two SQL strings.
ast, err := client.Parse("SELECT total FROM orders", "generic")
if err != nil {
	log.Fatal(err)
}

one, err := client.ParseOne("SELECT total FROM orders", "generic")
if err != nil {
	log.Fatal(err)
}

tokens, err := client.Tokenize("SELECT total FROM orders", "generic")
if err != nil {
	log.Fatal(err)
}

annotated, err := client.AnnotateTypes("SELECT total FROM orders", "generic", nil)
if err != nil {
	log.Fatal(err)
}

diff, err := client.Diff("SELECT a FROM t", "SELECT b FROM t", "generic")
if err != nil {
	log.Fatal(err)
}

fmt.Println(len(ast), len(one), len(tokens), len(annotated), len(diff))
Standalone Data Types

Data type parsing returns raw JSON because DataType is part of the AST model. Use GenerateDataType to render that JSON for a target dialect.

dataType, err := client.ParseDataType("DECIMAL(10, 2)", "duckdb")
if err != nil {
	log.Fatal(err)
}

sql, err := client.GenerateDataType(dataType, "postgres")
if err != nil {
	log.Fatal(err)
}
fmt.Println(sql) // DECIMAL(10, 2)
AST Transforms
API Description
QualifyTables(ast json.RawMessage, options QualifyTablesOptions) (json.RawMessage, error) Qualify table names and optionally generate stable aliases.
SetLimit(ast json.RawMessage, limit int) (json.RawMessage, error) Set LIMIT on a select or set-operation AST.
SetOffset(ast json.RawMessage, offset int) (json.RawMessage, error) Set OFFSET on a select or set-operation AST.
SetOrderBy(ast json.RawMessage, orderBy json.RawMessage) (json.RawMessage, error) Set ORDER BY on a select or set-operation AST. orderBy is a JSON array of expression nodes.
RenameTables(ast json.RawMessage, mapping map[string]string, options RenameTablesOptions) (json.RawMessage, error) Rename table references in a JSON AST.
ast, err := client.Parse("SELECT a FROM old_table", "generic")
if err != nil {
	log.Fatal(err)
}

qualified, err := client.QualifyTables(ast, polyglot.QualifyTablesOptions{
	Dialect: "generic",
	DB:      "analytics",
})
if err != nil {
	log.Fatal(err)
}

renamed, err := client.RenameTables(
	qualified,
	map[string]string{"old_table": "new_table"},
	polyglot.RenameTablesOptions{},
)
if err != nil {
	log.Fatal(err)
}

sql, err := client.Generate(renamed, "generic")
if err != nil {
	log.Fatal(err)
}
fmt.Println(sql[0])
ast, _ := client.Parse("SELECT id FROM a UNION ALL SELECT id FROM b", "generic")
ast, _ = client.SetLimit(ast, 100)
ast, _ = client.SetOffset(ast, 10)
ast, _ = client.SetOrderBy(ast, json.RawMessage(
	`[{"column":{"name":{"name":"id","quoted":false},"table":null,"join_mark":false,"trailing_comments":[]}}]`,
))
Lineage
API Description
Lineage(column, sql, dialect string) (LineageNode, error) Return a lineage tree for a selected output column.
LineageWithSchema(column, sql string, schema ValidationSchema, dialect string) (LineageNode, error) Return lineage using schema metadata for improved resolution.
SourceTables(column, sql, dialect string) ([]string, error) Return source table names for a selected output column.
AnalyzeQuery(sql string, options AnalyzeQueryOptions) (QueryAnalysis, error) Return compact projection, visible relation, transitive base-table, CTE, set-operation, and upstream-reference facts.
node, err := client.Lineage("total", "SELECT o.total FROM orders o", "generic")
if err != nil {
	log.Fatal(err)
}

tables, err := client.SourceTables("total", "SELECT o.total FROM orders o", "generic")
if err != nil {
	log.Fatal(err)
}
fmt.Println(node.Name, tables)
nullable := true
nonNull := false

schema := polyglot.ValidationSchema{
	Tables: []polyglot.SchemaTable{
		{
			Name: "orders",
			Columns: []polyglot.SchemaColumn{
				{Name: "id", Type: "INT", Nullable: &nonNull},
				{Name: "amount", Type: "DECIMAL(10,2)", Nullable: &nullable},
			},
		},
	},
}

analysis, err := client.AnalyzeQuery(
	"WITH base AS (SELECT id, amount FROM orders) SELECT * FROM base",
	polyglot.AnalyzeQueryOptions{
		Dialect: "generic",
		Schema:  &schema,
	},
)
if err != nil {
	log.Fatal(err)
}
fmt.Println(analysis.CTEFacts[0].BodySQL)                 // SELECT id, amount FROM orders
fmt.Println(analysis.StarProjections[0].ExpandedColumns)  // [id amount]
fmt.Println(analysis.Projections[0].Nullability)          // non_null
fmt.Println(analysis.BaseTables[0].Name)                  // orders

LineageNode.SourceKind identifies whether a source is a real table, CTE, derived table, virtual source, or unknown. LineageNode.SourceAlias is set for physical table aliases such as orders AS o and virtual sources such as BigQuery UNNEST(...) AS alias.

For AnalyzeQuery, Relations reports sources visible in the analyzed scope. BaseTables reports deduplicated physical table dependencies across nested CTEs, derived tables, subqueries, and set-operation branches. Schema-aware validation uses broad type families, while query analysis preserves parseable detailed schema type strings for projection TypeHint values. CTEFacts reports top-level CTE definitions, StarProjections records original star projections and schema-expanded columns, and ProjectionFact.Nullability is one of non_null, nullable, or unknown.

OpenLineage
API Description
OpenLineageColumnLineage(sql string, options OpenLineageOptions) (OpenLineageColumnLineageResult, error) Build a standalone OpenLineage-compatible columnLineage dataset facet plus inferred datasets.
OpenLineageJobEvent(sql string, options OpenLineageOptions) (OpenLineageEventResult, error) Build an OpenLineage-compatible job event payload.
OpenLineageRunEvent(sql string, options OpenLineageOptions) (OpenLineageEventResult, error) Build an OpenLineage-compatible run event payload.

The SDK builds OpenLineage-compatible payloads only. Transport and client emission are intentionally out of scope.

options := polyglot.OpenLineageOptions{
	Dialect:          "generic",
	Producer:         "https://github.com/tobilg/polyglot",
	DatasetNamespace: "warehouse",
	OutputDataset: &polyglot.OpenLineageDatasetID{
		Namespace: "warehouse",
		Name:      "daily_orders",
	},
}

columnLineage, err := client.OpenLineageColumnLineage("SELECT total FROM orders", options)
if err != nil {
	log.Fatal(err)
}

options.JobNamespace = "jobs"
options.JobName = "daily_orders"
options.EventTime = "2026-05-22T00:00:00Z"
jobEvent, err := client.OpenLineageJobEvent("SELECT total FROM orders", options)
if err != nil {
	log.Fatal(err)
}

options.RunID = "run-1"
options.EventType = polyglot.OpenLineageRunEventComplete
runEvent, err := client.OpenLineageRunEvent("SELECT total FROM orders", options)
if err != nil {
	log.Fatal(err)
}

fmt.Println(columnLineage.Facet.Fields, jobEvent.Event, runEvent.Event)
Options and Result Types
Type Fields
TranspileOptions Pretty, UnsupportedLevel, MaxUnsupported
UnsupportedLevel UnsupportedIgnore, UnsupportedWarn, UnsupportedRaise, UnsupportedImmediate
FormatOptions MaxInputBytes, MaxTokens, MaxASTNodes, MaxSetOpChain
OptimizeOptions Reserved for future optimizer options.
GenerateOptions Reserved for future generator options.
AnalyzeQueryOptions Dialect, Schema
QueryAnalysis Shape, CTEs, CTEFacts, Projections, Relations, BaseTables, StarProjections, SetOperations
ProjectionFact Index, Name, IsStar, StarTable, TransformKind, TransformFunction, CastType, TypeHint, Nullability, Upstream
TransformFunctionFact Name, LiteralArgs, ColumnArgs
CTEFact Name, Columns, BodySQL, OutputColumns
StarProjectionFact Index, Table, ExpandedColumns
ColumnReferenceFact SourceName, SourceAlias, SourceKind, Table, Column, Unqualified, Confidence
RelationFact Name, Alias, Kind, Columns, Catalog, Schema, Table
SetOperationFact Kind, All, Distinct, OutputColumns, Branches
ValidationResult Valid, Errors
ValidationError Message, Line, Column, Severity, Code, Start, End
ValidationSchema Tables, Strict
SchemaTable Name, Schema, Columns, Aliases, PrimaryKey, UniqueKeys, ForeignKeys
SchemaColumn Name, Type, Nullable, PrimaryKey, Unique, References
SchemaForeignKey Name, Columns, References
SchemaColumnReference Table, Column, Schema
SchemaTableReference Table, Columns, Schema

ValidationSchema serializes to the same JSON payload used by Rust, Python, FFI, and TypeScript:

{
  "strict": true,
  "tables": [
    {
      "name": "orders",
      "schema": "analytics",
      "aliases": ["o"],
      "primaryKey": ["id"],
      "uniqueKeys": [["external_id"]],
      "foreignKeys": [
        {
          "columns": ["customer_id"],
          "references": { "table": "customers", "columns": ["id"] }
        }
      ],
      "columns": [
        { "name": "id", "type": "INT", "nullable": false, "primaryKey": true },
        { "name": "amount", "type": "DECIMAL(10,2)", "nullable": true }
      ]
    }
  ]
}

Use the type JSON key for column types. dataType / data_type are not accepted aliases in this payload. | LineageNode | Name, Expression, Source, Downstream, SourceName, SourceKind, SourceAlias, ReferenceNodeName | | QualifyTablesOptions | DB, Catalog, Dialect, CanonicalizeTableAliases, AliasUnaliasedTables, AliasUnaliasedSubqueries, AliasPrefix, NormalizeSetOperationSubqueries | | RenameTablesOptions | AliasRenamedTables, PreserveExistingAliases | | OpenLineageOptions | Dialect, Producer, DatasetNamespace, DatasetMappings, OutputDataset, Schema, JobNamespace, JobName, EventTime, RunID, EventType | | OpenLineageDatasetID | Namespace, Name | | OpenLineageColumnLineageResult | Facet, Inputs, Outputs, Warnings | | OpenLineageEventResult | Event, Warnings | | OpenLineageWarning | Code, Message | | OpenLineageDataset | Namespace, Name, Facets | | OpenLineageColumnLineageFacet | Producer, SchemaURL, Fields | | OpenLineageColumnLineageField | InputFields | | OpenLineageInputField | Namespace, Name, Field, Transformations | | OpenLineageTransformation | Type, Subtype, Description, Masking |

OpenLineageRunEventType constants are OpenLineageRunEventStart, OpenLineageRunEventRunning, OpenLineageRunEventComplete, OpenLineageRunEventAbort, OpenLineageRunEventFail, and OpenLineageRunEventOther.

Validation

Invalid SQL is returned as validation data, not as a Go error, when the native call succeeds:

result, err := client.Validate("SELECT FROM", "generic")
if err != nil {
	log.Fatal(err)
}
fmt.Println(result.Valid)
fmt.Println(result.Errors)

Go errors are reserved for missing libraries, missing symbols, invalid option JSON, FFI failures, and lifecycle misuse.

Error Handling

The SDK exposes ErrClosed, ErrNoDefaultClient, and *polyglot.Error. *polyglot.Error includes the native FFI status code, operation name, and message.

_, err := client.Transpile("SELECT FROM", "generic", "postgres")
if err != nil {
	var ffiErr *polyglot.Error
	if errors.As(err, &ffiErr) {
		fmt.Println(ffiErr.Operation, ffiErr.Status, ffiErr.Message)
	}
}

Raw JSON APIs

AST-heavy APIs return json.RawMessage so applications can decode only the parts they need:

ast, err := client.Parse("SELECT a FROM t", "generic")
if err != nil {
	log.Fatal(err)
}

sql, err := client.Generate(ast, "generic")
if err != nil {
	log.Fatal(err)
}
fmt.Println(sql[0])

Schema Metadata

Schema metadata is used by validation, type annotation, lineage, and OpenLineage helpers:

nullable := false
schema := polyglot.ValidationSchema{
	Tables: []polyglot.SchemaTable{
		{
			Name: "orders",
			Columns: []polyglot.SchemaColumn{
				{Name: "id", Type: "INT", PrimaryKey: true, Nullable: &nullable},
				{Name: "total", Type: "DECIMAL"},
			},
		},
	},
}

annotated, err := client.AnnotateTypes("SELECT total FROM orders", "generic", &schema)
if err != nil {
	log.Fatal(err)
}

lineage, err := client.LineageWithSchema("total", "SELECT total FROM orders", schema, "generic")
if err != nil {
	log.Fatal(err)
}

fmt.Println(len(annotated), lineage.Name)

Default Client

Package-level convenience functions use only an explicitly configured default client:

API Description
SetDefaultClient(client *Client) Configure the process-wide default client used by package-level wrappers.
ClearDefaultClient() Remove the configured default client.
DefaultClient() (*Client, error) Return the configured default client or ErrNoDefaultClient.
client, err := polyglot.OpenDefault()
if err != nil {
	log.Fatal(err)
}
defer client.Close()

polyglot.SetDefaultClient(client)
sql, err := polyglot.Transpile("SELECT 1", "postgres", "postgres")
if err != nil {
	log.Fatal(err)
}
fmt.Println(sql[0])

If no default client is configured, package-level functions return ErrNoDefaultClient instead of panicking.

Documentation

Overview

Package polyglot is the official Go SDK for Polyglot SQL.

The SDK loads the polyglot-sql-ffi shared library at runtime through PureGo, so callers can keep CGO_ENABLED=0. It does not download or bundle native libraries; provide the shared library path with Open or POLYGLOT_SQL_FFI_PATH.

Index

Constants

View Source
const LibraryPathEnv = "POLYGLOT_SQL_FFI_PATH"

Variables

View Source
var (
	ErrClosed          = errors.New("polyglot: client is closed")
	ErrNoDefaultClient = errors.New("polyglot: default client is not configured")
)

Functions

func AnnotateTypes

func AnnotateTypes(sql, dialect string, schema *ValidationSchema) (json.RawMessage, error)

func ClearDefaultClient

func ClearDefaultClient()

func DialectCount

func DialectCount() (int, error)

func Dialects

func Dialects() ([]string, error)

func Diff

func Diff(sql1, sql2, dialect string) (json.RawMessage, error)

func Format

func Format(sql, dialect string, options ...FormatOptions) ([]string, error)

func Generate

func Generate(ast json.RawMessage, dialect string, options ...GenerateOptions) ([]string, error)

func GenerateDataType added in v0.5.1

func GenerateDataType(dataType json.RawMessage, dialect string) (string, error)

func Optimize

func Optimize(sql, dialect string, options ...OptimizeOptions) ([]string, error)

func Parse

func Parse(sql, dialect string) (json.RawMessage, error)

func ParseDataType added in v0.5.1

func ParseDataType(sql, dialect string) (json.RawMessage, error)

func ParseOne

func ParseOne(sql, dialect string) (json.RawMessage, error)

func QualifyTables

func QualifyTables(ast json.RawMessage, options QualifyTablesOptions) (json.RawMessage, error)

func RenameTables

func RenameTables(ast json.RawMessage, mapping map[string]string, options RenameTablesOptions) (json.RawMessage, error)

func RuntimeVersion

func RuntimeVersion() (string, error)

func SetDefaultClient

func SetDefaultClient(client *Client)

func SetLimit added in v0.5.4

func SetLimit(ast json.RawMessage, limit int) (json.RawMessage, error)

func SetOffset added in v0.5.4

func SetOffset(ast json.RawMessage, offset int) (json.RawMessage, error)

func SetOrderBy added in v0.5.4

func SetOrderBy(ast json.RawMessage, orderBy json.RawMessage) (json.RawMessage, error)

func SourceTables

func SourceTables(column, sql, dialect string) ([]string, error)

func Tokenize

func Tokenize(sql, dialect string) (json.RawMessage, error)

func Transpile

func Transpile(sql, fromDialect, toDialect string, options ...TranspileOptions) ([]string, error)

func Version

func Version() string

Types

type AnalyzeQueryOptions added in v0.5.1

type AnalyzeQueryOptions struct {
	Dialect string            `json:"dialect,omitempty"`
	Schema  *ValidationSchema `json:"schema,omitempty"`
}

type CTEFact added in v0.5.3

type CTEFact struct {
	Name          string   `json:"name"`
	Columns       []string `json:"columns"`
	BodySQL       string   `json:"bodySql"`
	OutputColumns []string `json:"outputColumns"`
}

type Client

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

func DefaultClient

func DefaultClient() (*Client, error)

func Open

func Open(path string) (*Client, error)

func OpenDefault

func OpenDefault() (*Client, error)

func (*Client) AnalyzeQuery added in v0.5.1

func (c *Client) AnalyzeQuery(sql string, options AnalyzeQueryOptions) (QueryAnalysis, error)

func (*Client) AnnotateTypes

func (c *Client) AnnotateTypes(sql, dialect string, schema *ValidationSchema) (json.RawMessage, error)

func (*Client) Close

func (c *Client) Close() error

func (*Client) DialectCount

func (c *Client) DialectCount() (int, error)

func (*Client) Dialects

func (c *Client) Dialects() ([]string, error)

func (*Client) Diff

func (c *Client) Diff(sql1, sql2, dialect string) (json.RawMessage, error)

func (*Client) Format

func (c *Client) Format(sql, dialect string, options ...FormatOptions) ([]string, error)

func (*Client) Generate

func (c *Client) Generate(ast json.RawMessage, dialect string, options ...GenerateOptions) ([]string, error)

func (*Client) GenerateDataType added in v0.5.1

func (c *Client) GenerateDataType(dataType json.RawMessage, dialect string) (string, error)

func (*Client) Lineage

func (c *Client) Lineage(column, sql, dialect string) (LineageNode, error)

func (*Client) LineageWithSchema

func (c *Client) LineageWithSchema(column, sql string, schema ValidationSchema, dialect string) (LineageNode, error)

func (*Client) OpenLineageColumnLineage

func (c *Client) OpenLineageColumnLineage(sql string, options OpenLineageOptions) (OpenLineageColumnLineageResult, error)

func (*Client) OpenLineageJobEvent

func (c *Client) OpenLineageJobEvent(sql string, options OpenLineageOptions) (OpenLineageEventResult, error)

func (*Client) OpenLineageRunEvent

func (c *Client) OpenLineageRunEvent(sql string, options OpenLineageOptions) (OpenLineageEventResult, error)

func (*Client) Optimize

func (c *Client) Optimize(sql, dialect string, options ...OptimizeOptions) ([]string, error)

func (*Client) Parse

func (c *Client) Parse(sql, dialect string) (json.RawMessage, error)

func (*Client) ParseDataType added in v0.5.1

func (c *Client) ParseDataType(sql, dialect string) (json.RawMessage, error)

func (*Client) ParseOne

func (c *Client) ParseOne(sql, dialect string) (json.RawMessage, error)

func (*Client) QualifyTables

func (c *Client) QualifyTables(ast json.RawMessage, options QualifyTablesOptions) (json.RawMessage, error)

func (*Client) RenameTables

func (c *Client) RenameTables(ast json.RawMessage, mapping map[string]string, options RenameTablesOptions) (json.RawMessage, error)

func (*Client) RuntimeVersion

func (c *Client) RuntimeVersion() (string, error)

func (*Client) SetLimit added in v0.5.4

func (c *Client) SetLimit(ast json.RawMessage, limit int) (json.RawMessage, error)

func (*Client) SetOffset added in v0.5.4

func (c *Client) SetOffset(ast json.RawMessage, offset int) (json.RawMessage, error)

func (*Client) SetOrderBy added in v0.5.4

func (c *Client) SetOrderBy(ast json.RawMessage, orderBy json.RawMessage) (json.RawMessage, error)

func (*Client) SourceTables

func (c *Client) SourceTables(column, sql, dialect string) ([]string, error)

func (*Client) Tokenize

func (c *Client) Tokenize(sql, dialect string) (json.RawMessage, error)

func (*Client) Transpile

func (c *Client) Transpile(sql, fromDialect, toDialect string, options ...TranspileOptions) ([]string, error)

func (*Client) Validate

func (c *Client) Validate(sql, dialect string) (ValidationResult, error)

func (*Client) Version

func (c *Client) Version() string

type ColumnReferenceFact added in v0.5.1

type ColumnReferenceFact struct {
	SourceName  *string `json:"sourceName"`
	SourceAlias *string `json:"sourceAlias"`
	SourceKind  string  `json:"sourceKind"`
	Table       *string `json:"table"`
	Column      string  `json:"column"`
	Unqualified bool    `json:"unqualified"`
	Confidence  string  `json:"confidence"`
}

type Error

type Error struct {
	Operation string
	Status    int32
	Message   string
}

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

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

type FormatOptions

type FormatOptions struct {
	MaxInputBytes *int `json:"maxInputBytes,omitempty"`
	MaxTokens     *int `json:"maxTokens,omitempty"`
	MaxASTNodes   *int `json:"maxAstNodes,omitempty"`
	MaxSetOpChain *int `json:"maxSetOpChain,omitempty"`
}

type GenerateOptions

type GenerateOptions struct{}

type LineageNode

type LineageNode struct {
	Name              string          `json:"name"`
	Expression        json.RawMessage `json:"expression"`
	Source            json.RawMessage `json:"source"`
	Downstream        []LineageNode   `json:"downstream"`
	SourceName        string          `json:"source_name"`
	SourceKind        string          `json:"source_kind"`
	SourceAlias       *string         `json:"source_alias,omitempty"`
	ReferenceNodeName string          `json:"reference_node_name"`
}

func Lineage

func Lineage(column, sql, dialect string) (LineageNode, error)

func LineageWithSchema

func LineageWithSchema(column, sql string, schema ValidationSchema, dialect string) (LineageNode, error)

type OpenLineageColumnLineageFacet

type OpenLineageColumnLineageFacet struct {
	Producer  string                                   `json:"_producer"`
	SchemaURL string                                   `json:"_schemaURL"`
	Fields    map[string]OpenLineageColumnLineageField `json:"fields"`
}

type OpenLineageColumnLineageField

type OpenLineageColumnLineageField struct {
	InputFields []OpenLineageInputField `json:"inputFields"`
}

type OpenLineageColumnLineageResult

type OpenLineageColumnLineageResult struct {
	Facet    OpenLineageColumnLineageFacet `json:"facet"`
	Inputs   []OpenLineageDataset          `json:"inputs"`
	Outputs  []OpenLineageDataset          `json:"outputs"`
	Warnings []OpenLineageWarning          `json:"warnings"`
}

func OpenLineageColumnLineage

func OpenLineageColumnLineage(sql string, options OpenLineageOptions) (OpenLineageColumnLineageResult, error)

type OpenLineageDataset

type OpenLineageDataset struct {
	Namespace string                     `json:"namespace"`
	Name      string                     `json:"name"`
	Facets    map[string]json.RawMessage `json:"facets,omitempty"`
}

type OpenLineageDatasetID

type OpenLineageDatasetID struct {
	Namespace string `json:"namespace"`
	Name      string `json:"name"`
}

type OpenLineageEventResult

type OpenLineageEventResult struct {
	Event    json.RawMessage      `json:"event"`
	Warnings []OpenLineageWarning `json:"warnings"`
}

func OpenLineageJobEvent

func OpenLineageJobEvent(sql string, options OpenLineageOptions) (OpenLineageEventResult, error)

func OpenLineageRunEvent

func OpenLineageRunEvent(sql string, options OpenLineageOptions) (OpenLineageEventResult, error)

type OpenLineageInputField

type OpenLineageInputField struct {
	Namespace       string                      `json:"namespace"`
	Name            string                      `json:"name"`
	Field           string                      `json:"field"`
	Transformations []OpenLineageTransformation `json:"transformations,omitempty"`
}

type OpenLineageOptions

type OpenLineageOptions struct {
	Dialect          string                          `json:"dialect,omitempty"`
	Producer         string                          `json:"producer"`
	DatasetNamespace string                          `json:"datasetNamespace,omitempty"`
	DatasetMappings  map[string]OpenLineageDatasetID `json:"datasetMappings"`
	OutputDataset    *OpenLineageDatasetID           `json:"outputDataset,omitempty"`
	Schema           *ValidationSchema               `json:"schema,omitempty"`
	JobNamespace     string                          `json:"jobNamespace,omitempty"`
	JobName          string                          `json:"jobName,omitempty"`
	EventTime        string                          `json:"eventTime,omitempty"`
	RunID            string                          `json:"runId,omitempty"`
	EventType        OpenLineageRunEventType         `json:"eventType,omitempty"`
}

type OpenLineageRunEventType

type OpenLineageRunEventType string
const (
	OpenLineageRunEventStart    OpenLineageRunEventType = "START"
	OpenLineageRunEventRunning  OpenLineageRunEventType = "RUNNING"
	OpenLineageRunEventComplete OpenLineageRunEventType = "COMPLETE"
	OpenLineageRunEventAbort    OpenLineageRunEventType = "ABORT"
	OpenLineageRunEventFail     OpenLineageRunEventType = "FAIL"
	OpenLineageRunEventOther    OpenLineageRunEventType = "OTHER"
)

type OpenLineageTransformation

type OpenLineageTransformation struct {
	Type        string `json:"type"`
	Subtype     string `json:"subtype"`
	Description string `json:"description,omitempty"`
	Masking     *bool  `json:"masking,omitempty"`
}

type OpenLineageWarning

type OpenLineageWarning struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

type OptimizeOptions

type OptimizeOptions struct{}

type ProjectionFact added in v0.5.1

type ProjectionFact struct {
	Index             int                    `json:"index"`
	Name              *string                `json:"name"`
	IsStar            bool                   `json:"isStar"`
	StarTable         *string                `json:"starTable"`
	TransformKind     string                 `json:"transformKind"`
	TransformFunction *TransformFunctionFact `json:"transformFunction,omitempty"`
	CastType          *string                `json:"castType"`
	TypeHint          *string                `json:"typeHint"`
	Nullability       string                 `json:"nullability"`
	Upstream          []ColumnReferenceFact  `json:"upstream"`
}

type QualifyTablesOptions

type QualifyTablesOptions struct {
	DB                              string `json:"db,omitempty"`
	Catalog                         string `json:"catalog,omitempty"`
	Dialect                         string `json:"dialect,omitempty"`
	CanonicalizeTableAliases        *bool  `json:"canonicalizeTableAliases,omitempty"`
	AliasUnaliasedTables            *bool  `json:"aliasUnaliasedTables,omitempty"`
	AliasUnaliasedSubqueries        *bool  `json:"aliasUnaliasedSubqueries,omitempty"`
	AliasPrefix                     string `json:"aliasPrefix,omitempty"`
	NormalizeSetOperationSubqueries *bool  `json:"normalizeSetOperationSubqueries,omitempty"`
}

type QueryAnalysis added in v0.5.1

type QueryAnalysis struct {
	Shape           string               `json:"shape"`
	CTEs            []string             `json:"ctes"`
	CTEFacts        []CTEFact            `json:"cteFacts"`
	Projections     []ProjectionFact     `json:"projections"`
	Relations       []RelationFact       `json:"relations"`
	BaseTables      []RelationFact       `json:"baseTables"`
	StarProjections []StarProjectionFact `json:"starProjections"`
	SetOperations   []SetOperationFact   `json:"setOperations"`
}

func AnalyzeQuery added in v0.5.1

func AnalyzeQuery(sql string, options AnalyzeQueryOptions) (QueryAnalysis, error)

type RelationFact added in v0.5.1

type RelationFact struct {
	Name    string   `json:"name"`
	Alias   *string  `json:"alias"`
	Kind    string   `json:"kind"`
	Columns []string `json:"columns"`
	Catalog *string  `json:"catalog"`
	Schema  *string  `json:"schema"`
	Table   *string  `json:"table"`
}

type RenameTablesOptions

type RenameTablesOptions struct {
	AliasRenamedTables      *bool `json:"aliasRenamedTables,omitempty"`
	PreserveExistingAliases *bool `json:"preserveExistingAliases,omitempty"`
}

type SchemaColumn

type SchemaColumn struct {
	Name       string                 `json:"name"`
	Type       string                 `json:"type,omitempty"`
	Nullable   *bool                  `json:"nullable,omitempty"`
	PrimaryKey bool                   `json:"primaryKey,omitempty"`
	Unique     bool                   `json:"unique,omitempty"`
	References *SchemaColumnReference `json:"references,omitempty"`
}

type SchemaColumnReference

type SchemaColumnReference struct {
	Table  string `json:"table"`
	Column string `json:"column"`
	Schema string `json:"schema,omitempty"`
}

type SchemaForeignKey

type SchemaForeignKey struct {
	Name       string               `json:"name,omitempty"`
	Columns    []string             `json:"columns"`
	References SchemaTableReference `json:"references"`
}

type SchemaTable

type SchemaTable struct {
	Name        string             `json:"name"`
	Schema      string             `json:"schema,omitempty"`
	Columns     []SchemaColumn     `json:"columns"`
	Aliases     []string           `json:"aliases,omitempty"`
	PrimaryKey  []string           `json:"primaryKey,omitempty"`
	UniqueKeys  [][]string         `json:"uniqueKeys,omitempty"`
	ForeignKeys []SchemaForeignKey `json:"foreignKeys,omitempty"`
}

type SchemaTableReference

type SchemaTableReference struct {
	Table   string   `json:"table"`
	Columns []string `json:"columns"`
	Schema  string   `json:"schema,omitempty"`
}

type SetOperationBranchFact added in v0.5.1

type SetOperationBranchFact struct {
	Index       int              `json:"index"`
	Projections []ProjectionFact `json:"projections"`
}

type SetOperationFact added in v0.5.1

type SetOperationFact struct {
	Kind          string                   `json:"kind"`
	All           bool                     `json:"all"`
	Distinct      bool                     `json:"distinct"`
	OutputColumns []string                 `json:"outputColumns"`
	Branches      []SetOperationBranchFact `json:"branches"`
}

type StarProjectionFact added in v0.5.3

type StarProjectionFact struct {
	Index           int      `json:"index"`
	Table           *string  `json:"table"`
	ExpandedColumns []string `json:"expandedColumns"`
}

type TransformFunctionFact added in v0.5.4

type TransformFunctionFact struct {
	Name        string                `json:"name"`
	LiteralArgs []string              `json:"literalArgs"`
	ColumnArgs  []ColumnReferenceFact `json:"columnArgs"`
}

type TranspileOptions

type TranspileOptions struct {
	Pretty           bool             `json:"pretty,omitempty"`
	UnsupportedLevel UnsupportedLevel `json:"unsupportedLevel,omitempty"`
	MaxUnsupported   int              `json:"maxUnsupported,omitempty"`
}

type UnsupportedLevel added in v0.5.0

type UnsupportedLevel string
const (
	UnsupportedIgnore    UnsupportedLevel = "ignore"
	UnsupportedWarn      UnsupportedLevel = "warn"
	UnsupportedRaise     UnsupportedLevel = "raise"
	UnsupportedImmediate UnsupportedLevel = "immediate"
)

type ValidationError

type ValidationError struct {
	Message  string `json:"message"`
	Line     *int   `json:"line,omitempty"`
	Column   *int   `json:"column,omitempty"`
	Severity string `json:"severity"`
	Code     string `json:"code"`
	Start    *int   `json:"start,omitempty"`
	End      *int   `json:"end,omitempty"`
}

type ValidationResult

type ValidationResult struct {
	Valid  bool              `json:"valid"`
	Errors []ValidationError `json:"errors"`
}

func Validate

func Validate(sql, dialect string) (ValidationResult, error)

type ValidationSchema

type ValidationSchema struct {
	Tables []SchemaTable `json:"tables"`
	Strict *bool         `json:"strict,omitempty"`
}

Directories

Path Synopsis
internal
ffi

Jump to

Keyboard shortcuts

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