executequery

package module
v0.2.20260510 Latest Latest
Warning

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

Go to latest
Published: May 10, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

README

go-googlesql-executequery

A Go-native port of upstream google/googlesql's execute_query tool, built on top of go-googlesql (pure-Go GoogleSQL bindings via wazero — no cgo).

This repository ships:

  • execute_query — a CLI binary that mirrors the upstream flag surface.
  • executequery — an exported Go package usable as a library.
  • executequery/cache — a small helper that resolves a safe, per-user, per-go-googlesql-version wazero compilation-cache directory.

Status

go-googlesql only exposes parser and analyzer functionality; its compiled googlesql.wasm does not yet ship a reference evaluator or a Resolved-AST → SQL builder. As a result this port supports three of the upstream tool's six modes today:

Mode Status
parse supported
unparse supported
analyze supported
unanalyze not supported (no SQLBuilder exposed by go-googlesql)
explain not supported (no reference evaluator exposed by go-googlesql)
execute not supported (no reference evaluator exposed by go-googlesql)

Every upstream execute_query flag is recognised by the CLI; flags that depend on the unsupported modes return a structured error rather than flag provided but not defined. The Go source-code declaration of each unsupported flag carries a comment explaining what it does in upstream, why it cannot be honoured today, and what change unblocks it.

Versioning

Releases use v<go-googlesql-Major.Minor>.<YYYYMMDD>, with date carry-over on collision. See RELEASING.md.

Quick start

mise install                       # installs Go and golangci-lint
git submodule update --init        # populates third_party/googlesql
mise run build                     # produces bin/execute_query

bin/execute_query --mode=parse 'SELECT 1+1'
bin/execute_query --mode=analyze --catalog=tpch 'SELECT count(*) FROM Orders'
bin/execute_query --catalog=tpch 'DESCRIBE Orders'

mise run ci runs lint, tests, and build.

Library

import (
    "context"
    "os"

    "github.com/apstndb/go-googlesql-executequery"
    "github.com/apstndb/go-googlesql-executequery/cache"
)

func main() {
    if err := cache.Setup(); err != nil {
        panic(err)
    }
    cfg := executequery.Config{Modes: []executequery.Mode{executequery.ModeAnalyze}}
    if err := executequery.Run(context.Background(), "SELECT 1+1",
        cfg, executequery.NewTextWriter(os.Stdout)); err != nil {
        panic(err)
    }
}

License

Apache-2.0. See LICENSE and NOTICE. This is a derivative work of google/googlesql (Apache-2.0); upstream files referenced under third_party/googlesql/ are imported via a git submodule pinned to a specific commit.

Documentation

Overview

Package executequery is a Go-native port of upstream google/googlesql's execute_query tool, layered on top of go-googlesql (pure-Go GoogleSQL bindings via wazero).

Today it supports the parse, unparse, and analyze tool modes; the unanalyze, explain, and execute modes are recognised at the CLI surface but return ErrUnsupportedMode because go-googlesql does not yet expose SQLBuilder or a reference evaluator. See AGENTS.md for the full feature matrix.

Proto binding architecture

go-googlesql exposes two kinds of generated Go types:

  1. Handle types (e.g. LanguageOptions, AnalyzerOptions, ResolvedNode) thin wrappers around a uint64 pointer to a C++ object living inside the WASM runtime.
  2. Message types (suffixed *Proto, e.g. LanguageOptionsProto) wrappers around C++ google::protobuf::Message objects generated by protoc-gen-cpp on the upstream side.

Because the C++ side is compiled with protoc-gen-cpp output, every *Proto type carries the standard protobuf wire-format methods ParseFromString and SerializeToString (inherited from MessageLite). This means any *Proto value can be exchanged with an idiomatic protoc-gen-go struct built from the same .proto definition, simply by passing wire-format bytes through the WASM boundary.

We already exploit this pattern in two places:

