bqsql

package
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 37 Imported by: ? 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 bqsql runs a GoogleSQL subset on SQLite and converts BigQuery values between their REST encodings.

Index

Constants

View Source
const (
	OpWrite           = "WRITE"
	OpCreateTable     = "CREATE_TABLE"
	OpCreateView      = "CREATE_VIEW"
	OpCreateSchema    = "CREATE_SCHEMA"
	OpDropTable       = "DROP_TABLE"
	OpDropView        = "DROP_VIEW"
	OpDropSchema      = "DROP_SCHEMA"
	OpAlter           = "ALTER"
	OpRefreshView     = "REFRESH_VIEW"
	OpCreateRoutine   = "CREATE_ROUTINE"
	OpDropRoutine     = "DROP_ROUTINE"
	OpCreateRowPolicy = "CREATE_ROW_POLICY"
	OpDropRowPolicy   = "DROP_ROW_POLICY"
)

Effect operations.

View Source
const (
	RoutineScalar    = "SCALAR_FUNCTION"
	RoutineTable     = "TABLE_VALUED_FUNCTION"
	RoutineProcedure = "PROCEDURE"
)

Routine kinds, spelled as in the REST routineType.

View Source
const (
	ModeIn    = "IN"
	ModeOut   = "OUT"
	ModeInOut = "INOUT"
)

Routine argument modes.

View Source
const (
	ModeNullable = "NULLABLE"
	ModeRequired = "REQUIRED"
	ModeRepeated = "REPEATED"
)

Schema modes.

View Source
const (
	TimestampLayout = "2006-01-02 15:04:05.000000"
	DateLayout      = "2006-01-02"
	DatetimeLayout  = "2006-01-02T15:04:05.000000"
	TimeLayout      = "15:04:05.000000"
)

Canonical stored encodings of temporal values.

View Source
const DefaultUser = "gopherstack@localhost"

DefaultUser is the identity SESSION_USER() reports when the request carries none.

Variables

View Source
var ErrDecimal = errors.New("decimal error")

ErrDecimal is wrapped by every NUMERIC/BIGNUMERIC arithmetic and conversion failure.

View Source
var ErrSchema = errors.New("invalid schema")

ErrSchema is wrapped by every schema validation failure.

View Source
var ErrSyntax = errors.New("syntax error")

ErrSyntax is wrapped by every parse failure.

View Source
var ErrValue = errors.New("invalid value")

ErrValue is wrapped by every value conversion failure.

Functions

func Cell

func Cell(f Field, stored any) any

Cell converts a stored value into the REST "v" encoding for f.

func CellFor

func CellFor(f Field, stored any, o CellOptions) any

CellFor converts a stored value into the REST "v" encoding for f under o.

func CheckRoutine

func CheckRoutine(in *Input, r *RoutineData) error

CheckRoutine validates a routine definition the way CREATE FUNCTION does: the body must analyse with its arguments.

func CheckRowPolicy

func CheckRowPolicy(in *Input, ref TableRef, grantees []string, filter string) error

CheckRowPolicy validates a policy for the table ref against the catalog, as CREATE ROW ACCESS POLICY does.

func FilterReferences

func FilterReferences(filter, column string) bool

FilterReferences reports whether the policy filter mentions column as an identifier.

func FormatFloat

func FormatFloat(f float64) string

FormatFloat renders f as the REST API does: shortest round-trip digits, with ".0" on whole numbers.

func FormatTemporal

func FormatTemporal(k Kind, t time.Time) string

FormatTemporal renders t in the canonical stored encoding for k.

func FromSQLite

func FromSQLite(f Field, v any) (any, error)

FromSQLite converts a value read from SQLite into the stored form for f.

func GranteeMatches

func GranteeMatches(grantee, user string) bool

GranteeMatches reports whether the caller identity user is covered by grantee. Group membership is not known to the emulator, so group grantees never match.

func IsSQLText

func IsSQLText(s string) bool

IsSQLText reports whether s is an encoding produced by SQLText.

func JSONText

func JSONText(f Field, stored any) string

JSONText renders a stored record or repeated value as JSON text with decimals as plain strings.

