Documentation
¶
Overview ¶
Package bqsql runs a GoogleSQL subset on SQLite and converts BigQuery values between their REST encodings.
Index ¶
- Constants
- Variables
- func Cell(f Field, stored any) any
- func CellFor(f Field, stored any, o CellOptions) any
- func CheckRoutine(in *Input, r *RoutineData) error
- func CheckRowPolicy(in *Input, ref TableRef, grantees []string, filter string) error
- func FilterReferences(filter, column string) bool
- func FormatFloat(f float64) string
- func FormatTemporal(k Kind, t time.Time) string
- func FromSQLite(f Field, v any) (any, error)
- func GranteeMatches(grantee, user string) bool
- func IsSQLText(s string) bool
- func JSONText(f Field, stored any) string
- func LogicalBytes(f Field, stored any) int64
- func NormalizeRows(fields []Field, rows [][]any)
- func NormalizeSchema(fs []Field) error
- func ParseRecord(fields []Field, obj map[string]any, o ParseOptions) ([]any, error)
- func ParseTemporal(k Kind, v any) (time.Time, error)
- func ParseValue(f Field, v any, o ParseOptions) (any, error)
- func Row(fields []Field, row []any) map[string]any
- func RowFor(fields []Field, row []any, o CellOptions) map[string]any
- func ToSQLite(f Field, stored any) driver.Value
- func ValidGrantee(g string) bool
- type Catalog
- type CellOptions
- type ChildEvent
- type Column
- type Decimal
- func (d Decimal) Abs() (Decimal, error)
- func (d Decimal) Add(o Decimal) (Decimal, error)
- func (d Decimal) As(k Kind) (Decimal, error)
- func (d Decimal) Ceil() (Decimal, error)
- func (d Decimal) Cmp(o Decimal) int
- func (d Decimal) Constrain(p, s int) (Decimal, error)
- func (d Decimal) Exp() (Decimal, error)
- func (d Decimal) Float64() float64
- func (d Decimal) Floor() (Decimal, error)
- func (d Decimal) Int64() (int64, error)
- func (d Decimal) IntDiv(o Decimal) (Decimal, error)
- func (d Decimal) Kind() Kind
- func (d Decimal) Ln() (Decimal, error)
- func (d Decimal) Log(base Decimal) (Decimal, error)
- func (d Decimal) Log10() (Decimal, error)
- func (d Decimal) Mod(o Decimal) (Decimal, error)
- func (d Decimal) Mul(o Decimal) (Decimal, error)
- func (d Decimal) Neg() (Decimal, error)
- func (d Decimal) Pow(e Decimal) (Decimal, error)
- func (d Decimal) Quo(o Decimal) (Decimal, error)
- func (d Decimal) Round(digits int, mode RoundMode) (Decimal, error)
- func (d Decimal) SQLText() string
- func (d Decimal) Sign() int
- func (d Decimal) Sqrt() (Decimal, error)
- func (d Decimal) String() string
- func (d Decimal) Sub(o Decimal) (Decimal, error)
- func (d Decimal) Trunc(digits int) Decimal
- type Effect
- type ErrKind
- type Error
- type Field
- type Input
- type Kind
- type Param
- type ParseOptions
- type Query
- type Result
- type RoundMode
- type RoutineArg
- type RoutineCatalog
- type RoutineData
- type RowPolicyData
- type Script
- type ScriptHost
- type ScriptResult
- type Statement
- type StmtKind
- type TableData
- type TableRef
- type TimeTravelCatalog
- type Type
- type VarScope
Constants ¶
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.
const ( RoutineScalar = "SCALAR_FUNCTION" RoutineTable = "TABLE_VALUED_FUNCTION" RoutineProcedure = "PROCEDURE" )
Routine kinds, spelled as in the REST routineType.
const ( ModeIn = "IN" ModeOut = "OUT" ModeInOut = "INOUT" )
Routine argument modes.
const ( ModeNullable = "NULLABLE" ModeRequired = "REQUIRED" ModeRepeated = "REPEATED" )
Schema modes.
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.
const DefaultUser = "gopherstack@localhost"
DefaultUser is the identity SESSION_USER() reports when the request carries none.
Variables ¶
var ErrDecimal = errors.New("decimal error")
ErrDecimal is wrapped by every NUMERIC/BIGNUMERIC arithmetic and conversion failure.
var ErrSchema = errors.New("invalid schema")
ErrSchema is wrapped by every schema validation failure.
var ErrSyntax = errors.New("syntax error")
ErrSyntax is wrapped by every parse failure.
var ErrValue = errors.New("invalid value")
ErrValue is wrapped by every value conversion failure.
Functions ¶
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 ¶
CheckRowPolicy validates a policy for the table ref against the catalog, as CREATE ROW ACCESS POLICY does.
func FilterReferences ¶
FilterReferences reports whether the policy filter mentions column as an identifier.
func FormatFloat ¶
FormatFloat renders f as the REST API does: shortest round-trip digits, with ".0" on whole numbers.
func FormatTemporal ¶
FormatTemporal renders t in the canonical stored encoding for k.
func FromSQLite ¶
FromSQLite converts a value read from SQLite into the stored form for f.
func GranteeMatches ¶
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 JSONText ¶
JSONText renders a stored record or repeated value as JSON text with decimals as plain strings.
func LogicalBytes ¶
LogicalBytes estimates the logical storage size of a stored value the way BigQuery bills it.
func NormalizeRows ¶
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 ¶
NormalizeSchema validates fs and rewrites type and mode names to their REST spellings.
func ParseRecord ¶
ParseRecord converts a JSON object into a positional record for fields.
func ParseTemporal ¶
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 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 ¶
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 ¶
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 ¶
ChildEvent describes one statement a script executed, for child job records.
type Column ¶
Column is a named, typed struct member or relation column.
func FieldColumns ¶
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 ¶
DecimalFromFloat converts a FLOAT64 exactly then rounds half away from zero; NaN and infinities are errors.
func DecimalFromInt ¶
DecimalFromInt converts an INT64 exactly.
func DecodeSQLText ¶
DecodeSQLText reverses SQLText into a value of kind k, rounding when a wider value is narrowed.
func ParseDecimal ¶
ParseDecimal parses a decimal literal or string (sign, fraction, exponent) and rounds half away from zero.
func ParseNumericText ¶
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) Constrain ¶
Constrain applies NUMERIC(p, s) or BIGNUMERIC(p, s): round to s digits, fail when more than p digits remain.
func (Decimal) IntDiv ¶
IntDiv returns the integer quotient truncated toward zero; a zero divisor is an error.
func (Decimal) Log ¶
Log returns the logarithm of d in the given base; d, base <= 0 and base = 1 are errors.
func (Decimal) Mod ¶
Mod returns the remainder of d / o with the sign of d; a zero divisor is an error.
func (Decimal) Pow ¶
Pow returns d^e. Underflow yields zero; a negative base with fractional exponent and 0^negative are errors.
func (Decimal) Round ¶
Round rounds to the given number of fractional digits (negative rounds integer digits).
func (Decimal) SQLText ¶
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) Sqrt ¶
Sqrt returns the square root rounded half away from zero; negative input is an error.
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 Error ¶
Error is a query analysis or execution failure.
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 ¶
ColumnFields renders typed columns as schema fields.
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.
type Param ¶
Param is a query parameter; Name is empty for positional parameters and Value is in stored form.
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.
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 ¶
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 ¶
ParseScript parses one or more statements with control flow.
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 ¶
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 ¶
Statement is one parsed GoogleSQL statement.
func ParseStatement ¶
ParseStatement parses a single GoogleSQL statement.
type StmtKind ¶
type StmtKind uint8
StmtKind classifies a parsed statement.
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 TimeTravelCatalog ¶
TimeTravelCatalog resolves a table as it was at a point in time.
Source Files
¶
- ast.go
- compile.go
- compile_decimal.go
- compile_expr.go
- compile_func.go
- consts.go
- ddl.go
- decimal.go
- decimal_format.go
- decimal_math.go
- dml.go
- errors.go
- exec.go
- external.go
- geo.go
- geo_noding.go
- grouping.go
- interval.go
- lexer.go
- merge.go
- parser.go
- parser_expr.go
- parser_stmt.go
- partition.go
- pivot.go
- recursive.go
- routines.go
- routines_compile.go
- rowpolicy.go
- script_parse.go
- script_run.go
- search.go
- sqlvalues.go
- timetravel.go
- types.go
- udf.go
- udf_agg.go
- udf_approx.go
- udf_array.go
- udf_cast.go
- udf_castformat.go
- udf_decimal.go
- udf_farm.go
- udf_geo.go
- udf_hll.go
- udf_json.go
- udf_math.go
- udf_net.go
- udf_regex.go
- udf_str.go
- udf_time.go
- values.go