1. catalog/sample_proto.go — wire-format shunt for descriptors:

	descriptorpb.FileDescriptorProto (protoc-gen-go)
	      | proto.Marshal
	      v
	[]byte wire
	      | ParseFromString(string(wire))
	      v
	googlesql.FileDescriptorProto (protoc-gen-wasmify-go)
	      | pool.BuildFile(wfdp)
	      v
	*googlesql.FileDescriptor   (C++ object inside WASM)

 2. enabledfeatures.go / enabledrewrites.go — protoreflect for
    enum metadata.  go-googlesql does not expose enum-descriptor
    iterators (no LanguageFeature_descriptor()->value_count()), so
    zz_enums.go mirrors the enum tables by hand.  But the
    *annotations* on each enum value (e.g. `in_development` options)
    *are* available through the protoc-gen-go copy of options.proto:
    File_googlesql_public_options_proto.Enums().ByName(...).
    This lets us read proto extensions from the standard Go struct
    and match them to go-googlesql enum values by name rather than
    by numeric value (which would be fragile because the wasm
    binding renumbers enums).

What is blocked by missing Serialize/Deserialize

The bridge only becomes useful when a Handle type exposes a method that converts to (or from) its matching *Proto type. Many important handles lack this, which prevents us from using protoc-gen-go structs to drive the API:

Handle type           Missing method                Impact
--------------------  ----------------------------  ------------------------------------------
AnalyzerOptions       Deserialize(proto)            Cannot load analyzer settings from JSON/YAML/proto
ASTNode (parse tree)  Serialize(proto)              Cannot emit AST as JSON/textproto (--output_mode)
ResolvedNode          Serialize(proto)              Cannot emit resolved AST as JSON/textproto
Value (evaluator)     Serialize(valueProto)         Cannot emit execute results as JSON/textproto
PreparedQuery         (entire type not exported)    execute / explain modes are impossible

If go-googlesql ever adds those methods, the missing features above could be implemented almost entirely with standard protoc-gen-go types plus the existing wire-format shunt, without any new wasm-side work.

Code generated by hack/gen-enums.sh from go-googlesql v0.2.1; DO NOT EDIT.

Workaround [go-googlesql v0.2.1]: there is no runtime accessor that enumerates the LanguageFeature / ResolvedASTRewrite enum values, so the FeatureSet / RewriteSet flag parsers cannot iterate "every known enum value" without help.

Upstream C++ API: protobuf-generated enum descriptor accessors

  • googlesql::LanguageFeature_descriptor()->value_count() / value(i)
  • googlesql::ResolvedASTRewrite_descriptor()->value_count() / value(i)

declared by protoc-gen-cpp from the enum definitions in third_party/googlesql/googlesql/public/options.proto (enum LanguageFeature is at line 119; enum ResolvedASTRewrite is in the same file).

Natural Go code:

for i := int32(0); i < googlesql.LanguageFeatureValuesCount(); i++ {
    f := googlesql.LanguageFeatureValue(i)
    ...
}

Instead, this generated file mirrors the enum tables out of go-googlesql's source via hack/gen-enums.sh. Regenerate after bumping the go-googlesql module version. Unblocked when go-googlesql binds the protobuf enum-descriptor iterators (or exports a curated "all values" slice).

Index

Constants

View Source
const ReasonFlagDescriptorPool = "" +
	"--descriptor_pool requires wasm-boundary descriptor-pool plumbing, which go-googlesql does not expose"

ReasonFlagDescriptorPool: upstream's `--descriptor_pool` selects the proto descriptor pool used to resolve proto types (`generated` = the C++ generated pool; `none` = no proto types).

Why unsupported: the C++ generated pool relies on protoc-compiled types linked into the upstream binary. Crossing the wasm boundary requires extra plumbing in go-googlesql to register Go proto descriptors with the wasm runtime.

Unblocked when: go-googlesql exposes a way to register a Go (protoreflect / google.golang.org/protobuf) descriptor pool with the wasm runtime.

View Source
const ReasonFlagEvaluatorMaxIntermediate = "" +
	"--evaluator_max_intermediate_byte_size only affects the execute mode, which is not supported"

ReasonFlagEvaluatorMaxIntermediate: upstream's `--evaluator_max_intermediate_byte_size` caps accumulated row memory in execute mode.

Why unsupported: evaluator-only flag.

View Source
const ReasonFlagEvaluatorMaxValue = "" +
	"--evaluator_max_value_byte_size only affects the execute mode, which is not supported"

ReasonFlagEvaluatorMaxValue: upstream's `--evaluator_max_value_byte_size` caps per-Value memory in execute mode.