func LogicalBytes

func LogicalBytes(f Field, stored any) int64

LogicalBytes estimates the logical storage size of a stored value the way BigQuery bills it.

func NormalizeRows

func NormalizeRows(fields []Field, rows [][]any)

NormalizeRows rewrites the NUMERIC and BIGNUMERIC cells of stored rows into the canonical decimal string, leaving any cell that does not parse as it was.

func NormalizeSchema

func NormalizeSchema(fs []Field) error

NormalizeSchema validates fs and rewrites type and mode names to their REST spellings.

func ParseRecord

func ParseRecord(fields []Field, obj map[string]any, o ParseOptions) ([]any, error)

ParseRecord converts a JSON object into a positional record for fields.

func ParseTemporal

func ParseTemporal(k Kind, v any) (time.Time, error)

ParseTemporal parses the many spellings BigQuery accepts for TIMESTAMP, DATE, DATETIME and TIME.

func ParseValue

func ParseValue(f Field, v any, o ParseOptions) (any, error)

ParseValue converts a decoded JSON value into the stored form for f. Stored scalars are strings, records are positional []any and repeated fields are []any; NULL is nil.

func Row

func Row(fields []Field, row []any) map[string]any

Row converts a stored row into the REST {"f":[{"v":...}]} encoding.

func RowFor

func RowFor(fields []Field, row []any, o CellOptions) map[string]any

RowFor converts a stored row into the REST {"f":[{"v":...}]} encoding under o.

func ToSQLite

func ToSQLite(f Field, stored any) driver.Value

ToSQLite converts a stored value into the value bound into SQLite: scalars map to INTEGER, REAL or TEXT and records and arrays to JSON text.

func ValidGrantee

func ValidGrantee(g string) bool

ValidGrantee reports whether g is one of the IAM member forms row access policies accept.

Types

type Catalog

type Catalog interface {
	Table(ref TableRef) (*TableData, bool)
	DatasetExists(project, dataset string) bool
}

Catalog resolves tables for the compiler.

type CellOptions

type CellOptions struct {
	// Int64Timestamp renders TIMESTAMP cells as integer microseconds, as formatOptions.useInt64Timestamp requests.
	Int64Timestamp bool
}

CellOptions tunes the REST cell encoding.

type ChildEvent

type ChildEvent struct {
	Result    *Result
	Err       error
	Text      string
	Statement string
}

ChildEvent describes one statement a script executed, for child job records.

type Column

type Column struct {
	Name string
	Type Type
}

Column is a named, typed struct member or relation column.

func FieldColumns

func FieldColumns(fs []Field) []Column

FieldColumns converts schema fields into typed columns.

type Decimal

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

Decimal is an immutable exact NUMERIC (scale 9) or BIGNUMERIC (scale 38) value held as a scaled integer. The zero value is NUMERIC 0.

func DecimalFromFloat

func DecimalFromFloat(k Kind, f float64) (Decimal, error)

DecimalFromFloat converts a FLOAT64 exactly then rounds half away from zero; NaN and infinities are errors.

func DecimalFromInt

func DecimalFromInt(k Kind, v int64) (Decimal, error)

DecimalFromInt converts an INT64 exactly.

func DecodeSQLText

func DecodeSQLText(s string, k Kind) (Decimal, error)

DecodeSQLText reverses SQLText into a value of kind k, rounding when a wider value is narrowed.

func ParseDecimal

func ParseDecimal(k Kind, s string) (Decimal, error)

ParseDecimal parses a decimal literal or string (sign, fraction, exponent) and rounds half away from zero.

func ParseNumericText

func ParseNumericText(k Kind, s string) (Decimal, error)

ParseNumericText parses the PARSE_NUMERIC and PARSE_BIGNUMERIC string form: commas before the point, one sign before or after the number, whitespace around the sign and the number, optional exponent.

func (Decimal) Abs

func (d Decimal) Abs() (Decimal, error)

Abs returns |d|.

func (Decimal) Add

func (d Decimal) Add(o Decimal) (Decimal, error)

Add returns d + o.

func (Decimal) As

func (d Decimal) As(k Kind) (Decimal, error)