Why unsupported: evaluator-only flag.

View Source
const ReasonFlagEvaluatorScramble = "" +
	"--evaluator_scramble_undefined_orderings only affects the execute mode, which is not supported"

ReasonFlagEvaluatorScramble: upstream's `--evaluator_scramble_undefined_orderings` shuffles unordered intermediate results in execute mode (a determinism-canary).

Why unsupported: evaluator-only flag.

View Source
const ReasonFlagImportPath = "" +
	"--import_path requires ModuleFactory, which go-googlesql does not expose"

ReasonFlagImportPath: upstream's `--import_path` adds directories to search for IMPORT MODULE.

Why unsupported: go-googlesql does not expose ModuleFactory, so resolution of IMPORT MODULE statements cannot be wired through.

Unblocked when: go-googlesql exposes ModuleFactory.

View Source
const ReasonFlagMaxStatementsToExecute = "" +
	"--max_statements_to_execute caps script execution, which is not supported"

ReasonFlagMaxStatementsToExecute: upstream's `--max_statements_to_execute` caps statements executed in script mode.

Why unsupported: script execution requires the reference evaluator. Script parsing and per-statement analysis are supported, but no execution count is meaningful.

View Source
const ReasonFlagOutputMode = "" +
	"--output_mode is execute-only; AST/Resolved Serialize is not exposed by go-googlesql"

ReasonFlagOutputMode: upstream's `--output_mode` controls execute-mode result rendering (box / json / textproto).

Why unsupported: the parse / analyze modes use upstream's own DebugString text format. Emitting AST or Resolved nodes as textproto / json would require Serialize(*Proto) on the AST and Resolved node types, which go-googlesql does not expose.

Note on the proto path: the C++ side inside the wasm module was built with protoc-gen-cpp, so every *Proto type there already implements google::protobuf::Message and can exchange wire-format bytes with a protoc-gen-go struct of the same definition. If go-googlesql exposed Serialize() on AST / Resolved handles, the resulting *Proto wire bytes could be fed straight into google.golang.org/protobuf/protojson.Marshal or prototext.Marshal to produce JSON / textproto output with no hand-written visitor. The only missing link is the Handle -> Proto conversion method on the wasm side.

Unblocked when: go-googlesql exposes Serialize on AST and Resolved node types (or the project commits to an in-process visitor implementation, which is significant work).

View Source
const ReasonFlagPort = "" +
	"--port only affects --web, which is not implemented"

ReasonFlagPort: upstream's `--port` selects the local HTTP port for `--web`.

Why unsupported: tied to --web.

View Source
const ReasonFlagTableSpec = "" +
	"--table_spec attaches data to tables for execute mode, which is not supported"

ReasonFlagTableSpec: upstream's `--table_spec` registers tables from CSV / binproto / textproto files for execute mode to query.

Why unsupported: row data is only meaningful for execute mode, which is unsupported.

View Source
const ReasonFlagTargetSyntax = "" +
	"--target_syntax only affects the unanalyze mode, which is not supported"

ReasonFlagTargetSyntax: upstream's `--target_syntax` selects the SQL dialect produced by the unanalyze mode (`standard` or `pipe`).

Why unsupported: only meaningful for unanalyze, which is itself unsupported (see ReasonModeUnanalyze).

View Source
const ReasonFlagUseBoxGlyphs = "" +
	"--use_box_glyphs only affects the execute-mode result table, which is not supported"

ReasonFlagUseBoxGlyphs: upstream's `--use_box_glyphs` toggles Unicode box characters in resolved-AST and result-table output.

Why unsupported: the result-table renderer is execute-only, and the resolved-AST output we emit (via DebugString) is upstream's own ASCII-only rendering — there is no glyph choice to make.

View Source
const ReasonFlagWeb = "" +
	"--web is not implemented in this Go port (and would have limited value without execute mode)"

ReasonFlagWeb: upstream's `--web` runs a local HTTP server with a query-and-execute UI.

Why unsupported: without execute mode the UI loses its primary utility; not currently planned for this Go port.

View Source
const ReasonModeExecute = "" +
	"the execute mode requires the reference evaluator, which go-googlesql does not expose"

ReasonModeExecute: upstream's `execute` mode runs the statement through the reference implementation's evaluator and renders rows.

Why unsupported: same as ReasonModeExplain — the reference evaluator is not exposed by go-googlesql.

Unblocked when: go-googlesql exposes PreparedQuery / PreparedStatement (or equivalent execution primitives).

View Source
const ReasonModeExplain = "" +
	"the explain mode requires the reference evaluator, which go-googlesql does not expose"

ReasonModeExplain: upstream's `explain` mode prints the reference implementation's evaluator query plan for a resolved statement.

Why unsupported: go-googlesql does not export the reference evaluator (no PreparedQuery / PreparedStatement / Evaluator constructors are public).

Unblocked when: go-googlesql exposes the reference evaluator (or at least its plan-string output).

View Source
const ReasonModeUnanalyze = "" +
	"the unanalyze mode (Resolved AST → SQL via SQLBuilder) is not exposed by go-googlesql"

ReasonModeUnanalyze: upstream's `unanalyze` (alias `sql_builder`) converts a Resolved AST back to SQL via SQLBuilder, with optional dialect selection through `--target_syntax`.

Why unsupported: go-googlesql does not export SQLBuilder or any other Resolved → SQL function.

Unblocked when: go-googlesql exposes a Resolved → SQL builder (tracked at: TBD upstream issue once filed).

Variables

View Source
var (
	ErrUnsupportedMode    = errors.New("mode not supported by go-googlesql")
	ErrUnsupportedSQLMode = errors.New("sql_mode not supported by go-googlesql")
	ErrUnsupportedCatalog = errors.New("catalog not supported by go-googlesql")
	ErrUnsupportedFlag    = errors.New("flag not supported by go-googlesql")
)

Sentinel errors. Wrapped at use-site with a per-feature reason constant so callers can errors.Is the category and end users see the upstream-blocking detail in the message.

Functions

func FlagUnsupportedError

func FlagUnsupportedError(name, reason string) error

FlagUnsupportedError builds an error describing an unsupported flag set to a non-default value. Exported so the CLI layer can produce identical messages for every rejected flag.

func Run

func Run(ctx context.Context, sql string, cfg Config, w Writer) error

Run is the top-level entry point. It validates cfg, constructs the GoogleSQL parser/analyzer state, and dispatches sql through each requested Mode for each statement, emitting via w.

Run does not initialise go-googlesql; callers must call cache.Setup or googlesql.Init once before the first call.

Types

type Config

type Config struct {
	// Modes default to []Mode{ModeAnalyze} when empty.
	Modes []Mode

	// SQLMode defaults to SQLModeQuery.
	SQLMode SQLMode

	// CatalogName selects the active catalog (none / sample / tpch).
	// Empty defaults to "none". The catalog is built by package
	// catalog and passed to AnalyzeStatement; CatalogName here is
	// just the chosen identifier so options.go remains decoupled
	// from the catalog package.
	CatalogName string

	// LanguageOptions inputs.
	ProductMode               ProductMode
	StrictNameResolutionMode  bool
	EnabledLanguageFeatures   FeatureSet
	SupportsAllStatementKinds bool // default true; set false to honour upstream's per-mode kind set

	// AnalyzerOptions inputs.
	FoldLiteralCast           *bool
	PruneUnusedColumns        *bool
	ParseLocationRecordType   ParseLocationRecordType
	EnabledASTRewrites        RewriteSet
	Parameters                []QueryParameter
	AllowUndeclaredParameters bool

	// Unsupported sinks. The CLI layer populates these so Run can
	// surface a structured ErrUnsupportedFlag at validation time.
	ImportPaths                         []string
	TableSpecs                          []string
	DescriptorPool                      string
	TargetSyntax                        string
	UseBoxGlyphs                        *bool
	OutputMode                          string
	EvaluatorMaxValueByteSize           *int64
	EvaluatorMaxIntermediateByteSize    *int64
	EvaluatorScrambleUndefinedOrderings *bool
	MaxStatementsToExecute              *int64
	Web                                 bool
	Port                                *int
}

Config carries the user's effective request to Run. The exported fields mirror the upstream ExecuteQueryConfig surface plus the flag-rejection slots required by the unsupported flags (CLI layer uses these as sinks).