As converts to the target kind, rounding half away from zero when narrowing.

func (Decimal) Ceil

func (d Decimal) Ceil() (Decimal, error)

Ceil returns the smallest integer value not less than d.

func (Decimal) Cmp

func (d Decimal) Cmp(o Decimal) int

Cmp compares two values of any decimal kind.

func (Decimal) Constrain

func (d Decimal) Constrain(p, s int) (Decimal, error)

Constrain applies NUMERIC(p, s) or BIGNUMERIC(p, s): round to s digits, fail when more than p digits remain.

func (Decimal) Exp

func (d Decimal) Exp() (Decimal, error)

Exp returns e^d; huge results overflow and tiny ones underflow to zero.

func (Decimal) Float64

func (d Decimal) Float64() float64

Float64 returns the nearest FLOAT64.

func (Decimal) Floor

func (d Decimal) Floor() (Decimal, error)

Floor returns the largest integer value not greater than d.

func (Decimal) Int64

func (d Decimal) Int64() (int64, error)

Int64 rounds half away from zero to an INT64 and fails when out of range.

func (Decimal) IntDiv

func (d Decimal) IntDiv(o Decimal) (Decimal, error)

IntDiv returns the integer quotient truncated toward zero; a zero divisor is an error.

func (Decimal) Kind

func (d Decimal) Kind() Kind

Kind reports NUMERIC or BIGNUMERIC.

func (Decimal) Ln

func (d Decimal) Ln() (Decimal, error)

Ln returns the natural logarithm; non-positive input is an error.

func (Decimal) Log

func (d Decimal) Log(base Decimal) (Decimal, error)

Log returns the logarithm of d in the given base; d, base <= 0 and base = 1 are errors.

func (Decimal) Log10

func (d Decimal) Log10() (Decimal, error)

Log10 returns the base-10 logarithm; non-positive input is an error.

func (Decimal) Mod

func (d Decimal) Mod(o Decimal) (Decimal, error)

Mod returns the remainder of d / o with the sign of d; a zero divisor is an error.

func (Decimal) Mul

func (d Decimal) Mul(o Decimal) (Decimal, error)

Mul returns d * o rounded to the result scale.

func (Decimal) Neg

func (d Decimal) Neg() (Decimal, error)

Neg returns -d.

func (Decimal) Pow

func (d Decimal) Pow(e Decimal) (Decimal, error)

Pow returns d^e. Underflow yields zero; a negative base with fractional exponent and 0^negative are errors.

func (Decimal) Quo

func (d Decimal) Quo(o Decimal) (Decimal, error)

Quo returns d / o rounded to the result scale; a zero divisor is an error.

func (Decimal) Round

func (d Decimal) Round(digits int, mode RoundMode) (Decimal, error)

Round rounds to the given number of fractional digits (negative rounds integer digits).

func (Decimal) SQLText

func (d Decimal) SQLText() string

SQLText encodes d for storage in SQLite: '#' plus 64 hex digits of (value*10^38 + 2^255), so byte order equals numeric order and equal values share one encoding for either kind.

func (Decimal) Sign

func (d Decimal) Sign() int

Sign returns -1, 0 or +1.

func (Decimal) Sqrt

func (d Decimal) Sqrt() (Decimal, error)

Sqrt returns the square root rounded half away from zero; negative input is an error.

func (Decimal) String

func (d Decimal) String() string

String renders the value as BigQuery prints it: no exponent, no trailing zeros, never "-0".

func (Decimal) Sub

func (d Decimal) Sub(o Decimal) (Decimal, error)

Sub returns d - o.

func (Decimal) Trunc

func (d Decimal) Trunc(digits int) Decimal

Trunc drops fractional digits beyond the given count toward zero.

type Effect

type Effect struct {
	Partition    map[string]any
	Cluster      []string
	PartitionKey string
	Options      map[string]string
	Routine      *RoutineData
	Policy       *RowPolicyData
	PolicyName   string
	Ref          TableRef
	Op           string
	ViewQuery    string
	AlterOp      string
	PartFields   []Field
	Fields       []Field
	Rows         [][]any
	OrReplace    bool
	IfNotExist   bool
	IfExists     bool
	Materialized bool
	Cascade      bool
	DropAll      bool
	External     bool
	WithPartCols bool
}