func (*Config) Validate

func (c *Config) Validate() error

Validate inspects cfg for unsupported flag values, returning the first ErrUnsupported* (wrapped) error found. The order is stable so test goldens can pin it.

type FeatureBase

type FeatureBase int

FeatureBase mirrors upstream's set-base keyword.

const (
	// FeatureBaseUnset means no base keyword was provided. Apply only
	// the +/- modifiers.
	FeatureBaseUnset FeatureBase = iota

	// FeatureBaseNone disables all features.
	FeatureBaseNone

	// FeatureBaseAll enables all features (including in-development).
	// Maps to LanguageOptions.EnableMaximumLanguageFeaturesForDevelopment.
	FeatureBaseAll

	// FeatureBaseAllMinusDev enables non-in-development features.
	// Maps to LanguageOptions.EnableMaximumLanguageFeatures.
	FeatureBaseAllMinusDev

	// FeatureBaseDefaults uses NewLanguageOptions's defaults.
	FeatureBaseDefaults

	// FeatureBaseDefaultsMinusDev uses NewLanguageOptions's defaults
	// minus features that are in development.
	FeatureBaseDefaultsMinusDev
)

type FeatureSet

type FeatureSet struct {
	Base     FeatureBase
	Enabled  []googlesql.LanguageFeature
	Disabled []googlesql.LanguageFeature
}

FeatureSet is the parsed value of `--enabled_language_features`.

Upstream's flag format is BASE[,+FOO][,-BAR]:

BASE   ∈ {NONE, ALL, ALL_MINUS_DEV, DEFAULTS, DEFAULTS_MINUS_DEV}
+FOO   enable feature FOO on top of BASE
-BAR   disable feature BAR from BASE

Feature names are upstream's enum spelling (e.g. FEATURE_RANGE_TYPE or FEATURE_V_1_1_WITH_ON_SUBQUERY). Names are matched case-insensitively and underscore-insensitively against the Go binding's LanguageFeature enum, which collapses runs like "V_1_1" to "V11" — both forms are accepted.

func ParseFeatureSet

func ParseFeatureSet(s string) (FeatureSet, error)

ParseFeatureSet parses the `--enabled_language_features` flag.

func (FeatureSet) Apply

func (fs FeatureSet) Apply(lo *googlesql.LanguageOptions) error

Apply mutates lo to reflect fs.

type Mode

type Mode string

Mode mirrors upstream ExecuteQueryConfig::ToolMode.

const (
	// ModeParse — parse the input and emit upstream's DebugString.
	ModeParse Mode = "parse"

	// ModeUnparse — parse the input and emit canonical SQL via
	// go-googlesql.Unparse.
	ModeUnparse Mode = "unparse"

	// ModeAnalyze — analyze the input and emit upstream's resolved
	// DebugString. Alias accepted on the CLI: "resolve".
	ModeAnalyze Mode = "analyze"

	// ModeUnanalyze — upstream's Resolved → SQL via SQLBuilder.
	// Returns ErrUnsupportedMode wrapping ReasonModeUnanalyze.
	ModeUnanalyze Mode = "unanalyze"

	// ModeExplain — upstream's evaluator query plan.
	// Returns ErrUnsupportedMode wrapping ReasonModeExplain.
	ModeExplain Mode = "explain"

	// ModeExecute — upstream's evaluator-driven execution.
	// Returns ErrUnsupportedMode wrapping ReasonModeExecute.
	ModeExecute Mode = "execute"
)

func ParseMode

func ParseMode(s string) (Mode, bool)

ParseMode normalizes a CLI-style mode string (handling the "resolve" / "sql_builder" aliases) and returns the corresponding Mode. Unknown names yield "", false.

func (Mode) IsSupported

func (m Mode) IsSupported() bool

IsSupported reports whether m can be run by this Go port.

func (Mode) UnsupportedReason

func (m Mode) UnsupportedReason() string

UnsupportedReason returns the per-mode reason constant for a Mode that is not supported. Returns "" for supported modes.

type ParseLocationRecordType

type ParseLocationRecordType string

ParseLocationRecordType mirrors googlesql::ParseLocationRecordType.

const (
	// ParseLocationRecordNone — record no parse locations.
	ParseLocationRecordNone ParseLocationRecordType = "NONE"

	// ParseLocationRecordFullNodeScope — record full-node-scope
	// locations.
	ParseLocationRecordFullNodeScope ParseLocationRecordType = "FULL_NODE_SCOPE"

	// ParseLocationRecordCodeSearch — record locations suitable for
	// code-search.
	ParseLocationRecordCodeSearch ParseLocationRecordType = "CODE_SEARCH"
)

func ParseParseLocationRecordType

func ParseParseLocationRecordType(s string) (ParseLocationRecordType, bool)

ParseParseLocationRecordType parses a CLI-style value. Names match upstream's enum spelling (case-insensitive).

type ProductMode

type ProductMode string

ProductMode mirrors googlesql::ProductMode.

const (
	// ProductModeInternal — upstream's PRODUCT_INTERNAL (e.g.
	// supports proto types and DOUBLE).
	ProductModeInternal ProductMode = "internal"

	// ProductModeExternal — upstream's PRODUCT_EXTERNAL.
	ProductModeExternal ProductMode = "external"
)

func ParseProductMode

func ParseProductMode(s string) (ProductMode, bool)

ParseProductMode parses a CLI-style product_mode value.

type QueryParameter

type QueryParameter struct {
	Name    string
	Type    googlesql.TypeKind
	Literal string // raw text from the CLI flag
}

QueryParameter is one entry registered with the analyzer for an `@name` parameter reference. The Type field is what AnalyzerOptions.AddQueryParameter actually consumes; Literal is preserved for diagnostics and would be the Value for execute mode (unsupported in this Go port).

func ParseParameters

func ParseParameters(s string) ([]QueryParameter, error)

ParseParameters parses upstream's `--parameters` flag format, `name=literal,name=literal,...`.

Implementation note: upstream `googlesql::AnalyzeExpression` (third_party/googlesql/googlesql/public/analyzer.h:127) is the general path for inferring a parameter literal's type, and go-googlesql does expose it — but routing parameter parsing through the analyzer would require constructing an AnalyzerOptions + Catalog + TypeFactory just to type a `42` or a `'foo'`. Until we have a real need for richer literal forms (array / struct / NUMERIC / etc.), the simple regex-style recognition below is cheaper and easier to read; switch to AnalyzeExpression when the trade-off flips.

42        → INT64
3.14      → DOUBLE
'foo' or "foo"  → STRING
TRUE / FALSE     → BOOL
NULL             → error (no type information)

type RewriteBase

type RewriteBase int

RewriteBase mirrors upstream's set-base keyword.

const (
	// RewriteBaseUnset means no base; apply only +/- modifiers.
	RewriteBaseUnset RewriteBase = iota

	// RewriteBaseNone disables all rewrites.
	RewriteBaseNone

	// RewriteBaseAll enables all rewrites (including in-development).
	RewriteBaseAll

	// RewriteBaseAllMinusDev enables non-in-development rewrites.
	// (Default upstream behaviour.)
	RewriteBaseAllMinusDev

	// RewriteBaseDefaults uses NewAnalyzerOptions's defaults.
	//
	// Workaround [go-googlesql v0.2.1]: the static helper that
	// returns upstream's DEFAULTS rewrite set is not exposed.
	//
	// Upstream C++ API:
	// googlesql::AnalyzerOptions::DefaultRewrites() (static, returning
	// `absl::btree_set<ResolvedASTRewrite>`) at
	// third_party/googlesql/googlesql/public/analyzer_options.h:342.
	// `enabled_rewrites = DefaultRewrites()` is what
	// `NewAnalyzerOptions()` initialises with (analyzer_options.h:1067),
	// so the post-construction state is already DEFAULTS — but we
	// can't *recompute* the set later if the user mixes DEFAULTS with
	// `+REWRITE_FOO` / `-REWRITE_BAR` modifiers.
	//
	// Natural Go code:
	//   ao.SetEnabledRewrites(googlesql.DefaultRewrites())
	//
	// Instead, DEFAULTS is treated as the NewAnalyzerOptions zero
	// state. Unblocked when go-googlesql exposes
	// `AnalyzerOptions.DefaultRewrites` (or an equivalent static
	// accessor).
	RewriteBaseDefaults

	// RewriteBaseDefaultsMinusDev — see RewriteBaseDefaults caveat.
	RewriteBaseDefaultsMinusDev
)