Effect is a catalog change a statement asks the caller to apply.

type ErrKind

type ErrKind uint8

ErrKind classifies a query failure for HTTP status mapping.

const (
	ErrInvalid ErrKind = iota
	ErrNotFound
	ErrExists
	ErrRuntime
	ErrUnsupported
)

Error kinds.

type Error

type Error struct {
	Message string
	Kind    ErrKind
}

Error is a query analysis or execution failure.

func AsError

func AsError(err error) *Error

AsError returns err as an *Error, wrapping syntax errors as invalid-query failures.

func (*Error) Error

func (e *Error) Error() string

Error implements error.

type Field

type Field struct {
	Name        string  `json:"name"`
	Type        string  `json:"type"`
	Mode        string  `json:"mode,omitempty"`
	Description string  `json:"description,omitempty"`
	MaxLength   string  `json:"maxLength,omitempty"`
	Precision   string  `json:"precision,omitempty"`
	Scale       string  `json:"scale,omitempty"`
	Fields      []Field `json:"fields,omitempty"`
}

Field is one schema column in the REST TableFieldSchema encoding.

func ColumnFields

func ColumnFields(cols []Column) []Field

ColumnFields renders typed columns as schema fields.

func TypeField

func TypeField(name string, t Type) Field

TypeField renders a column as a schema field with REST type names.

func (Field) SQLType

func (f Field) SQLType() Type

SQLType converts the schema field, including its mode, into a Type.

type Input

type Input struct {
	Catalog Catalog
	Temp    map[string]*RoutineData
	Vars    VarScope
	Project string
	Dataset string
	User    string
	Params  []Param
}

Input configures one statement run.

type Kind

type Kind uint8

Kind is a GoogleSQL type family.

const (
	KindUnknown Kind = iota
	KindInt
	KindFloat
	KindBool
	KindString
	KindBytes
	KindTimestamp
	KindDate
	KindTime
	KindDatetime
	KindNumeric
	KindBigNumeric
	KindJSON
	KindGeography
	KindStruct
	KindArray
	KindInterval
)

Type kinds.

func KindOf

func KindOf(name string) (Kind, bool)

KindOf resolves a REST or GoogleSQL scalar type name.

func (Kind) IsNumber

func (k Kind) IsNumber() bool

IsNumber reports whether k is INT64, FLOAT64, NUMERIC or BIGNUMERIC.

func (Kind) RESTName

func (k Kind) RESTName() string

RESTName is the type name the REST API reports for k.

func (Kind) SQLName

func (k Kind) SQLName() string

SQLName is the GoogleSQL spelling of k.

type Param

type Param struct {
	Value any
	Name  string
	Field Field
}

Param is a query parameter; Name is empty for positional parameters and Value is in stored form.

type ParseOptions

type ParseOptions struct {
	IgnoreUnknown bool
}

ParseOptions tunes ParseValue.

type Query

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

Query is a parsed SELECT statement, possibly with set operations, CTEs, ORDER BY and LIMIT.

type Result

type Result struct {
	Statement string
	Fields    []Field
	Rows      [][]any
	Effects   []Effect
	Affected  int64
	Inserted  int64
	Updated   int64
	Deleted   int64
	Kind      StmtKind
}

Result is the outcome of one statement.

func Run

func Run(ctx context.Context, st *Statement, in *Input, dryRun bool) (*Result, error)

Run executes st. With dryRun set, queries are only analysed and the result carries the schema alone.

type RoundMode

type RoundMode uint8

RoundMode selects how ROUND breaks ties.

const (
	RoundHalfAwayFromZero RoundMode = iota
	RoundHalfEven
)

Rounding modes of ROUND(x, n, mode).

type RoutineArg

type RoutineArg struct {
	Name     string
	Mode     string
	Table    []Column
	Type     Type
	AnyType  bool
	AnyTable bool
	IsTable  bool
}

RoutineArg is one routine parameter.

type RoutineCatalog

type RoutineCatalog interface {
	Routine(ref TableRef) (*RoutineData, bool)
}