type RewriteSet

type RewriteSet struct {
	Base     RewriteBase
	Enabled  []googlesql.ResolvedASTRewrite
	Disabled []googlesql.ResolvedASTRewrite
}

RewriteSet is the parsed value of `--enabled_ast_rewrites`.

Upstream's flag format mirrors --enabled_language_features: BASE[,+REWRITE_FOO][,-REWRITE_BAR]. The default upstream base is ALL_MINUS_DEV.

func ParseRewriteSet

func ParseRewriteSet(s string) (RewriteSet, error)

ParseRewriteSet parses the `--enabled_ast_rewrites` flag.

func (RewriteSet) Apply

func (rs RewriteSet) Apply(ao *googlesql.AnalyzerOptions) error

Apply mutates ao to reflect rs. Note: setting BASE iterates every known rewrite and toggles it explicitly; this matches upstream (which builds the effective set the same way).

type SQLMode

type SQLMode string

SQLMode mirrors upstream ExecuteQueryConfig::SqlMode.

const (
	// SQLModeQuery treats the input as one or more SQL statements.
	SQLModeQuery SQLMode = "query"

	// SQLModeExpression treats the input as a single SQL expression.
	SQLModeExpression SQLMode = "expression"

	// SQLModeScript treats the input as a script (multiple
	// statements with control flow). Parsing and per-statement
	// analysis are supported; script-level execution is not.
	SQLModeScript SQLMode = "script"
)

func ParseSQLMode

func ParseSQLMode(s string) (SQLMode, bool)

ParseSQLMode parses a CLI-style sql_mode value.

type Writer

type Writer interface {
	// StatementText writes the source SQL of the current statement
	// (called once per statement before any other emit method).
	StatementText(text string) error

	// Parsed emits parse-mode output (the parse tree).
	Parsed(debug string) error

	// Unparsed emits unparse-mode output (canonical SQL).
	Unparsed(sql string) error

	// Resolved emits analyze-mode output (the resolved AST).
	Resolved(debug string) error

	// Described emits DESCRIBE-statement output (table schema /
	// function signature / etc.).
	Described(text string) error

	// StartStatement is called at the start of each statement.
	// isFirst is true for the first statement only.
	StartStatement(isFirst bool) error

	// FlushStatement is called at the end of each statement, or
	// when an error truncates it. atEnd is true when the entire
	// input has been consumed; errMsg is non-empty iff the
	// statement failed.
	FlushStatement(atEnd bool, errMsg string) error
}

Writer is the sink that Run streams its output through.

The interface is a deliberately reduced port of upstream's ExecuteQueryWriter. Only the methods covering supported modes (parse / unparse / analyze / describe) are present. Each method returns an error so an io.Writer-backed implementation can propagate write failures.

func NewTextWriter

func NewTextWriter(w io.Writer) Writer

NewTextWriter returns a Writer that emits labeled sections to w.

Output is plain text:

[statement]
  <SQL source line>

[parse]
  <debug string>

[unparse]
  <SQL>

[analyze]
  <debug string>

[describe]
  <description>

Directories

Path Synopsis
Package cache resolves a safe, OS-appropriate wazero compilation-cache directory for go-googlesql.
Package cache resolves a safe, OS-appropriate wazero compilation-cache directory for go-googlesql.
Package catalog ports the upstream `--catalog` option's selectable catalogs into Go.
Package catalog ports the upstream `--catalog` option's selectable catalogs into Go.
cmd
execute_query command
Command execute_query is a Go-native port of upstream google/googlesql's execute_query tool, layered on top of go-googlesql.
Command execute_query is a Go-native port of upstream google/googlesql's execute_query tool, layered on top of go-googlesql.
internal
runtime
Package runtime is an internal helper that ensures go-googlesql is initialised exactly once for callers that do not go through cache.Setup directly.
Package runtime is an internal helper that ensures go-googlesql is initialised exactly once for callers that do not go through cache.Setup directly.
webui
Package webui serves an interactive HTTP UI for execute_query.
Package webui serves an interactive HTTP UI for execute_query.

Jump to

Keyboard shortcuts

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