RoutineCatalog is implemented by catalogs that store routines.

type RoutineData

type RoutineData struct {
	Returns     *Type
	Ref         TableRef
	Kind        string
	Language    string
	Body        string
	Description string
	Args        []RoutineArg
	ReturnTable []Column
	Temp        bool
}

RoutineData is a persistent or temporary function, table function or procedure.

type RowPolicyData

type RowPolicyData struct {
	Name     string
	Filter   string
	Grantees []string
}

RowPolicyData is a row access policy as the engine sees it.

type Script

type Script struct {
	Text string
	// contains filtered or unexported fields
}

Script is a parsed multi-statement GoogleSQL script.

func ParseScript

func ParseScript(sql string) (*Script, error)

ParseScript parses one or more statements with control flow.

func (*Script) Single

func (s *Script) Single() (*Statement, bool)

Single returns the only statement of a script that is one plain SQL statement.

type ScriptHost

type ScriptHost interface {
	// Apply commits catalog and table changes so later statements see them.
	Apply(ctx context.Context, effects []Effect) error
	BeginTx() error
	CommitTx() error
	RollbackTx() error
	Child(ev ChildEvent)
}

ScriptHost applies a script's side effects to live state.

type ScriptResult

type ScriptResult struct {
	Last     *Result
	Children int
}

ScriptResult is the outcome of running a script: the last statement's result and the number of child statements.

func RunScript

func RunScript(ctx context.Context, sc *Script, in *Input, host ScriptHost) (*ScriptResult, error)

RunScript executes sc against host. A transaction left open when the script ends is rolled back.

type Statement

type Statement struct {
	Text string

	Kind StmtKind
	// contains filtered or unexported fields
}

Statement is one parsed GoogleSQL statement.

func ParseStatement

func ParseStatement(sql string) (*Statement, error)

ParseStatement parses a single GoogleSQL statement.

type StmtKind

type StmtKind uint8

StmtKind classifies a parsed statement.

const (
	StmtQuery StmtKind = iota
	StmtInsert
	StmtUpdate
	StmtDelete
	StmtMerge
	StmtCreateTable
	StmtCreateView
	StmtCreateSchema
	StmtDrop
	StmtTruncate
	StmtAlter
	StmtCreateRoutine
	StmtDropRoutine
	StmtCreateRowPolicy
	StmtDropRowPolicy
)

Statement kinds.

func (StmtKind) DML

func (k StmtKind) DML() bool

DML reports whether the statement modifies table rows.

type TableData

type TableData struct {
	// RowsFn supplies the rows of an external table at query time; they carry the Pseudo columns after Fields.
	RowsFn    func() ([][]any, error)
	Ref       TableRef
	ViewQuery string
	Fields    []Field
	Rows      [][]any
	// RowPolicies are the row access policies in force on the table.
	RowPolicies []RowPolicyData
	// Pseudo lists columns selectable by name but not part of the schema, such as _FILE_NAME.
	Pseudo []Field
	// PartitionFilter names the columns a query must filter on (require_hive_partition_filter).
	PartitionFilter []string
	Materialized    bool
	External        bool
}

TableData is a table's schema and rows as the catalog holds them.

type TableRef

type TableRef struct {
	Project string
	Dataset string
	Table   string
}

TableRef names a table.

func (TableRef) String

func (r TableRef) String() string

String renders the legacy project:dataset.table form BigQuery error messages use.

type TimeTravelCatalog

type TimeTravelCatalog interface {
	TableAt(ref TableRef, at time.Time) (*TableData, error)
}

TimeTravelCatalog resolves a table as it was at a point in time.

type Type

type Type struct {
	Elem   *Type
	Fields []Column
	Prec   int
	Scale  int
	Kind   Kind
}

Type is a GoogleSQL type; Elem is set for arrays and Fields for structs.

func (Type) IsNumeric

func (t Type) IsNumeric() bool

IsNumeric reports whether the type is a number.

type VarScope

type VarScope interface {
	Lookup(name string) (*Param, bool)
}

VarScope resolves script variables for the compiler.

Jump to

Keyboard shortcuts

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