From a970efd2b62044bc945e693309884bfce4d9fddc Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 16:17:49 -0600 Subject: [PATCH 1/9] feat(timestreamquery): static result types, typeof, element-free lambdas, temporal range and spatial coverage insights Queries are parsed and typed before execution, so column types are known for empty results and nested values, typeof reports Timestream type names, and filter and reduce are recognised by their argument's type. Comments are stripped before any rewrite. Query insights report the temporal range and spatial coverage, apply the one query per second limit and are returned only when enabled. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- .../testdata/snapshot_inventory.json | 11 + services/timestreamquery/PARITY.md | 32 +- services/timestreamquery/errors.go | 2 + services/timestreamquery/handler.go | 2 + .../handler_query_execution.go | 32 +- .../handler_scheduled_queries.go | 4 + services/timestreamquery/models.go | 47 +- services/timestreamquery/persistence_test.go | 25 + services/timestreamquery/query_execution.go | 129 ++- services/timestreamquery/scheduled_write.go | 3 +- services/timestreamquery/source.go | 6 + services/timestreamquery/store.go | 3 + services/timestreamquery/ts_annotate.go | 98 ++ services/timestreamquery/ts_boolean.go | 8 +- services/timestreamquery/ts_boolean_test.go | 4 +- services/timestreamquery/ts_engine.go | 38 +- services/timestreamquery/ts_funcs.go | 110 +- services/timestreamquery/ts_functions_test.go | 2 +- services/timestreamquery/ts_infer.go | 761 ++++++++++++++ services/timestreamquery/ts_infer_funcs.go | 249 +++++ .../timestreamquery/ts_infer_internal_test.go | 143 +++ .../timestreamquery/ts_interval_type_test.go | 2 +- services/timestreamquery/ts_lambda.go | 18 +- services/timestreamquery/ts_prune.go | 540 ++++++++++ services/timestreamquery/ts_render.go | 301 ++++++ services/timestreamquery/ts_result.go | 127 ++- services/timestreamquery/ts_rewrite.go | 9 +- .../timestreamquery/ts_sdk_insights_test.go | 314 ++++++ services/timestreamquery/ts_sdk_types_test.go | 404 +++++++ services/timestreamquery/ts_sqlast.go | 140 +++ services/timestreamquery/ts_sqlexpr.go | 993 ++++++++++++++++++ services/timestreamquery/ts_sqllex.go | 276 +++++ services/timestreamquery/ts_sqlparse.go | 763 ++++++++++++++ services/timestreamquery/ts_types.go | 255 +++++ 34 files changed, 5724 insertions(+), 127 deletions(-) create mode 100644 services/timestreamquery/ts_annotate.go create mode 100644 services/timestreamquery/ts_infer.go create mode 100644 services/timestreamquery/ts_infer_funcs.go create mode 100644 services/timestreamquery/ts_infer_internal_test.go create mode 100644 services/timestreamquery/ts_prune.go create mode 100644 services/timestreamquery/ts_render.go create mode 100644 services/timestreamquery/ts_sdk_insights_test.go create mode 100644 services/timestreamquery/ts_sdk_types_test.go create mode 100644 services/timestreamquery/ts_sqlast.go create mode 100644 services/timestreamquery/ts_sqlexpr.go create mode 100644 services/timestreamquery/ts_sqllex.go create mode 100644 services/timestreamquery/ts_sqlparse.go create mode 100644 services/timestreamquery/ts_types.go diff --git a/pkgs/persistence/testdata/snapshot_inventory.json b/pkgs/persistence/testdata/snapshot_inventory.json index ab59e36fe3..55d545ceae 100644 --- a/pkgs/persistence/testdata/snapshot_inventory.json +++ b/pkgs/persistence/testdata/snapshot_inventory.json @@ -38327,6 +38327,8 @@ "QueryInsightsResponse.OutputRows int64 `json:\"OutputRows\"`", "QueryInsightsResponse.QuerySpatialCoverage float64 `json:\"QuerySpatialCoverage,omitempty\"`", "QueryInsightsResponse.QueryTableCount int64 `json:\"QueryTableCount\"`", + "QueryInsightsResponse.SpatialCoverage *QuerySpatialCoverage `json:\"spatial_coverage,omitempty\"`", + "QueryInsightsResponse.TemporalRange *QueryTemporalRange `json:\"temporal_range,omitempty\"`", "QueryInsightsResponse.UnloadPartitionCount int64 `json:\"UnloadPartitionCount,omitempty\"`", "QueryInsightsResponse.UnloadWrittenBytes int64 `json:\"UnloadWrittenBytes,omitempty\"`", "QueryInsightsResponse.UnloadWrittenRows int64 `json:\"UnloadWrittenRows,omitempty\"`", @@ -38336,9 +38338,16 @@ "QueryResult.QueryID string", "QueryResult.QueryStatus QueryStatusDetail", "QueryResult.Rows []Row", + "QuerySpatialCoverage.Max *QuerySpatialCoverageMax `json:\"Max,omitempty\"`", + "QuerySpatialCoverageMax.PartitionKey []string `json:\"PartitionKey\"`", + "QuerySpatialCoverageMax.TableArn string `json:\"TableArn\"`", + "QuerySpatialCoverageMax.Value float64 `json:\"Value\"`", "QueryStatusDetail.CumulativeBytesMetered int64 `json:\"CumulativeBytesMetered\"`", "QueryStatusDetail.CumulativeBytesScanned int64 `json:\"CumulativeBytesScanned\"`", "QueryStatusDetail.ProgressPercentage float64 `json:\"ProgressPercentage\"`", + "QueryTemporalRange.Max *QueryTemporalRangeMax `json:\"Max,omitempty\"`", + "QueryTemporalRangeMax.TableArn string `json:\"TableArn\"`", + "QueryTemporalRangeMax.Value int64 `json:\"Value\"`", "Row.Data []Datum `json:\"Data\"`", "S3ReportLocation.BucketName string `json:\"BucketName,omitempty\"`", "S3ReportLocation.ObjectKey string `json:\"ObjectKey,omitempty\"`", @@ -38369,7 +38378,9 @@ "ScheduledQuery.TargetTable string `json:\"target_table\"`", "ScheduledQueryInsightsResponse.OutputBytes int64 `json:\"OutputBytes\"`", "ScheduledQueryInsightsResponse.OutputRows int64 `json:\"OutputRows\"`", + "ScheduledQueryInsightsResponse.QuerySpatialCoverage *QuerySpatialCoverage `json:\"QuerySpatialCoverage,omitempty\"`", "ScheduledQueryInsightsResponse.QueryTableCount int64 `json:\"QueryTableCount\"`", + "ScheduledQueryInsightsResponse.QueryTemporalRange *QueryTemporalRange `json:\"QueryTemporalRange,omitempty\"`", "ScheduledQueryTargetDetail.DimensionMappings []DimensionMapping", "ScheduledQueryTargetDetail.MeasureNameColumn string", "ScheduledQueryTargetDetail.MixedMeasureMappings []MixedMeasureMapping", diff --git a/services/timestreamquery/PARITY.md b/services/timestreamquery/PARITY.md index 56d686914b..6634208b98 100644 --- a/services/timestreamquery/PARITY.md +++ b/services/timestreamquery/PARITY.md @@ -39,10 +39,9 @@ families: route_matching: {status: ok, note: "X-Amz-Target prefix Timestream_20181101., Content-Type application/x-amz-json-1.0 (awsjson1.0) verified against serializers.go (awsAwsjson10_*). DescribeEndpoints wired for SDK endpoint-discovery (fetchOpQueryDiscoverEndpoint calls DescribeEndpoints first)."} gaps: [] items_still_open: - - "Query engine typeof: the engine is SQLite, so typeof returns SQLite storage names (integer/text/real/null) rather than the Timestream names listed in supported-data-types.html (bigint, double, varchar, boolean, timestamp, date, time, interval, unknown); values carry no static type at the UDF boundary (ts_funcs.go), so a correct typeof needs the static type inference the engine lacks" - - "Time-series lambdas: filter/reduce lambdas are recognised only when the body reads the element as p.value/p.time, so a lambda over a timeseries that never reads the element falls through to the stock engine" - - "Query engine: result ColumnInfo types for non-boolean expressions are inferred from values (BIGINT/DOUBLE/VARCHAR/TIMESTAMP) and an empty result reports VARCHAR for computed non-boolean columns. Boolean typing (ts_boolean.go) is syntactic: a CASE/CAST wrapping booleans, or a boolean function outside the known list, still reports its engine type. Plain column references keep their declared type." - - "QueryInsightsResponse (Query and ExecuteScheduledQuery runs) carries OutputRows, OutputBytes and QueryTableCount but not QueryTemporalRange or QuerySpatialCoverage: both need time-predicate and partition-key pruning analysis the engine does not do (the dormant QuerySpatialCoverage float field in models.go is never set, so it cannot reach the wire; the SDK shape is a struct). ENABLED_WITH_RATE_CONTROL does not apply the 1 QPS rate limit, and an unknown QueryInsights.Mode is ignored rather than rejected. OutputBytes sums scalar value lengths only" + - "Static type inference (ts_infer.go) types every select-list expression before execution, but a query using a construct it cannot parse or type keeps the older value-based column typing (and syntactic boolean/interval typing, ts_boolean.go) for the affected columns: positional ? and named @parameters (PrepareQuery), AT TIME ZONE, TABLESAMPLE, recursive CTEs, transform() over a timeseries (the engine has no implementation), and any function without a return-type rule (SQLite built-ins outside the Timestream function list); an empty result of such a column still reports VARCHAR" + - "Unverified against the service: integer literals are typed INTEGER when they fit 32 bits else BIGINT (supported-data-types.html lists int and bigint but not which a literal gets), and typeof() prints array(T), row(name T, ...) and timeseries(T) for nested types where the page gives only the notations array[T,...], row(T,...) and timeseries[row(timestamp, T,...)]" + - "QueryInsights QuerySpatialCoverage reports the table's partition key as measure_name unless the RecordSource implements PartitionKeySource (TablePartitionKeys); internal/app's timestreamRecordSource (internal/app/timestream_source.go) does not implement it yet, so a table with a customer-defined partition key is not measured on that key" structural_gaps: - "CreateScheduledQuery KmsKeyId is stored and echoed, but there is no at-rest encryption layer to apply it to." @@ -93,6 +92,31 @@ queries in hours: 1; queries that take longer will timeout"); SQL support (no EX ColumnInfo BOOLEAN and ScalarValue "true"/"false" (ts_boolean.go; aliases of boolean expressions propagate through CTEs/subqueries). - Query timeout defaults to 1 hour (the earlier "60 s" note was wrong); `SetQueryTimeout` overrides it; expiry returns QueryExecutionException (HTTP 400). +## Static types and QueryInsights + +Sources: supported-data-types.html (types), using-query-insights.html and optimize-query-using-query-insights.html (insights examples, +1 QPS note), aws-sdk-go-v2/service/timestreamquery@v1.44.3 (ScalarType, QueryInsightsResponse, QueryTemporalRange, QuerySpatialCoverage). + +- ts_sqllex.go/ts_sqlparse.go/ts_sqlexpr.go parse the statement (comments skipped everywhere, including inside lambdas; bounded depth and token + count); ts_infer.go types every expression with the engine's coercions; ts_infer_funcs.go holds the return-type rules, and a test fails when a + function registered with the engine has no rule. ColumnInfo (Query and PrepareQuery), Datum rendering (ts_render.go: arrays, rows, timeseries, + DATE, TIME, intervals), typeof() and the timeseries filter/reduce recognition all read the inferred types. timestamp - timestamp becomes + an INTERVAL DAY TO SECOND via ts_tsdiff. +- Lambdas over a TIMESERIES-typed argument are recognised by that type, so bodies that never read the element work. +- QueryInsights is returned only for ENABLED_WITH_RATE_CONTROL (absent or DISABLED returns none), an unknown Mode is a ValidationException, and + a second enabled Query within one second on the same region gets ThrottlingException (backend clock). Scheduled-query runs carry the same + QueryTemporalRange/QuerySpatialCoverage; they are not rate limited. OutputBytes counts array, row and timeseries values. + +## Emulator choices where the vendor is silent + +- Time bounds come from comparisons, BETWEEN and AND of constants built from now(), ago(), bin(), literals and interval arithmetic; a side the + WHERE clause leaves open is the table's earliest queryable record (lower) or the query clock (upper), because the pages give only the + 365-day example without saying how an open side is measured. A table with no queryable records and an open lower side reports 0. +- Spatial coverage is the share of distinct partition-key tuples (measure_name, or the customer-defined key) of the queryable records that the + equality / IN / OR-of-equality predicates on the key admit; no key predicate is 1.0, a predicate on an empty table is 0.0. +- The ThrottlingException message text is not specified. +- Queries the engine runs are not rejected for operand type mismatches (for example varchar = bigint); the pages give no message or rule to copy. + ## Notes **2026-10-10 (realism pass):** Query and PrepareQuery reject statements that cannot parse (unknown leading keyword, unbalanced parentheses, unterminated literal) with ValidationException; this is a shallow check, not a SQL parser. CreateScheduledQuery validates Name (1-64 of letters, digits, `_`, `.`, `-`) and the query text; ListScheduledQueries tokens are opaque and malformed ones, or MaxResults over 1000, return ValidationException. Tests: TestQuerySyntaxValidation, TestScheduledQueryPagingAndNames. diff --git a/services/timestreamquery/errors.go b/services/timestreamquery/errors.go index 52e0435a4f..eb9001d21a 100644 --- a/services/timestreamquery/errors.go +++ b/services/timestreamquery/errors.go @@ -9,6 +9,8 @@ var ( ErrAlreadyExists = errors.New("ConflictException") // ErrValidation is returned when request input fails validation. ErrValidation = errors.New("ValidationException") + // ErrThrottling is returned when a request exceeds a documented rate limit. + ErrThrottling = errors.New("ThrottlingException") // ErrQueryExecution is returned when Timestream cannot run a query (for example on timeout). ErrQueryExecution = errors.New("QueryExecutionException") ) diff --git a/services/timestreamquery/handler.go b/services/timestreamquery/handler.go index c7ac977d5c..c52237905c 100644 --- a/services/timestreamquery/handler.go +++ b/services/timestreamquery/handler.go @@ -286,6 +286,8 @@ func (h *Handler) handleError(c *echo.Context, err error) error { return c.JSONBlob(http.StatusConflict, errorPayload("ConflictException", err.Error())) case errors.Is(err, ErrValidation): return c.JSONBlob(http.StatusBadRequest, errorPayload("ValidationException", err.Error())) + case errors.Is(err, ErrThrottling): + return c.JSONBlob(http.StatusBadRequest, errorPayload("ThrottlingException", err.Error())) case errors.Is(err, ErrQueryExecution): return c.JSONBlob(http.StatusBadRequest, errorPayload("QueryExecutionException", err.Error())) case errors.Is(err, ErrUnknownOperation): diff --git a/services/timestreamquery/handler_query_execution.go b/services/timestreamquery/handler_query_execution.go index 14a8ec30cd..d5d6d3cf1f 100644 --- a/services/timestreamquery/handler_query_execution.go +++ b/services/timestreamquery/handler_query_execution.go @@ -59,7 +59,7 @@ func (h *Handler) handleQuery(ctx context.Context, body []byte) ([]byte, error) resp["NextToken"] = page.NextToken } if page.Insights != nil { - resp["QueryInsightsResponse"] = page.Insights + resp["QueryInsightsResponse"] = queryInsightsWire(page.Insights) } return json.Marshal(resp, jsonx.V1()) @@ -119,3 +119,33 @@ func (h *Handler) handleCancelQuery(ctx context.Context, body []byte) ([]byte, e "CancellationMessage": "Query has been successfully cancelled.", }, jsonx.V1()) } + +func queryInsightsWire(in *QueryInsightsResponse) map[string]any { + out := map[string]any{ + "OutputRows": in.OutputRows, + "OutputBytes": in.OutputBytes, + "QueryTableCount": in.QueryTableCount, + } + + if in.UnloadPartitionCount != 0 { + out["UnloadPartitionCount"] = in.UnloadPartitionCount + } + + if in.UnloadWrittenRows != 0 { + out["UnloadWrittenRows"] = in.UnloadWrittenRows + } + + if in.UnloadWrittenBytes != 0 { + out["UnloadWrittenBytes"] = in.UnloadWrittenBytes + } + + if in.TemporalRange != nil { + out["QueryTemporalRange"] = in.TemporalRange + } + + if in.SpatialCoverage != nil { + out["QuerySpatialCoverage"] = in.SpatialCoverage + } + + return out +} diff --git a/services/timestreamquery/handler_scheduled_queries.go b/services/timestreamquery/handler_scheduled_queries.go index 37bb3cbb6c..79040ba23d 100644 --- a/services/timestreamquery/handler_scheduled_queries.go +++ b/services/timestreamquery/handler_scheduled_queries.go @@ -287,6 +287,10 @@ func (h *Handler) handleExecuteScheduledQuery(ctx context.Context, body []byte) insightsMode = req.QueryInsights.Mode } + if err := validateInsightsMode("queryInsights.mode", insightsMode); err != nil { + return nil, err + } + if err := h.Backend.ExecuteScheduledQuery(ctx, req.ScheduledQueryArn, invocationTime, insightsMode); err != nil { return nil, err } diff --git a/services/timestreamquery/models.go b/services/timestreamquery/models.go index 1e4b6262f2..890a3bb5c4 100644 --- a/services/timestreamquery/models.go +++ b/services/timestreamquery/models.go @@ -197,13 +197,38 @@ type clientTokenEntry struct { // QueryInsightsResponse holds the insights payload returned alongside query results. type QueryInsightsResponse struct { - OutputRows int64 `json:"OutputRows"` - OutputBytes int64 `json:"OutputBytes"` - UnloadPartitionCount int64 `json:"UnloadPartitionCount,omitempty"` - UnloadWrittenRows int64 `json:"UnloadWrittenRows,omitempty"` - UnloadWrittenBytes int64 `json:"UnloadWrittenBytes,omitempty"` - QuerySpatialCoverage float64 `json:"QuerySpatialCoverage,omitempty"` - QueryTableCount int64 `json:"QueryTableCount"` + TemporalRange *QueryTemporalRange `json:"temporal_range,omitempty"` + SpatialCoverage *QuerySpatialCoverage `json:"spatial_coverage,omitempty"` + OutputRows int64 `json:"OutputRows"` + OutputBytes int64 `json:"OutputBytes"` + UnloadPartitionCount int64 `json:"UnloadPartitionCount,omitempty"` + UnloadWrittenRows int64 `json:"UnloadWrittenRows,omitempty"` + UnloadWrittenBytes int64 `json:"UnloadWrittenBytes,omitempty"` + QuerySpatialCoverage float64 `json:"QuerySpatialCoverage,omitempty"` + QueryTableCount int64 `json:"QueryTableCount"` +} + +// QueryTemporalRange mirrors types.QueryTemporalRange. +type QueryTemporalRange struct { + Max *QueryTemporalRangeMax `json:"Max,omitempty"` +} + +// QueryTemporalRangeMax mirrors types.QueryTemporalRangeMax; Value is the scanned time range in nanoseconds. +type QueryTemporalRangeMax struct { + TableArn string `json:"TableArn"` + Value int64 `json:"Value"` +} + +// QuerySpatialCoverage mirrors types.QuerySpatialCoverage. +type QuerySpatialCoverage struct { + Max *QuerySpatialCoverageMax `json:"Max,omitempty"` +} + +// QuerySpatialCoverageMax mirrors types.QuerySpatialCoverageMax; Value is the fraction of partitions scanned. +type QuerySpatialCoverageMax struct { + TableArn string `json:"TableArn"` + PartitionKey []string `json:"PartitionKey"` + Value float64 `json:"Value"` } // ProvisionedCapacity holds the response-side provisioned-TCU configuration @@ -277,9 +302,11 @@ type ExecutionStats struct { // ScheduledQueryInsightsResponse mirrors types.ScheduledQueryInsightsResponse. type ScheduledQueryInsightsResponse struct { - OutputRows int64 `json:"OutputRows"` - OutputBytes int64 `json:"OutputBytes"` - QueryTableCount int64 `json:"QueryTableCount"` + QuerySpatialCoverage *QuerySpatialCoverage `json:"QuerySpatialCoverage,omitempty"` + QueryTemporalRange *QueryTemporalRange `json:"QueryTemporalRange,omitempty"` + OutputRows int64 `json:"OutputRows"` + OutputBytes int64 `json:"OutputBytes"` + QueryTableCount int64 `json:"QueryTableCount"` } // ErrorReportLocation holds the S3 error report location for a scheduled query run. diff --git a/services/timestreamquery/persistence_test.go b/services/timestreamquery/persistence_test.go index 1d2ce67ec1..f984f7a13d 100644 --- a/services/timestreamquery/persistence_test.go +++ b/services/timestreamquery/persistence_test.go @@ -343,3 +343,28 @@ func TestPersistence_RestoreInvalidJSON(t *testing.T) { }) } } + +func TestInMemoryBackend_SnapshotRestoreKeepsInsights(t *testing.T) { + t.Parallel() + + b := NewInMemoryBackend("000000000000", "us-east-1") + b.queries.Put(&QueryResult{ + QueryID: "q1", + Insights: QueryInsightsResponse{ + OutputRows: 2, + TemporalRange: &QueryTemporalRange{Max: &QueryTemporalRangeMax{TableArn: "arn", Value: 42}}, + SpatialCoverage: &QuerySpatialCoverage{ + Max: &QuerySpatialCoverageMax{TableArn: "arn", PartitionKey: []string{"host"}, Value: 0.5}, + }, + }, + }) + + restored := NewInMemoryBackend("000000000000", "us-east-1") + require.NoError(t, restored.Restore(t.Context(), b.Snapshot(t.Context()))) + + got, ok := restored.queries.Get("q1") + require.True(t, ok) + assert.Equal(t, int64(42), got.Insights.TemporalRange.Max.Value) + assert.InDelta(t, 0.5, got.Insights.SpatialCoverage.Max.Value, 1e-9) + assert.Equal(t, []string{"host"}, got.Insights.SpatialCoverage.Max.PartitionKey) +} diff --git a/services/timestreamquery/query_execution.go b/services/timestreamquery/query_execution.go index 932fdad252..c41bd86fa3 100644 --- a/services/timestreamquery/query_execution.go +++ b/services/timestreamquery/query_execution.go @@ -18,6 +18,7 @@ import ( const ( queryProgressComplete = 100.0 insightsModeEnabled = "ENABLED_WITH_RATE_CONTROL" + insightsModeDisabled = "DISABLED" ) // maxRetainedQueries bounds the queries map so a long-running instance cannot @@ -32,7 +33,7 @@ const maxRetainedQueries = 10000 // ctx is accepted for interface consistency; query results are not region-isolated. func (b *InMemoryBackend) QueryWithOptions(ctx context.Context, opts QueryOptions) (*QueryPage, error) { // Validate MaxRows. - maxRows, err := validateMaxRows(opts.MaxRows) + maxRows, err := validateQueryOptions(opts) if err != nil { return nil, err } @@ -56,7 +57,7 @@ func (b *InMemoryBackend) QueryWithOptions(ctx context.Context, opts QueryOption return nil, err } - if err = b.checkTableRefs(ctx, opts.QueryString); err != nil { + if err = b.checkTableRefs(ctx, stripSQLComments(opts.QueryString)); err != nil { return nil, err } @@ -66,6 +67,12 @@ func (b *InMemoryBackend) QueryWithOptions(ctx context.Context, opts QueryOption } } + region := getRegion(ctx, b.defaultRegion) + + if err = b.admitInsights(region, opts.InsightsMode); err != nil { + return nil, err + } + queryID := newQueryID() rs, err := b.execute(ctx, opts.QueryString, nil, queryID) @@ -80,7 +87,7 @@ func (b *InMemoryBackend) QueryWithOptions(ctx context.Context, opts QueryOption QueryStatus: status, Rows: rs.rows, Columns: rs.cols, - Insights: buildQueryInsightsResponse(rs), + Insights: b.buildQueryInsightsResponse(region, rs), } b.mu.Lock("QueryWithOptions") @@ -98,7 +105,7 @@ func (b *InMemoryBackend) QueryWithOptions(ctx context.Context, opts QueryOption } var insights *QueryInsightsResponse - if opts.InsightsMode != "DISABLED" { + if opts.InsightsMode == insightsModeEnabled { ins := result.Insights insights = &ins } @@ -226,6 +233,9 @@ func (b *InMemoryBackend) PrepareQuery( } cols, params := inferColumnsFromSQL(queryString) + if static, ok := b.staticColumns(ctx, queryString); ok { + cols = static + } return &PrepareQueryResult{ QueryString: queryString, @@ -287,13 +297,82 @@ func statusFor(rs *resultSet) QueryStatusDetail { } // buildQueryInsightsResponse builds the insights payload for a completed query. -func buildQueryInsightsResponse(rs *resultSet) QueryInsightsResponse { - return QueryInsightsResponse{ - OutputRows: int64(len(rs.rows)), - OutputBytes: rs.outBytes(), - +func (b *InMemoryBackend) buildQueryInsightsResponse(region string, rs *resultSet) QueryInsightsResponse { + resp := QueryInsightsResponse{ + OutputRows: int64(len(rs.rows)), + OutputBytes: rs.outBytes(), QueryTableCount: int64(rs.tables), } + + var temporal, spatial *tableScanInsight + + for i := range rs.scans { + s := &rs.scans[i] + if temporal == nil || s.rangeNs > temporal.rangeNs { + temporal = s + } + + if spatial == nil || s.coverage > spatial.coverage { + spatial = s + } + } + + if temporal != nil { + resp.TemporalRange = &QueryTemporalRange{ + Max: &QueryTemporalRangeMax{TableArn: b.tableARN(region, *temporal), Value: temporal.rangeNs}, + } + } + + if spatial != nil { + resp.SpatialCoverage = &QuerySpatialCoverage{ + Max: &QuerySpatialCoverageMax{ + TableArn: b.tableARN(region, *spatial), PartitionKey: spatial.keys, Value: spatial.coverage, + }, + } + } + + return resp +} + +func validateQueryOptions(opts QueryOptions) (int, error) { + if err := validateInsightsMode("queryInsights.mode", opts.InsightsMode); err != nil { + return 0, err + } + + return validateMaxRows(opts.MaxRows) +} + +// validateInsightsMode rejects a QueryInsights.Mode outside the documented enum. +func validateInsightsMode(field, mode string) error { + switch mode { + case "", insightsModeEnabled, insightsModeDisabled: + return nil + } + + return validationf( + "1 validation error detected: Value '%s' at '%s' failed to satisfy constraint: "+ + "Member must satisfy enum value set: [%s, %s]", + mode, field, insightsModeEnabled, insightsModeDisabled) +} + +// admitInsights applies the documented 1 query per second limit to queries run with insights enabled. +func (b *InMemoryBackend) admitInsights(region, mode string) error { + if mode != insightsModeEnabled { + return nil + } + + now := b.clock() + + b.mu.Lock("admitInsights") + defer b.mu.Unlock() + + if last, ok := b.insightsLast[region]; ok && now.Sub(last) < time.Second { + return fmt.Errorf("%w: query insights is limited to 1 query per second", ErrThrottling) + } + + b.insightsLast[region] = now + + return nil } // --------------------------------------------------------------------------- @@ -758,3 +837,35 @@ func inferScalarType(expr string) string { return ScalarTypeVarchar } } + +// staticColumns types the query's result columns from the referenced tables' schemas; ok is false when any column +// type cannot be inferred statically. +func (b *InMemoryBackend) staticColumns(ctx context.Context, queryString string) ([]ColumnInfo, bool) { + if b.recordSource() == nil { + return nil, false + } + + q := strings.TrimSpace(strings.TrimRight(strings.TrimSpace(stripSQLComments(queryString)), ";")) + + tables, _, err := loadSourceTables(getRegion(ctx, b.defaultRegion), b.recordSource(), q, b.clock()) + if err != nil { + return nil, false + } + + ann := annotateQuery(q, tables, b.clock(), nil) + if !ann.ok || len(ann.cols) == 0 { + return nil, false + } + + cols := make([]ColumnInfo, len(ann.cols)) + + for i, c := range ann.cols { + if !c.typ.known() { + return nil, false + } + + cols[i] = c.typ.columnInfo(columnName(c.name, i)) + } + + return cols, true +} diff --git a/services/timestreamquery/scheduled_write.go b/services/timestreamquery/scheduled_write.go index 6589f91b03..7c5c777134 100644 --- a/services/timestreamquery/scheduled_write.go +++ b/services/timestreamquery/scheduled_write.go @@ -46,9 +46,10 @@ func (b *InMemoryBackend) runScheduledQuery( var insights *ScheduledQueryInsightsResponse if withInsights { - q := buildQueryInsightsResponse(rs) + q := b.buildQueryInsightsResponse(getRegion(ctx, b.defaultRegion), rs) insights = &ScheduledQueryInsightsResponse{ OutputRows: q.OutputRows, OutputBytes: q.OutputBytes, QueryTableCount: q.QueryTableCount, + QueryTemporalRange: q.TemporalRange, QuerySpatialCoverage: q.SpatialCoverage, } } diff --git a/services/timestreamquery/source.go b/services/timestreamquery/source.go index 5bd8b9b08c..ff41e89961 100644 --- a/services/timestreamquery/source.go +++ b/services/timestreamquery/source.go @@ -77,6 +77,12 @@ type SchemaSource interface { TableShapes(region, database, table string) []SourceRecord } +// PartitionKeySource is optionally implemented by a RecordSource that knows a table's customer-defined partition key: +// the dimension names, or measure_name for a measure key, in schema order. +type PartitionKeySource interface { + TablePartitionKeys(region, database, table string) []string +} + // SetRecordSource wires the record source used to execute queries and scheduled-query writes. // It also serves as the table catalog. func (b *InMemoryBackend) SetRecordSource(s RecordSource) { diff --git a/services/timestreamquery/store.go b/services/timestreamquery/store.go index 68302c625b..c73e52df2a 100644 --- a/services/timestreamquery/store.go +++ b/services/timestreamquery/store.go @@ -53,6 +53,7 @@ type InMemoryBackend struct { notifier Notifier objects billingexport.ObjectStore nowFn func() time.Time + insightsLast map[string]time.Time accountID string defaultRegion string queryTimeout time.Duration @@ -87,6 +88,7 @@ func NewInMemoryBackend(accountID, region string) *InMemoryBackend { mu: lockmetrics.New("timestreamquery"), registry: store.NewRegistry(), accountSettings: make(map[string]AccountSettings), + insightsLast: make(map[string]time.Time), clientTokens: newClientTokenCache(queryClientTokenTTL), scheduledQueryTokens: newClientTokenCache(createScheduledQueryClientTokenTTL), pageStore: newNextTokenStore(), @@ -105,6 +107,7 @@ func (b *InMemoryBackend) Reset() { b.registry.ResetAll() b.accountSettings = make(map[string]AccountSettings) + b.insightsLast = make(map[string]time.Time) b.clientTokens = newClientTokenCache(queryClientTokenTTL) b.scheduledQueryTokens = newClientTokenCache(createScheduledQueryClientTokenTTL) b.pageStore = newNextTokenStore() diff --git a/services/timestreamquery/ts_annotate.go b/services/timestreamquery/ts_annotate.go new file mode 100644 index 0000000000..4862a40013 --- /dev/null +++ b/services/timestreamquery/ts_annotate.go @@ -0,0 +1,98 @@ +package timestreamquery + +import ( + "slices" + "strings" + "time" +) + +// annotation is a query with its type-dependent rewrites applied and the static type of each result column. +type annotation struct { + query string + cols []outCol + unsupported []string + scans []pruneScan + ok bool +} + +func compareEdits(a, b typedEdit) int { + switch { + case a.start != b.start: + return a.start - b.start + case a.closing != b.closing: + if a.closing { + return -1 + } + + return 1 + case a.closing: + return a.seq - b.seq + } + + return b.seq - a.seq +} + +func applyEdits(q string, edits []typedEdit) string { + sorted := slices.Clone(edits) + slices.SortStableFunc(sorted, compareEdits) + + var sb strings.Builder + + cur := 0 + + for _, e := range sorted { + if e.start < cur || e.end > len(q) { + continue + } + + sb.WriteString(q[cur:e.start]) + sb.WriteString(e.text) + + cur = e.end + } + + sb.WriteString(q[cur:]) + + return sb.String() +} + +// annotateQuery parses q and infers the type of every result column; ok is false when q is not parsed. +func annotateQuery(q string, tables loadedSet, now time.Time, vars map[string]string) annotation { + res := annotation{query: q} + + func() { + defer func() { _ = recover() }() + + res = buildAnnotation(q, tables, now, vars) + }() + + return res +} + +func buildAnnotation(q string, tables loadedSet, now time.Time, vars map[string]string) annotation { + qn, err := parseSQL(q) + if err != nil { + return annotation{query: q} + } + + inf := newInferrer(tables, now, vars) + cols := inf.inferQuery(qn, nil) + + return annotation{ + query: applyEdits(q, inf.edits), cols: cols, unsupported: inf.unsupported, scans: inf.scans, ok: true, + } +} + +// columnTypes returns the per-column static types, or nil when they cannot be aligned with n result columns. +func (a annotation) columnTypes(n int) []tsType { + if !a.ok || len(a.cols) != n { + return nil + } + + out := make([]tsType, n) + for i, c := range a.cols { + out[i] = c.typ + } + + return out +} diff --git a/services/timestreamquery/ts_boolean.go b/services/timestreamquery/ts_boolean.go index 5a6b1bf379..71199bd430 100644 --- a/services/timestreamquery/ts_boolean.go +++ b/services/timestreamquery/ts_boolean.go @@ -12,7 +12,7 @@ var reCallHead = regexp.MustCompile(`^([A-Za-z_][A-Za-z0-9_]*)\s*\(`) func isBooleanKeyword(w string) bool { switch w { - case "AND", "OR", "NOT", "IS", "LIKE", "BETWEEN", "IN", "EXISTS", + case opAnd, "OR", opNot, "IS", "LIKE", "BETWEEN", "IN", "EXISTS", "=", "<>", "!=", "<", ">", "<=", ">=": return true } @@ -271,7 +271,7 @@ func isBooleanExpr(expr string) bool { } if len(toks) == 1 { - return toks[0] == "TRUE" || toks[0] == "FALSE" || toks[0] == "NOT" || toks[0] == "EXISTS" + return toks[0] == "TRUE" || toks[0] == "FALSE" || toks[0] == opNot || toks[0] == "EXISTS" } return slices.ContainsFunc(toks, isBooleanKeyword) @@ -348,7 +348,7 @@ func applyBooleanTypes(rs *resultSet, query string) { plan := typedColumnPlan(query, names, isBooleanExpr) for i, isBool := range plan { - if !isBool || (rs.cols[i].Type.ScalarType != ScalarTypeBigint && len(rs.rows) != 0) { + if !isBool || rs.isStatic(i) || (rs.cols[i].Type.ScalarType != ScalarTypeBigint && len(rs.rows) != 0) { continue } @@ -385,7 +385,7 @@ func applyIntervalTypes(rs *resultSet, query string) { } for i, isInterval := range typedColumnPlan(query, names, isIntervalExpr) { - if isInterval { + if isInterval && !rs.isStatic(i) { rs.cols[i].Type.ScalarType = ScalarTypeIntervalDayToSecond } } diff --git a/services/timestreamquery/ts_boolean_test.go b/services/timestreamquery/ts_boolean_test.go index 938652ffe7..e50bd88f0a 100644 --- a/services/timestreamquery/ts_boolean_test.go +++ b/services/timestreamquery/ts_boolean_test.go @@ -38,8 +38,8 @@ func TestQuery_BooleanExpressionTypes(t *testing.T) { }, {"empty result", `SELECT measure_value::double > 5 AS big FROM db.t WHERE measure_name = 'nope'`, [][]string{}, []string{"big:BOOLEAN"}}, - {"arithmetic stays bigint", `SELECT 1 + 2 AS s, CASE WHEN 1 < 2 THEN 1 ELSE 0 END AS c`, - [][]string{{"3", "1"}}, []string{"s:BIGINT", "c:BIGINT"}}, + {"arithmetic stays integer", `SELECT 1 + 2 AS s, CASE WHEN 1 < 2 THEN 1 ELSE 0 END AS c`, + [][]string{{"3", "1"}}, []string{"s:INTEGER", "c:INTEGER"}}, {"string literal with operator", `SELECT 'a > b' AS s`, [][]string{{"a > b"}}, []string{"s:VARCHAR"}}, } diff --git a/services/timestreamquery/ts_engine.go b/services/timestreamquery/ts_engine.go index fe429e8b7e..30941d95ed 100644 --- a/services/timestreamquery/ts_engine.go +++ b/services/timestreamquery/ts_engine.go @@ -54,7 +54,7 @@ func (b *InMemoryBackend) execute( func (b *InMemoryBackend) executeStatement( ctx context.Context, query string, vars map[string]string, queryID string, ) (*resultSet, error) { - query = strings.TrimSpace(strings.TrimRight(strings.TrimSpace(query), ";")) + query = strings.TrimSpace(strings.TrimRight(strings.TrimSpace(stripSQLComments(query)), ";")) region := getRegion(ctx, b.defaultRegion) switch firstWord(query) { @@ -76,12 +76,14 @@ func (b *InMemoryBackend) executeStatement( return nil, err } - translated, err := translateTimestream(rewriteTimestream(query, now, vars), tables) + ann := annotateQuery(query, tables, now, vars) + + translated, err := translateTimestream(rewriteTimestream(ann.query, now, vars), tables) if err != nil { return nil, err } - rs, err := runTranslated(ctx, translated, tables) + rs, err := runTranslated(ctx, translated, tables, ann) if err != nil { return nil, err } @@ -90,6 +92,7 @@ func (b *InMemoryBackend) executeStatement( applyIntervalTypes(rs, query) rs.scanned = scanned rs.tables = len(tables) + rs.scans = b.scanInsights(region, ann.scans, tables, now, src) return rs, nil } @@ -104,9 +107,11 @@ func firstWord(q string) string { } type tableData struct { - sqlName string - schema tableSchema - records []SourceRecord + sqlName string + database string + table string + schema tableSchema + records []SourceRecord } type loadedSet map[string]*tableData @@ -143,9 +148,11 @@ func loadSourceTables( } set[key] = &tableData{ - sqlName: engineTablePrefix + strconv.Itoa(len(set)), - schema: deriveSchema(withShapes(src, region, ref, recs)), - records: recs, + sqlName: engineTablePrefix + strconv.Itoa(len(set)), + database: ref.database, + table: ref.table, + schema: deriveSchema(withShapes(src, region, ref, recs)), + records: recs, } } @@ -201,7 +208,7 @@ func translate(q string, set loadedSet) (string, error) { return out, nil } -func runTranslated(ctx context.Context, q string, set loadedSet) (*resultSet, error) { +func runTranslated(ctx context.Context, q string, set loadedSet, ann annotation) (*resultSet, error) { registerTimestreamFuncs() db, err := athena.OpenEngineDB() @@ -247,7 +254,7 @@ func runTranslated(ctx context.Context, q string, set loadedSet) (*resultSet, er } defer func() { _ = rows.Close() }() - rs, err := readRows(rows) + rs, err := readRows(rows, ann.columnTypes(columnCount(rows))) if err != nil { return nil, mapEngineError(err) } @@ -316,3 +323,12 @@ func mapEngineError(err error) error { return validationf("line 1:1: %s", reSQLiteTag.ReplaceAllString(msg, "")) } + +func columnCount(rows *sql.Rows) int { + names, err := rows.Columns() + if err != nil { + return -1 + } + + return len(names) +} diff --git a/services/timestreamquery/ts_funcs.go b/services/timestreamquery/ts_funcs.go index 52d149e143..cedcaffc3e 100644 --- a/services/timestreamquery/ts_funcs.go +++ b/services/timestreamquery/ts_funcs.go @@ -146,47 +146,81 @@ func toUnit(per func(time.Time) int64) func(*sqlitedriver.FunctionContext, []dri } } +type scalarImpl = func(*sqlitedriver.FunctionContext, []driver.Value) (driver.Value, error) + +type scalarFunc struct { + impl scalarImpl + name string + nargs int32 +} + +func scalarFn(name string, nargs int32, impl scalarImpl) scalarFunc { + return scalarFunc{name: name, nargs: nargs, impl: impl} +} + +// tsScalarFuncs lists the scalar functions this package registers with the engine. +func tsScalarFuncs() []scalarFunc { + isoYear := toUnit(func(t time.Time) int64 { + y, _ := t.ISOWeek() + + return int64(y) + }) + + return []scalarFunc{ + scalarFn("ts_bin", argsTwo, udfBin), + scalarFn("ts_ago", argsTwo, udfAgo), + scalarFn("ts_tsdiff", argsTwo, udfTimestampDiff), + scalarFn("from_milliseconds", 1, unitFunc(time.UnixMilli)), + scalarFn("from_nanoseconds", 1, unitFunc(func(n int64) time.Time { return time.Unix(0, n) })), + scalarFn("to_milliseconds", 1, toUnit(func(t time.Time) int64 { return t.UnixMilli() })), + scalarFn("to_nanoseconds", 1, toUnit(func(t time.Time) int64 { return t.UnixNano() })), + scalarFn("year_of_week", 1, isoYear), + scalarFn("yow", 1, isoYear), + scalarFn("nanosecond", 1, toUnit(func(t time.Time) int64 { return int64(t.Nanosecond()) })), + scalarFn("parse_duration", 1, udfParseDuration), + scalarFn("interpolate_linear", argsTwo, udfInterpolate(linearAt)), + scalarFn("interpolate_spline_cubic", argsTwo, udfInterpolate(splineAt)), + scalarFn("interpolate_locf", argsTwo, udfInterpolate(locfAt)), + scalarFn("interpolate_fill", argsThree, udfInterpolateFill), + scalarFn("derivative_linear", argsTwo, udfDerivative(false)), + scalarFn("non_negative_derivative_linear", argsTwo, udfDerivative(true)), + scalarFn("integral_trapezoidal", -1, udfIntegral), + scalarFn("correlate_pearson", argsTwo, udfCorrelate(false)), + scalarFn("correlate_spearman", argsTwo, udfCorrelate(true)), + scalarFn("sequence", -1, udfSequence), + scalarFn("ts_series_json", 1, udfSeriesJSON), + } +} + +// udfTimestampDiff implements timestamp - timestamp as an INTERVAL DAY TO SECOND. +func udfTimestampDiff(_ *sqlitedriver.FunctionContext, args []driver.Value) (driver.Value, error) { + if args[0] == nil || args[1] == nil { + return nil, nil //nolint:nilnil // SQL NULL + } + + a, okA := parseTSValue(args[0]) + b, okB := parseTSValue(args[1]) + + if !okA || !okB { + return nil, errBadArg + } + + return formatInterval(a.Sub(b).Nanoseconds()), nil +} + func registerTimestreamFuncs() { registerFuncsOnce.Do(func() { registerUnnestModule() - reg := sqlitedriver.MustRegisterDeterministicScalarFunction - reg("ts_bin", argsTwo, udfBin) - reg("ts_ago", argsTwo, udfAgo) - reg("from_milliseconds", 1, unitFunc(time.UnixMilli)) - reg("from_nanoseconds", 1, unitFunc(func(n int64) time.Time { return time.Unix(0, n) })) - reg("to_milliseconds", 1, toUnit(func(t time.Time) int64 { return t.UnixMilli() })) - reg("to_nanoseconds", 1, toUnit(func(t time.Time) int64 { return t.UnixNano() })) - isoYear := toUnit(func(t time.Time) int64 { - y, _ := t.ISOWeek() - - return int64(y) - }) - reg("year_of_week", 1, isoYear) - reg("yow", 1, isoYear) - reg("nanosecond", 1, toUnit(func(t time.Time) int64 { return int64(t.Nanosecond()) })) - reg("parse_duration", 1, udfParseDuration) - registerSeriesFuncs() - }) -} -func registerSeriesFuncs() { - reg := sqlitedriver.MustRegisterDeterministicScalarFunction - reg("interpolate_linear", argsTwo, udfInterpolate(linearAt)) - reg("interpolate_spline_cubic", argsTwo, udfInterpolate(splineAt)) - reg("interpolate_locf", argsTwo, udfInterpolate(locfAt)) - reg("interpolate_fill", argsThree, udfInterpolateFill) - reg("derivative_linear", argsTwo, udfDerivative(false)) - reg("non_negative_derivative_linear", argsTwo, udfDerivative(true)) - reg("integral_trapezoidal", -1, udfIntegral) - reg("correlate_pearson", argsTwo, udfCorrelate(false)) - reg("correlate_spearman", argsTwo, udfCorrelate(true)) - reg("sequence", -1, udfSequence) - reg("ts_series_json", 1, udfSeriesJSON) - - sqlitedriver.MustRegisterFunction("create_time_series", &sqlitedriver.FunctionImpl{ - NArgs: argsTwo, - MakeAggregate: func(_ fnCtx) (sqlitedriver.AggregateFunction, error) { - return &seriesAgg{}, nil - }, + for _, f := range tsScalarFuncs() { + sqlitedriver.MustRegisterDeterministicScalarFunction(f.name, f.nargs, f.impl) + } + + sqlitedriver.MustRegisterFunction("create_time_series", &sqlitedriver.FunctionImpl{ + NArgs: argsTwo, + MakeAggregate: func(_ fnCtx) (sqlitedriver.AggregateFunction, error) { + return &seriesAgg{}, nil + }, + }) }) } diff --git a/services/timestreamquery/ts_functions_test.go b/services/timestreamquery/ts_functions_test.go index 3ba48dae60..57d7e6c4f4 100644 --- a/services/timestreamquery/ts_functions_test.go +++ b/services/timestreamquery/ts_functions_test.go @@ -282,7 +282,7 @@ func TestQuery_TimeSeriesFunctions(t *testing.T) { "[2022-06-17 00:00:00.000000000, 2022-06-17 00:00:15.000000000, 2022-06-17 00:00:30.000000000]", "array(TIMESTAMP)", }, - {"sequence integers", `SELECT sequence(1, 5, 2)`, "[1, 3, 5]", "array(BIGINT)"}, + {"sequence integers", `SELECT sequence(1, 5, 2)`, "[1, 3, 5]", "array(INTEGER)"}, { "filter timeseries", `WITH v AS (SELECT ` + series + ` AS cpu ` + fromT + `) SELECT filter(cpu, x -> x.value > 15.0) FROM v`, diff --git a/services/timestreamquery/ts_infer.go b/services/timestreamquery/ts_infer.go new file mode 100644 index 0000000000..a7705e81ec --- /dev/null +++ b/services/timestreamquery/ts_infer.go @@ -0,0 +1,761 @@ +package timestreamquery + +import ( + "slices" + "strings" + "time" +) + +type column struct { + rel string + name string + typ tsType +} + +type scope struct { + vars map[string]tsType + outer *scope + cols []column +} + +func (s *scope) withVars(vars map[string]tsType) *scope { + return &scope{vars: vars, outer: s} +} + +type outCol struct { + name string + typ tsType +} + +// inferrer computes static types for a parsed query and collects the text edits that depend on them. +type inferrer struct { + tables loadedSet + vars map[string]string + rules map[string]funcRule + scans []pruneScan + now time.Time + ctes []map[string][]outCol + edits []typedEdit + unsupported []string + steps int +} + +const maxInferSteps = 200000 + +func newInferrer(tables loadedSet, now time.Time, vars map[string]string) *inferrer { + return &inferrer{tables: tables, rules: funcRules(), now: now, vars: vars} +} + +func (inf *inferrer) unsupportedf(reason string) tsType { + inf.unsupported = append(inf.unsupported, reason) + + return tsType{} +} + +func (inf *inferrer) edit(text string, start, end int) { + inf.edits = append(inf.edits, typedEdit{text: text, start: start, end: end, seq: len(inf.edits)}) +} + +func (inf *inferrer) closeEdit(text string, pos int) { + inf.edits = append(inf.edits, typedEdit{text: text, start: pos, end: pos, seq: len(inf.edits), closing: true}) +} + +func fieldType(t tsType, name string) tsType { + if t.kind != tyRow { + return tsType{} + } + + for _, f := range t.fields { + if strings.EqualFold(f.name, name) { + return f.typ + } + } + + return tsType{} +} + +func (s *scope) lookupVar(name string) (tsType, bool) { + for c := s; c != nil; c = c.outer { + for k, v := range c.vars { + if strings.EqualFold(k, name) { + return v, true + } + } + } + + return tsType{}, false +} + +func (s *scope) lookupColumn(rel, name string) (tsType, bool) { + for c := s; c != nil; c = c.outer { + for _, col := range c.cols { + if strings.EqualFold(col.name, name) && (rel == "" || strings.EqualFold(col.rel, rel)) { + return col.typ, true + } + } + } + + return tsType{}, false +} + +func (inf *inferrer) resolveColumn(parts []string, sc *scope) tsType { + if t, ok := sc.lookupVar(parts[0]); ok { + return fieldChain(t, parts[1:]) + } + + if len(parts) >= argsTwo { + if t, ok := sc.lookupColumn(parts[len(parts)-argsTwo], parts[len(parts)-1]); ok && len(parts) <= argsThree { + return t + } + } + + if t, ok := sc.lookupColumn("", parts[0]); ok { + return fieldChain(t, parts[1:]) + } + + if len(parts) == 1 { + return bareFunctionType(parts[0]) + } + + return tsType{} +} + +func fieldChain(t tsType, fields []string) tsType { + for _, f := range fields { + t = fieldType(t, f) + } + + return t +} + +func (inf *inferrer) inferAll(nodes []*node, sc *scope) []tsType { + out := make([]tsType, len(nodes)) + for i, n := range nodes { + out[i] = inf.infer(n, sc) + } + + return out +} + +func (inf *inferrer) infer(n *node, sc *scope) tsType { + if n == nil { + return tsType{} + } + + if inf.steps++; inf.steps > maxInferSteps { + return tsType{} + } + + switch n.kind { + case nLiteral, nInterval: + return n.typ + case nTypedLit: + if n.typ.kind == tyTime { + inf.edit("'"+strings.ReplaceAll(n.name, "'", "''")+"'", n.start, n.end) + } + + return n.typ + case nVar: + if strings.EqualFold(n.name, "@scheduled_runtime") { + return scalar(tyTimestamp) + } + + return inf.unsupportedf("query variable " + n.name) + case nParam: + return inf.unsupportedf("positional parameter") + case nColumn: + return inf.resolveColumn(n.parts, sc) + case nStar: + return tsType{} + case nCall: + return inf.inferCall(n, sc) + case nBinary, nUnary: + return inf.inferOperator(n, sc) + case nLambda: + return inf.unsupportedf("lambda outside a higher-order function") + default: + return inf.inferCompound(n, sc) + } +} + +func (inf *inferrer) inferCompound(n *node, sc *scope) tsType { + switch n.kind { + case nCase: + return inf.inferCase(n, sc) + case nCast: + inf.infer(n.args[0], sc) + + return n.typ + case nIsNull, nBetween, nInList, nLike: + inf.inferAll(n.args, sc) + + return scalar(tyBoolean) + case nInSub, nExists: + inf.inferAll(n.args, sc) + inf.inferQuery(n.sub, sc) + + return scalar(tyBoolean) + case nSubquery: + cols := inf.inferQuery(n.sub, sc) + if len(cols) != 1 { + return tsType{} + } + + return cols[0].typ + case nArrayCtor: + return inf.inferArrayCtor(n, sc) + case nRowCtor: + return inf.inferRowCtor(n, sc) + case nSubscript: + base := inf.infer(n.args[0], sc) + inf.infer(n.args[1], sc) + + if base.kind == tyArray { + return *base.elem + } + + return tsType{} + case nField: + return fieldType(inf.infer(n.args[0], sc), n.name) + default: + return tsType{} + } +} + +func (inf *inferrer) inferCase(n *node, sc *scope) tsType { + args := inf.inferAll(n.args, sc) + + skip := 0 + if n.operand { + skip = 1 + } + + res := scalar(tyUnknown) + pairs := len(args) - skip + + if n.hasElse { + pairs-- + res = args[len(args)-1] + } + + for i := skip + 1; i < skip+1+pairs; i += argsTwo { + res = supertype(res, args[i]) + } + + return res +} + +func (inf *inferrer) inferArrayCtor(n *node, sc *scope) tsType { + res := scalar(tyUnknown) + for _, t := range inf.inferAll(n.args, sc) { + res = supertype(res, t) + } + + if res.kind == tyInvalid { + return tsType{} + } + + return arrayOf(res) +} + +func (inf *inferrer) inferRowCtor(n *node, sc *scope) tsType { + fields := make([]tsField, len(n.args)) + for i, t := range inf.inferAll(n.args, sc) { + fields[i] = tsField{typ: t} + } + + return rowOf(fields) +} + +func (inf *inferrer) inferOperator(n *node, sc *scope) tsType { + args := inf.inferAll(n.args, sc) + + if n.kind == nUnary { + if n.name == opNot { + return scalar(tyBoolean) + } + + return args[0] + } + + switch n.name { + case opAnd, "OR", "=", "<>", "!=", "<", ">", "<=", ">=", "IS DISTINCT": + return scalar(tyBoolean) + case "||": + return concatType(args[0], args[1]) + } + + if n.name == "-" && args[0].kind == tyTimestamp && args[1].kind == tyTimestamp { + inf.edit("ts_tsdiff(", n.start, n.start) + inf.edit(",", n.opStart, n.opEnd) + inf.closeEdit(")", n.end) + + return scalar(tyIntervalDS) + } + + return arithType(n.name, args[0], args[1]) +} + +func concatType(a, b tsType) tsType { + if a.kind == tyArray || b.kind == tyArray { + return supertype(a, b) + } + + if a.kind == tyVarchar || b.kind == tyVarchar || a.kind == tyUnknown && b.kind == tyUnknown { + return scalar(tyVarchar) + } + + return tsType{} +} + +func arithType(op string, a, b tsType) tsType { + switch { + case a.kind == tyInvalid || b.kind == tyInvalid: + return tsType{} + case a.isNumeric() && b.isNumeric(): + return supertype(a, b) + case a.kind == tyUnknown && (b.isNumeric() || b.isInterval()): + return b + case b.kind == tyUnknown && (a.isNumeric() || a.isInterval()): + return a + } + + return intervalArith(op, a, b) +} + +func intervalArith(op string, a, b tsType) tsType { + addSub := op == "+" || op == "-" + + switch { + case a.isTemporal() && b.isInterval() && addSub: + return a + case a.isInterval() && b.isTemporal() && op == "+": + return b + case a.isInterval() && b.isInterval() && addSub: + return a + } + + return scaleOrDiff(op, a, b) +} + +func scaleOrDiff(op string, a, b tsType) tsType { + switch { + case a.isInterval() && b.isNumeric() && (op == "*" || op == "/"): + return a + case a.isNumeric() && b.isInterval() && op == "*": + return b + case a.kind == b.kind && (a.kind == tyDate || a.kind == tyTime) && op == "-": + return scalar(tyIntervalDS) + } + + return tsType{} +} + +// inferQuery types every output column of a query expression; clauses are visited for their edits. +func (inf *inferrer) inferQuery(qn *queryNode, outer *scope) []outCol { + frame := map[string][]outCol{} + inf.ctes = append(inf.ctes, frame) + + defer func() { inf.ctes = inf.ctes[:len(inf.ctes)-1] }() + + for _, c := range qn.ctes { + cols := inf.inferQuery(c.query, outer) + frame[strings.ToLower(c.name)] = renameCols(cols, c.cols) + } + + var cols []outCol + + if qn.setOp != "" { + cols = inf.inferSetOp(qn, outer) + } else { + cols = inf.inferSelect(qn.sel, qn, outer) + } + + return cols +} + +func renameCols(cols []outCol, names []string) []outCol { + out := slices.Clone(cols) + for i := range names { + if i < len(out) { + out[i].name = names[i] + } + } + + return out +} + +func (inf *inferrer) inferSetOp(qn *queryNode, outer *scope) []outCol { + l, r := inf.inferQuery(qn.left, outer), inf.inferQuery(qn.right, outer) + out := slices.Clone(l) + + for i := range out { + if i >= len(r) { + out[i].typ = tsType{} + + continue + } + + out[i].typ = supertype(l[i].typ, r[i].typ) + } + + inf.orderBy(qn, &scope{outer: outer}, out) + + return out +} + +func (inf *inferrer) orderBy(qn *queryNode, sc *scope, out []outCol) { + if len(qn.orderBy) == 0 && len(qn.limit) == 0 { + return + } + + alias := &scope{outer: sc} + for _, c := range out { + if c.name != "" { + alias.cols = append(alias.cols, column{name: c.name, typ: c.typ}) + } + } + + for _, o := range qn.orderBy { + inf.infer(o.expr, alias) + } +} + +func (inf *inferrer) inferSelect(sel *selectSpec, qn *queryNode, outer *scope) []outCol { + sc := &scope{outer: outer} + if sel.from != nil { + sc.cols = inf.relationColumns(sel.from, outer) + inf.recordScans(sel) + } + + inf.infer(sel.where, sc) + + for _, g := range sel.groupBy { + inf.infer(g, sc) + } + + inf.infer(sel.having, sc) + + out := make([]outCol, 0, len(sel.items)) + + for _, it := range sel.items { + out = append(out, inf.inferItem(it, sc)...) + } + + inf.orderBy(qn, sc, out) + + return out +} + +func itemName(it selectItem) string { + if it.alias != "" { + return it.alias + } + + if it.expr != nil && it.expr.kind == nColumn { + return it.expr.parts[len(it.expr.parts)-1] + } + + return "" +} + +func (inf *inferrer) inferItem(it selectItem, sc *scope) []outCol { + if !it.star { + return []outCol{{name: itemName(it), typ: inf.infer(it.expr, sc)}} + } + + var out []outCol + + for _, c := range sc.cols { + if len(it.qual) == 0 || strings.EqualFold(c.rel, it.qual[len(it.qual)-1]) { + out = append(out, outCol{name: c.name, typ: c.typ}) + } + } + + return out +} + +func (inf *inferrer) lookupCTE(name string) ([]outCol, bool) { + for _, frame := range slices.Backward(inf.ctes) { + if cols, ok := frame[strings.ToLower(name)]; ok { + return cols, true + } + } + + return nil, false +} + +func qualify(rel string, cols []outCol, aliases []string) []column { + out := make([]column, len(cols)) + for i, c := range renameCols(cols, aliases) { + out[i] = column{rel: rel, name: c.name, typ: c.typ} + } + + return out +} + +func (inf *inferrer) relationColumns(r *relation, outer *scope) []column { + switch r.kind { + case relTable: + return inf.tableColumns(r) + case relSubquery: + return qualify(r.alias, inf.inferQuery(r.sub, outer), r.colAliases) + case relJoin: + return inf.joinColumns(r, outer) + case relUnnest: + return inf.unnestColumns(r, outer) + case relValues: + return inf.valuesColumns(r, outer) + } + + return nil +} + +func (inf *inferrer) tableColumns(r *relation) []column { + rel := r.alias + if rel == "" { + rel = r.ref[len(r.ref)-1] + } + + if len(r.ref) == 1 { + if cols, ok := inf.lookupCTE(r.ref[0]); ok { + return qualify(rel, cols, r.colAliases) + } + + inf.unsupportedf("unresolved relation " + r.ref[0]) + + return nil + } + + t, ok := inf.tables[tableKey(r.ref[0], r.ref[1])] + if !ok || len(r.ref) != argsTwo { + inf.unsupportedf("unresolved table") + + return nil + } + + cols := make([]outCol, len(t.schema.cols)) + for i, c := range t.schema.cols { + cols[i] = outCol{name: c.name, typ: typeFromDecl(c.typ)} + } + + return qualify(rel, cols, r.colAliases) +} + +func (inf *inferrer) joinColumns(r *relation, outer *scope) []column { + left, right := inf.relationColumns(r.left, outer), inf.relationColumns(r.right, outer) + all := slices.Concat(left, right) + inf.infer(r.on, &scope{cols: all, outer: outer}) + + if len(r.using) == 0 { + return all + } + + var merged []column + + isUsing := func(c column) bool { + return slices.ContainsFunc(r.using, func(u string) bool { return strings.EqualFold(u, c.name) }) + } + + for _, u := range r.using { + for _, c := range left { + if strings.EqualFold(c.name, u) { + merged = append(merged, c) + + break + } + } + } + + for _, c := range left { + if !isUsing(c) { + merged = append(merged, c) + } + } + + for _, c := range right { + if !isUsing(c) { + merged = append(merged, c) + } + } + + return merged +} + +func (inf *inferrer) unnestColumns(r *relation, outer *scope) []column { + var cols []outCol + + sc := &scope{outer: outer} + + for _, a := range r.args { + t := inf.infer(a, sc) + + switch t.kind { + case tyArray: + cols = append(cols, outCol{typ: *t.elem}) + case tyTimeseries: + cols = append(cols, outCol{name: colTime, typ: scalar(tyTimestamp)}, outCol{name: colValue, typ: *t.elem}) + default: + cols = append(cols, outCol{}) + } + } + + if r.ordinality { + cols = append(cols, outCol{name: "ordinality", typ: scalar(tyBigint)}) + } + + return qualify(r.alias, cols, r.colAliases) +} + +func (inf *inferrer) valuesColumns(r *relation, outer *scope) []column { + var cols []outCol + + sc := &scope{outer: outer} + + for _, row := range r.rows { + for i, t := range inf.inferAll(row, sc) { + if i >= len(cols) { + cols = append(cols, outCol{typ: t}) + + continue + } + + cols[i].typ = supertype(cols[i].typ, t) + } + } + + return qualify(r.alias, cols, r.colAliases) +} + +func (inf *inferrer) inferCall(n *node, sc *scope) tsType { + lw := strings.ToLower(n.name) + + if t, ok := inf.inferHigherOrder(lw, n, sc); ok { + return t + } + + args := inf.inferAll(n.args, sc) + + if lw == "typeof" && len(args) == 1 && !n.over { + return inf.inferTypeof(n, args[0]) + } + + rule, ok := inf.rules[lw] + if !ok { + return inf.unsupportedf("function " + lw) + } + + return rule(&callCtx{inf: inf, n: n, args: args}) +} + +func (inf *inferrer) inferTypeof(n *node, arg tsType) tsType { + if arg.known() { + inf.edit("(CASE WHEN 0 THEN ", n.start, n.start+len(n.name)) + inf.closeEdit(" ELSE '"+arg.typeofName()+"' END)", n.end) + } + + return scalar(tyVarchar) +} + +func lambdaParam(t tsType) tsType { + if t.kind == tyTimeseries { + return rowOf([]tsField{{name: colTime, typ: scalar(tyTimestamp)}, {name: colValue, typ: *t.elem}}) + } + + if t.kind == tyArray { + return *t.elem + } + + return tsType{} +} + +func (inf *inferrer) lambdaBody(l *node, sc *scope, params ...tsType) tsType { + if l.kind != nLambda || len(l.params) != len(params) || len(l.args) == 0 { + return tsType{} + } + + vars := map[string]tsType{} + for i, t := range params { + if i < len(l.params) { + vars[l.params[i]] = t + } + } + + return inf.infer(l.arg(0), sc.withVars(vars)) +} + +// inferHigherOrder types filter/transform/reduce and the *_match functions, whose lambdas see the element type. +func (inf *inferrer) inferHigherOrder(lw string, n *node, sc *scope) (tsType, bool) { + switch lw { + case fnFilter, "transform", "any_match", "all_match", "none_match": + if len(n.args) != argsTwo { + return tsType{}, false + } + + subject := inf.infer(n.args[0], sc) + body := inf.lambdaBody(n.args[1], sc, lambdaParam(subject)) + + return inf.higherOrderResult(lw, n, subject, body), true + case "reduce": + if len(n.args) != argsFour { + return tsType{}, false + } + + return inf.inferReduce(n, sc), true + } + + return tsType{}, false +} + +func (inf *inferrer) higherOrderResult(lw string, n *node, subject, body tsType) tsType { + switch lw { + case fnFilter: + if subject.kind == tyTimeseries && isLambda(n.args[1], 1) { + inf.edit("ts_", n.start, n.start) + } + + return subject + case "transform": + if subject.kind == tyArray && body.known() { + return arrayOf(body) + } + + return tsType{} + } + + return scalar(tyBoolean) +} + +const argsFour = 4 + +func isLambda(n *node, params int) bool { return n.kind == nLambda && len(n.params) == params } + +func (inf *inferrer) inferReduce(n *node, sc *scope) tsType { + subject, init := inf.infer(n.args[0], sc), inf.infer(n.args[1], sc) + elem := lambdaParam(subject) + + if subject.kind == tyTimeseries && isLambda(n.args[2], argsTwo) && isLambda(n.args[3], 1) { + inf.edit("ts_", n.start, n.start) + } + + state := init + if step := inf.lambdaBody(n.args[2], sc, init, elem); step.known() { + state = supertype(init, step) + } + + return inf.lambdaBody(n.args[3], sc, state) +} + +// bareFunctionType types the parenthesis-free SQL functions such as current_date. +func bareFunctionType(name string) tsType { + switch strings.ToLower(name) { + case "current_date": + return scalar(tyDate) + case "current_time", "localtime": + return scalar(tyTime) + case fnCurTS, fnLocalTS: + return scalar(tyTimestamp) + } + + return tsType{} +} diff --git a/services/timestreamquery/ts_infer_funcs.go b/services/timestreamquery/ts_infer_funcs.go new file mode 100644 index 0000000000..83b03783e8 --- /dev/null +++ b/services/timestreamquery/ts_infer_funcs.go @@ -0,0 +1,249 @@ +package timestreamquery + +import ( + "maps" + "strings" +) + +type callCtx struct { + inf *inferrer + n *node + args []tsType +} + +type funcRule func(c *callCtx) tsType + +func fixed(k tsKind) funcRule { return func(*callCtx) tsType { return scalar(k) } } + +func same(i int) funcRule { + return func(c *callCtx) tsType { + if i < len(c.args) { + return c.args[i] + } + + return tsType{} + } +} + +func elemOf(i int) funcRule { + return func(c *callCtx) tsType { + if i < len(c.args) && c.args[i].kind == tyArray { + return *c.args[i].elem + } + + return tsType{} + } +} + +func arrayOfArg(i int) funcRule { + return func(c *callCtx) tsType { + if i < len(c.args) && c.args[i].kind != tyInvalid { + return arrayOf(c.args[i]) + } + + return tsType{} + } +} + +func arrayOfKind(k tsKind) funcRule { + return func(*callCtx) tsType { return arrayOf(scalar(k)) } +} + +func seriesOfDouble(*callCtx) tsType { return seriesOf(scalar(tyDouble)) } + +func superAll(c *callCtx) tsType { + res := scalar(tyUnknown) + for _, a := range c.args { + res = supertype(res, a) + } + + return res +} + +func superFrom(from int) funcRule { + return func(c *callCtx) tsType { + res := scalar(tyUnknown) + + for i := from; i < len(c.args); i++ { + res = supertype(res, c.args[i]) + } + + return res + } +} + +func internalFn(*callCtx) tsType { return tsType{} } + +func unsupportedFn(reason string) funcRule { + return func(c *callCtx) tsType { return c.inf.unsupportedf(reason) } +} + +func sumRule(c *callCtx) tsType { + if len(c.args) == 0 { + return tsType{} + } + + switch c.args[0].kind { + case tyInteger, tyBigint: + return scalar(tyBigint) + case tyDouble: + return scalar(tyDouble) + default: + return tsType{} + } +} + +func concatRule(c *callCtx) tsType { + for _, a := range c.args { + if a.kind == tyArray { + return superAll(c) + } + } + + return scalar(tyVarchar) +} + +func createSeriesRule(c *callCtx) tsType { + if len(c.args) == argsTwo && c.args[1].known() { + return seriesOf(c.args[1]) + } + + return tsType{} +} + +func interpolateRule(c *callCtx) tsType { + if len(c.args) < argsTwo || c.args[0].kind != tyTimeseries { + return tsType{} + } + + if c.args[1].kind == tyTimestamp { + return *c.args[0].elem + } + + return c.args[0] +} + +func binRule(c *callCtx) tsType { + if len(c.args) > 0 && (c.args[0].isTemporal() || c.args[0].isNumeric()) { + return c.args[0] + } + + return tsType{} +} + +func sequenceRule(c *callCtx) tsType { + t := superFrom(0)(c) + if t.kind == tyDate { + return arrayOf(t) + } + + if t.known() { + return arrayOf(t) + } + + return tsType{} +} + +func funcRules() map[string]funcRule { + m := map[string]funcRule{} + for _, group := range []map[string]funcRule{ + bigintRules(), doubleRules(), varcharRules(), booleanRules(), temporalRules(), passThroughRules(), + collectionRules(), seriesRules(), + } { + maps.Copy(m, group) + } + + return m +} + +func ruleSet(r funcRule, names string) map[string]funcRule { + m := map[string]funcRule{} + for n := range strings.FieldsSeq(names) { + m[n] = r + } + + return m +} + +func union(sets ...map[string]funcRule) map[string]funcRule { + m := map[string]funcRule{} + for _, s := range sets { + maps.Copy(m, s) + } + + return m +} + +func bigintRules() map[string]funcRule { + return ruleSet(fixed(tyBigint), "count count_if approx_distinct length char_length character_length cardinality "+ + "strpos instr position levenshtein_distance hamming_distance codepoint unicode json_array_length json_size "+ + "year month day day_of_month hour minute second millisecond quarter week week_of_year day_of_week dow "+ + "day_of_year doy year_of_week yow nanosecond to_milliseconds to_nanoseconds date_diff regexp_count "+ + "bitwise_and bitwise_or bitwise_xor bitwise_not bit_count crc32 row_number rank dense_rank ntile "+ + "array_position extract width_bucket") +} + +func doubleRules() map[string]funcRule { + return ruleSet(fixed(tyDouble), "avg stddev stddev_pop stddev_samp variance var_pop var_samp corr covar_pop "+ + "covar_samp geometric_mean sqrt cbrt exp ln log log10 log2 pi e rand random radians degrees sin cos tan asin "+ + "acos atan atan2 sinh cosh tanh asinh acosh atanh power pow to_unixtime integral_trapezoidal "+ + "correlate_pearson correlate_spearman cume_dist percent_rank total infinity nan regr_slope regr_intercept") +} + +func varcharRules() map[string]funcRule { + return union( + ruleSet(fixed(tyVarchar), "lower upper trim ltrim rtrim replace substr substring lpad rpad split_part "+ + "regexp_extract regexp_replace to_hex md5 sha1 sha256 sha512 to_base64 from_base64 from_hex to_utf8 "+ + "from_utf8 date_format format_datetime to_iso8601 json_format json_extract_scalar json_extract json_parse "+ + "typeof url_extract_fragment url_extract_host url_extract_parameter url_extract_path "+ + "url_extract_protocol url_extract_query chr array_join format current_timezone concat_ws "+ + "printf hex char quote group_concat string_agg listagg soundex json_array json_object"), + map[string]funcRule{"concat": concatRule}, + ) +} + +func booleanRules() map[string]funcRule { + return ruleSet(fixed(tyBoolean), "contains regexp_like starts_with ends_with is_nan is_finite is_infinite "+ + "any_match all_match none_match bool_and bool_or every arrays_overlap json_array_contains is_json_scalar "+ + "like glob") +} + +func temporalRules() map[string]funcRule { + return union( + ruleSet(fixed(tyTimestamp), "now current_timestamp localtimestamp ago ts_ago from_unixtime from_milliseconds "+ + "from_nanoseconds from_iso8601_timestamp parse_datetime date_parse"), + ruleSet(fixed(tyDate), "current_date from_iso8601_date to_date date last_day_of_month"), + ruleSet(fixed(tyTime), "current_time localtime"), + ruleSet(fixed(tyIntervalDS), "parse_duration ts_tsdiff"), + map[string]funcRule{"date_trunc": same(1), "date_add": same(argsTwo), "bin": binRule, "ts_bin": binRule}, + ) +} + +func passThroughRules() map[string]funcRule { + return union( + ruleSet(same(0), "min max arbitrary any_value first_value last_value lag lead nth_value max_by min_by "+ + "approx_percentile nullif abs round ceil ceiling floor truncate trunc sign try mod"), + ruleSet(superAll, "coalesce greatest least ifnull"), + map[string]funcRule{"sum": sumRule, "if": superFrom(1), "iif": superFrom(1)}, + ) +} + +func collectionRules() map[string]funcRule { + return union( + ruleSet(same(0), "array_distinct array_sort array_remove slice reverse array_concat"), + ruleSet(arrayOfKind(tyVarchar), "split regexp_extract_all regexp_split"), + ruleSet(elemOf(0), "array_max array_min element_at"), + map[string]funcRule{"array_agg": arrayOfArg(0), "sequence": sequenceRule}, + ruleSet(unsupportedFn("map type"), "map map_agg map_keys map_values histogram"), + ruleSet(internalFn, "array elem field fold index_list iv_cast iv_dt iv_op iv_part iv_str iv_ym row row_cast "+ + "row_compare row_max row_min row_sortkey subscript unmark"), + ) +} + +func seriesRules() map[string]funcRule { + return union( + ruleSet(interpolateRule, "interpolate_linear interpolate_spline_cubic interpolate_locf interpolate_fill"), + ruleSet(seriesOfDouble, "derivative_linear non_negative_derivative_linear"), + map[string]funcRule{"create_time_series": createSeriesRule, "ts_series_json": internalFn}, + ) +} diff --git a/services/timestreamquery/ts_infer_internal_test.go b/services/timestreamquery/ts_infer_internal_test.go new file mode 100644 index 0000000000..058ece804f --- /dev/null +++ b/services/timestreamquery/ts_infer_internal_test.go @@ -0,0 +1,143 @@ +package timestreamquery + +import ( + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/athena" +) + +func TestEveryEngineFunctionHasReturnTypeRule(t *testing.T) { + t.Parallel() + + registerTimestreamFuncs() + + db, err := athena.OpenEngineDB() + require.NoError(t, err) + + t.Cleanup(func() { _ = db.Close() }) + + rows, err := db.QueryContext( + t.Context(), + `SELECT DISTINCT name FROM pragma_function_list WHERE name LIKE 'athena\_%' ESCAPE '\'`, + ) + require.NoError(t, err) + + defer func() { _ = rows.Close() }() + + names := map[string]bool{"create_time_series": true} + + for rows.Next() { + var n string + require.NoError(t, rows.Scan(&n)) + + names[strings.TrimPrefix(n, "athena_")] = true + } + + require.NoError(t, rows.Err()) + + for _, f := range tsScalarFuncs() { + names[f.name] = true + } + + require.Greater(t, len(names), 100) + + rules := funcRules() + + for name := range names { + assert.Contains(t, rules, name, "engine function %q has no return-type rule", name) + } +} + +func TestParseSQLBounds(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + query string + ok bool + }{ + {"simple", "SELECT 1", true}, + {"deep parens", "SELECT " + strings.Repeat("(", 5000) + "1" + strings.Repeat(")", 5000), false}, + {"deep subqueries", strings.Repeat("SELECT * FROM (", 3000) + "SELECT 1" + strings.Repeat(")", 3000), false}, + {"unterminated string", "SELECT 'abc", false}, + {"garbage", "SELECT ) FROM", false}, + {"lone operators", "SELECT + - * /", false}, + {"unterminated comment", "SELECT 1 /* abc", true}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + _, err := parseSQL(tc.query) + assert.Equal(t, tc.ok, err == nil) + }) + } +} + +func TestStripSQLComments(t *testing.T) { + t.Parallel() + + tests := []struct{ name, in, want string }{ + {"line", "SELECT 1 -- c\nFROM t", "SELECT 1 \nFROM t"}, + {"block", "SELECT /* c */ 1", "SELECT 1"}, + {"string", "SELECT '-- x', '/* y */'", "SELECT '-- x', '/* y */'"}, + {"quoted ident", `SELECT "a--b"`, `SELECT "a--b"`}, + {"unterminated", "SELECT 1 /* x", "SELECT 1 "}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, tc.want, stripSQLComments(tc.in)) + }) + } +} + +func TestAnnotateReportsUnsupportedFunction(t *testing.T) { + t.Parallel() + + ann := annotateQuery("SELECT some_future_function(1), 2", loadedSet{}, time.Time{}, nil) + require.True(t, ann.ok) + require.Len(t, ann.cols, 2) + + assert.False(t, ann.cols[0].typ.known()) + assert.Equal(t, tyInteger, ann.cols[1].typ.kind) + assert.Equal(t, []string{"function some_future_function"}, ann.unsupported) +} + +func TestAnnotateParsesAnalyticClauses(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + query string + want tsKind + }{ + {"window clause", "SELECT rank() OVER w FROM t WINDOW w AS (PARTITION BY a ORDER BY b)", tyBigint}, + {"grouping sets", "SELECT count(*) FROM t GROUP BY GROUPING SETS ((a), (b))", tyBigint}, + {"rollup", "SELECT count(*) FROM t GROUP BY ROLLUP (a, b)", tyBigint}, + {"filter clause", "SELECT count(*) FILTER (WHERE a > 1) FROM t", tyBigint}, + {"quoted identifiers", `SELECT "my col" FROM (SELECT 1 AS "my col")`, tyInteger}, + {"correlated subquery", "SELECT (SELECT max(1.5)) FROM (SELECT 1 AS a)", tyDouble}, + {"in subquery", "SELECT 1 IN (SELECT 2)", tyBoolean}, + {"union precedence", "SELECT 1 UNION SELECT 2.5 INTERSECT SELECT 3", tyDouble}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + ann := annotateQuery(tc.query, loadedSet{}, time.Time{}, nil) + require.True(t, ann.ok, "query must parse") + require.NotEmpty(t, ann.cols) + assert.Equal(t, tc.want, ann.cols[0].typ.kind) + }) + } +} diff --git a/services/timestreamquery/ts_interval_type_test.go b/services/timestreamquery/ts_interval_type_test.go index b45cd91adc..ff83df6766 100644 --- a/services/timestreamquery/ts_interval_type_test.go +++ b/services/timestreamquery/ts_interval_type_test.go @@ -15,7 +15,7 @@ func TestQueryIntervalColumnType(t *testing.T) { query string want []string }{ - {"direct", "SELECT parse_duration('42.8ms') AS d, 1 AS n", []string{"INTERVAL_DAY_TO_SECOND", "BIGINT"}}, + {"direct", "SELECT parse_duration('42.8ms') AS d, 1 AS n", []string{"INTERVAL_DAY_TO_SECOND", "INTEGER"}}, { "through an alias", "SELECT d FROM (SELECT parse_duration('1d') AS d) AS t", []string{"INTERVAL_DAY_TO_SECOND"}, diff --git a/services/timestreamquery/ts_lambda.go b/services/timestreamquery/ts_lambda.go index f573a586e6..eb4b3b422b 100644 --- a/services/timestreamquery/ts_lambda.go +++ b/services/timestreamquery/ts_lambda.go @@ -11,7 +11,7 @@ const placeholderPrefix = "__tsl" var ( reLambdaOne = regexp.MustCompile(`(?s)^\s*([A-Za-z_]\w*)\s*->\s*(.*)$`) reLambdaTwo = regexp.MustCompile(`(?s)^\s*\(\s*([A-Za-z_]\w*)\s*,\s*([A-Za-z_]\w*)\s*\)\s*->\s*(.*)$`) - reCallStart = regexp.MustCompile(`(?i)\b(filter|reduce|unnest)\s*\(`) + reCallStart = regexp.MustCompile(`(?i)\b(ts_filter|ts_reduce|filter|reduce|unnest)\s*\(`) reOrdinal = regexp.MustCompile(`(?is)^\s+with\s+ordinality\b`) reUnnestAs = regexp.MustCompile(`(?is)^\s+as\s+([A-Za-z_]\w*)(?:\s*\(([^)]*)\))?`) reUnnestBare = regexp.MustCompile(`(?is)^\s+([A-Za-z_]\w*)\s*\(([^)]*)\)`) @@ -143,15 +143,21 @@ func replaceOutsideStrings(s, old, repl string) string { return sb.String() } +// classify recognises a timeseries lambda call: ts_-tagged calls were typed as timeseries by inference, untagged +// ones (queries inference could not parse) are recognised by the lambda reading the element. func classify(name string, args []string) (seriesSub, bool) { - switch strings.ToLower(name) { - case "filter": + lw := strings.ToLower(name) + typed := strings.HasPrefix(lw, "ts_") + isSeries := func(p, body string) bool { return typed || seriesLambda(p, body) } + + switch strings.TrimPrefix(lw, "ts_") { + case fnFilter: if len(args) != argsTwo { return seriesSub{}, false } m := reLambdaOne.FindStringSubmatch(args[1]) - if m == nil || !seriesLambda(m[1], m[2]) { + if m == nil || !isSeries(m[1], m[2]) { return seriesSub{}, false } @@ -165,7 +171,7 @@ func classify(name string, args []string) (seriesSub, bool) { step := reLambdaTwo.FindStringSubmatch(args[2]) out := reLambdaOne.FindStringSubmatch(args[3]) - if step == nil || out == nil || !seriesLambda(step[2], step[3]) { + if step == nil || out == nil || !isSeries(step[2], step[3]) { return seriesSub{}, false } @@ -325,7 +331,7 @@ func rewriteUnnest( return pos, false } - alias, cols, end := "", []string{"time", "value"}, closeIdx+1 + alias, cols, end := "", []string{colTime, colValue}, closeIdx+1 m := reUnnestAs.FindStringSubmatch(tail) if m == nil { diff --git a/services/timestreamquery/ts_prune.go b/services/timestreamquery/ts_prune.go new file mode 100644 index 0000000000..3dbebd38d7 --- /dev/null +++ b/services/timestreamquery/ts_prune.go @@ -0,0 +1,540 @@ +package timestreamquery + +import ( + "slices" + "strconv" + "strings" + "time" + + "github.com/blackbirdworks/gopherstack/pkgs/arn" +) + +// pruneScan is what one table reference of a SELECT constrains: bounds on time and allowed values of equality-filtered +// columns. +type pruneScan struct { + lo *int64 + hi *int64 + eq map[string][]string + database string + table string +} + +// tableScanInsight is the per-table result reported through QueryInsights. +type tableScanInsight struct { + database string + table string + keys []string + rangeNs int64 + coverage float64 +} + +type tableInst struct { + data *tableData + rel string +} + +func (s *pruneScan) lower(t time.Time) { + if v := t.UnixNano(); s.lo == nil || v > *s.lo { + s.lo = &v + } +} + +func (s *pruneScan) upper(t time.Time) { + if v := t.UnixNano(); s.hi == nil || v < *s.hi { + s.hi = &v + } +} + +func (s *pruneScan) restrict(col string, vals []string) { + if s.eq == nil { + s.eq = map[string][]string{} + } + + prev, seen := s.eq[col] + if !seen { + s.eq[col] = vals + + return + } + + s.eq[col] = slices.DeleteFunc(slices.Clone(prev), func(v string) bool { return !slices.Contains(vals, v) }) +} + +func (t tableInst) hasColumn(col string) bool { + return slices.ContainsFunc(t.data.schema.cols, func(c tsColumn) bool { return strings.EqualFold(c.name, col) }) +} + +func collectInstances(r *relation, tables loadedSet, insts *[]tableInst, conds *[]*node) { + switch r.kind { + case relTable: + if t, ok := tables[tableKey(refPart(r.ref, 0), refPart(r.ref, 1))]; ok && len(r.ref) == qualifiedParts { + rel := r.alias + if rel == "" { + rel = r.ref[1] + } + + *insts = append(*insts, tableInst{data: t, rel: rel}) + } + case relJoin: + collectInstances(r.left, tables, insts, conds) + collectInstances(r.right, tables, insts, conds) + + if r.on != nil { + *conds = append(*conds, splitAnd(r.on)...) + } + case relSubquery, relUnnest, relValues: + } +} + +func refPart(ref []string, i int) string { + if i < len(ref) { + return ref[i] + } + + return "" +} + +func splitAnd(n *node) []*node { + if n == nil { + return nil + } + + if n.kind == nBinary && n.name == opAnd { + return append(splitAnd(n.args[0]), splitAnd(n.args[1])...) + } + + return []*node{n} +} + +func splitOr(n *node) []*node { + if n.kind == nBinary && n.name == "OR" { + return append(splitOr(n.args[0]), splitOr(n.args[1])...) + } + + return []*node{n} +} + +// recordScans notes the pruning predicates of every real table in sel's FROM clause. +func (inf *inferrer) recordScans(sel *selectSpec) { + if len(inf.tables) == 0 { + return + } + + var ( + insts []tableInst + conds = splitAnd(sel.where) + ) + + collectInstances(sel.from, inf.tables, &insts, &conds) + + for _, inst := range insts { + scan := pruneScan{database: inst.data.database, table: inst.data.table} + + for _, c := range conds { + inf.applyConjunct(&scan, inst, insts, c) + } + + inf.scans = append(inf.scans, scan) + } +} + +// columnOf returns the lower-cased column of inst that n references, or "". +func columnOf(n *node, inst tableInst, insts []tableInst) string { + if n.kind != nColumn { + return "" + } + + col := n.parts[len(n.parts)-1] + + switch { + case len(n.parts) == 1: + for _, other := range insts { + if other.data != inst.data && other.hasColumn(col) { + return "" + } + } + case len(n.parts) <= argsThree && strings.EqualFold(n.parts[len(n.parts)-argsTwo], inst.rel): + default: + return "" + } + + if !inst.hasColumn(col) { + return "" + } + + return strings.ToLower(col) +} + +func (inf *inferrer) applyConjunct(scan *pruneScan, inst tableInst, insts []tableInst, c *node) { + switch c.kind { + case nBetween: + if !c.neg && columnOf(c.args[0], inst, insts) == colTime { + inf.applyBounds(scan, ">=", c.args[1]) + inf.applyBounds(scan, "<=", c.args[argsTwo]) + } + case nBinary: + inf.applyComparison(scan, inst, insts, c) + case nInList: + if col := columnOf(c.args[0], inst, insts); !c.neg && col != "" && col != colTime { + if vals, ok := literalStrings(c.args[1:]); ok { + scan.restrict(col, vals) + } + } + default: + } +} + +func (inf *inferrer) applyComparison(scan *pruneScan, inst tableInst, insts []tableInst, c *node) { + if c.name == "OR" { + inf.applyDisjunction(scan, inst, insts, c) + + return + } + + left, right := columnOf(c.args[0], inst, insts), columnOf(c.args[1], inst, insts) + op, expr, col := c.name, c.args[1], left + + if left == "" && right != "" { + op, expr, col = flipComparison(c.name), c.args[0], right + } + + switch { + case col == colTime: + inf.applyBounds(scan, op, expr) + case col != "" && op == "=": + if v, ok := literalString(expr); ok { + scan.restrict(col, []string{v}) + } + } +} + +func (inf *inferrer) applyDisjunction(scan *pruneScan, inst tableInst, insts []tableInst, c *node) { + var ( + col string + vals []string + ) + + for _, d := range splitOr(c) { + if d.kind != nBinary || d.name != "=" { + return + } + + dc, lit := columnOf(d.args[0], inst, insts), d.args[1] + if dc == "" { + dc, lit = columnOf(d.args[1], inst, insts), d.args[0] + } + + v, ok := literalString(lit) + if dc == "" || dc == colTime || !ok || (col != "" && col != dc) { + return + } + + col = dc + vals = append(vals, v) + } + + scan.restrict(col, vals) +} + +func flipComparison(op string) string { + switch op { + case "<": + return ">" + case "<=": + return ">=" + case ">": + return "<" + case ">=": + return "<=" + } + + return op +} + +func (inf *inferrer) applyBounds(scan *pruneScan, op string, expr *node) { + t, ok := inf.constTime(expr) + if !ok { + return + } + + switch op { + case ">", ">=": + scan.lower(t) + case "<", "<=": + scan.upper(t) + case "=": + scan.lower(t) + scan.upper(t) + } +} + +func literalString(n *node) (string, bool) { + if n.kind == nLiteral && n.typ.kind == tyVarchar { + return n.name, true + } + + return "", false +} + +func literalStrings(nodes []*node) ([]string, bool) { + out := make([]string, 0, len(nodes)) + + for _, n := range nodes { + v, ok := literalString(n) + if !ok { + return nil, false + } + + out = append(out, v) + } + + return out, true +} + +// constTime evaluates a time expression made of now(), ago(), literals and interval arithmetic. +func (inf *inferrer) constTime(n *node) (time.Time, bool) { + switch n.kind { + case nCall: + return inf.constTimeCall(n) + case nColumn: + return inf.bareTime(n) + case nTypedLit: + if n.typ.kind == tyTimestamp || n.typ.kind == tyDate { + return parseTSValue(n.name) + } + case nLiteral: + if n.typ.kind == tyVarchar { + return parseTSValue(n.name) + } + case nCast: + if n.typ.kind == tyTimestamp { + return inf.constTime(n.args[0]) + } + case nVar: + if v, ok := inf.vars[n.name]; ok { + return parseTSValue(v) + } + case nBinary: + return inf.constTimeArith(n) + default: + } + + return time.Time{}, false +} + +func (inf *inferrer) bareTime(n *node) (time.Time, bool) { + if len(n.parts) != 1 { + return time.Time{}, false + } + + switch strings.ToLower(n.parts[0]) { + case fnCurTS, fnLocalTS: + return inf.now.UTC(), true + case "current_date": + return inf.now.UTC().Truncate(hoursInDay * time.Hour), true + } + + return time.Time{}, false +} + +func (inf *inferrer) constTimeCall(n *node) (time.Time, bool) { + switch strings.ToLower(n.name) { + case "now", fnCurTS, fnLocalTS: + return inf.now.UTC(), true + case "ago": + d, ok := constDuration(n.arg(0)) + + return inf.now.UTC().Add(-time.Duration(d)), ok && n.arg(0) != nil + case "bin": + t, okT := inf.constTime(n.arg(0)) + d, okD := constDuration(n.arg(1)) + + if !okT || !okD || d <= 0 { + return time.Time{}, false + } + + ns := t.UnixNano() + + return time.Unix(0, ns-floorMod(ns, d)).UTC(), true + } + + return time.Time{}, false +} + +func (inf *inferrer) constTimeArith(n *node) (time.Time, bool) { + if n.name != "+" && n.name != "-" { + return time.Time{}, false + } + + if t, ok := inf.constTime(n.args[0]); ok { + d, okD := constDuration(n.args[1]) + if n.name == "-" { + d = -d + } + + return t.Add(time.Duration(d)), okD + } + + if n.name == "+" { + d, okD := constDuration(n.args[0]) + t, okT := inf.constTime(n.args[1]) + + return t.Add(time.Duration(d)), okD && okT + } + + return time.Time{}, false +} + +// constDuration evaluates an INTERVAL literal, a duration literal such as 15m or parse_duration('1d') to nanoseconds. +func constDuration(n *node) (int64, bool) { + if n == nil { + return 0, false + } + + switch { + case n.kind == nLiteral && n.typ.kind == tyIntervalDS: + return durationText(n.name) + case n.kind == nInterval && n.typ.kind == tyIntervalDS && len(n.parts) == 1: + return durationText(n.name + n.parts[0]) + case n.kind == nCall && strings.EqualFold(n.name, "parse_duration") && n.arg(0) != nil: + if v, ok := literalString(n.args[0]); ok { + return durationText(v) + } + } + + return 0, false +} + +func durationText(s string) (int64, bool) { + m := reDurationText.FindStringSubmatch(s) + if m == nil { + return 0, false + } + + f, err := strconv.ParseFloat(m[1], 64) + if err != nil { + return 0, false + } + + return int64(f * float64(unitNanos(m[argsTwo]))), true +} + +// partitionKeys returns the table's partition key columns: its customer-defined keys, else measure_name. +func partitionKeys(src RecordSource, region, db, table string) []string { + if ks, ok := src.(PartitionKeySource); ok { + if keys := ks.TablePartitionKeys(region, db, table); len(keys) > 0 { + return keys + } + } + + return []string{colMeasureName} +} + +func partitionTuple(r SourceRecord, keys []string) string { + vals := make([]string, len(keys)) + + for i, k := range keys { + if strings.EqualFold(k, colMeasureName) { + vals[i] = r.MeasureName + + continue + } + + for _, d := range r.Dimensions { + if strings.EqualFold(d.Name, k) { + vals[i] = d.Value + } + } + } + + return strings.Join(vals, "\x00") +} + +func spatialCoverage(scan pruneScan, keys []string, recs []SourceRecord) float64 { + constrained := false + + for _, k := range keys { + if _, ok := scan.eq[strings.ToLower(k)]; ok { + constrained = true + } + } + + if !constrained { + return 1 + } + + total, matched := map[string]bool{}, map[string]bool{} + + for _, r := range recs { + tuple := partitionTuple(r, keys) + total[tuple] = true + + if tupleAllowed(scan, keys, strings.Split(tuple, "\x00")) { + matched[tuple] = true + } + } + + if len(total) == 0 { + return 0 + } + + return float64(len(matched)) / float64(len(total)) +} + +func tupleAllowed(scan pruneScan, keys, vals []string) bool { + for i, k := range keys { + if allowed, ok := scan.eq[strings.ToLower(k)]; ok && !slices.Contains(allowed, vals[i]) { + return false + } + } + + return true +} + +func temporalRange(scan pruneScan, recs []SourceRecord, now time.Time) int64 { + lo, hi := scan.lo, scan.hi + + if lo == nil && len(recs) > 0 { + first := recs[0].Time.UnixNano() + lo = &first + } + + if hi == nil { + upper := now.UnixNano() + hi = &upper + } + + if lo == nil || *hi < *lo { + return 0 + } + + return *hi - *lo +} + +// scanInsights computes the temporal range and spatial coverage of each table reference in a query. +func (b *InMemoryBackend) scanInsights( + region string, scans []pruneScan, tables loadedSet, now time.Time, src RecordSource, +) []tableScanInsight { + out := make([]tableScanInsight, 0, len(scans)) + + for _, s := range scans { + t, ok := tables[tableKey(s.database, s.table)] + if !ok { + continue + } + + keys := partitionKeys(src, region, s.database, s.table) + + out = append(out, tableScanInsight{ + database: s.database, table: s.table, keys: keys, + rangeNs: temporalRange(s, t.records, now), + coverage: spatialCoverage(s, keys, t.records), + }) + } + + return out +} + +func (b *InMemoryBackend) tableARN(region string, t tableScanInsight) string { + return arn.Build("timestream", region, b.accountID, "database/"+t.database+"/table/"+t.table) +} diff --git a/services/timestreamquery/ts_render.go b/services/timestreamquery/ts_render.go new file mode 100644 index 0000000000..14b9ff8d7b --- /dev/null +++ b/services/timestreamquery/ts_render.go @@ -0,0 +1,301 @@ +package timestreamquery + +import ( + "bytes" + "encoding/binary" + "encoding/json/jsontext" + "encoding/json/v2" + "fmt" + "strconv" + "strings" + "time" + + "github.com/blackbirdworks/gopherstack/pkgs/jsonx" +) + +const ( + rowOrderKey = "\x00row" + ivBlobLen = 13 + ivKindOffset = 4 + ivSignFlip = uint64(1) << 63 + msToNs = int64(time.Millisecond) +) + +func ivBlobMagic() []byte { return []byte{0xF3, 'i', 'v', 0x1D} } + +// renderValue formats an engine value as a Datum of the static type t. +func renderValue(v any, t tsType) Datum { + if v == nil { + return NullDatum() + } + + switch t.kind { + case tyArray, tyRow, tyTimeseries: + return renderComplexValue(v, t) + default: + return renderScalar(v, t.kind) + } +} + +func renderScalar(v any, k tsKind) Datum { + if b, ok := v.([]byte); ok { + if kind, n, isIv := decodeIntervalBlob(b); isIv { + return renderIntervalBlob(kind, n) + } + + v = string(b) + } + + switch k { + case tyBoolean: + return renderBool(v) + case tyInteger, tyBigint: + return renderInt(v) + case tyDouble: + return renderDouble(v) + case tyTimestamp: + return renderTimestamp(v) + case tyDate: + return renderDate(v) + case tyTime: + return renderTimeOfDay(v) + case tyIntervalDS: + return renderIntervalDS(v) + default: + return renderText(v) + } +} + +func decodeIntervalBlob(b []byte) (byte, int64, bool) { + if len(b) != ivBlobLen || !bytes.HasPrefix(b, ivBlobMagic()) { + return 0, 0, false + } + + raw := binary.BigEndian.Uint64(b[ivKindOffset+1:]) ^ ivSignFlip + + return b[ivKindOffset], int64(raw), true //nolint:gosec // offset-binary payload, wrap-around intended +} + +func renderIntervalBlob(kind byte, n int64) Datum { + if kind == 'Y' { + return ScalarDatum(fmt.Sprintf("%d-%d", n/monthsPerYear, n%monthsPerYear)) + } + + return ScalarDatum(formatInterval(n * msToNs)) +} + +const monthsPerYear = 12 + +func renderBool(v any) Datum { + switch x := v.(type) { + case int64: + return ScalarDatum(strconv.FormatBool(x != 0)) + case float64: + return ScalarDatum(strconv.FormatBool(x != 0)) + case bool: + return ScalarDatum(strconv.FormatBool(x)) + case string: + return ScalarDatum(strconv.FormatBool(strings.EqualFold(x, "true") || x == "1")) + } + + return renderText(v) +} + +func renderInt(v any) Datum { + switch x := v.(type) { + case int64: + return ScalarDatum(strconv.FormatInt(x, 10)) + case float64: + return ScalarDatum(strconv.FormatInt(int64(x), 10)) + case bool: + if x { + return ScalarDatum("1") + } + + return ScalarDatum("0") + } + + return renderText(v) +} + +func renderDouble(v any) Datum { + switch x := v.(type) { + case int64: + return ScalarDatum(javaDouble(float64(x))) + case float64: + return ScalarDatum(javaDouble(x)) + case string: + if f, err := strconv.ParseFloat(x, 64); err == nil { + return ScalarDatum(javaDouble(f)) + } + } + + return renderText(v) +} + +func renderTimestamp(v any) Datum { + if s, ok := v.(string); ok { + if t, parsed := parseTSValue(s); parsed { + return ScalarDatum(formatTS(t)) + } + } + + if t, ok := v.(time.Time); ok { + return ScalarDatum(formatTS(t)) + } + + return renderText(v) +} + +func renderDate(v any) Datum { + if s, ok := v.(string); ok { + if t, parsed := parseTSValue(s); parsed { + return ScalarDatum(t.Format(time.DateOnly)) + } + } + + return renderText(v) +} + +func renderTimeOfDay(v any) Datum { + s, ok := v.(string) + if !ok { + return renderText(v) + } + + for _, l := range []string{"15:04:05.999999999", "15:04:05"} { + if t, err := time.Parse(l, s); err == nil { + return ScalarDatum(t.Format("15:04:05.000000000")) + } + } + + return ScalarDatum(s) +} + +func renderIntervalDS(v any) Datum { + if n, ok := v.(int64); ok { + return ScalarDatum(formatInterval(n)) + } + + return renderText(v) +} + +func renderText(v any) Datum { + switch x := v.(type) { + case string: + return ScalarDatum(x) + case []byte: + return ScalarDatum(string(x)) + case int64: + return ScalarDatum(strconv.FormatInt(x, 10)) + case float64: + return ScalarDatum(javaDouble(x)) + case bool: + return ScalarDatum(strconv.FormatBool(x)) + case time.Time: + return ScalarDatum(formatTS(x)) + } + + return ScalarDatum(fmt.Sprint(v)) +} + +func decodeJSONText(s string, out any) bool { + dec := jsontext.NewDecoder(strings.NewReader(s)) + + return json.UnmarshalDecode(dec, out, jsonx.V1(), jsonx.UseNumber()) == nil +} + +func renderComplexValue(v any, t tsType) Datum { + s, ok := stringOf(v) + if !ok { + return NullDatum() + } + + switch t.kind { + case tyTimeseries: + pts, err := decodeSeries(s) + if err != nil { + return NullDatum() + } + + out := make([]TimeSeriesDataPoint, 0, len(pts)) + for _, p := range pts { + out = append(out, TimeSeriesDataPoint{Time: formatTS(p.t), Value: renderJSON(p.v, *t.elem)}) + } + + return Datum{TimeSeriesValue: out} + case tyArray: + var arr []any + if !decodeJSONText(strings.TrimPrefix(s, arrayMark), &arr) { + return NullDatum() + } + + return renderJSON(arr, t) + default: + } + + var obj any + if !decodeJSONText(strings.TrimPrefix(s, arrayMark), &obj) { + return NullDatum() + } + + return renderJSON(obj, t) +} + +func rowKeys(obj map[string]any, t tsType) []string { + keys := make([]string, len(t.fields)) + + var order []any + + if o, ok := obj[rowOrderKey].([]any); ok { + order = o + } + + for i, f := range t.fields { + switch { + case i < len(order): + keys[i], _ = order[i].(string) + case f.name != "": + keys[i] = f.name + default: + keys[i] = "\x00" + strconv.Itoa(i) + } + } + + return keys +} + +// renderJSON formats a decoded JSON value (array, row object or scalar) as a Datum of type t. +func renderJSON(v any, t tsType) Datum { + v = decodeJSONScalar(v) + if v == nil { + return NullDatum() + } + + switch x := v.(type) { + case []any: + if t.kind != tyArray { + break + } + + out := make([]Datum, len(x)) + for i, e := range x { + out[i] = renderJSON(e, *t.elem) + } + + return Datum{ArrayValue: out} + case map[string]any: + if t.kind != tyRow { + break + } + + data := make([]Datum, len(t.fields)) + for i, key := range rowKeys(x, t) { + data[i] = renderJSON(x[key], t.fields[i].typ) + } + + return Datum{RowValue: &Row{Data: data}} + } + + return renderScalar(v, t.kind) +} diff --git a/services/timestreamquery/ts_result.go b/services/timestreamquery/ts_result.go index 1e1fed4206..0119d8c737 100644 --- a/services/timestreamquery/ts_result.go +++ b/services/timestreamquery/ts_result.go @@ -14,11 +14,15 @@ var ( reTSText = regexp.MustCompile(`^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.(\d{3}|\d{9})$`) ) -const kwNull = "null" +const ( + kwNull = "null" + kwTrue = "true" + kwFalse = "false" +) func isLiteralName(name string) bool { switch strings.ToLower(name) { - case kwNull, "true", "false": + case kwNull, kwTrue, kwFalse: return true } @@ -28,23 +32,50 @@ func isLiteralName(name string) bool { // resultSet is a fully materialised query result. type resultSet struct { cols []ColumnInfo + static []bool + scans []tableScanInsight rows []Row scanned int64 tables int } +func (r *resultSet) isStatic(i int) bool { return i < len(r.static) && r.static[i] } + // outBytes is the size of the rendered scalar values, reported as insights OutputBytes. func (r *resultSet) outBytes() int64 { var n int64 for _, row := range r.rows { for _, d := range row.Data { - if d.ScalarValue != nil { - n += int64(len(*d.ScalarValue)) - } + n += datumBytes(d) + } + } + + return n +} + +// datumBytes is the rendered size of a cell, counting every nested array, row and timeseries value. +func datumBytes(d Datum) int64 { + var n int64 + + if d.ScalarValue != nil { + n += int64(len(*d.ScalarValue)) + } + + for _, e := range d.ArrayValue { + n += datumBytes(e) + } + + if d.RowValue != nil { + for _, e := range d.RowValue.Data { + n += datumBytes(e) } } + for _, p := range d.TimeSeriesValue { + n += int64(len(p.Time)) + datumBytes(p.Value) + } + return n } @@ -98,7 +129,7 @@ func inferType(col []any) string { return ScalarTypeVarchar } -func readRows(rows *sql.Rows) (*resultSet, error) { +func readRows(rows *sql.Rows, plan []tsType) (*resultSet, error) { names, err := rows.Columns() if err != nil { return nil, err @@ -109,24 +140,8 @@ func readRows(rows *sql.Rows) (*resultSet, error) { return nil, err } - var raw [][]any - - for rows.Next() { - dest := make([]any, len(names)) - ptrs := make([]any, len(names)) - - for i := range dest { - ptrs[i] = &dest[i] - } - - if err = rows.Scan(ptrs...); err != nil { - return nil, err - } - - raw = append(raw, dest) - } - - if err = rows.Err(); err != nil { + raw, err := scanAll(rows, len(names)) + if err != nil { return nil, err } @@ -139,25 +154,26 @@ func readRows(rows *sql.Rows) (*resultSet, error) { col[r] = raw[r][i] } - if kind := complexKind(col); kind != "" { - types[i] = kind - rs.cols = append(rs.cols, complexColumnInfo(columnName(n, i), kind, col)) - - continue - } - - t := declType(ctypes[i].DatabaseTypeName()) - if t == "" { - t = inferType(col) + var static tsType + if i < len(plan) { + static = plan[i] } - types[i] = t - rs.cols = append(rs.cols, scalarColumnInfo(columnName(n, i), t)) + info, typ, isStatic := columnFor(columnName(n, i), ctypes[i].DatabaseTypeName(), static, col) + rs.cols = append(rs.cols, info) + rs.static = append(rs.static, isStatic) + types[i] = typ } for _, r := range raw { data := make([]Datum, len(r)) for i, v := range r { + if rs.static[i] { + data[i] = renderValue(v, plan[i]) + + continue + } + data[i] = datumFor(v, types[i]) } @@ -167,6 +183,45 @@ func readRows(rows *sql.Rows) (*resultSet, error) { return rs, nil } +func scanAll(rows *sql.Rows, width int) ([][]any, error) { + var raw [][]any + + for rows.Next() { + dest := make([]any, width) + ptrs := make([]any, width) + + for i := range dest { + ptrs[i] = &dest[i] + } + + if err := rows.Scan(ptrs...); err != nil { + return nil, err + } + + raw = append(raw, dest) + } + + return raw, rows.Err() +} + +// columnFor describes one result column: the statically inferred type when known, else one derived from the values. +func columnFor(name, decl string, static tsType, col []any) (ColumnInfo, string, bool) { + if static.known() { + return static.columnInfo(name), "", true + } + + if kind := complexKind(col); kind != "" { + return complexColumnInfo(name, kind, col), kind, false + } + + t := declType(decl) + if t == "" { + t = inferType(col) + } + + return scalarColumnInfo(name, t), t, false +} + func datumOf(v any, typ string) Datum { if v == nil { return NullDatum() diff --git a/services/timestreamquery/ts_rewrite.go b/services/timestreamquery/ts_rewrite.go index bee865e3d1..b223303350 100644 --- a/services/timestreamquery/ts_rewrite.go +++ b/services/timestreamquery/ts_rewrite.go @@ -24,6 +24,7 @@ var ( reBin = regexp.MustCompile(`(?i)\bbin\(`) reNow = regexp.MustCompile(`(?i)\bnow\(\s*\)|\bcurrent_timestamp\b(\s*\(\s*\))?|\blocaltimestamp\b`) reDate = regexp.MustCompile(`(?i)\bcurrent_date\b`) + reTimeOfDay = regexp.MustCompile(`(?i)\bcurrent_time\b(\s*\(\s*\))?|\blocaltime\b(\s*\(\s*\))?`) reTimezone = regexp.MustCompile(`(?i)\bcurrent_timezone\(\s*\)`) ) @@ -94,18 +95,19 @@ func rewriteTimestream(q string, now time.Time, vars map[string]string) string { nowLit := "'" + formatTS(now) + "'" dateLit := "'" + now.UTC().Format("2006-01-02") + "'" + timeLit := "'" + now.UTC().Format("15:04:05.000000000") + "'" var b strings.Builder for len(q) > 0 { i := strings.IndexAny(q, `'"`) if i < 0 { - b.WriteString(rewriteCode(q, nowLit, dateLit, vars)) + b.WriteString(rewriteCode(q, nowLit, dateLit, timeLit, vars)) break } - b.WriteString(rewriteCode(q[:i], nowLit, dateLit, vars)) + b.WriteString(rewriteCode(q[:i], nowLit, dateLit, timeLit, vars)) end := closingQuote(q, i) b.WriteString(q[i:end]) @@ -136,7 +138,7 @@ func closingQuote(q string, i int) int { return len(q) } -func rewriteCode(seg, nowLit, dateLit string, vars map[string]string) string { +func rewriteCode(seg, nowLit, dateLit, timeLit string, vars map[string]string) string { for name, v := range vars { seg = strings.ReplaceAll(seg, name, "'"+v+"'") } @@ -161,6 +163,7 @@ func rewriteCode(seg, nowLit, dateLit string, vars map[string]string) string { seg = reBin.ReplaceAllString(seg, "ts_bin(") seg = reNow.ReplaceAllString(seg, nowLit) seg = reDate.ReplaceAllString(seg, dateLit) + seg = reTimeOfDay.ReplaceAllString(seg, timeLit) seg = reTimezone.ReplaceAllString(seg, "'UTC'") return seg diff --git a/services/timestreamquery/ts_sdk_insights_test.go b/services/timestreamquery/ts_sdk_insights_test.go new file mode 100644 index 0000000000..e74fecfb1a --- /dev/null +++ b/services/timestreamquery/ts_sdk_insights_test.go @@ -0,0 +1,314 @@ +package timestreamquery_test + +import ( + "strings" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + tqsdk "github.com/aws/aws-sdk-go-v2/service/timestreamquery" + "github.com/aws/aws-sdk-go-v2/service/timestreamquery/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func tableARN(table string) string { + return "arn:aws:timestream:" + rtTestRegion + ":" + rtTestAccountID + ":database/db/table/" + table +} + +func TestSDKQuery_InsightsTemporalAndSpatial(t *testing.T) { + t.Parallel() + + const hour = int64(time.Hour) + + tests := []struct { + name string + query string + wantTable string + wantKey []string + wantRange int64 + wantCoverage float64 + }{ + { + "ago bound", `SELECT * FROM db.t WHERE time > ago(1h)`, + "t", []string{"measure_name"}, hour, 1, + }, + { + "between", `SELECT * FROM db.t WHERE time BETWEEN ago(2h) AND ago(1h)`, + "t", []string{"measure_name"}, hour, 1, + }, + { + "unbounded uses data extent", `SELECT * FROM db.t`, + "t", []string{"measure_name"}, 3 * hour, 1, + }, + { + "timestamp literal to now", + `SELECT * FROM db.t WHERE time >= TIMESTAMP '2026-10-31 10:00:00' AND time < now()`, + "t", []string{"measure_name"}, 2 * hour, 1, + }, + { + "bin and interval arithmetic", + `SELECT * FROM db.t WHERE time >= bin(now(), 1h) - 1h AND time < bin(now(), 1h)`, + "t", []string{"measure_name"}, hour, 1, + }, + { + "reversed comparison", `SELECT * FROM db.t WHERE ago(30m) <= time`, + "t", []string{"measure_name"}, hour / 2, 1, + }, + { + "measure name equality", `SELECT * FROM db.t WHERE time > ago(1h) AND measure_name = 'cpu'`, + "t", []string{"measure_name"}, hour, 0.5, + }, + { + "measure name in all", `SELECT * FROM db.t WHERE time > ago(1h) AND measure_name IN ('cpu', 'n')`, + "t", []string{"measure_name"}, hour, 1, + }, + { + "unknown partition value", `SELECT * FROM db.t WHERE time > ago(1h) AND measure_name = 'nope'`, + "t", []string{"measure_name"}, hour, 0, + }, + { + "customer partition key", `SELECT * FROM db.m WHERE time > ago(1h) AND host = 'h1'`, + "m", []string{"host"}, hour, 0.25, + }, + { + "customer partition key in", `SELECT * FROM db.m WHERE time > ago(1h) AND host IN ('h1', 'h2')`, + "m", []string{"host"}, hour, 0.5, + }, + { + "customer partition key or", `SELECT * FROM db.m WHERE time > ago(1h) AND (host = 'h1' OR host = 'h3')`, + "m", []string{"host"}, hour, 0.5, + }, + { + "function around key does not prune", `SELECT * FROM db.m WHERE time > ago(1h) AND upper(host) = 'H1'`, + "m", []string{"host"}, hour, 1, + }, + { + "join reports widest table", + `SELECT a.host FROM db.t a JOIN db.m b ON a.host = b.host WHERE b.time > ago(1h) AND b.host = 'h1'`, + "t", []string{"measure_name"}, 3 * hour, 1, + }, + { + "join with bounded sides", + `SELECT a.host FROM db.t a JOIN db.m b ON a.host = b.host WHERE a.time > ago(2h) AND b.time > ago(1h)`, + "t", []string{"measure_name"}, 2 * hour, 1, + }, + { + "subquery bounds its own table", + `SELECT * FROM (SELECT * FROM db.m WHERE time > ago(1h) AND host = 'h4') x`, + "m", []string{"host"}, hour, 0.25, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + client, _ := newSDKQueryEnv(t) + + out, err := client.Query(t.Context(), &tqsdk.QueryInput{ + QueryString: aws.String(tc.query), + QueryInsights: &types.QueryInsights{Mode: types.QueryInsightsModeEnabledWithRateControl}, + }) + require.NoError(t, err) + require.NotNil(t, out.QueryInsightsResponse) + + temporal := out.QueryInsightsResponse.QueryTemporalRange + require.NotNil(t, temporal) + require.NotNil(t, temporal.Max) + assert.Equal(t, tc.wantRange, temporal.Max.Value) + assert.Equal(t, tableARN(tc.wantTable), aws.ToString(temporal.Max.TableArn)) + + spatial := out.QueryInsightsResponse.QuerySpatialCoverage + require.NotNil(t, spatial) + require.NotNil(t, spatial.Max) + assert.InDelta(t, tc.wantCoverage, spatial.Max.Value, 1e-9) + assert.Equal(t, tc.wantKey, spatial.Max.PartitionKey) + }) + } +} + +func TestSDKQuery_InsightsModes(t *testing.T) { + t.Parallel() + + tests := []struct { + insights *types.QueryInsights + name string + wantErr string + wantPresent bool + }{ + {&types.QueryInsights{Mode: types.QueryInsightsModeEnabledWithRateControl}, "enabled", "", true}, + {&types.QueryInsights{Mode: types.QueryInsightsModeDisabled}, "disabled", "", false}, + {nil, "absent", "", false}, + {&types.QueryInsights{Mode: "BOGUS"}, "unknown", "ValidationException", false}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + client, _ := newSDKQueryEnv(t) + + out, err := client.Query(t.Context(), &tqsdk.QueryInput{ + QueryString: aws.String("SELECT * FROM db.t"), QueryInsights: tc.insights, + }) + if tc.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tc.wantErr) + + return + } + + require.NoError(t, err) + assert.Equal(t, tc.wantPresent, out.QueryInsightsResponse != nil) + }) + } +} + +func TestSDKQuery_InsightsRateLimit(t *testing.T) { + t.Parallel() + + client, clock := newSDKQueryEnv(t) + enabled := &types.QueryInsights{Mode: types.QueryInsightsModeEnabledWithRateControl} + run := func(in *types.QueryInsights) error { + _, err := client.Query(t.Context(), &tqsdk.QueryInput{QueryString: aws.String("SELECT 1"), QueryInsights: in}) + + return err + } + + require.NoError(t, run(enabled)) + + err := run(enabled) + require.Error(t, err) + + var throttled *types.ThrottlingException + + require.ErrorAs(t, err, &throttled, "second insights query within a second must be throttled") + require.NoError(t, run(nil)) + require.NoError(t, run(&types.QueryInsights{Mode: types.QueryInsightsModeDisabled})) + + clock.advance(time.Second) + require.NoError(t, run(enabled)) +} + +func TestSDKQuery_InsightsOutputBytes(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + query string + want int64 + }{ + {"scalar", `SELECT 'abc', 12`, 5}, + {"array", `SELECT ARRAY[1, 22, 333]`, 6}, + {"row", `SELECT ROW(1, 'ab')`, 3}, + {"array of rows", `SELECT ARRAY[ROW(1, 'a'), ROW(2, 'b')]`, 4}, + { + "series", + `SELECT create_time_series(time, measure_value::double) FROM db.m`, + int64(4 * (len("2026-10-31 11:50:00.000000000") + 3)), + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + client, _ := newSDKQueryEnv(t) + + out, err := client.Query(t.Context(), &tqsdk.QueryInput{ + QueryString: aws.String(tc.query), + QueryInsights: &types.QueryInsights{Mode: types.QueryInsightsModeEnabledWithRateControl}, + }) + require.NoError(t, err) + assert.Equal(t, tc.want, aws.ToInt64(out.QueryInsightsResponse.OutputBytes)) + }) + } +} + +func TestSDKScheduledQuery_InsightsRun(t *testing.T) { + t.Parallel() + + client, _ := newSDKQueryEnv(t) + + created, err := client.CreateScheduledQuery(t.Context(), &tqsdk.CreateScheduledQueryInput{ + Name: aws.String("insights-run"), + QueryString: aws.String(`SELECT count(*) FROM db.m WHERE time > ago(1h) AND host = 'h1'`), + ScheduledQueryExecutionRoleArn: aws.String("arn:aws:iam::000000000000:role/tsq-role"), + ScheduleConfiguration: &types.ScheduleConfiguration{ScheduleExpression: aws.String("rate(1 hour)")}, + NotificationConfiguration: &types.NotificationConfiguration{ + SnsConfiguration: &types.SnsConfiguration{TopicArn: aws.String("arn:aws:sns:us-east-1:000000000000:tsq")}, + }, + ErrorReportConfiguration: &types.ErrorReportConfiguration{ + S3Configuration: &types.S3Configuration{BucketName: aws.String("tsq-errors")}, + }, + }) + require.NoError(t, err) + + _, err = client.ExecuteScheduledQuery(t.Context(), &tqsdk.ExecuteScheduledQueryInput{ + ScheduledQueryArn: created.Arn, + InvocationTime: aws.Time(sdkNow()), + QueryInsights: &types.ScheduledQueryInsights{Mode: types.ScheduledQueryInsightsModeEnabledWithRateControl}, + }) + require.NoError(t, err) + + desc, err := client.DescribeScheduledQuery(t.Context(), &tqsdk.DescribeScheduledQueryInput{ + ScheduledQueryArn: created.Arn, + }) + require.NoError(t, err) + + ins := desc.ScheduledQuery.LastRunSummary.QueryInsightsResponse + require.NotNil(t, ins) + require.NotNil(t, ins.QueryTemporalRange) + assert.Equal(t, int64(time.Hour), ins.QueryTemporalRange.Max.Value) + assert.Equal(t, tableARN("m"), aws.ToString(ins.QueryTemporalRange.Max.TableArn)) + require.NotNil(t, ins.QuerySpatialCoverage) + assert.InDelta(t, 0.25, ins.QuerySpatialCoverage.Max.Value, 1e-9) + assert.Equal(t, []string{"host"}, ins.QuerySpatialCoverage.Max.PartitionKey) + assert.EqualValues(t, 1, aws.ToInt64(ins.QueryTableCount)) +} + +func TestSDKPrepareQuery_StaticColumns(t *testing.T) { + t.Parallel() + + const series = `create_time_series(time, measure_value::double)` + + tests := []struct { + name string + query string + want string + }{ + { + "scalars and series", + `SELECT host, count(*) AS c, ` + series + ` FROM db.t GROUP BY host`, + "host:VARCHAR,c:BIGINT,_col2:TIMESERIES(DOUBLE)", + }, + { + "nested", + `SELECT ARRAY[1], ROW(1, 'a') AS r, typeof(time) AS ty, now() FROM db.t`, + "_col0:ARRAY(INTEGER),r:ROW(:INTEGER,:VARCHAR),ty:VARCHAR,_col3:TIMESTAMP", + }, + { + "star with comment", "SELECT * FROM db.m -- all columns", + "host:VARCHAR,measure_name:VARCHAR,time:TIMESTAMP,measure_value::double:DOUBLE", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + client := newSDKQueryClient(t) + + out, err := client.PrepareQuery(t.Context(), &tqsdk.PrepareQueryInput{QueryString: aws.String(tc.query)}) + require.NoError(t, err) + + cols := make([]string, len(out.Columns)) + for i, c := range out.Columns { + cols[i] = aws.ToString(c.Name) + ":" + typeLabel(c.Type) + } + + assert.Equal(t, tc.want, strings.Join(cols, ",")) + }) + } +} diff --git a/services/timestreamquery/ts_sdk_types_test.go b/services/timestreamquery/ts_sdk_types_test.go new file mode 100644 index 0000000000..3c4d46dd20 --- /dev/null +++ b/services/timestreamquery/ts_sdk_types_test.go @@ -0,0 +1,404 @@ +package timestreamquery_test + +import ( + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + awscfg "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/credentials" + tqsdk "github.com/aws/aws-sdk-go-v2/service/timestreamquery" + "github.com/aws/aws-sdk-go-v2/service/timestreamquery/types" + "github.com/labstack/echo/v5" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/pkgs/service" + "github.com/blackbirdworks/gopherstack/services/timestreamquery" +) + +func sdkNow() time.Time { return time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC) } + +type sdkClock struct{ nanos atomic.Int64 } + +func newSDKClock() *sdkClock { + c := &sdkClock{} + c.nanos.Store(sdkNow().UnixNano()) + + return c +} + +func (c *sdkClock) now() time.Time { return time.Unix(0, c.nanos.Load()).UTC() } + +func (c *sdkClock) advance(d time.Duration) { c.nanos.Add(int64(d)) } + +// hostPartitioned reports the host dimension as the customer-defined partition key of db.m. +type hostPartitioned struct{ *memSource } + +func (hostPartitioned) TablePartitionKeys(_, _, table string) []string { + if table == "m" { + return []string{"host"} + } + + return nil +} + +func sdkTables() map[string][]timestreamquery.SourceRecord { + at := func(d time.Duration) time.Time { return sdkNow().Add(-d) } + dims := []timestreamquery.SourceDimension{{Name: "host", Value: "a"}} + + m := make([]timestreamquery.SourceRecord, 0, 4) + + for i, h := range []string{"h1", "h2", "h3", "h4"} { + m = append(m, timestreamquery.SourceRecord{ + Time: at(time.Duration(i+1) * 10 * time.Minute), MeasureName: "cpu", MeasureValueType: "DOUBLE", + MeasureValue: "5", Dimensions: []timestreamquery.SourceDimension{{Name: "host", Value: h}}, + }) + } + + return map[string][]timestreamquery.SourceRecord{ + "db.t": { + { + Time: at(3 * time.Hour), + MeasureName: "cpu", + MeasureValueType: "DOUBLE", + MeasureValue: "1", + Dimensions: dims, + }, + { + Time: at(20 * time.Minute), + MeasureName: "cpu", + MeasureValueType: "DOUBLE", + MeasureValue: "10", + Dimensions: dims, + }, + { + Time: at(5 * time.Minute), + MeasureName: "cpu", + MeasureValueType: "DOUBLE", + MeasureValue: "30", + Dimensions: dims, + }, + {Time: at(time.Minute), MeasureName: "n", MeasureValueType: "BIGINT", MeasureValue: "7"}, + }, + "db.m": m, + } +} + +func newSDKQueryClient(t *testing.T) *tqsdk.Client { + t.Helper() + + client, _ := newSDKQueryEnv(t) + + return client +} + +func newSDKQueryEnv(t *testing.T) (*tqsdk.Client, *sdkClock) { + t.Helper() + + clock := newSDKClock() + backend := timestreamquery.NewInMemoryBackend(rtTestAccountID, rtTestRegion) + backend.SetClock(clock.now) + backend.SetRecordSource(hostPartitioned{&memSource{tables: sdkTables()}}) + + registry := service.NewRegistry() + require.NoError(t, registry.Register(timestreamquery.NewHandler(backend))) + + e := echo.New() + e.Use(service.NewServiceRouter(registry).RouteHandler()) + + srv := httptest.NewServer(e) + t.Cleanup(srv.Close) + + cfg, err := awscfg.LoadDefaultConfig(t.Context(), awscfg.WithRegion(rtTestRegion), + awscfg.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("test", "test", ""))) + require.NoError(t, err) + + return tqsdk.NewFromConfig(cfg, func(o *tqsdk.Options) { + o.BaseEndpoint = aws.String(srv.URL) + o.Retryer = aws.NopRetryer{} + }), clock +} + +func typeLabel(t *types.Type) string { + switch { + case t == nil: + return "" + case t.ArrayColumnInfo != nil: + return "ARRAY(" + typeLabel(t.ArrayColumnInfo.Type) + ")" + case t.TimeSeriesMeasureValueColumnInfo != nil: + return "TIMESERIES(" + typeLabel(t.TimeSeriesMeasureValueColumnInfo.Type) + ")" + case t.RowColumnInfo != nil: + parts := make([]string, len(t.RowColumnInfo)) + for i, f := range t.RowColumnInfo { + parts[i] = aws.ToString(f.Name) + ":" + typeLabel(f.Type) + } + + return "ROW(" + strings.Join(parts, ",") + ")" + default: + return string(t.ScalarType) + } +} + +func datumLabel(d types.Datum) string { + switch { + case d.NullValue != nil: + return "null" + case d.ScalarValue != nil: + return *d.ScalarValue + case d.RowValue != nil: + parts := make([]string, len(d.RowValue.Data)) + for i, e := range d.RowValue.Data { + parts[i] = datumLabel(e) + } + + return "(" + strings.Join(parts, ",") + ")" + case d.TimeSeriesValue != nil: + parts := make([]string, len(d.TimeSeriesValue)) + for i, p := range d.TimeSeriesValue { + parts[i] = datumLabel(*p.Value) + } + + return "ts[" + strings.Join(parts, ",") + "]" + default: + parts := make([]string, len(d.ArrayValue)) + for i, e := range d.ArrayValue { + parts[i] = datumLabel(e) + } + + return "[" + strings.Join(parts, ",") + "]" + } +} + +func queryLabels(t *testing.T, client *tqsdk.Client, q string) (string, string) { + t.Helper() + + out, err := client.Query(t.Context(), &tqsdk.QueryInput{QueryString: aws.String(q)}) + require.NoError(t, err) + + cols := make([]string, len(out.ColumnInfo)) + for i, c := range out.ColumnInfo { + cols[i] = typeLabel(c.Type) + } + + if len(out.Rows) == 0 { + return strings.Join(cols, ","), "" + } + + cells := make([]string, len(out.Rows[0].Data)) + for i, d := range out.Rows[0].Data { + cells[i] = datumLabel(d) + } + + return strings.Join(cols, ","), strings.Join(cells, "|") +} + +func TestSDKQuery_StaticColumnTypes(t *testing.T) { + t.Parallel() + + const ( + fromCPU = ` FROM db.t WHERE measure_name = 'cpu'` + series = `create_time_series(time, measure_value::double)` + ) + + tests := []struct { + name string + query string + wantTypes string + wantRow string + }{ + { + "scalar types", + `SELECT 1, 3000000000, 1.5, 'a', true, NULL, DATE '2020-01-02', TIMESTAMP '2020-01-02 03:04:05', ` + + `INTERVAL '1' DAY, INTERVAL '1' YEAR, TIME '10:11:12'`, + "INTEGER,BIGINT,DOUBLE,VARCHAR,BOOLEAN,UNKNOWN,DATE,TIMESTAMP,INTERVAL_DAY_TO_SECOND," + + "INTERVAL_YEAR_TO_MONTH,TIME", + "1|3000000000|1.5|a|true|null|2020-01-02|2020-01-02 03:04:05.000000000|1 00:00:00.000000000|1-0|" + + "10:11:12.000000000", + }, + { + "nested types", + `SELECT ARRAY[1,2,3], ROW(1,'a'), CAST(ROW(1,2) AS ROW(a bigint, b bigint)), ARRAY[ROW(1,'a')]`, + "ARRAY(INTEGER),ROW(:INTEGER,:VARCHAR),ROW(a:BIGINT,b:BIGINT),ARRAY(ROW(:INTEGER,:VARCHAR))", + "[1,2,3]|(1,a)|(1,2)|[(1,a)]", + }, + { + "empty result", + `SELECT host, measure_value::double > 5 AS big, count(*), time, ` + series + + ` FROM db.t WHERE measure_name = 'nope' GROUP BY host, time`, + "VARCHAR,BOOLEAN,BIGINT,TIMESTAMP,TIMESERIES(DOUBLE)", + "", + }, + { + "empty star", + `SELECT * FROM db.t WHERE 1 = 0`, + "VARCHAR,VARCHAR,TIMESTAMP,BIGINT,DOUBLE", + "", + }, + { + "boolean case cast", + `SELECT CASE WHEN measure_value::double > 5 THEN true ELSE false END, ` + + `CAST(measure_value::double > 5 AS boolean), coalesce(measure_value::double > 5, false), ` + + `if(measure_value::double > 5, true, false), NOT contains(ARRAY[1], 1), ` + + `CASE WHEN true THEN measure_value::double > 5 END` + fromCPU + ` ORDER BY time LIMIT 1`, + "BOOLEAN,BOOLEAN,BOOLEAN,BOOLEAN,BOOLEAN,BOOLEAN", + "false|false|false|false|false|false", + }, + { + "aggregates", + `SELECT count(*), sum(measure_value::double), avg(measure_value::double), max(time), min(host), ` + + `approx_percentile(measure_value::double, 0.5), count_if(measure_value::double > 5), ` + + `sum(1), max(1.5)` + fromCPU, + "BIGINT,DOUBLE,DOUBLE,TIMESTAMP,VARCHAR,DOUBLE,BIGINT,BIGINT,DOUBLE", + "3|41.0|13.666666666666666|2026-10-31 11:55:00.000000000|a|10.0|2|3|1.5", + }, + { + "series column", + `SELECT host, ` + series + fromCPU + ` GROUP BY host`, + "VARCHAR,TIMESERIES(DOUBLE)", + "a|ts[1.0,10.0,30.0]", + }, + { + "date functions", + `SELECT now(), current_date, ago(1h), bin(time, 1h), date_trunc('day', time), ` + + `to_milliseconds(time), parse_duration('1d'), time - ago(1h), year(time), date_diff('day', time, now())` + + fromCPU + ` ORDER BY time LIMIT 1`, + "TIMESTAMP,DATE,TIMESTAMP,TIMESTAMP,TIMESTAMP,BIGINT,INTERVAL_DAY_TO_SECOND,INTERVAL_DAY_TO_SECOND," + + "BIGINT,BIGINT", + "2026-10-31 12:00:00.000000000|2026-10-31|2026-10-31 11:00:00.000000000|2026-10-31 09:00:00.000000000|" + + "2026-10-31 00:00:00.000000000|1793437200000|1 00:00:00.000000000|-0 02:00:00.000000000|2026|0", + }, + { + "set operation supertype", + `SELECT * FROM (SELECT 1 AS a UNION ALL SELECT 2.5)`, + "DOUBLE", + "1.0", + }, + { + "join and cte", + `WITH x AS (SELECT host AS h, count(*) AS c FROM db.t GROUP BY host) ` + + `SELECT a.host, x.c, a.time FROM db.t a JOIN x ON a.host = x.h ORDER BY a.time LIMIT 1`, + "VARCHAR,BIGINT,TIMESTAMP", + "a|3|2026-10-31 09:00:00.000000000", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + client := newSDKQueryClient(t) + gotTypes, gotRow := queryLabels(t, client, tc.query) + assert.Equal(t, tc.wantTypes, gotTypes) + assert.Equal(t, tc.wantRow, gotRow) + }) + } +} + +func TestSDKQuery_Typeof(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + query string + want string + }{ + { + "scalars", + `SELECT typeof(1), typeof(3000000000), typeof(1.5), typeof('a'), typeof(true), typeof(NULL), ` + + `typeof(DATE '2020-01-02'), typeof(TIME '10:11:12'), typeof(TIMESTAMP '2020-01-02 03:04:05'), ` + + `typeof(INTERVAL '1' DAY), typeof(INTERVAL '1' YEAR)`, + "integer|bigint|double|varchar|boolean|unknown|date|time|timestamp|interval day to second|" + + "interval year to month", + }, + { + "nested", + `SELECT typeof(ARRAY[1,2]), typeof(ROW(1,'a')), typeof(CAST(ROW(1,2) AS ROW(a bigint, b varchar))), ` + + `typeof(ARRAY[ARRAY[1.5]])`, + "array(integer)|row(integer, varchar)|row(a bigint, b varchar)|array(array(double))", + }, + { + "columns", + `SELECT typeof(host), typeof(time), typeof(measure_name), typeof(measure_value::double), ` + + `typeof(count(*)), typeof(avg(measure_value::double)), typeof(1 = 1) ` + + `FROM db.t WHERE measure_name = 'cpu'`, + "varchar|timestamp|varchar|double|bigint|double|boolean", + }, + { + "series", + `SELECT typeof(create_time_series(time, measure_value::double)) FROM db.t WHERE measure_name = 'cpu'`, + "timeseries(double)", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + client := newSDKQueryClient(t) + _, row := queryLabels(t, client, tc.query) + assert.Equal(t, tc.want, row) + }) + } +} + +func TestSDKQuery_SeriesLambdas(t *testing.T) { + t.Parallel() + + const ( + series = `create_time_series(time, measure_value::double)` + from = ` FROM db.t WHERE measure_name = 'cpu'` + ) + + tests := []struct { + name string + query string + wantTypes string + wantRow string + }{ + { + "filter ignoring element", + `SELECT filter(` + series + `, x -> true)` + from, + "TIMESERIES(DOUBLE)", "ts[1.0,10.0,30.0]", + }, + { + "filter reading element", + `SELECT filter(` + series + `, x -> x.value > 5)` + from, + "TIMESERIES(DOUBLE)", "ts[10.0,30.0]", + }, + { + "reduce ignoring element", + `SELECT reduce(` + series + `, 0, (s, x) -> s + 1, s -> s)` + from, + "INTEGER", "3", + }, + { + "reduce reading element", + `SELECT reduce(` + series + `, 0.0, (s, x) -> s + x.value, s -> s)` + from, + "DOUBLE", "41.0", + }, + { + "comment inside lambda", + `SELECT filter(` + series + `, x -> x.value > 5 -- keep big` + "\n" + `) /* tail */` + from + ` -- end`, + "TIMESERIES(DOUBLE)", "ts[10.0,30.0]", + }, + { + "comment markers in strings", + `SELECT '-- not a comment', '/* nor this */' /* real */ -- real`, + "VARCHAR,VARCHAR", "-- not a comment|/* nor this */", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + client := newSDKQueryClient(t) + gotTypes, gotRow := queryLabels(t, client, tc.query) + assert.Equal(t, tc.wantTypes, gotTypes) + assert.Equal(t, tc.wantRow, gotRow) + }) + } +} diff --git a/services/timestreamquery/ts_sqlast.go b/services/timestreamquery/ts_sqlast.go new file mode 100644 index 0000000000..733893da22 --- /dev/null +++ b/services/timestreamquery/ts_sqlast.go @@ -0,0 +1,140 @@ +package timestreamquery + +const ( + opNot = "NOT" + opAnd = "AND" + fnCurTS = "current_timestamp" + fnLocalTS = "localtimestamp" + opNotLower = "not" + fnFilter = "filter" + kwDate = "date" + kwMonth = "month" + kwYear = "year" + kwInteger = "integer" + colValue = "value" +) + +type nodeKind uint8 + +const ( + nLiteral nodeKind = iota + nColumn + nStar + nCall + nBinary + nUnary + nCase + nCast + nIsNull + nBetween + nInList + nInSub + nLike + nExists + nSubquery + nArrayCtor + nRowCtor + nSubscript + nField + nLambda + nTypedLit + nInterval + nVar + nParam +) + +// node is one SQL expression; start/end are byte offsets into the source. +type node struct { + sub *queryNode + name string + args []*node + parts []string + params []string + typ tsType + start int + end int + opStart int + opEnd int + kind nodeKind + distinct bool + star bool + over bool + neg bool + hasElse bool + operand bool +} + +type selectItem struct { + expr *node + alias string + qual []string + star bool +} + +type relKind uint8 + +const ( + relTable relKind = iota + relSubquery + relJoin + relUnnest + relValues +) + +type relation struct { + sub *queryNode + left *relation + right *relation + on *node + joinType string + ref []string + alias string + colAliases []string + using []string + args []*node + rows [][]*node + kind relKind + ordinality bool +} + +type cteDef struct { + query *queryNode + name string + cols []string +} + +type orderItem struct{ expr *node } + +type selectSpec struct { + where *node + having *node + from *relation + items []selectItem + groupBy []*node + distinct bool +} + +type queryNode struct { + sel *selectSpec + left *queryNode + right *queryNode + setOp string + ctes []cteDef + orderBy []orderItem + limit []*node +} + +type typedEdit struct { + text string + start, end int + seq int + closing bool +} + +func (n *node) arg(i int) *node { + if i < len(n.args) { + return n.args[i] + } + + return nil +} diff --git a/services/timestreamquery/ts_sqlexpr.go b/services/timestreamquery/ts_sqlexpr.go new file mode 100644 index 0000000000..3bf7b5319b --- /dev/null +++ b/services/timestreamquery/ts_sqlexpr.go @@ -0,0 +1,993 @@ +package timestreamquery + +import "strings" + +func (p *sqlParser) parseExpr() (*node, error) { + if err := p.enter(); err != nil { + return nil, err + } + defer p.leave() + + if l, ok, err := p.tryLambda(); ok || err != nil { + return l, err + } + + return p.parseOr() +} + +func (p *sqlParser) tryLambda() (*node, bool, error) { + start := p.peek().start + + var params []string + + switch t := p.peek(); { + case t.kind == tkIdent && p.peekAt(1).isOp("->"): + params = []string{t.text} + p.pos += argsTwo + case t.isOp("("): + i, names := 1, []string{} + + for p.peekAt(i).kind == tkIdent { + names = append(names, p.peekAt(i).text) + i++ + + if !p.peekAt(i).isOp(",") { + break + } + + i++ + } + + if len(names) == 0 || !p.peekAt(i).isOp(")") || !p.peekAt(i+1).isOp("->") { + return nil, false, nil + } + + params = names + p.pos += i + argsTwo + default: + return nil, false, nil + } + + body, err := p.parseExpr() + if err != nil { + return nil, true, err + } + + return &node{kind: nLambda, params: params, args: []*node{body}, start: start, end: body.end}, true, nil +} + +func (p *sqlParser) binary(op string, l, r *node) *node { + return &node{kind: nBinary, name: op, args: []*node{l, r}, start: l.start, end: r.end} +} + +func (p *sqlParser) parseOr() (*node, error) { + l, err := p.parseAnd() + if err != nil { + return nil, err + } + + for p.acceptKw("or") { + r, rerr := p.parseAnd() + if rerr != nil { + return nil, rerr + } + + l = p.binary("OR", l, r) + } + + return l, nil +} + +func (p *sqlParser) parseAnd() (*node, error) { + l, err := p.parseNot() + if err != nil { + return nil, err + } + + for p.acceptKw("and") { + r, rerr := p.parseNot() + if rerr != nil { + return nil, rerr + } + + l = p.binary("AND", l, r) + } + + return l, nil +} + +func (p *sqlParser) parseNot() (*node, error) { + if t := p.peek(); t.is("not") { + p.pos++ + + e, err := p.parseNot() + if err != nil { + return nil, err + } + + return &node{kind: nUnary, name: opNot, args: []*node{e}, start: t.start, end: e.end}, nil + } + + return p.parsePredicate() +} + +func isCmpOp(op string) bool { + switch op { + case "=", "<>", "!=", "<", ">", "<=", ">=": + return true + } + + return false +} + +func (p *sqlParser) parsePredicate() (*node, error) { + l, err := p.parseConcat() + if err != nil { + return nil, err + } + + for { + t := p.peek() + + switch { + case t.kind == tkOp && isCmpOp(t.text): + p.pos++ + + r, rerr := p.parseConcat() + if rerr != nil { + return nil, rerr + } + + l = p.binary(t.text, l, r) + case t.is("is"): + if l, err = p.parseIs(l); err != nil { + return nil, err + } + case t.is("not") || t.is("between") || t.is("in") || t.is("like"): + if l, err = p.parseNegatable(l); err != nil { + return nil, err + } + default: + return l, nil + } + } +} + +func (p *sqlParser) parseIs(l *node) (*node, error) { + p.pos++ + + neg := p.acceptKw("not") + + if p.acceptKw("distinct") { + if err := p.expectKw("from"); err != nil { + return nil, err + } + + r, err := p.parseConcat() + if err != nil { + return nil, err + } + + return p.binary("IS DISTINCT", l, r), nil + } + + end := p.next() + if end.kind != tkIdent { + return nil, errSQLSyntax + } + + return &node{kind: nIsNull, neg: neg, args: []*node{l}, start: l.start, end: end.end}, nil +} + +func (p *sqlParser) parseNegatable(l *node) (*node, error) { + neg := p.acceptKw("not") + + t := p.next() + + switch strings.ToLower(t.text) { + case "between": + lo, err := p.parseConcat() + if err != nil { + return nil, err + } + + if err = p.expectKw("and"); err != nil { + return nil, err + } + + hi, err := p.parseConcat() + if err != nil { + return nil, err + } + + return &node{kind: nBetween, neg: neg, args: []*node{l, lo, hi}, start: l.start, end: hi.end}, nil + case "in": + return p.parseIn(l, neg) + case "like": + pat, err := p.parseConcat() + if err != nil { + return nil, err + } + + n := &node{kind: nLike, neg: neg, args: []*node{l, pat}, start: l.start, end: pat.end} + if p.acceptKw("escape") { + esc, eerr := p.parseConcat() + if eerr != nil { + return nil, eerr + } + + n.args, n.end = append(n.args, esc), esc.end + } + + return n, nil + } + + return nil, errSQLSyntax +} + +func (p *sqlParser) parseIn(l *node, neg bool) (*node, error) { + if err := p.expectOp("("); err != nil { + return nil, err + } + + if p.peek().is("select") || p.peek().is("with") { + qn, err := p.parseQuery() + if err != nil { + return nil, err + } + + end := p.peek().end + + return &node{kind: nInSub, neg: neg, sub: qn, args: []*node{l}, start: l.start, end: end}, p.expectOp(")") + } + + items, err := p.parseExprList(")") + if err != nil { + return nil, err + } + + return &node{ + kind: nInList, neg: neg, args: append([]*node{l}, items...), start: l.start, end: p.toks[p.pos-1].end, + }, nil +} + +func (p *sqlParser) parseConcat() (*node, error) { + l, err := p.parseAdditive() + if err != nil { + return nil, err + } + + for p.peek().isOp("||") { + p.pos++ + + r, rerr := p.parseAdditive() + if rerr != nil { + return nil, rerr + } + + l = p.binary("||", l, r) + } + + return l, nil +} + +func (p *sqlParser) parseAdditive() (*node, error) { + l, err := p.parseMultiplicative() + if err != nil { + return nil, err + } + + for p.peek().isOp("+") || p.peek().isOp("-") { + opTok := p.next() + + r, rerr := p.parseMultiplicative() + if rerr != nil { + return nil, rerr + } + + l = p.binary(opTok.text, l, r) + l.opStart, l.opEnd = opTok.start, opTok.end + } + + return l, nil +} + +func (p *sqlParser) parseMultiplicative() (*node, error) { + l, err := p.parseUnary() + if err != nil { + return nil, err + } + + for p.peek().isOp("*") || p.peek().isOp("/") || p.peek().isOp("%") { + op := p.next().text + + r, rerr := p.parseUnary() + if rerr != nil { + return nil, rerr + } + + l = p.binary(op, l, r) + } + + return l, nil +} + +func (p *sqlParser) parseUnary() (*node, error) { + if err := p.enter(); err != nil { + return nil, err + } + defer p.leave() + + if t := p.peek(); t.isOp("-") || t.isOp("+") { + p.pos++ + + e, err := p.parseUnary() + if err != nil { + return nil, err + } + + return &node{kind: nUnary, name: t.text, args: []*node{e}, start: t.start, end: e.end}, nil + } + + e, err := p.parsePrimary() + if err != nil { + return nil, err + } + + return p.parsePostfix(e) +} + +func (p *sqlParser) parsePostfix(e *node) (*node, error) { + for { + switch t := p.peek(); { + case t.isOp("["): + p.pos++ + + idx, err := p.parseExpr() + if err != nil { + return nil, err + } + + end := p.peek().end + if err = p.expectOp("]"); err != nil { + return nil, err + } + + e = &node{kind: nSubscript, args: []*node{e, idx}, start: e.start, end: end} + case t.isOp(".") && (p.peekAt(1).kind == tkIdent || p.peekAt(1).kind == tkQuoted): + p.pos++ + f := p.next() + e = &node{kind: nField, name: f.text, args: []*node{e}, start: e.start, end: f.end} + case t.is("at") && p.peekAt(1).is("time"): + return nil, errSQLSyntax + default: + return e, nil + } + } +} + +func typedLitKind(lw string) tsKind { + switch lw { + case kwDate: + return tyDate + case colTime: + return tyTime + case typTimestamp: + return tyTimestamp + case typDouble, "real": + return tyDouble + case typBigint: + return tyBigint + case kwInteger: + return tyInteger + case typVarchar: + return tyVarchar + case typBoolean: + return tyBoolean + } + + return tyInvalid +} + +func (p *sqlParser) parsePrimary() (*node, error) { + t := p.peek() + + switch t.kind { + case tkNumber: + p.pos++ + + k := tyInteger + if strings.ContainsAny(t.text, ".eE") { + k = tyDouble + } else if n, ok := atoiSafe(t.text); !ok || n > maxInt32 { + k = tyBigint + } + + return &node{kind: nLiteral, name: t.text, typ: scalar(k), start: t.start, end: t.end}, nil + case tkDuration: + p.pos++ + + return &node{kind: nLiteral, name: t.text, typ: scalar(tyIntervalDS), start: t.start, end: t.end}, nil + case tkString: + p.pos++ + + return &node{kind: nLiteral, name: t.text, typ: scalar(tyVarchar), start: t.start, end: t.end}, nil + case tkVar: + p.pos++ + + return &node{kind: nVar, name: t.text, start: t.start, end: t.end}, nil + case tkQuoted: + return p.parseNameOrCall() + case tkIdent: + return p.parseKeywordOrName() + case tkOp: + return p.parseOpPrimary() + case tkEOF: + } + + return nil, errSQLSyntax +} + +const maxInt32 = 1<<31 - 1 + +func (p *sqlParser) parseOpPrimary() (*node, error) { + t := p.peek() + + switch { + case t.isOp("?"): + p.pos++ + + return &node{kind: nParam, start: t.start, end: t.end}, nil + case t.isOp("("): + p.pos++ + + if p.peek().is("select") || p.peek().is("with") { + qn, err := p.parseQuery() + if err != nil { + return nil, err + } + + end := p.peek().end + + return &node{kind: nSubquery, sub: qn, start: t.start, end: end}, p.expectOp(")") + } + + items, err := p.parseExprList(")") + if err != nil || len(items) == 0 { + return nil, errSQLSyntax + } + + if len(items) == 1 { + return items[0], nil + } + + return &node{kind: nRowCtor, args: items, start: t.start, end: p.toks[p.pos-1].end}, nil + } + + return nil, errSQLSyntax +} + +func (p *sqlParser) parseKeywordOrName() (*node, error) { + t := p.peek() + lw := strings.ToLower(t.text) + nx := p.peekAt(1) + + switch { + case lw == kwNull: + p.pos++ + + return &node{kind: nLiteral, name: kwNull, typ: scalar(tyUnknown), start: t.start, end: t.end}, nil + case lw == kwTrue || lw == kwFalse: + p.pos++ + + return &node{kind: nLiteral, name: lw, typ: scalar(tyBoolean), start: t.start, end: t.end}, nil + case lw == "case": + return p.parseCase() + case lw == "interval": + return p.parseInterval() + case nx.kind == tkString && typedLitKind(lw) != tyInvalid: + p.pos += argsTwo + + return &node{ + kind: nTypedLit, name: nx.text, typ: scalar(typedLitKind(lw)), start: t.start, end: nx.end, + }, nil + case nx.isOp("("): + if n, ok, err := p.parseParenKeyword(lw); ok || err != nil { + return n, err + } + case lw == "array" && nx.isOp("["): + return p.parseArrayCtor() + } + + return p.parseNameOrCall() +} + +// parseParenKeyword parses the constructs that look like a call but have their own grammar. +func (p *sqlParser) parseParenKeyword(lw string) (*node, bool, error) { + var ( + n *node + err error + ) + + switch lw { + case "cast", "try_cast": + n, err = p.parseCast() + case "exists": + n, err = p.parseExists() + case "extract": + n, err = p.parseExtract() + case "row": + n, err = p.parseRowCtor() + default: + return nil, false, nil + } + + return n, true, err +} + +func (p *sqlParser) parseRowCtor() (*node, error) { + t := p.next() + p.pos++ + + items, err := p.parseExprList(")") + if err != nil { + return nil, err + } + + return &node{kind: nRowCtor, args: items, start: t.start, end: p.toks[p.pos-1].end}, nil +} + +func (p *sqlParser) parseNameOrCall() (*node, error) { + t := p.next() + + if p.peek().isOp("(") && t.kind == tkIdent { + return p.parseCall(t) + } + + n := &node{kind: nColumn, parts: []string{t.text}, start: t.start, end: t.end} + + for p.peek().isOp(".") && (p.peekAt(1).kind == tkIdent || p.peekAt(1).kind == tkQuoted) { + p.pos++ + f := p.next() + n.parts = append(n.parts, f.text) + n.end = f.end + } + + return n, nil +} + +func (p *sqlParser) parseCall(name token) (*node, error) { + p.pos++ + + n := &node{kind: nCall, name: name.text, start: name.start} + + if p.peek().isOp("*") && p.peekAt(1).isOp(")") { + p.pos++ + n.star = true + } else { + if p.acceptKw("distinct") { + n.distinct = true + } else { + p.acceptKw("all") + } + + args, err := p.parseExprList(")") + if err != nil { + return nil, err + } + + n.args = args + } + + if n.star { + p.pos++ + } + + n.end = p.toks[p.pos-1].end + + return n, p.parseCallSuffix(n) +} + +func (p *sqlParser) skipBalanced() error { + if err := p.expectOp("("); err != nil { + return err + } + + depth := 1 + + for depth > 0 { + t := p.next() + + switch { + case t.kind == tkEOF: + return errSQLSyntax + case t.isOp("("): + depth++ + case t.isOp(")"): + depth-- + } + } + + return nil +} + +func (p *sqlParser) parseCallSuffix(n *node) error { + for { + advanced, err := p.parseOneSuffix(n) + if err != nil { + return err + } + + if !advanced { + n.end = p.toks[p.pos-1].end + + return nil + } + } +} + +func (p *sqlParser) parseOneSuffix(n *node) (bool, error) { + t, nx := p.peek(), p.peekAt(1) + + switch { + case t.is("filter") && nx.isOp("("): + p.pos++ + + return true, p.skipBalanced() + case t.is("within") && nx.is("group"): + p.pos += argsTwo + + return true, p.skipBalanced() + case (t.is("ignore") || t.is("respect")) && nx.is("nulls"): + p.pos += argsTwo + + return true, nil + case t.is("over"): + p.pos++ + + n.over = true + + if p.peek().isOp("(") { + return true, p.skipBalanced() + } + + if _, ok := p.identNameAny(); !ok { + return false, errSQLSyntax + } + + return true, nil + } + + return false, nil +} + +func (p *sqlParser) parseCase() (*node, error) { + t := p.next() + n := &node{kind: nCase, start: t.start} + + if !p.peek().is("when") { + op, err := p.parseExpr() + if err != nil { + return nil, err + } + + n.operand = true + n.args = append(n.args, op) + } + + for p.acceptKw("when") { + w, err := p.parseExpr() + if err != nil { + return nil, err + } + + if err = p.expectKw("then"); err != nil { + return nil, err + } + + r, err := p.parseExpr() + if err != nil { + return nil, err + } + + n.args = append(n.args, w, r) + } + + if p.acceptKw("else") { + e, err := p.parseExpr() + if err != nil { + return nil, err + } + + n.hasElse = true + n.args = append(n.args, e) + } + + end := p.peek().end + if err := p.expectKw("end"); err != nil { + return nil, err + } + + n.end = end + + return n, nil +} + +func (p *sqlParser) parseCast() (*node, error) { + t := p.next() + p.pos++ + + e, err := p.parseExpr() + if err != nil { + return nil, err + } + + if err = p.expectKw("as"); err != nil { + return nil, err + } + + typ, err := p.parseType() + if err != nil { + return nil, err + } + + end := p.peek().end + + return &node{ + kind: nCast, name: strings.ToLower(t.text), typ: typ, args: []*node{e}, start: t.start, end: end, + }, p.expectOp(")") +} + +func (p *sqlParser) parseExists() (*node, error) { + t := p.next() + p.pos++ + + qn, err := p.parseQuery() + if err != nil { + return nil, err + } + + end := p.peek().end + + return &node{kind: nExists, sub: qn, start: t.start, end: end}, p.expectOp(")") +} + +func (p *sqlParser) parseArrayCtor() (*node, error) { + t := p.next() + p.pos++ + + items, err := p.parseExprList("]") + if err != nil { + return nil, err + } + + return &node{kind: nArrayCtor, args: items, start: t.start, end: p.toks[p.pos-1].end}, nil +} + +func isIntervalUnit(u string) bool { + switch strings.ToLower(u) { + case kwYear, kwMonth, "day", "hour", "minute", "second": + return true + } + + return false +} + +func (p *sqlParser) parseInterval() (*node, error) { + t := p.next() + + sign := p.peek() + if sign.isOp("-") || sign.isOp("+") { + p.pos++ + } + + lit := p.next() + if lit.kind != tkString && lit.kind != tkNumber { + return nil, errSQLSyntax + } + + unit := p.next() + if unit.kind != tkIdent || !isIntervalUnit(unit.text) { + return nil, errSQLSyntax + } + + end, k := unit.end, tyIntervalDS + if lw := strings.ToLower(unit.text); lw == kwYear || lw == kwMonth { + k = tyIntervalYM + } + + if p.acceptKw("to") { + u2 := p.next() + if u2.kind != tkIdent || !isIntervalUnit(u2.text) { + return nil, errSQLSyntax + } + + end = u2.end + } + + return &node{ + kind: nInterval, name: lit.text, parts: []string{unit.text}, typ: scalar(k), start: t.start, end: end, + }, nil +} + +func (p *sqlParser) parseExtract() (*node, error) { + t := p.next() + p.pos++ + + field := p.next() + if field.kind != tkIdent { + return nil, errSQLSyntax + } + + if err := p.expectKw("from"); err != nil { + return nil, err + } + + e, err := p.parseExpr() + if err != nil { + return nil, err + } + + end := p.peek().end + + return &node{ + kind: nCall, name: "extract", args: []*node{e}, start: t.start, end: end, parts: []string{field.text}, + }, p.expectOp(")") +} + +func (p *sqlParser) parseType() (tsType, error) { + if err := p.enter(); err != nil { + return tsType{}, err + } + defer p.leave() + + t := p.next() + if t.kind != tkIdent { + return tsType{}, errSQLSyntax + } + + switch lw := strings.ToLower(t.text); lw { + case "array": + return p.parseArrayType() + case "row": + return p.parseRowType() + case "timeseries": + inner, err := p.parseAngleOrParenType() + if err != nil { + return tsType{}, err + } + + return seriesOf(inner), nil + case "interval": + return p.parseIntervalType() + default: + return p.parseScalarType(lw) + } +} + +func (p *sqlParser) parseAngleOrParenType() (tsType, error) { + closer := ")" + + switch { + case p.acceptOp("("): + case p.acceptOp("<"): + closer = ">" + default: + return tsType{}, errSQLSyntax + } + + inner, err := p.parseType() + if err != nil { + return tsType{}, err + } + + return inner, p.expectOp(closer) +} + +func (p *sqlParser) parseArrayType() (tsType, error) { + e, err := p.parseAngleOrParenType() + if err != nil { + return tsType{}, err + } + + return arrayOf(e), nil +} + +func (p *sqlParser) parseRowType() (tsType, error) { + if err := p.expectOp("("); err != nil { + return tsType{}, err + } + + var fields []tsField + + for { + name := "" + if (p.peek().kind == tkIdent || p.peek().kind == tkQuoted) && p.peekAt(1).kind == tkIdent { + name = p.next().text + } + + ft, err := p.parseType() + if err != nil { + return tsType{}, err + } + + fields = append(fields, tsField{name: name, typ: ft}) + + if p.acceptOp(")") { + return rowOf(fields), nil + } + + if err = p.expectOp(","); err != nil { + return tsType{}, err + } + } +} + +func (p *sqlParser) parseIntervalType() (tsType, error) { + a := p.next() + if !isIntervalUnit(a.text) { + return tsType{}, errSQLSyntax + } + + if err := p.expectKw("to"); err != nil { + return tsType{}, err + } + + b := p.next() + if !isIntervalUnit(b.text) { + return tsType{}, errSQLSyntax + } + + if lw := strings.ToLower(a.text); lw == kwYear || lw == kwMonth { + return scalar(tyIntervalYM), nil + } + + return scalar(tyIntervalDS), nil +} + +func (p *sqlParser) skipTypeParams() { + if p.peek().isOp("(") && p.peekAt(1).kind == tkNumber { + for !p.peek().isOp(")") && p.peek().kind != tkEOF { + p.pos++ + } + + p.pos++ + } +} + +func (p *sqlParser) parseScalarType(lw string) (tsType, error) { + p.skipTypeParams() + + switch lw { + case typBigint, "long": + return scalar(tyBigint), nil + case "int", kwInteger, "smallint", "tinyint": + return scalar(tyInteger), nil + case typDouble, "real", "float", "decimal", "numeric": + p.acceptKw("precision") + + return scalar(tyDouble), nil + case "varchar", "char", "string": + return scalar(tyVarchar), nil + case typBoolean: + return scalar(tyBoolean), nil + case "date": + return scalar(tyDate), nil + case "time": + p.skipTimeZoneSuffix() + + return scalar(tyTime), nil + case "timestamp": + p.skipTimeZoneSuffix() + + return scalar(tyTimestamp), nil + } + + return tsType{}, errSQLSyntax +} + +func (p *sqlParser) skipTimeZoneSuffix() { + if (p.peek().is("with") || p.peek().is("without")) && p.peekAt(1).is("time") { + p.pos += argsThree + } +} diff --git a/services/timestreamquery/ts_sqllex.go b/services/timestreamquery/ts_sqllex.go new file mode 100644 index 0000000000..d1fd915c88 --- /dev/null +++ b/services/timestreamquery/ts_sqllex.go @@ -0,0 +1,276 @@ +package timestreamquery + +import ( + "errors" + "strings" + "unicode" +) + +type tokKind uint8 + +const ( + tkEOF tokKind = iota + tkIdent + tkQuoted + tkString + tkNumber + tkDuration + tkOp + tkVar +) + +const ( + maxSQLTokens = 100000 + maxSQLDepth = 200 +) + +var errSQLSyntax = errors.New("unsupported sql syntax") + +type token struct { + text string + start, end int + kind tokKind +} + +func (t token) is(kw string) bool { return t.kind == tkIdent && strings.EqualFold(t.text, kw) } + +func (t token) isOp(op string) bool { return t.kind == tkOp && t.text == op } + +func isIdentStart(c byte) bool { return c == '_' || unicode.IsLetter(rune(c)) } + +func isIdentPart(c byte) bool { return isIdentStart(c) || (c >= '0' && c <= '9') } + +func isDigit(c byte) bool { return c >= '0' && c <= '9' } + +// skipComment returns the index after a `--` or `/* */` comment starting at q[i], or i when none starts there. +const commentDelimLen = 2 + +// skipComment returns the index after a `--` or `/* */` comment starting at q[i], or i when none starts there. +func skipComment(q string, i int) int { + switch { + case strings.HasPrefix(q[i:], "--"): + if nl := strings.IndexByte(q[i:], '\n'); nl >= 0 { + return i + nl + } + + return len(q) + case strings.HasPrefix(q[i:], "/*"): + if end := strings.Index(q[i+commentDelimLen:], "*/"); end >= 0 { + return i + commentDelimLen + end + commentDelimLen + } + + return len(q) + } + + return i +} + +// stripSQLComments replaces comments outside quoted literals and identifiers with a single space. +func stripSQLComments(q string) string { + if !strings.Contains(q, "--") && !strings.Contains(q, "/*") { + return q + } + + var sb strings.Builder + + for i := 0; i < len(q); { + if q[i] == '\'' || q[i] == '"' { + end := closingQuote(q, i) + sb.WriteString(q[i:end]) + + i = end + + continue + } + + if j := skipComment(q, i); j != i { + sb.WriteByte(' ') + + i = j + + continue + } + + sb.WriteByte(q[i]) + + i++ + } + + return sb.String() +} + +func unquoteBody(q string, start, end int) string { + quote := q[start] + + return strings.ReplaceAll(q[start+1:end-1], string([]byte{quote, quote}), string([]byte{quote})) +} + +func skipDigits(q string, i int) int { + for i < len(q) && isDigit(q[i]) { + i++ + } + + return i +} + +func skipExponent(q string, j int) int { + if j >= len(q) || (q[j] != 'e' && q[j] != 'E') { + return j + } + + k := j + 1 + if k < len(q) && (q[k] == '+' || q[k] == '-') { + k++ + } + + if k < len(q) && isDigit(q[k]) { + return skipDigits(q, k) + } + + return j +} + +func lexNumber(q string, i int) int { + j := skipDigits(q, i) + + if j < len(q) && q[j] == '.' { + j = skipDigits(q, j+1) + } + + return skipExponent(q, j) +} + +func isDurationUnit(w string) bool { + switch strings.ToLower(w) { + case "ns", "us", "ms", "s", "m", "h", "d", "nanosecond", "microsecond", "millisecond", "second", "minute", + "hour", "day", "nanoseconds", "microseconds", "milliseconds", "seconds", "minutes", "hours", "days": + return true + } + + return false +} + +func lexOp(q string, i int) string { + for _, op := range []string{"<>", "!=", "<=", ">=", "||", "->", "::", "=>"} { + if strings.HasPrefix(q[i:], op) { + return op + } + } + + return q[i : i+1] +} + +func lexQuotedTok(q string, i int) (token, int, error) { + c := q[i] + + end := closingQuote(q, i) + if end > len(q) || q[end-1] != c || end-i < commentDelimLen { + return token{}, 0, errSQLSyntax + } + + k := tkString + if c == '"' { + k = tkQuoted + } + + return token{kind: k, text: unquoteBody(q, i, end), start: i, end: end}, end, nil +} + +func lexNumberTok(q string, i int) (token, int, error) { + j := lexNumber(q, i) + k := tkNumber + + if j < len(q) && isIdentStart(q[j]) { + w := j + for w < len(q) && isIdentPart(q[w]) { + w++ + } + + if !isDurationUnit(q[j:w]) { + return token{}, 0, errSQLSyntax + } + + j, k = w, tkDuration + } + + return token{kind: k, text: q[i:j], start: i, end: j}, j, nil +} + +func lexIdentTok(q string, i int) (token, int) { + j := i + for j < len(q) && isIdentPart(q[j]) { + j++ + } + + if strings.EqualFold(q[i:j], "measure_value") && strings.HasPrefix(q[j:], "::") { + k := j + commentDelimLen + for k < len(q) && isIdentPart(q[k]) { + k++ + } + + j = k + } + + return token{kind: tkIdent, text: q[i:j], start: i, end: j}, j +} + +func lexOne(q string, i int) (token, int, error) { + c := q[i] + + switch { + case c == '\'' || c == '"': + return lexQuotedTok(q, i) + case isDigit(c) || (c == '.' && i+1 < len(q) && isDigit(q[i+1])): + return lexNumberTok(q, i) + case isIdentStart(c): + t, j := lexIdentTok(q, i) + + return t, j, nil + case c == '@': + j := i + 1 + for j < len(q) && isIdentPart(q[j]) { + j++ + } + + return token{kind: tkVar, text: q[i:j], start: i, end: j}, j, nil + } + + op := lexOp(q, i) + + return token{kind: tkOp, text: op, start: i, end: i + len(op)}, i + len(op), nil +} + +func isSpaceByte(c byte) bool { return c == ' ' || c == '\t' || c == '\n' || c == '\r' } + +// tokenizeSQL splits q into tokens, dropping comments; measure_value::type is one identifier. +func tokenizeSQL(q string) ([]token, error) { + var toks []token + + for i := 0; i < len(q); { + if len(toks) > maxSQLTokens { + return nil, errSQLSyntax + } + + if j := skipComment(q, i); j != i { + i = j + + continue + } + + if isSpaceByte(q[i]) { + i++ + + continue + } + + t, next, err := lexOne(q, i) + if err != nil { + return nil, err + } + + toks = append(toks, t) + i = next + } + + return append(toks, token{kind: tkEOF, start: len(q), end: len(q)}), nil +} diff --git a/services/timestreamquery/ts_sqlparse.go b/services/timestreamquery/ts_sqlparse.go new file mode 100644 index 0000000000..f67d56a04b --- /dev/null +++ b/services/timestreamquery/ts_sqlparse.go @@ -0,0 +1,763 @@ +package timestreamquery + +import ( + "strconv" + "strings" +) + +type sqlParser struct { + q string + toks []token + pos int + depth int +} + +func parseSQL(q string) (*queryNode, error) { + toks, err := tokenizeSQL(q) + if err != nil { + return nil, err + } + + p := &sqlParser{q: q, toks: toks} + + qn, err := p.parseQuery() + if err != nil { + return nil, err + } + + if p.peek().kind != tkEOF { + return nil, errSQLSyntax + } + + return qn, nil +} + +func (p *sqlParser) peek() token { return p.toks[p.pos] } + +func (p *sqlParser) peekAt(n int) token { + if p.pos+n >= len(p.toks) { + return p.toks[len(p.toks)-1] + } + + return p.toks[p.pos+n] +} + +func (p *sqlParser) next() token { + t := p.toks[p.pos] + if t.kind != tkEOF { + p.pos++ + } + + return t +} + +func (p *sqlParser) acceptKw(kw string) bool { + if p.peek().is(kw) { + p.pos++ + + return true + } + + return false +} + +func (p *sqlParser) acceptOp(op string) bool { + if p.peek().isOp(op) { + p.pos++ + + return true + } + + return false +} + +func (p *sqlParser) expectOp(op string) error { + if !p.acceptOp(op) { + return errSQLSyntax + } + + return nil +} + +func (p *sqlParser) expectKw(kw string) error { + if !p.acceptKw(kw) { + return errSQLSyntax + } + + return nil +} + +func (p *sqlParser) enter() error { + p.depth++ + if p.depth > maxSQLDepth { + return errSQLSyntax + } + + return nil +} + +func (p *sqlParser) leave() { p.depth-- } + +func isReservedWord(lw string) bool { + switch lw { + case "from", "where", "group", "having", "order", "limit", "offset", "union", "intersect", "except", "on", + "using", "join", "inner", "left", "right", "full", "cross", "natural", "window", "fetch", "as", "when", + "then", "else", "end", "and", "or", opNotLower, "is", "in", "between", "like", "select", "with", "over": + return true + } + + return false +} + +func (p *sqlParser) identName() (string, bool) { + t := p.peek() + if t.kind == tkQuoted || (t.kind == tkIdent && !isReservedWord(strings.ToLower(t.text))) { + p.pos++ + + return t.text, true + } + + return "", false +} + +func (p *sqlParser) parseQuery() (*queryNode, error) { + if err := p.enter(); err != nil { + return nil, err + } + defer p.leave() + + var ctes []cteDef + + if p.acceptKw("with") { + if p.peek().is("recursive") { + return nil, errSQLSyntax + } + + for { + c, err := p.parseCTE() + if err != nil { + return nil, err + } + + ctes = append(ctes, c) + + if !p.acceptOp(",") { + break + } + } + } + + qn, err := p.parseSetExpr(1) + if err != nil { + return nil, err + } + + qn.ctes = append(ctes, qn.ctes...) + + if err = p.parseTail(qn); err != nil { + return nil, err + } + + return qn, nil +} + +func (p *sqlParser) parseCTE() (cteDef, error) { + name, ok := p.identName() + if !ok { + return cteDef{}, errSQLSyntax + } + + def := cteDef{name: name} + + if p.acceptOp("(") { + cols, err := p.parseNameList() + if err != nil { + return def, err + } + + def.cols = cols + } + + if err := p.expectKw("as"); err != nil { + return def, err + } + + if err := p.expectOp("("); err != nil { + return def, err + } + + qn, err := p.parseQuery() + if err != nil { + return def, err + } + + def.query = qn + + return def, p.expectOp(")") +} + +// parseNameList reads identifiers up to the closing paren (the opening one is consumed). +func (p *sqlParser) parseNameList() ([]string, error) { + var out []string + + for { + n, ok := p.identName() + if !ok { + return nil, errSQLSyntax + } + + out = append(out, n) + + if p.acceptOp(")") { + return out, nil + } + + if err := p.expectOp(","); err != nil { + return nil, err + } + } +} + +func setOpPrec(t token) int { + switch { + case t.is("intersect"): + return argsTwo + case t.is("union"), t.is("except"): + return 1 + } + + return 0 +} + +func (p *sqlParser) parseSetExpr(minPrec int) (*queryNode, error) { + left, err := p.parseSetPrimary() + if err != nil { + return nil, err + } + + for { + prec := setOpPrec(p.peek()) + if prec == 0 || prec < minPrec { + return left, nil + } + + op := strings.ToUpper(p.next().text) + if p.peek().is("all") || p.peek().is("distinct") { + p.pos++ + } + + right, rerr := p.parseSetExpr(prec + 1) + if rerr != nil { + return nil, rerr + } + + left = &queryNode{left: left, right: right, setOp: op} + } +} + +func (p *sqlParser) parseSetPrimary() (*queryNode, error) { + if p.peek().isOp("(") { + p.pos++ + + qn, err := p.parseQuery() + if err != nil { + return nil, err + } + + return qn, p.expectOp(")") + } + + if p.peek().is("values") { + rel, err := p.parseValues() + if err != nil { + return nil, err + } + + return &queryNode{sel: &selectSpec{items: []selectItem{{star: true}}, from: rel}}, nil + } + + return p.parseSelect() +} + +func (p *sqlParser) parseTail(qn *queryNode) error { + if p.acceptKw("order") { + if err := p.parseOrderBy(qn); err != nil { + return err + } + } + + for p.peek().is("offset") || p.peek().is("limit") { + p.pos++ + + if p.acceptKw("all") { + continue + } + + e, err := p.parseExpr() + if err != nil { + return err + } + + qn.limit = append(qn.limit, e) + } + + return nil +} + +func (p *sqlParser) parseOrderBy(qn *queryNode) error { + if err := p.expectKw("by"); err != nil { + return err + } + + for { + e, err := p.parseExpr() + if err != nil { + return err + } + + qn.orderBy = append(qn.orderBy, orderItem{expr: e}) + + if p.peek().is("asc") || p.peek().is("desc") { + p.pos++ + } + + if p.acceptKw("nulls") { + p.pos++ + } + + if !p.acceptOp(",") { + return nil + } + } +} + +func (p *sqlParser) parseSelect() (*queryNode, error) { + if err := p.expectKw("select"); err != nil { + return nil, err + } + + sel := &selectSpec{} + + if p.acceptKw("distinct") { + sel.distinct = true + } else { + p.acceptKw("all") + } + + for { + it, err := p.parseSelectItem() + if err != nil { + return nil, err + } + + sel.items = append(sel.items, it) + + if !p.acceptOp(",") { + break + } + } + + if err := p.parseSelectClauses(sel); err != nil { + return nil, err + } + + return &queryNode{sel: sel}, nil +} + +func (p *sqlParser) parseSelectClauses(sel *selectSpec) error { + var err error + + if p.acceptKw("from") { + if sel.from, err = p.parseFrom(); err != nil { + return err + } + } + + if p.acceptKw("where") { + if sel.where, err = p.parseExpr(); err != nil { + return err + } + } + + if p.acceptKw("group") { + if sel.groupBy, err = p.parseGroupBy(); err != nil { + return err + } + } + + if p.acceptKw("having") { + if sel.having, err = p.parseExpr(); err != nil { + return err + } + } + + if p.acceptKw("window") { + return p.skipWindowDefs() + } + + return nil +} + +// skipWindowDefs consumes `name AS (spec) [, ...]`; window specs never change a column's type. +func (p *sqlParser) skipWindowDefs() error { + for { + if _, ok := p.identNameAny(); !ok { + return errSQLSyntax + } + + if err := p.expectKw("as"); err != nil { + return err + } + + if err := p.skipBalanced(); err != nil { + return err + } + + if !p.acceptOp(",") { + return nil + } + } +} + +func (p *sqlParser) parseGroupBy() ([]*node, error) { + if err := p.expectKw("by"); err != nil { + return nil, err + } + + p.acceptKw("distinct") + + var out []*node + + for { + if p.peek().is("grouping") && p.peekAt(1).is("sets") { + p.pos += argsTwo + + if err := p.skipBalanced(); err != nil { + return nil, err + } + + if !p.acceptOp(",") { + return out, nil + } + + continue + } + + e, err := p.parseExpr() + if err != nil { + return nil, err + } + + out = append(out, e) + + if !p.acceptOp(",") { + return out, nil + } + } +} + +func (p *sqlParser) parseSelectItem() (selectItem, error) { + if p.peek().isOp("*") { + p.pos++ + + return selectItem{star: true}, nil + } + + if t := p.peek(); (t.kind == tkIdent || t.kind == tkQuoted) && p.starQualifier() { + var qual []string + + for !p.peek().isOp("*") { + qual = append(qual, p.next().text) + p.acceptOp(".") + } + + p.pos++ + + return selectItem{star: true, qual: qual}, nil + } + + e, err := p.parseExpr() + if err != nil { + return selectItem{}, err + } + + it := selectItem{expr: e} + + if p.acceptKw("as") { + n, ok := p.identNameAny() + if !ok { + return it, errSQLSyntax + } + + it.alias = n + } else if n, ok := p.identName(); ok { + it.alias = n + } + + return it, nil +} + +func (p *sqlParser) identNameAny() (string, bool) { + t := p.peek() + if t.kind == tkQuoted || t.kind == tkIdent { + p.pos++ + + return t.text, true + } + + return "", false +} + +// starQualifier reports whether the upcoming tokens are `ident(.ident)* . *`. +func (p *sqlParser) starQualifier() bool { + for i := 0; ; i += argsTwo { + t := p.peekAt(i) + if t.kind != tkIdent && t.kind != tkQuoted { + return false + } + + if !p.peekAt(i + 1).isOp(".") { + return false + } + + if p.peekAt(i + argsTwo).isOp("*") { + return true + } + } +} + +func (p *sqlParser) parseValues() (*relation, error) { + p.pos++ + + rel := &relation{kind: relValues} + + for { + if err := p.expectOp("("); err != nil { + return nil, err + } + + row, err := p.parseExprList(")") + if err != nil { + return nil, err + } + + rel.rows = append(rel.rows, row) + + if !p.acceptOp(",") { + return rel, nil + } + } +} + +// parseExprList reads comma-separated expressions up to and including closer. +func (p *sqlParser) parseExprList(closer string) ([]*node, error) { + var out []*node + + if p.acceptOp(closer) { + return out, nil + } + + for { + e, err := p.parseExpr() + if err != nil { + return nil, err + } + + out = append(out, e) + + if p.acceptOp(closer) { + return out, nil + } + + if err = p.expectOp(","); err != nil { + return nil, err + } + } +} + +func (p *sqlParser) parseFrom() (*relation, error) { + left, err := p.parseJoined() + if err != nil { + return nil, err + } + + for p.acceptOp(",") { + right, rerr := p.parseJoined() + if rerr != nil { + return nil, rerr + } + + left = &relation{kind: relJoin, left: left, right: right, joinType: "CROSS"} + } + + return left, nil +} + +func (p *sqlParser) joinKind() (string, bool) { + t := p.peek() + + switch { + case t.is("join"): + p.pos++ + + return "INNER", true + case t.is("inner"), t.is("cross"): + p.pos++ + + return strings.ToUpper(t.text), p.expectKw("join") == nil + case t.is("left"), t.is("right"), t.is("full"): + p.pos++ + p.acceptKw("outer") + + return strings.ToUpper(t.text), p.expectKw("join") == nil + } + + return "", false +} + +func (p *sqlParser) parseJoined() (*relation, error) { + left, err := p.parsePrimaryRel() + if err != nil { + return nil, err + } + + for { + kind, ok := p.joinKind() + if !ok { + return left, nil + } + + right, rerr := p.parsePrimaryRel() + if rerr != nil { + return nil, rerr + } + + j := &relation{kind: relJoin, left: left, right: right, joinType: kind} + + switch { + case p.acceptKw("on"): + if j.on, rerr = p.parseExpr(); rerr != nil { + return nil, rerr + } + case p.acceptKw("using"): + if rerr = p.expectOp("("); rerr != nil { + return nil, rerr + } + + if j.using, rerr = p.parseNameList(); rerr != nil { + return nil, rerr + } + } + + left = j + } +} + +func (p *sqlParser) parseRelAlias(rel *relation) error { + p.acceptKw("as") + + if n, ok := p.identName(); ok { + rel.alias = n + + if p.acceptOp("(") { + cols, err := p.parseNameList() + if err != nil { + return err + } + + rel.colAliases = cols + } + } + + return nil +} + +func (p *sqlParser) parsePrimaryRel() (*relation, error) { + if err := p.enter(); err != nil { + return nil, err + } + defer p.leave() + + t := p.peek() + + switch { + case t.isOp("("): + return p.parseParenRel() + case t.is("unnest"): + p.pos++ + + if err := p.expectOp("("); err != nil { + return nil, err + } + + args, err := p.parseExprList(")") + if err != nil { + return nil, err + } + + rel := &relation{kind: relUnnest, args: args} + + if p.acceptKw("with") { + if err = p.expectKw("ordinality"); err != nil { + return nil, err + } + + rel.ordinality = true + } + + return rel, p.parseRelAlias(rel) + case t.kind == tkIdent || t.kind == tkQuoted: + var ref []string + + for { + n, ok := p.identNameAny() + if !ok { + return nil, errSQLSyntax + } + + ref = append(ref, n) + + if !p.acceptOp(".") { + break + } + } + + rel := &relation{kind: relTable, ref: ref} + + return rel, p.parseRelAlias(rel) + } + + return nil, errSQLSyntax +} + +func (p *sqlParser) parseParenRel() (*relation, error) { + p.pos++ + + if p.peek().is("select") || p.peek().is("with") || p.peek().is("values") || p.peek().isOp("(") { + qn, err := p.parseQuery() + if err != nil { + return nil, err + } + + if err = p.expectOp(")"); err != nil { + return nil, err + } + + rel := &relation{kind: relSubquery, sub: qn} + + return rel, p.parseRelAlias(rel) + } + + inner, err := p.parseFrom() + if err != nil { + return nil, err + } + + return inner, p.expectOp(")") +} + +func atoiSafe(s string) (int, bool) { + n, err := strconv.Atoi(s) + + return n, err == nil +} diff --git a/services/timestreamquery/ts_types.go b/services/timestreamquery/ts_types.go new file mode 100644 index 0000000000..e1a1101726 --- /dev/null +++ b/services/timestreamquery/ts_types.go @@ -0,0 +1,255 @@ +package timestreamquery + +import "strings" + +type tsKind uint8 + +const ( + tyInvalid tsKind = iota + tyUnknown + tyBoolean + tyInteger + tyBigint + tyDouble + tyVarchar + tyDate + tyTime + tyTimestamp + tyIntervalDS + tyIntervalYM + tyArray + tyRow + tyTimeseries +) + +type tsField struct { + name string + typ tsType +} + +// tsType is a Timestream type; the zero value means the type could not be inferred. +type tsType struct { + elem *tsType + fields []tsField + kind tsKind +} + +func scalar(k tsKind) tsType { return tsType{kind: k} } + +func arrayOf(e tsType) tsType { return tsType{kind: tyArray, elem: &e} } + +func seriesOf(e tsType) tsType { return tsType{kind: tyTimeseries, elem: &e} } + +func rowOf(fields []tsField) tsType { return tsType{kind: tyRow, fields: fields} } + +// known reports whether the type and every nested component were inferred. +func (t tsType) known() bool { + switch t.kind { + case tyInvalid: + return false + case tyArray, tyTimeseries: + return t.elem != nil && t.elem.known() + case tyRow: + for _, f := range t.fields { + if !f.typ.known() { + return false + } + } + default: + } + + return true +} + +func (t tsType) isNumeric() bool { + return t.kind == tyInteger || t.kind == tyBigint || t.kind == tyDouble +} + +func (t tsType) isInterval() bool { return t.kind == tyIntervalDS || t.kind == tyIntervalYM } + +func (t tsType) isTemporal() bool { + return t.kind == tyDate || t.kind == tyTimestamp || t.kind == tyTime +} + +func scalarName(k tsKind) string { + switch k { + case tyUnknown: + return ScalarTypeUnknown + case tyBoolean: + return ScalarTypeBoolean + case tyInteger: + return "INTEGER" + case tyBigint: + return ScalarTypeBigint + case tyDouble: + return ScalarTypeDouble + case tyVarchar: + return ScalarTypeVarchar + case tyDate: + return ScalarTypeDate + case tyTime: + return ScalarTypeTime + case tyTimestamp: + return ScalarTypeTimestamp + case tyIntervalDS: + return ScalarTypeIntervalDayToSecond + case tyIntervalYM: + return ScalarTypeIntervalYearToMonth + default: + return "" + } +} + +func scalarTypeofName(k tsKind) string { + switch k { + case tyIntervalDS: + return "interval day to second" + case tyIntervalYM: + return "interval year to month" + case tyInteger: + return kwInteger + default: + return strings.ToLower(scalarName(k)) + } +} + +// typeofName spells the type the way typeof() prints it. +func (t tsType) typeofName() string { + switch t.kind { + case tyArray: + return "array(" + t.elem.typeofName() + ")" + case tyTimeseries: + return "timeseries(" + t.elem.typeofName() + ")" + case tyRow: + parts := make([]string, len(t.fields)) + for i, f := range t.fields { + parts[i] = f.typ.typeofName() + if f.name != "" { + parts[i] = f.name + " " + parts[i] + } + } + + return "row(" + strings.Join(parts, ", ") + ")" + default: + return scalarTypeofName(t.kind) + } +} + +func (t tsType) columnType() ColumnType { + switch t.kind { + case tyArray: + return ColumnType{ArrayColumnInfo: &ColumnInfo{Type: t.elem.columnType()}} + case tyTimeseries: + return ColumnType{TimeSeriesMeasureValueColumnInfo: &ColumnInfo{Type: t.elem.columnType()}} + case tyRow: + fields := make([]ColumnInfo, len(t.fields)) + for i, f := range t.fields { + fields[i] = ColumnInfo{Name: f.name, Type: f.typ.columnType()} + } + + return ColumnType{RowColumnInfo: fields} + default: + return ColumnType{ScalarType: scalarName(t.kind)} + } +} + +func (t tsType) columnInfo(name string) ColumnInfo { + return ColumnInfo{Name: name, Type: t.columnType()} +} + +func typeFromDecl(decl string) tsType { + switch decl { + case typBigint: + return scalar(tyBigint) + case typBoolean: + return scalar(tyBoolean) + case typDouble: + return scalar(tyDouble) + case typTimestamp: + return scalar(tyTimestamp) + case typVarchar: + return scalar(tyVarchar) + default: + return tsType{} + } +} + +func numericRank(k tsKind) int { + switch k { + case tyInteger: + return 1 + case tyBigint: + return argsTwo + case tyDouble: + return argsThree + default: + return 0 + } +} + +// supertype is the common type two values coerce to; the zero type when none exists. +func supertype(a, b tsType) tsType { + switch { + case a.kind == tyInvalid || b.kind == tyInvalid: + return tsType{} + case a.kind == tyUnknown: + return b + case b.kind == tyUnknown: + return a + case a.isNumeric() && b.isNumeric(): + if numericRank(a.kind) >= numericRank(b.kind) { + return a + } + + return b + case a.isTemporal() && b.isTemporal() && a.kind != b.kind: + return superTemporal(a, b) + case a.kind != b.kind: + return tsType{} + } + + return superSame(a, b) +} + +func superTemporal(a, b tsType) tsType { + if a.kind != tyTime && b.kind != tyTime { + return scalar(tyTimestamp) + } + + return tsType{} +} + +func superSame(a, b tsType) tsType { + switch a.kind { + case tyArray, tyTimeseries: + e := supertype(*a.elem, *b.elem) + if e.kind == tyInvalid { + return tsType{} + } + + return tsType{kind: a.kind, elem: &e} + case tyRow: + return superRow(a, b) + default: + return a + } +} + +func superRow(a, b tsType) tsType { + if len(a.fields) != len(b.fields) { + return tsType{} + } + + fields := make([]tsField, len(a.fields)) + + for i, f := range a.fields { + st := supertype(f.typ, b.fields[i].typ) + if st.kind == tyInvalid { + return tsType{} + } + + fields[i] = tsField{name: f.name, typ: st} + } + + return rowOf(fields) +} From 7f13819ca860aefe980ac87709acb26416427b39 Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 16:20:55 -0600 Subject: [PATCH 2/9] feat(gcpbigquery): exact NUMERIC and BIGNUMERIC arithmetic Decimal values are stored in an order-preserving encoding and computed with exact arithmetic across operators, math functions, casts, aggregates, window functions, formatting, loading, results and extracts. BIGNUMERIC no longer loses digits past scale 9. Parameterised NUMERIC(P,S) types are enforced. Older snapshots convert on restore. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- services/gcpbigquery/PARITY.md | 17 +- services/gcpbigquery/README.md | 2 +- services/gcpbigquery/avro_read.go | 2 +- services/gcpbigquery/bqsql/compile.go | 6 +- services/gcpbigquery/bqsql/compile_decimal.go | 527 ++++++++++++++ services/gcpbigquery/bqsql/compile_expr.go | 134 +++- services/gcpbigquery/bqsql/compile_func.go | 50 +- services/gcpbigquery/bqsql/decimal.go | 681 ++++++++++++++++++ .../bqsql/decimal_encoding_test.go | 354 +++++++++ services/gcpbigquery/bqsql/decimal_format.go | 218 ++++++ services/gcpbigquery/bqsql/decimal_math.go | 270 +++++++ services/gcpbigquery/bqsql/decimal_test.go | 465 ++++++++++++ services/gcpbigquery/bqsql/exec.go | 7 +- services/gcpbigquery/bqsql/interval.go | 2 +- .../gcpbigquery/bqsql/numeric_engine_test.go | 388 ++++++++++ services/gcpbigquery/bqsql/parser_expr.go | 62 +- services/gcpbigquery/bqsql/sqlvalues.go | 63 +- services/gcpbigquery/bqsql/types.go | 51 ++ services/gcpbigquery/bqsql/udf.go | 3 + services/gcpbigquery/bqsql/udf_cast.go | 19 +- services/gcpbigquery/bqsql/udf_decimal.go | 610 ++++++++++++++++ services/gcpbigquery/bqsql/udf_json.go | 10 +- services/gcpbigquery/bqsql/values.go | 112 ++- services/gcpbigquery/jobs_extract.go | 4 +- services/gcpbigquery/persistence.go | 7 + services/gcpbigquery/sdk_numeric_test.go | 456 ++++++++++++ 26 files changed, 4410 insertions(+), 110 deletions(-) create mode 100644 services/gcpbigquery/bqsql/compile_decimal.go create mode 100644 services/gcpbigquery/bqsql/decimal.go create mode 100644 services/gcpbigquery/bqsql/decimal_encoding_test.go create mode 100644 services/gcpbigquery/bqsql/decimal_format.go create mode 100644 services/gcpbigquery/bqsql/decimal_math.go create mode 100644 services/gcpbigquery/bqsql/decimal_test.go create mode 100644 services/gcpbigquery/bqsql/numeric_engine_test.go create mode 100644 services/gcpbigquery/bqsql/udf_decimal.go create mode 100644 services/gcpbigquery/sdk_numeric_test.go diff --git a/services/gcpbigquery/PARITY.md b/services/gcpbigquery/PARITY.md index 140fc1742a..04f92a9591 100644 --- a/services/gcpbigquery/PARITY.md +++ b/services/gcpbigquery/PARITY.md @@ -47,7 +47,7 @@ families: ddl: {status: ok, note: "CREATE [OR REPLACE] TABLE (column list or AS SELECT) with OPTIONS description, friendly_name, labels and expiration_timestamp, CREATE VIEW, CREATE MATERIALIZED VIEW (OPTIONS enable_refresh, refresh_interval_minutes, max_staleness), CREATE SCHEMA, DROP TABLE/VIEW/MATERIALIZED VIEW/SCHEMA [CASCADE], ALTER TABLE ADD COLUMN, DROP COLUMN and SET OPTIONS, and the routine statements. PARTITION BY and CLUSTER BY clauses parse but are dropped."} materialized_views: {status: ok, note: "tables.insert with materializedView {query, enableRefresh, refreshIntervalMs, maxStaleness} (MaterializedViewDefinition in bigquery-gen.go) and CREATE MATERIALIZED VIEW make a MATERIALIZED_VIEW table whose schema comes from the query; reads always evaluate the query over the current base tables, writes are rejected, CALL BQ.REFRESH_MATERIALIZED_VIEW moves lastRefreshTime."} load_extract_copy: {status: partial, note: "Load reads gs:// URIs (wildcards, gzip) from the GCS emulator through a hook wired in internal/app, or an uploaded body: CSV (skipLeadingRows, fieldDelimiter, nullMarker, allowJaggedRows, maxBadRecords, any single-character quote or none), NEWLINE_DELIMITED_JSON, PARQUET, AVRO and ORC, with explicit schema, the existing table's schema or autodetect, all create/write dispositions, schemaUpdateOptions (ALLOW_FIELD_ADDITION, ALLOW_FIELD_RELAXATION) on WRITE_APPEND with columns matched by name, hivePartitioningOptions (AUTO, STRINGS, CUSTOM), and caps of 1000 source files and 512 MiB decompressed per job. Source files are read before the backend lock is taken and the table changes only when every check passed. Extract writes CSV, NEWLINE_DELIMITED_JSON, PARQUET and AVRO (GZIP for CSV and JSON, DEFLATE or SNAPPY for Avro) to one or more URIs: shards are numbered 000000000000 per URI from a wildcard, distributed round-robin over the URIs and cut at 1 GiB logical bytes. Copy supports several sources and the dispositions."} - value_encoding: {status: ok, note: "Stored values keep the REST string form; schema types are reported as INTEGER, FLOAT, BOOLEAN, RECORD...; NUMERIC keeps 9 decimal digits through float64; DATETIME and TIME drop trailing zero fractions."} + value_encoding: {status: ok, note: "Stored values keep the REST string form; schema types are reported as INTEGER, FLOAT, BOOLEAN, RECORD...; NUMERIC (scale 9) and BIGNUMERIC (scale 38) are canonical decimal strings, exact end to end; DATETIME and TIME drop trailing zero fractions."} error_envelope: {status: ok, note: "Errors are {error:{code,message,errors:[{message,domain,reason}],status}} with reasons notFound, duplicate, invalid, invalidQuery, resourceInUse, uploadTooLarge and backendError."} routing_isolation: {status: ok, note: "Own http.Server bound in StartWorker to --gcp-bigquery-port / GCP_BIGQUERY_PORT (default 9050, fails fast if taken); never registered on the shared AWS router. cli.go reserves the port in the shared PortAlloc pool. Point the Go client at it with option.WithEndpoint(http://localhost:9050) and option.WithoutAuthentication(); paths work with or without the /bigquery/v2 prefix."} persistence: {status: ok, note: "Datasets, tables with rows and time-travel history, routines, streaming insertIds and the retained jobs with their query results persist in one snapshot (version 1); upload sessions do not."} @@ -60,7 +60,7 @@ items_still_open: - "Unsupported functions: RANGE values, ML.*, GEOGRAPHY beyond the implemented ST_* set (use_spheroid => TRUE, make_valid => TRUE, ST_UNION, ST_BUFFER and the other constructors and aggregates), SEARCH over a table reference or a tuple, JSON constructors and mutators beyond JSON_VALUE/JSON_QUERY/PARSE_JSON/TO_JSON_STRING, FORMAT patterns beyond %s %d %i %f %g %e %t %T %x %o, collation." - "ST_MAKELINE does not snap sufficiently short edges together (geography_functions ST_MAKELINE constraints; snap radius not stated there). Overlap detection of edges beyond the first 1024 only collapses repeated identical edges, and detection off the equator and meridians uses a floating-point tolerance, not an exact predicate. The error text for an edge of 180 degrees or more is emulator wording." - "SEARCH NO_OP_ANALYZER: the page's example SEARCH(R'\"foo bar\"', R'\"foo Bar\"', analyzer=>'NO_OP_ANALYZER') is TRUE with the comment 'analysis is case-insensitive', while its 'Foobar' vs 'foobar' example is FALSE; the emulator keeps NO_OP case-sensitive and returns FALSE for the first. SEARCH also reads upper-case AND/OR inside a double-quoted phrase as logical operators (the page's SEARCH(R'foo bar', R'\"foo AND (bar OR baz)\"') is TRUE, commented as a logical match); the rule for phrases that really contain those words is not documented, so 'Clyde and Bonnie' matches the query \"Bonnie AND Clyde\"." - - "Engine fidelity: NUMERIC and BIGNUMERIC are computed in float64, so values past 15 significant digits lose precision." + - "NUMERIC and BIGNUMERIC: a RANGE window frame with an offset over a NUMERIC or BIGNUMERIC ORDER BY key is rejected as unsupported (SQLite applies the offset to the encoded text); Parquet export writes BIGNUMERIC as STRING because pkgs/parquetio caps DECIMAL precision at 38 (the exporting-data page's BIGNUMERIC type mapping was not read)." - "Jobs: no slot or priority scheduling, no query cache, anonymous result tables are not created, script expression evaluations are not recorded as EXPRESSION child jobs, and execution holds the backend write lock (jobs_async.go runLocked), so jobs.cancel and jobTimeoutMs stop a job before it executes and a script between statements, not a plain statement in flight." - "Load: Datastore and Firestore backups, nested CSV and column-name flexibility options are not supported. External tables: GOOGLE_SHEETS, DATASTORE_BACKUP, BIGTABLE and DELTA_LAKE sources and WITH CONNECTION need services the emulator does not have. External tables and CREATE EXTERNAL TABLE read Cloud Storage while the backend lock is held (external.go readExternalRows). The NDJSON TIMESTAMP and CSV float rendering of extract have not been checked against the live service." leaks: {status: clean, note: "Background resources are the HTTP listener and the job workers; Shutdown joins both (Backend.Close cancels and waits for unfinished jobs). goleak runs in TestMain."} @@ -116,3 +116,16 @@ Pass 2026-11-14: row access policies per https://docs.cloud.google.com/bigquery/ ST_MAKELINE nodes retraced and overlapping edges into the documented MULTILINESTRING (example `MULTILINESTRING((1 0, 5 0, 10 0), (5 0, 5 4))`); SEARCH reads AND/OR inside a double-quoted phrase as logical operators (documented example `SEARCH(R'foo bar', R'"foo AND (bar OR baz)"')` is TRUE). Partitioning: PARTITION BY maps onto timePartitioning (DATE column, DATE(ts), DATE_TRUNC, DATETIME_TRUNC, TIMESTAMP_TRUNC, _PARTITIONDATE) or rangePartitioning (RANGE_BUCKET with GENERATE_ARRAY) and CLUSTER BY onto clustering.fields, with the documented "PARTITION BY expression must be ..." error; require_partition_filter and requirePartitionFilter make a query without a top-level predicate over the partition column fail (https://docs.cloud.google.com/bigquery/docs/querying-partitioned-tables). TABLESAMPLE SYSTEM (percent PERCENT) per https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax. Tables report streamingBuffer after insertAll (Table.streamingBuffer in the REST reference). + +Pass 2026-11-21: NUMERIC and BIGNUMERIC are exact decimals end to end (bqsql/decimal.go, decimal_math.go, decimal_format.go, udf_decimal.go, compile_decimal.go). Values are math/big scaled integers; inside SQLite they are '#' plus 64 hex digits of value*10^38+2^255, so `=`, DISTINCT, GROUP BY, JOIN keys, ORDER BY, MIN, MAX and comparisons are plain text operations and equal values encode alike for both kinds, while the kind travels in the compiled expression type. The compiler coerces INT64 and literal FLOAT64 operands to the decimal kind (data-type coercion table and literal coercion in https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/conversion_rules, read through a page summary) in operators, comparisons, CASE, IF, COALESCE, IFNULL, NULLIF, IN, BETWEEN, UNION and the other set operators, array and struct literals, DML targets and routine arguments; NUMERIC with BIGNUMERIC is BIGNUMERIC, anything with a non-literal FLOAT64 is FLOAT64. ABS, SIGN, CEIL, FLOOR, ROUND (with ROUND_HALF_AWAY_FROM_ZERO and ROUND_HALF_EVEN), TRUNC, MOD, DIV, POW, SQRT, EXP, LN, LOG, LOG10, SAFE_ADD, SAFE_SUBTRACT, SAFE_MULTIPLY, SAFE_DIVIDE, SAFE_NEGATE, GREATEST, LEAST and GENERATE_ARRAY return NUMERIC or BIGNUMERIC per the mathematical functions page (summary). SUM and AVG return the input type through aggregate and window callbacks; VARIANCE and STDDEV keep exact power sums and convert the result to FLOAT64 (statistical aggregate page summary); MIN, MAX, ANY_VALUE, ARRAY_AGG, COUNT(DISTINCT) and LAG/LEAD work on the encoding. CAST and SAFE_CAST between INT64, FLOAT64, STRING, NUMERIC and BIGNUMERIC, PARSE_NUMERIC and PARSE_BIGNUMERIC (commas before the point, one sign before or after, whitespace around, exponent), NUMERIC(P[, S]) and BIGNUMERIC(P[, S]) on CAST, DDL, insertAll, load and DML (round to S, error past P), FORMAT %f %e %g %t %T and TO_JSON_STRING work on exact digits. Avro decimal load keeps all 38 BIGNUMERIC digits and Parquet, CSV, NDJSON and insertAll parse the decimal text. Stored rows and snapshots keep the canonical decimal string, so old snapshots restore unchanged and Restore rewrites every NUMERIC cell through the canonical parser. + +## Emulator choices where the vendor is silent (NUMERIC) + +- Overflow errors read "numeric overflow: a + b" and "BIGNUMERIC overflow: a + b", division by zero "division by zero: a / b", and the other decimal errors carry the emulator's wording; the pages only say the operation errors. +- POW, EXP, LN, LOG, LOG10 and SQRT of decimals are evaluated at 640 bits (exact for integer exponents up to 256) and rounded half away from zero to the result scale; the functions page gives result types, not an algorithm. +- CAST of NUMERIC to INT64 rounds half away from zero; the conversion page does not describe it. AVG of NUMERIC rounds half away from zero at the result scale. +- FORMAT %f, %e and %g of NUMERIC print exact digits with ties away from zero; %t prints a whole value with ".0" and %T as NUMERIC "1.25" or BIGNUMERIC "1.25" as the format table shows. +- A NUMERIC literal or string with more fraction digits than the scale rounds half away from zero, as CAST of STRING does. +- Parameterised NUMERIC(P, S) values on insertAll, load and DML are rounded to S and fail with the emulator's message when more than P digits remain. +- HLL_COUNT.INIT hashes the decimal's internal encoding, so NUMERIC and BIGNUMERIC sketches of equal values agree with each other, not with BigQuery. + diff --git a/services/gcpbigquery/README.md b/services/gcpbigquery/README.md index c3e32bc5a5..b5c8e4dfe8 100644 --- a/services/gcpbigquery/README.md +++ b/services/gcpbigquery/README.md @@ -20,7 +20,7 @@ - Unsupported functions: RANGE values, ML.*, GEOGRAPHY beyond the implemented ST_* set (use_spheroid => TRUE, make_valid => TRUE, ST_UNION, ST_BUFFER and the other constructors and aggregates), SEARCH over a table reference or a tuple, JSON constructors and mutators beyond JSON_VALUE/JSON_QUERY/PARSE_JSON/TO_JSON_STRING, FORMAT patterns beyond %s %d %i %f %g %e %t %T %x %o, collation. - ST_MAKELINE does not snap sufficiently short edges together (geography_functions ST_MAKELINE constraints; snap radius not stated there). Overlap detection of edges beyond the first 1024 only collapses repeated identical edges, and detection off the equator and meridians uses a floating-point tolerance, not an exact predicate. The error text for an edge of 180 degrees or more is emulator wording. - SEARCH NO_OP_ANALYZER: the page's example SEARCH(R'"foo bar"', R'"foo Bar"', analyzer=>'NO_OP_ANALYZER') is TRUE with the comment 'analysis is case-insensitive', while its 'Foobar' vs 'foobar' example is FALSE; the emulator keeps NO_OP case-sensitive and returns FALSE for the first. SEARCH also reads upper-case AND/OR inside a double-quoted phrase as logical operators (the page's SEARCH(R'foo bar', R'"foo AND (bar OR baz)"') is TRUE, commented as a logical match); the rule for phrases that really contain those words is not documented, so 'Clyde and Bonnie' matches the query "Bonnie AND Clyde". -- Engine fidelity: NUMERIC and BIGNUMERIC are computed in float64, so values past 15 significant digits lose precision. +- NUMERIC and BIGNUMERIC: a RANGE window frame with an offset over a NUMERIC or BIGNUMERIC ORDER BY key is rejected as unsupported, and Parquet export writes BIGNUMERIC as STRING (pkgs/parquetio caps DECIMAL precision at 38). - Jobs: no slot or priority scheduling, no query cache, anonymous result tables are not created, script expression evaluations are not recorded as EXPRESSION child jobs, and execution holds the backend write lock (jobs_async.go runLocked), so jobs.cancel and jobTimeoutMs stop a job before it executes and a script between statements, not a plain statement in flight. - Load: Datastore and Firestore backups, nested CSV and column-name flexibility options are not supported. External tables: GOOGLE_SHEETS, DATASTORE_BACKUP, BIGTABLE and DELTA_LAKE sources and WITH CONNECTION need services the emulator does not have. External tables and CREATE EXTERNAL TABLE read Cloud Storage while the backend lock is held (external.go readExternalRows). The NDJSON TIMESTAMP and CSV float rendering of extract have not been checked against the live service. diff --git a/services/gcpbigquery/avro_read.go b/services/gcpbigquery/avro_read.go index dec3bfd464..7c5c82a74e 100644 --- a/services/gcpbigquery/avro_read.go +++ b/services/gcpbigquery/avro_read.go @@ -308,7 +308,7 @@ func avroScalar(v any, typ string) any { case time.Duration: return time.Unix(0, int64(t)).UTC().Format(timeLayoutMicros) case *big.Rat: - return t.FloatString(numericMaxScale) + return t.FloatString(bigNumericScale) } return v diff --git a/services/gcpbigquery/bqsql/compile.go b/services/gcpbigquery/bqsql/compile.go index de999beea5..0e1ddbd86f 100644 --- a/services/gcpbigquery/bqsql/compile.go +++ b/services/gcpbigquery/bqsql/compile.go @@ -385,9 +385,11 @@ func (c *compiler) compileSetOp(s *setExpr, outer *scope) (*compiledQuery, *selO cols[i] = Column{Name: left.cols[i].Name, Type: commonType(left.cols[i].Type, right.cols[i].Type)} } - sql := "SELECT * FROM (" + left.sql + ") " + setOpSQL()[s.op] + " SELECT * FROM (" + right.sql + ")" + leftSQL, rightSQL := unifySetColumns(left, cols), unifySetColumns(right, cols) + + sql := "SELECT * FROM (" + leftSQL + ") " + setOpSQL()[s.op] + " SELECT * FROM (" + rightSQL + ")" if s.op == "INTERSECT ALL" || s.op == "EXCEPT ALL" { - sql = bagSetOpSQL(strings.TrimSuffix(s.op, " ALL"), left.sql, right.sql, len(cols)) + sql = bagSetOpSQL(strings.TrimSuffix(s.op, " ALL"), leftSQL, rightSQL, len(cols)) } return &compiledQuery{sql: sql, cols: cols, aliases: left.aliases}, nil, nil diff --git a/services/gcpbigquery/bqsql/compile_decimal.go b/services/gcpbigquery/bqsql/compile_decimal.go new file mode 100644 index 0000000000..755b142d80 --- /dev/null +++ b/services/gcpbigquery/bqsql/compile_decimal.go @@ -0,0 +1,527 @@ +package bqsql + +import ( + "strconv" + "strings" +) + +func isDec(t Type) bool { return t.Kind == KindNumeric || t.Kind == KindBigNumeric } + +func decFlag(t Type) string { + if t.Kind == KindBigNumeric { + return "1" + } + + return "0" +} + +func (g *gx) floatLiteral() bool { return g.lit != nil && g.lit.kind == nFloat } + +func decCall(name string, args ...string) string { + return "bq_dec_" + name + "(" + strings.Join(args, ", ") + ")" +} + +// toType adapts g to type t the way implicit coercion does: INT64 and literal FLOAT64 become decimals when t is +// NUMERIC or BIGNUMERIC, decimals become FLOAT64 when t is FLOAT64. +func toType(g *gx, t Type) *gx { + switch { + case isDec(t) && g.typ.Kind == KindInt: + if g.lit != nil && g.lit.kind == nInt { + if d, err := ParseDecimal(t.Kind, g.lit.str); err == nil { + return &gx{sql: quoteStr(d.SQLText()), typ: t, lit: g.lit} + } + } + + return &gx{sql: decCall("from_int", g.sql, decFlag(t)), typ: t} + case isDec(t) && g.typ.Kind == KindFloat: + if g.floatLiteral() { + if d, err := ParseDecimal(t.Kind, g.lit.str); err == nil { + return &gx{sql: quoteStr(d.SQLText()), typ: t} + } + } + + return &gx{sql: decCall("from_float", g.sql, decFlag(t)), typ: t} + case isDec(t) && isDec(g.typ): + return &gx{sql: g.sql, typ: t, lit: g.lit} + case t.Kind == KindFloat && isDec(g.typ): + return &gx{sql: decCall("to_float", g.sql), typ: t} + } + + return g +} + +func hasDec(gs []*gx) bool { + for _, g := range gs { + if isDec(g.typ) { + return true + } + } + + return false +} + +// unifyAll computes the common type of gs and coerces every member to it. Without a decimal member it is the +// identity on the SQL. +func unifyAll(gs []*gx) (Type, []*gx) { + var t Type + for _, g := range gs { + t = commonType(t, g.typ) + } + + if !hasDec(gs) { + return t, gs + } + + var strict Type + + for _, g := range gs { + if !g.floatLiteral() { + strict = commonType(strict, g.typ) + } + } + + if isDec(strict) { + t = strict + } + + out := make([]*gx, len(gs)) + for i, g := range gs { + out[i] = toType(g, t) + } + + return t, out +} + +func unifyPair(l, r *gx) (*gx, *gx, Type) { + t, out := unifyAll([]*gx{l, r}) + + return out[0], out[1], t +} + +// decOperator compiles an operator with at least one decimal operand; ok is false for operators that are not numeric. +func decOperator(op string, l, r *gx) (*gx, bool) { + switch op { + case "=", "!=", "<", ">", "<=", ">=": + l2, r2, _ := unifyPair(l, r) + + return &gx{sql: "(" + l2.sql + " " + op + " " + r2.sql + ")", typ: scalar(KindBool)}, true + case "+", "-", "*", "/": + default: + return nil, false + } + + l2, r2, t := unifyPair(l, r) + if !isDec(t) { + return nil, false + } + + fn := map[string]string{"+": decAdd, "-": decSub, "*": decMul, "/": decDiv}[op] + + return &gx{sql: decCall(fn, l2.sql, r2.sql, decFlag(t)), typ: t}, true +} + +// constrainDec enforces NUMERIC(P, S) on g when the target type is parameterised. +func constrainDec(g *gx, t Type) *gx { + if !isDec(t) || t.Prec == 0 || !isDec(g.typ) { + return g + } + + return &gx{ + sql: decCall("constrain", g.sql, strconv.Itoa(t.Prec), strconv.Itoa(t.Scale), decFlag(t)), + typ: t, + } +} + +func decFunc(safe bool, name string, args ...string) string { + if safe { + return "bq_safe_" + decCall(name, args...)[3:] + } + + return decCall(name, args...) +} + +// decCast compiles CAST/SAFE_CAST when the source or the target is NUMERIC or BIGNUMERIC. +func decCast(a *gx, to Type, safe bool) (*gx, error) { + if a.typ.Kind == KindUnknown { + return &gx{sql: a.sql, typ: to}, nil + } + + switch { + case isDec(to): + sql, ok := decCastTo(a, to, safe) + if !ok { + return nil, invalid("Invalid cast from %s to %s", a.typ.Kind.SQLName(), to.Kind.SQLName()) + } + + g := &gx{sql: sql, typ: to} + if to.Prec > 0 { + g.sql = decFunc(safe, "constrain", sql, strconv.Itoa(to.Prec), strconv.Itoa(to.Scale), decFlag(to)) + } + + return g, nil + case to.Kind == KindInt: + return &gx{sql: decFunc(safe, "to_int", a.sql), typ: to}, nil + case to.Kind == KindFloat: + return &gx{sql: decCall("to_float", a.sql), typ: to}, nil + case to.Kind == KindString: + return &gx{sql: decCall("to_str", a.sql), typ: to}, nil + } + + return nil, invalid("Invalid cast from %s to %s", a.typ.Kind.SQLName(), to.Kind.SQLName()) +} + +func decCastTo(a *gx, to Type, safe bool) (string, bool) { + switch a.typ.Kind { //nolint:exhaustive // other sources are not castable to decimals + case KindInt: + return decFunc(safe, "from_int", a.sql, decFlag(to)), true + case KindFloat: + return decFunc(safe, "from_float", a.sql, decFlag(to)), true + case KindString: + return decFunc(safe, "from_str", a.sql, decFlag(to)), true + case KindNumeric, KindBigNumeric: + if a.typ.Kind == to.Kind { + return a.sql, true + } + + return decFunc(safe, "convert", a.sql, decFlag(to)), true + } + + return "", false +} + +func floatArgs(args []*gx) []*gx { + out := make([]*gx, len(args)) + for i, g := range args { + out[i] = toType(g, scalar(KindFloat)) + } + + return out +} + +func roundMode(g *gx) (string, error) { + if g.lit == nil || g.lit.kind != nString { + return "", invalid("ROUND rounding mode must be a string literal") + } + + switch strings.ToUpper(g.lit.str) { + case "ROUND_HALF_AWAY_FROM_ZERO": + return "0", nil + case "ROUND_HALF_EVEN": + return "1", nil + } + + return "", invalid("Invalid rounding mode %q", g.lit.str) +} + +const ( + decAdd = "add" + decSub = "sub" + decMul = "mul" + decDiv = "div" + decNegName = "neg" + udfSneg = "sneg" +) + +// decFunction compiles a scalar function whose arguments include a decimal. handled is false when the generic +// path should run with the decimals decoded to FLOAT64. +func decFunction(udf string, safe bool, args []*gx) (*gx, bool, error) { + switch udf { + case "abs", "sign", "ceil", "floor", "sqrt", "exp", "ln", "log10", udfSneg: + return decUnaryFn(udf, safe, args) + case "round", "trunc": + return decRoundFn(udf, safe, args) + case "log": + if len(args) == 1 && isDec(args[0].typ) { + return &gx{sql: decFunc(safe, "ln", args[0].sql, decFlag(args[0].typ)), typ: args[0].typ}, true, nil + } + + return decPair("log", safe, args) + case "pow", "mod", "intdiv": + return decPair(udf, safe, args) + case "sdiv", "sadd", "ssub", "smul": + name := map[string]string{"sdiv": decDiv, "sadd": decAdd, "ssub": decSub, "smul": decMul}[udf] + + return decPair(name, true, args) + case "greatest", "least": + return decExtreme(udf, args) + case "generate_array": + return decGenerateArraySQL(args) + } + + return nil, false, nil +} + +func decUnaryFn(udf string, safe bool, args []*gx) (*gx, bool, error) { + t := args[0].typ + if len(args) != 1 || !isDec(t) { + return nil, false, nil + } + + name := udf + if udf == udfSneg { + name, safe = decNegName, true + } + + return &gx{sql: decFunc(safe, name, args[0].sql, decFlag(t)), typ: t}, true, nil +} + +func decExtreme(udf string, args []*gx) (*gx, bool, error) { + ct, us := unifyAll(args) + if !isDec(ct) { + return nil, false, nil + } + + if len(us) == 1 { + return us[0], true, nil + } + + fn := map[string]string{"greatest": "max", "least": "min"}[udf] + parts := make([]string, len(us)) + + for i, u := range us { + parts[i] = u.sql + } + + return &gx{sql: fn + "(" + strings.Join(parts, ", ") + ")", typ: ct}, true, nil +} + +func decPair(name string, safe bool, args []*gx) (*gx, bool, error) { + if len(args) != 2 { //nolint:mnd // binary functions + return nil, false, nil + } + + l, r, t := unifyPair(args[0], args[1]) + if !isDec(t) { + return nil, false, nil + } + + return &gx{sql: decFunc(safe, name, l.sql, r.sql, decFlag(t)), typ: t}, true, nil +} + +func decRoundFn(udf string, safe bool, args []*gx) (*gx, bool, error) { + t := args[0].typ + if !isDec(t) { + return nil, false, nil + } + + digits := "0" + + if len(args) > 1 { + d := toType(args[1], scalar(KindInt)) + digits = d.sql + } + + if udf == "trunc" { + return &gx{sql: decFunc(safe, "trunc", args[0].sql, digits, decFlag(t)), typ: t}, true, nil + } + + mode := "0" + + if len(args) > 2 { //nolint:mnd // optional rounding mode + m, err := roundMode(args[2]) + if err != nil { + return nil, false, err + } + + mode = m + } + + return &gx{sql: decFunc(safe, "round", args[0].sql, digits, mode, decFlag(t)), typ: t}, true, nil +} + +func decGenerateArraySQL(args []*gx) (*gx, bool, error) { + if !hasDec(args) { + return nil, false, nil + } + + step := &gx{sql: "1", typ: scalar(KindInt)} + if len(args) > 2 { //nolint:mnd // optional step + step = args[2] + } + + t, us := unifyAll([]*gx{args[0], args[1], step}) + if !isDec(t) { + return nil, false, nil + } + + return &gx{ + sql: decCall("generate_array", us[0].sql, us[1].sql, toType(step, t).sql, decFlag(t)), + typ: arrayOf(t), + }, true, nil +} + +// decCallArgs routes a scalar call with decimal arguments: it returns the finished expression, or the arguments +// the generic function should receive (decimals decoded to FLOAT64, or FORMAT's tagged strings). +func decCallArgs(udf string, safe bool, args []*gx) ([]*gx, *gx, error) { + if !hasDec(args) { + if udf == "round" && len(args) > arityTwo { + return nil, nil, invalid("ROUND rounding mode requires a NUMERIC or BIGNUMERIC argument") + } + + return args, nil, nil + } + + if udf == "format" { + return formatArgs(args), nil, nil + } + + g, ok, err := decFunction(udf, safe, args) + if err != nil || ok { + return nil, g, err + } + + return floatArgs(args), nil, nil +} + +// formatArgs tags decimal FORMAT arguments with their kind so the formatter can print them exactly. +func formatArgs(args []*gx) []*gx { + out := make([]*gx, len(args)) + + for i, g := range args { + out[i] = g + if isDec(g.typ) { + out[i] = &gx{sql: decCall("fmt", g.sql, decFlag(g.typ)), typ: scalar(KindString)} + } + } + + return out +} + +func containsDec(t Type) bool { + switch { + case isDec(t): + return true + case t.Kind == KindArray && t.Elem != nil: + return containsDec(*t.Elem) + case t.Kind == KindStruct: + for _, f := range t.Fields { + if containsDec(f.Type) { + return true + } + } + } + + return false +} + +func addDecimalFuncs(t map[string]*fnDef) { + t["PARSE_NUMERIC"] = custom(1, 1, genParseDecimal(KindNumeric)) + t["PARSE_BIGNUMERIC"] = custom(1, 1, genParseDecimal(KindBigNumeric)) + t["SUM"] = custom(1, 1, genSumAvg("sum", sumType)) + t["AVG"] = custom(1, 1, genSumAvg("avg", avgType)) + + for name, udf := range map[string]string{ + "STDDEV": "stddev_samp", "STDDEV_SAMP": "stddev_samp", "STDDEV_POP": "stddev_pop", "VARIANCE": "var_samp", + "VAR_SAMP": "var_samp", "VAR_POP": "var_pop", + } { + t[name] = custom(1, 1, genMoment(udf)) + } +} + +func genParseDecimal(k Kind) func(c *compiler, n *node, sc *scope) (*gx, error) { + return func(c *compiler, n *node, sc *scope) (*gx, error) { + a, err := c.args(n, sc) + if err != nil { + return nil, err + } + + return &gx{sql: decFunc(n.safe, "parse", a[0].sql, decFlag(scalar(k))), typ: scalar(k)}, nil + } +} + +func genSumAvg(name string, ret func([]*gx) Type) func(c *compiler, n *node, sc *scope) (*gx, error) { + plain := aggGen(name, ret, false) + + return func(c *compiler, n *node, sc *scope) (*gx, error) { + a, err := c.args(n, sc) + if err != nil { + return nil, err + } + + if !isDec(a[0].typ) { + return plain(c, n, sc) + } + + suffix := "_n" + if a[0].typ.Kind == KindBigNumeric { + suffix = "_b" + } + + sql, err := c.aggSQL(n, sc, "bq_dec_"+name+suffix, []string{a[0].sql}, "") + if err != nil { + return nil, err + } + + return &gx{sql: sql, typ: ret(a)}, nil + } +} + +// unifySetColumns coerces the columns of one set-operation side to the unified column types. +func unifySetColumns(cq *compiledQuery, target []Column) string { + parts := make([]string, len(target)) + changed := false + + for i, col := range target { + src := &gx{sql: quoteIdent(cq.aliases[i]), typ: cq.cols[i].Type} + g := toType(src, col.Type) + + if g.sql != src.sql { + changed = true + } + + parts[i] = g.sql + " AS " + quoteIdent(cq.aliases[i]) + } + + if !changed { + return cq.sql + } + + return "SELECT " + strings.Join(parts, ", ") + " FROM (" + cq.sql + ")" +} + +func genMoment(udf string) func(c *compiler, n *node, sc *scope) (*gx, error) { + plain := aggGen("bq_"+udf, fixed(KindFloat), false) + + return func(c *compiler, n *node, sc *scope) (*gx, error) { + a, err := c.args(n, sc) + if err != nil { + return nil, err + } + + if !isDec(a[0].typ) { + return plain(c, n, sc) + } + + sql, err := c.aggSQL(n, sc, "bq_dec_"+udf, []string{a[0].sql}, "") + if err != nil { + return nil, err + } + + return &gx{sql: sql, typ: scalar(KindFloat)}, nil + } +} + +// rangeOffsetFrame reports a RANGE frame with a numeric offset such as RANGE BETWEEN 1 PRECEDING AND CURRENT ROW. +func rangeOffsetFrame(frame string) bool { + up := strings.ToUpper(strings.TrimSpace(frame)) + if !strings.HasPrefix(up, "RANGE") { + return false + } + + for _, dir := range []string{" PRECEDING", " FOLLOWING"} { + for rest := up; ; { + i := strings.Index(rest, dir) + if i < 0 { + break + } + + if i > 0 && rest[i-1] >= '0' && rest[i-1] <= '9' { + return true + } + + rest = rest[i+len(dir):] + } + } + + return false +} diff --git a/services/gcpbigquery/bqsql/compile_expr.go b/services/gcpbigquery/bqsql/compile_expr.go index 12959354fe..3387e6a5e9 100644 --- a/services/gcpbigquery/bqsql/compile_expr.go +++ b/services/gcpbigquery/bqsql/compile_expr.go @@ -213,12 +213,12 @@ func (c *compiler) typedLiteral(n *node) (*gx, error) { } if k == KindNumeric || k == KindBigNumeric { - s, err := storedNumeric(n.str) + d, err := ParseDecimal(k, n.str) if err != nil { return nil, invalid("Invalid %s literal: %q", n.name, n.str) } - return &gx{sql: s, typ: scalar(k)}, nil + return &gx{sql: quoteStr(d.SQLText()), typ: scalar(k)}, nil } return &gx{sql: quoteStr(n.str), typ: scalar(KindJSON)}, nil @@ -412,6 +412,10 @@ func (c *compiler) unary(n *node, sc *scope) (*gx, error) { return &gx{sql: "bq_interval_neg(" + a.sql + ")", typ: a.typ}, nil } + if isDec(a.typ) { + return &gx{sql: decCall("neg", a.sql, decFlag(a.typ)), typ: a.typ}, nil + } + return &gx{sql: "(-" + a.sql + ")", typ: a.typ}, nil case "~": return &gx{sql: "(~" + a.sql + ")", typ: a.typ}, nil @@ -457,6 +461,16 @@ func (c *compiler) binary(n *node, sc *scope) (*gx, error) { return g, ierr } + if isDec(l.typ) || isDec(r.typ) { + if g, ok := decOperator(op, l, r); ok { + return g, nil + } + + if op == "+" || op == "-" || op == "*" || op == "/" { + l, r, _ = unifyPair(l, r) + } + } + switch op { case litAnd, "OR": return &gx{sql: "(" + l.sql + " " + op + " " + r.sql + ")", typ: scalar(KindBool)}, nil @@ -529,28 +543,25 @@ func coalesceNumeric(t Type) Type { func (c *compiler) caseExpr(n *node, sc *scope) (*gx, error) { args := n.args - var sb strings.Builder - - sb.WriteString("(CASE") + var op *gx if n.operand { - op, err := c.expr(args[0], sc) + g, err := c.expr(args[0], sc) if err != nil { return nil, err } - sb.WriteString(" " + op.sql) - - args = args[1:] + op, args = g, args[1:] } - var typ Type - nWhen := len(args) if n.hasElse { nWhen-- } + whens := make([]*gx, 0, nWhen/2+1) + results := make([]*gx, 0, nWhen/2+1) + for i := 0; i+1 < nWhen+1 && i < nWhen; i += 2 { w, err := c.expr(args[i], sc) if err != nil { @@ -562,8 +573,7 @@ func (c *compiler) caseExpr(n *node, sc *scope) (*gx, error) { return nil, err } - typ = commonType(typ, t.typ) - sb.WriteString(" WHEN " + w.sql + " THEN " + t.sql) + whens, results = append(whens, w), append(results, t) } if n.hasElse { @@ -572,8 +582,29 @@ func (c *compiler) caseExpr(n *node, sc *scope) (*gx, error) { return nil, err } - typ = commonType(typ, e.typ) - sb.WriteString(" ELSE " + e.sql) + results = append(results, e) + } + + typ, results := unifyAll(results) + + var sb strings.Builder + + sb.WriteString("(CASE") + + if op != nil { + ws := append([]*gx{op}, whens...) + _, ws = unifyAll(ws) + op, whens = ws[0], ws[1:] + + sb.WriteString(" " + op.sql) + } + + for i, w := range whens { + sb.WriteString(" WHEN " + w.sql + " THEN " + results[i].sql) + } + + if n.hasElse { + sb.WriteString(" ELSE " + results[len(results)-1].sql) } sb.WriteString(" END)") @@ -590,6 +621,14 @@ func (c *compiler) cast(n *node, sc *scope) (*gx, error) { to := *n.castTo fn := "bq_cast" + if isDec(to) || isDec(a.typ) { + if len(n.args) > 1 { + return nil, unsupported("CAST ... FORMAT with NUMERIC or BIGNUMERIC") + } + + return decCast(a, to, n.safe) + } + if len(n.args) > 1 { return c.castFormat(n, sc, a, to) } @@ -603,7 +642,10 @@ func (c *compiler) cast(n *node, sc *scope) (*gx, error) { return nil, invalid("Invalid cast from %s to %s", a.typ.Kind.SQLName(), to.Kind.SQLName()) } - return &gx{sql: a.sql, typ: to}, nil + out := *coerceTo(a, to) + out.typ = to + + return &out, nil } return &gx{ @@ -684,6 +726,10 @@ func (c *compiler) predicate(n *node, sc *scope) (*gx, error) { not = "NOT " } + if n.kind == nBetween && hasDec(args) { + _, args = unifyAll(args) + } + switch n.kind { case nLike: return &gx{sql: "(" + not + "bq_like(" + args[0].sql + ", " + args[1].sql + "))", typ: boolT}, nil @@ -733,6 +779,10 @@ func (c *compiler) inPredicate(n *node, args []*gx, sc *scope) (*gx, error) { switch { case n.name == litUnnest: + if el := args[1].typ.Elem; el != nil && isDec(*el) { + args[0] = toType(args[0], *el) + } + return &gx{ sql: "(" + args[0].sql + " " + op + " (SELECT \"value\" FROM json_each(" + args[1].sql + ")))", typ: boolT, @@ -747,9 +797,17 @@ func (c *compiler) inPredicate(n *node, args []*gx, sc *scope) (*gx, error) { return nil, invalid("Subquery of type IN must have only one output column") } + if isDec(cq.cols[0].Type) { + args[0] = toType(args[0], cq.cols[0].Type) + } + return &gx{sql: "(" + args[0].sql + " " + op + " (" + cq.sql + "))", typ: boolT}, nil } + if hasDec(args) { + _, args = unifyAll(args) + } + list := make([]string, len(args)-1) for i, a := range args[1:] { list[i] = coerceLiteral(a, args[0].typ).sql @@ -793,9 +851,7 @@ func (c *compiler) subquery(n *node, sc *scope) (*gx, error) { } func (c *compiler) arrayLit(n *node, sc *scope) (*gx, error) { - var elem Type - - parts := make([]string, len(n.args)) + items := make([]*gx, len(n.args)) for i, a := range n.args { g, err := c.expr(a, sc) @@ -803,12 +859,21 @@ func (c *compiler) arrayLit(n *node, sc *scope) (*gx, error) { return nil, err } - elem = commonType(elem, g.typ) - parts[i] = jsonVal(g) + items[i] = g } + elem, items := unifyAll(items) if n.elemType != nil { elem = *n.elemType + + for i, g := range items { + items[i] = toType(g, elem) + } + } + + parts := make([]string, len(items)) + for i, g := range items { + parts[i] = jsonVal(g) } if elem.Kind == KindUnknown { @@ -844,6 +909,7 @@ func (c *compiler) structLit(n *node, sc *scope) (*gx, error) { typ := g.typ if n.castTo != nil && i < len(n.castTo.Fields) { typ = n.castTo.Fields[i].Type + g = toType(g, typ) } cols[i] = Column{Name: name, Type: typ} @@ -895,6 +961,15 @@ func coerceFor(g *gx, target Type) *gx { func coerceTo(g *gx, target Type) *gx { switch { + case isDec(target) || target.Kind == KindFloat && isDec(g.typ): + return constrainDec(toType(g, target), target) + case arrayNeedsCoerce(g.typ, target): + elem := coerceTo(&gx{sql: `"_ce"."value"`, typ: *g.typ.Elem}, *target.Elem) + + return &gx{ + sql: "(SELECT json_group_array(" + jsonVal(elem) + ") FROM json_each(" + g.sql + ") AS \"_ce\")", + typ: target, + } case g.typ.Kind == KindStruct && target.Kind == KindStruct && len(g.typ.Fields) == len(target.Fields): parts := make([]string, 0, len(target.Fields)*2) //nolint:mnd // name and value per member @@ -905,15 +980,16 @@ func coerceTo(g *gx, target Type) *gx { } return &gx{sql: "json_object(" + strings.Join(parts, ", ") + ")", typ: target} - case g.typ.Kind == KindArray && target.Kind == KindArray && g.typ.Elem != nil && target.Elem != nil && - target.Elem.Kind == KindStruct: - elem := coerceTo(&gx{sql: `"_ce"."value"`, typ: *g.typ.Elem}, *target.Elem) - - return &gx{ - sql: "(SELECT json_group_array(" + jsonVal(elem) + ") FROM json_each(" + g.sql + ") AS \"_ce\")", - typ: target, - } } return g } + +// arrayNeedsCoerce reports an array whose elements must be rewritten to reach the target element type. +func arrayNeedsCoerce(from, to Type) bool { + if from.Kind != KindArray || to.Kind != KindArray || from.Elem == nil || to.Elem == nil { + return false + } + + return to.Elem.Kind == KindStruct || isDec(*to.Elem) && (from.Elem.Kind != to.Elem.Kind || to.Elem.Prec > 0) +} diff --git a/services/gcpbigquery/bqsql/compile_func.go b/services/gcpbigquery/bqsql/compile_func.go index c21c9899ec..f4e40cf09c 100644 --- a/services/gcpbigquery/bqsql/compile_func.go +++ b/services/gcpbigquery/bqsql/compile_func.go @@ -82,6 +82,7 @@ func functionTable() map[string]*fnDef { addArrayFuncs(t) addAggFuncs(t) addMiscFuncs(t) + addDecimalFuncs(t) return t } @@ -99,7 +100,7 @@ func addMathFuncs(t map[string]*fnDef) { t["SIGN"] = def("sign", 1, 1, firstArgType) t["CEIL"], t["CEILING"] = def("ceil", 1, 1, floatish), def("ceil", 1, 1, floatish) t["FLOOR"] = def("floor", 1, 1, floatish) - t["ROUND"] = def("round", 1, arityTwo, floatish) + t["ROUND"] = def("round", 1, arityThree, floatish) t["TRUNC"] = def("trunc", 1, arityTwo, floatish) t["POW"], t["POWER"] = def( "pow", @@ -255,6 +256,12 @@ func addMiscFuncs(t map[string]*fnDef) { return nil, err } + if hasDec(a) { + _, u := unifyAll(a) + + return &gx{sql: "NULLIF(" + u[0].sql + ", " + u[1].sql + ")", typ: u[0].typ}, nil + } + return &gx{sql: "NULLIF(" + a[0].sql + ", " + coerceLiteral(a[1], a[0].typ).sql + ")", typ: a[0].typ}, nil }) addNetFuncs(t) @@ -341,6 +348,11 @@ func (c *compiler) call(n *node, sc *scope) (*gx, error) { args[i] = g } + args, done, err := decCallArgs(d.udf, n.safe, args) + if done != nil || err != nil { + return done, err + } + name := "bq_" + d.udf if n.safe { name = "bq_safe_" + d.udf @@ -382,9 +394,11 @@ func genIf(c *compiler, n *node, sc *scope) (*gx, error) { return nil, err } + typ, res := unifyAll(a[1:]) + return &gx{ - sql: "(CASE WHEN " + a[0].sql + " THEN " + a[1].sql + " ELSE " + a[2].sql + " END)", - typ: commonType(a[1].typ, a[2].typ), + sql: "(CASE WHEN " + a[0].sql + " THEN " + res[0].sql + " ELSE " + res[1].sql + " END)", + typ: typ, }, nil } @@ -394,6 +408,8 @@ func genCoalesce(c *compiler, n *node, sc *scope) (*gx, error) { return nil, err } + typ, a := unifyAll(a) + parts := make([]string, len(a)) for i, g := range a { parts[i] = g.sql @@ -403,7 +419,7 @@ func genCoalesce(c *compiler, n *node, sc *scope) (*gx, error) { return a[0], nil } - return &gx{sql: "COALESCE(" + strings.Join(parts, ", ") + ")", typ: commonOf(a)}, nil + return &gx{sql: "COALESCE(" + strings.Join(parts, ", ") + ")", typ: typ}, nil } func genToJSONString(c *compiler, n *node, sc *scope) (*gx, error) { @@ -416,13 +432,19 @@ func genToJSONString(c *compiler, n *node, sc *scope) (*gx, error) { switch x.typ.Kind { case KindStruct, KindArray: + if containsDec(x.typ) { + return &gx{sql: "bq_dec_json_nested(json(" + x.sql + "))", typ: scalar(KindString)}, nil + } + return &gx{sql: "CAST(json(" + x.sql + ") AS TEXT)", typ: scalar(KindString)}, nil case KindBool: return &gx{ sql: "(CASE WHEN " + x.sql + " IS NULL THEN 'null' WHEN " + x.sql + " THEN 'true' ELSE 'false' END)", typ: scalar(KindString), }, nil - case KindInt, KindFloat, KindNumeric, KindBigNumeric: + case KindNumeric, KindBigNumeric: + return &gx{sql: decCall("json", x.sql), typ: scalar(KindString)}, nil + case KindInt, KindFloat: return &gx{sql: "COALESCE(CAST(" + x.sql + " AS TEXT), 'null')", typ: scalar(KindString)}, nil case KindJSON: return &gx{sql: x.sql, typ: scalar(KindString)}, nil @@ -508,8 +530,6 @@ func genDateArray(k Kind) func(c *compiler, n *node, sc *scope) (*gx, error) { func addAggFuncs(t map[string]*fnDef) { t["COUNT"] = custom(1, 1, aggGen("count", fixed(KindInt), false)) t["COUNTIF"] = custom(1, 1, genCountIf) - t["SUM"] = custom(1, 1, aggGen("sum", sumType, false)) - t["AVG"] = custom(1, 1, aggGen("avg", avgType, false)) t["MIN"] = custom(1, 1, aggGen("min", firstArgType, false)) t["MAX"] = custom(1, 1, aggGen("max", firstArgType, false)) t["ANY_VALUE"] = custom(1, 1, aggGen("min", firstArgType, false)) @@ -521,13 +541,6 @@ func addAggFuncs(t map[string]*fnDef) { t["APPROX_QUANTILES"] = custom(arityTwo, arityTwo, genApproxQuantiles) t["APPROX_TOP_COUNT"] = custom(arityTwo, arityTwo, genApproxTopCount) - for name, udf := range map[string]string{ - "STDDEV": "stddev_samp", "STDDEV_SAMP": "stddev_samp", "STDDEV_POP": "stddev_pop", "VARIANCE": "var_samp", - "VAR_SAMP": "var_samp", "VAR_POP": "var_pop", - } { - t[name] = custom(1, 1, aggGen("bq_"+udf, fixed(KindFloat), false)) - } - for name, ret := range map[string]func([]*gx) Type{ "ROW_NUMBER": fixed(KindInt), "RANK": fixed(KindInt), "DENSE_RANK": fixed(KindInt), "NTILE": fixed(KindInt), "PERCENT_RANK": fixed(KindFloat), "CUME_DIST": fixed(KindFloat), "LAG": firstArgType, "LEAD": firstArgType, @@ -628,6 +641,10 @@ func (c *compiler) overSQL(w *windowSpec, sc *scope) (string, error) { return "", err } + if isDec(g.typ) && rangeOffsetFrame(w.frame) { + return "", unsupported("RANGE window frame offsets over a NUMERIC or BIGNUMERIC ORDER BY key") + } + list[i] = g.sql if o.desc { list[i] += litDesc @@ -670,6 +687,11 @@ func aggGen(fname string, ret func([]*gx) Type, distinct bool) func(c *compiler, args = append(args, g.sql) } + if (fname == "lag" || fname == "lead") && len(gs) == arityThree && isDec(gs[0].typ) { + gs[2] = toType(gs[2], gs[0].typ) + args[2] = gs[2].sql + } + sql, err := c.aggSQL(n, sc, fname, args, "") if err != nil { return nil, err diff --git a/services/gcpbigquery/bqsql/decimal.go b/services/gcpbigquery/bqsql/decimal.go new file mode 100644 index 0000000000..8976a3eb88 --- /dev/null +++ b/services/gcpbigquery/bqsql/decimal.go @@ -0,0 +1,681 @@ +package bqsql + +import ( + "encoding/hex" + "errors" + "fmt" + "math" + "math/big" + "strings" +) + +// ErrDecimal is wrapped by every NUMERIC/BIGNUMERIC arithmetic and conversion failure. +var ErrDecimal = errors.New("decimal error") + +const ( + numericScale = 9 + bigNumericScale = 38 + numericDigits = 38 + maxDecimalText = 512 + maxDecimalExp = 1024 + maxDecimalDigits = 160 + bigNumericBits = 255 + paramNumericInt = 29 + paramBigInt = 38 +) + +// RoundMode selects how ROUND breaks ties. +type RoundMode uint8 + +// Rounding modes of ROUND(x, n, mode). +const ( + RoundHalfAwayFromZero RoundMode = iota + RoundHalfEven +) + +// Decimal is an immutable exact NUMERIC (scale 9) or BIGNUMERIC (scale 38) value held as a scaled integer. +// The zero value is NUMERIC 0. +type Decimal struct { + n *big.Int + kind Kind +} + +func decScale(k Kind) int { + if k == KindBigNumeric { + return bigNumericScale + } + + return numericScale +} + +func pow10(n int) *big.Int { + return new(big.Int).Exp(big.NewInt(decimalBase), big.NewInt(int64(n)), nil) +} + +func decKind(k Kind) Kind { + if k == KindBigNumeric { + return KindBigNumeric + } + + return KindNumeric +} + +func (d Decimal) unscaled() *big.Int { + if d.n == nil { + return new(big.Int) + } + + return d.n +} + +func decOverflow(k Kind, expr string, args ...any) error { + name := "numeric" + if k == KindBigNumeric { + name = litBignumeric + } + + return fmt.Errorf("%w: %s overflow: %s", ErrDecimal, name, fmt.Sprintf(expr, args...)) +} + +func inRange(k Kind, n *big.Int) bool { + if k == KindBigNumeric { + lim := new(big.Int).Lsh(big.NewInt(1), bigNumericBits) + if n.Sign() < 0 { + return n.Cmp(new(big.Int).Neg(lim)) >= 0 + } + + return n.Cmp(lim) < 0 + } + + return new(big.Int).Abs(n).Cmp(pow10(numericDigits)) < 0 +} + +func newDecimal(k Kind, n *big.Int, expr string, args ...any) (Decimal, error) { + k = decKind(k) + if !inRange(k, n) { + return Decimal{}, decOverflow(k, expr, args...) + } + + return Decimal{n: n, kind: k}, nil +} + +// divRound returns num/den rounded half away from zero; den must be non-zero. +func divRound(num, den *big.Int) *big.Int { + q, r := new(big.Int).QuoRem(new(big.Int).Abs(num), new(big.Int).Abs(den), new(big.Int)) + if r.Lsh(r, 1).Cmp(new(big.Int).Abs(den)) >= 0 { + q.Add(q, big.NewInt(1)) + } + + if num.Sign()*den.Sign() < 0 { + q.Neg(q) + } + + return q +} + +// ParseDecimal parses a decimal literal or string (sign, fraction, exponent) and rounds half away from zero. +func ParseDecimal(k Kind, s string) (Decimal, error) { + k = decKind(k) + bad := fmt.Errorf("%w: invalid %s value %q", ErrDecimal, k.RESTName(), clip(s)) + + s = strings.TrimSpace(s) + if s == "" || len(s) > maxDecimalText { + return Decimal{}, bad + } + + neg := false + + switch s[0] { + case '-': + neg = true + s = s[1:] + case '+': + s = s[1:] + } + + digits, exp10, ok := splitDecimal(s) + if !ok { + return Decimal{}, bad + } + + return scaleDigits(k, digits, exp10, neg) +} + +func clip(s string) string { + const limit = 64 + if len(s) > limit { + return s[:limit] + "..." + } + + return s +} + +// splitDecimal returns the significant digits (no leading zeros) and the power of ten that scales them. +func splitDecimal(s string) (string, int, bool) { + mant, expText, hasExp := strings.Cut(strings.ToLower(s), "e") + intPart, frac, _ := strings.Cut(mant, ".") + + if intPart == "" && frac == "" || !allDigits(intPart) || !allDigits(frac) { + return "", 0, false + } + + exp := 0 + + if hasExp { + e, ok := parseExp(expText) + if !ok { + return "", 0, false + } + + exp = e + } + + return strings.TrimLeft(intPart+frac, "0"), exp - len(frac), true +} + +func allDigits(s string) bool { + for i := range len(s) { + if s[i] < '0' || s[i] > '9' { + return false + } + } + + return true +} + +func parseExp(s string) (int, bool) { + sign := 1 + + if s != "" && (s[0] == '-' || s[0] == '+') { + if s[0] == '-' { + sign = -1 + } + + s = s[1:] + } + + if s == "" || len(s) > 5 || !allDigits(s) { + return 0, false + } + + e := 0 + for i := range len(s) { + e = e*decimalBase + int(s[i]-'0') + } + + if e > maxDecimalExp { + return 0, false + } + + return sign * e, true +} + +func scaleDigits(k Kind, digits string, exp10 int, neg bool) (Decimal, error) { + if digits == "" { + return Decimal{n: new(big.Int), kind: k}, nil + } + + n, ok := new(big.Int).SetString(digits, decimalBase) + if !ok { + return Decimal{}, fmt.Errorf("%w: invalid %s value %q", ErrDecimal, k.RESTName(), clip(digits)) + } + + shift := exp10 + decScale(k) + + switch { + case shift >= 0: + if len(digits)+shift > maxDecimalDigits { + return Decimal{}, decOverflow(k, "%s", clip(digits)) + } + + n.Mul(n, pow10(shift)) + case -shift > len(digits)+1: + n.SetInt64(0) + default: + n = divRound(n, pow10(-shift)) + } + + if neg { + n.Neg(n) + } + + return newDecimal(k, n, "%s", clip(digits)) +} + +// DecimalFromInt converts an INT64 exactly. +func DecimalFromInt(k Kind, v int64) (Decimal, error) { + n := new(big.Int).Mul(big.NewInt(v), pow10(decScale(k))) + + return newDecimal(k, n, "%d", v) +} + +// DecimalFromFloat converts a FLOAT64 exactly then rounds half away from zero; NaN and infinities are errors. +func DecimalFromFloat(k Kind, f float64) (Decimal, error) { + k = decKind(k) + if math.IsNaN(f) || math.IsInf(f, 0) { + return Decimal{}, fmt.Errorf("%w: cannot convert %v to %s", ErrDecimal, f, k.RESTName()) + } + + r := new(big.Rat).SetFloat64(f) + n := divRound(new(big.Int).Mul(r.Num(), pow10(decScale(k))), r.Denom()) + + return newDecimal(k, n, "%v", f) +} + +// Kind reports NUMERIC or BIGNUMERIC. +func (d Decimal) Kind() Kind { return decKind(d.kind) } + +// Sign returns -1, 0 or +1. +func (d Decimal) Sign() int { return d.unscaled().Sign() } + +// String renders the value as BigQuery prints it: no exponent, no trailing zeros, never "-0". +func (d Decimal) String() string { + n := d.unscaled() + if n.Sign() == 0 { + return "0" + } + + sc := decScale(d.kind) + s := new(big.Int).Abs(n).String() + + if len(s) <= sc { + s = strings.Repeat("0", sc-len(s)+1) + s + } + + out := trimDecimal(s[:len(s)-sc] + "." + s[len(s)-sc:]) + if n.Sign() < 0 { + return "-" + out + } + + return out +} + +// Float64 returns the nearest FLOAT64. +func (d Decimal) Float64() float64 { + f, _ := new(big.Rat).SetFrac(d.unscaled(), pow10(decScale(d.kind))).Float64() + + return f +} + +// Int64 rounds half away from zero to an INT64 and fails when out of range. +func (d Decimal) Int64() (int64, error) { + n := divRound(d.unscaled(), pow10(decScale(d.kind))) + if !n.IsInt64() { + return 0, fmt.Errorf("%w: INT64 out of range: %s", ErrDecimal, d.String()) + } + + return n.Int64(), nil +} + +// As converts to the target kind, rounding half away from zero when narrowing. +func (d Decimal) As(k Kind) (Decimal, error) { + k = decKind(k) + from, to := decScale(d.kind), decScale(k) + + switch { + case from == to: + return newDecimal(k, d.unscaled(), "%s", d.String()) + case to > from: + return newDecimal(k, new(big.Int).Mul(d.unscaled(), pow10(to-from)), "%s", d.String()) + } + + return newDecimal(k, divRound(d.unscaled(), pow10(from-to)), "%s", d.String()) +} + +func widest(a, b Decimal) (Kind, *big.Int, *big.Int, error) { + k := KindNumeric + if a.kind == KindBigNumeric || b.kind == KindBigNumeric { + k = KindBigNumeric + } + + x, err := a.As(k) + if err != nil { + return k, nil, nil, err + } + + y, err := b.As(k) + if err != nil { + return k, nil, nil, err + } + + return k, x.unscaled(), y.unscaled(), nil +} + +// Cmp compares two values of any decimal kind. +func (d Decimal) Cmp(o Decimal) int { + _, x, y, err := widest(d, o) + if err != nil { + return d.unscaled().Sign() - o.unscaled().Sign() + } + + return x.Cmp(y) +} + +// Add returns d + o. +func (d Decimal) Add(o Decimal) (Decimal, error) { + k, x, y, err := widest(d, o) + if err != nil { + return Decimal{}, err + } + + return newDecimal(k, new(big.Int).Add(x, y), "%s + %s", d.String(), o.String()) +} + +// Sub returns d - o. +func (d Decimal) Sub(o Decimal) (Decimal, error) { + k, x, y, err := widest(d, o) + if err != nil { + return Decimal{}, err + } + + return newDecimal(k, new(big.Int).Sub(x, y), "%s - %s", d.String(), o.String()) +} + +// Mul returns d * o rounded to the result scale. +func (d Decimal) Mul(o Decimal) (Decimal, error) { + k, x, y, err := widest(d, o) + if err != nil { + return Decimal{}, err + } + + p := divRound(new(big.Int).Mul(x, y), pow10(decScale(k))) + + return newDecimal(k, p, "%s * %s", d.String(), o.String()) +} + +// Quo returns d / o rounded to the result scale; a zero divisor is an error. +func (d Decimal) Quo(o Decimal) (Decimal, error) { + k, x, y, err := widest(d, o) + if err != nil { + return Decimal{}, err + } + + if y.Sign() == 0 { + return Decimal{}, fmt.Errorf("%w: division by zero: %s / %s", ErrDecimal, d.String(), o.String()) + } + + q := divRound(new(big.Int).Mul(x, pow10(decScale(k))), y) + + return newDecimal(k, q, "%s / %s", d.String(), o.String()) +} + +// Mod returns the remainder of d / o with the sign of d; a zero divisor is an error. +func (d Decimal) Mod(o Decimal) (Decimal, error) { + k, x, y, err := widest(d, o) + if err != nil { + return Decimal{}, err + } + + if y.Sign() == 0 { + return Decimal{}, fmt.Errorf("%w: division by zero: MOD(%s, %s)", ErrDecimal, d.String(), o.String()) + } + + return newDecimal(k, new(big.Int).Rem(x, y), "MOD(%s, %s)", d.String(), o.String()) +} + +// Neg returns -d. +func (d Decimal) Neg() (Decimal, error) { + return newDecimal(d.kind, new(big.Int).Neg(d.unscaled()), "-%s", d.String()) +} + +// Abs returns |d|. +func (d Decimal) Abs() (Decimal, error) { + return newDecimal(d.kind, new(big.Int).Abs(d.unscaled()), "ABS(%s)", d.String()) +} + +// Round rounds to the given number of fractional digits (negative rounds integer digits). +func (d Decimal) Round(digits int, mode RoundMode) (Decimal, error) { + drop := decScale(d.kind) - digits + if drop <= 0 { + return d, nil + } + + if drop > maxDecimalDigits { + return Decimal{n: new(big.Int), kind: decKind(d.kind)}, nil + } + + unit := pow10(drop) + n := d.unscaled() + + var q *big.Int + + if mode == RoundHalfEven { + q = divRoundEven(n, unit) + } else { + q = divRound(n, unit) + } + + return newDecimal(d.kind, q.Mul(q, unit), "ROUND(%s, %d)", d.String(), digits) +} + +func divRoundEven(num, den *big.Int) *big.Int { + q, r := new(big.Int).QuoRem(new(big.Int).Abs(num), den, new(big.Int)) + switch r.Lsh(r, 1).Cmp(den) { + case 1: + q.Add(q, big.NewInt(1)) + case 0: + if q.Bit(0) == 1 { + q.Add(q, big.NewInt(1)) + } + } + + if num.Sign() < 0 { + q.Neg(q) + } + + return q +} + +// Trunc drops fractional digits beyond the given count toward zero. +func (d Decimal) Trunc(digits int) Decimal { + drop := decScale(d.kind) - digits + if drop <= 0 { + return d + } + + if drop > maxDecimalDigits { + return Decimal{n: new(big.Int), kind: decKind(d.kind)} + } + + unit := pow10(drop) + q := new(big.Int).Quo(d.unscaled(), unit) + + return Decimal{n: q.Mul(q, unit), kind: decKind(d.kind)} +} + +// Floor returns the largest integer value not greater than d. +func (d Decimal) Floor() (Decimal, error) { + t := d.Trunc(0) + if d.Sign() < 0 && t.Cmp(d) != 0 { + return t.Sub(unitDecimal(t.kind)) + } + + return t, nil +} + +// Ceil returns the smallest integer value not less than d. +func (d Decimal) Ceil() (Decimal, error) { + t := d.Trunc(0) + if d.Sign() > 0 && t.Cmp(d) != 0 { + return t.Add(unitDecimal(t.kind)) + } + + return t, nil +} + +func unitDecimal(k Kind) Decimal { + return Decimal{n: pow10(decScale(k)), kind: decKind(k)} +} + +// Constrain applies NUMERIC(p, s) or BIGNUMERIC(p, s): round to s digits, fail when more than p digits remain. +func (d Decimal) Constrain(p, s int) (Decimal, error) { + k := decKind(d.kind) + if err := checkDecimalParams(k, p, s); err != nil { + return Decimal{}, err + } + + r, err := d.Round(s, RoundHalfAwayFromZero) + if err != nil { + return Decimal{}, err + } + + lim := pow10(p - s + decScale(k)) + if new(big.Int).Abs(r.unscaled()).Cmp(lim) >= 0 { + return Decimal{}, fmt.Errorf("%w: %s out of range for %s(%d, %d)", ErrDecimal, d.String(), k.RESTName(), p, s) + } + + return r, nil +} + +const ( + sqlTextPrefix = '#' + sqlTextBytes = 32 + sqlTextLen = 1 + 2*sqlTextBytes + narrowShift = bigNumericScale - numericScale +) + +// 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 (d Decimal) SQLText() string { + v := new(big.Int).Set(d.unscaled()) + if decKind(d.kind) == KindNumeric { + v.Mul(v, pow10(narrowShift)) + } + + v.Add(v, new(big.Int).Lsh(big.NewInt(1), bigNumericBits)) + + buf := make([]byte, sqlTextLen) + buf[0] = sqlTextPrefix + hex.Encode(buf[1:], v.FillBytes(make([]byte, sqlTextBytes))) + + return string(buf) +} + +// IsSQLText reports whether s is an encoding produced by SQLText. +func IsSQLText(s string) bool { + if len(s) != sqlTextLen || s[0] != sqlTextPrefix { + return false + } + + for i := 1; i < len(s); i++ { + c := s[i] + if c < '0' || c > '9' && c < 'a' || c > 'f' { + return false + } + } + + return true +} + +// DecodeSQLText reverses SQLText into a value of kind k, rounding when a wider value is narrowed. +func DecodeSQLText(s string, k Kind) (Decimal, error) { + if !IsSQLText(s) { + return Decimal{}, fmt.Errorf("%w: malformed %s value", ErrDecimal, decKind(k).RESTName()) + } + + raw, err := hex.DecodeString(s[1:]) + if err != nil { + return Decimal{}, fmt.Errorf("%w: malformed %s value", ErrDecimal, decKind(k).RESTName()) + } + + v := new(big.Int).SetBytes(raw) + v.Sub(v, new(big.Int).Lsh(big.NewInt(1), bigNumericBits)) + + if decKind(k) == KindNumeric { + v = divRound(v, pow10(narrowShift)) + } + + return newDecimal(k, v, "%s", s) +} + +// 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 ParseNumericText(k Kind, s string) (Decimal, error) { + bad := fmt.Errorf("%w: invalid %s value %q", ErrDecimal, decKind(k).RESTName(), clip(s)) + if len(s) > maxDecimalText { + return Decimal{}, bad + } + + sign, body := splitSign(s) + if body == "" || body[0] == '+' || body[0] == '-' || strings.ContainsAny(body, numericBlanks) { + return Decimal{}, bad + } + + whole, rest := body, "" + if i := strings.IndexAny(body, ".eE"); i >= 0 { + whole, rest = body[:i], body[i:] + } + + if strings.HasPrefix(whole, ",") || strings.Contains(rest, ",") { + return Decimal{}, bad + } + + d, err := ParseDecimal(k, strings.ReplaceAll(whole, ",", "")+rest) + if err != nil { + return Decimal{}, bad + } + + if sign == '-' { + return d.Neg() + } + + return d, nil +} + +const numericBlanks = " \t\r\n" + +// splitSign removes one leading or trailing sign and the whitespace around it. +func splitSign(s string) (byte, string) { + s = strings.Trim(s, numericBlanks) + if s == "" { + return 0, s + } + + if s[0] == '+' || s[0] == '-' { + return s[0], strings.Trim(s[1:], numericBlanks) + } + + last := s[len(s)-1] + if len(s) > 1 && (last == '+' || last == '-') && s[len(s)-2] != 'e' && s[len(s)-2] != 'E' { + return last, strings.Trim(s[:len(s)-1], numericBlanks) + } + + return 0, s +} + +func decodeScaled(s string) (*big.Int, error) { + if !IsSQLText(s) { + return nil, fmt.Errorf("%w: malformed decimal value", ErrDecimal) + } + + raw, err := hex.DecodeString(s[1:]) + if err != nil { + return nil, fmt.Errorf("%w: malformed decimal value", ErrDecimal) + } + + v := new(big.Int).SetBytes(raw) + + return v.Sub(v, new(big.Int).Lsh(big.NewInt(1), bigNumericBits)), nil +} + +func decimalFromScaled(k Kind, v *big.Int, expr string, args ...any) (Decimal, error) { + if decKind(k) == KindNumeric { + v = divRound(v, pow10(narrowShift)) + } + + return newDecimal(k, v, expr, args...) +} + +func checkDecimalParams(k Kind, p, s int) error { + maxScale, maxInt := numericScale, paramNumericInt + + if decKind(k) == KindBigNumeric { + maxScale, maxInt = bigNumericScale, paramBigInt + } + + if s < 0 || s > maxScale || p < max(1, s) || p > s+maxInt { + return fmt.Errorf("%w: invalid %s(%d, %d)", ErrDecimal, decKind(k).RESTName(), p, s) + } + + return nil +} diff --git a/services/gcpbigquery/bqsql/decimal_encoding_test.go b/services/gcpbigquery/bqsql/decimal_encoding_test.go new file mode 100644 index 0000000000..09670f8ce7 --- /dev/null +++ b/services/gcpbigquery/bqsql/decimal_encoding_test.go @@ -0,0 +1,354 @@ +package bqsql_test + +import ( + "math/rand/v2" + "sort" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/gcpbigquery/bqsql" +) + +func randomDecimal(r *rand.Rand, k bqsql.Kind) string { + digits := 1 + r.IntN(36) + if k == bqsql.KindBigNumeric { + digits = 1 + r.IntN(70) + } + + var sb strings.Builder + + if r.IntN(2) == 0 { + sb.WriteByte('-') + } + + for range digits { + sb.WriteByte(byte('0' + r.IntN(10))) + } + + frac := r.IntN(9) + s := sb.String() + + if k == bqsql.KindBigNumeric { + frac = r.IntN(38) + } + + if frac > 0 && len(s) > frac+1 { + s = s[:len(s)-frac] + "." + s[len(s)-frac:] + } + + return s +} + +func TestDecimalSQLTextOrdering(t *testing.T) { + t.Parallel() + + r := rand.New(rand.NewPCG(1, 2)) + + var vals []bqsql.Decimal + + for _, s := range []string{"0", "-0.000000001", "0.000000001", numMax, "-" + numMax, "1", "-1"} { + vals = append(vals, dec(t, bqsql.KindNumeric, s)) + } + + for _, s := range []string{"0", bigMax, bigMin, "0.00000000000000000000000000000000000001"} { + vals = append(vals, dec(t, bqsql.KindBigNumeric, s)) + } + + for range 400 { + k := bqsql.KindNumeric + if r.IntN(2) == 0 { + k = bqsql.KindBigNumeric + } + + d, err := bqsql.ParseDecimal(k, randomDecimal(r, k)) + if err == nil { + vals = append(vals, d) + } + } + + for i := range vals { + for j := range vals { + a, b := vals[i], vals[j] + assert.Equal(t, a.Cmp(b), strings.Compare(a.SQLText(), b.SQLText()), "%s vs %s", a.String(), b.String()) + } + } + + sorted := append([]bqsql.Decimal{}, vals...) + sort.Slice(sorted, func(i, j int) bool { return sorted[i].SQLText() < sorted[j].SQLText() }) + + for i := 1; i < len(sorted); i++ { + assert.LessOrEqual(t, sorted[i-1].Cmp(sorted[i]), 0) + } +} + +func TestDecimalSQLTextRoundTrip(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + in string + kind bqsql.Kind + }{ + {"zero", "0", bqsql.KindNumeric}, + {"neg", "-12.5", bqsql.KindNumeric}, + {"nummax", numMax, bqsql.KindNumeric}, + {"numnegmax", "-" + numMax, bqsql.KindNumeric}, + {"bigmax", bigMax, bqsql.KindBigNumeric}, + {"bigmin", bigMin, bqsql.KindBigNumeric}, + {"bigtiny", "0.00000000000000000000000000000000000001", bqsql.KindBigNumeric}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + d := dec(t, tt.kind, tt.in) + txt := d.SQLText() + assert.True(t, bqsql.IsSQLText(txt)) + + back, err := bqsql.DecodeSQLText(txt, tt.kind) + require.NoError(t, err) + assert.Equal(t, d.String(), back.String()) + }) + } + + same := dec(t, bqsql.KindNumeric, "2.5") + wide := dec(t, bqsql.KindBigNumeric, "2.5") + assert.Equal(t, same.SQLText(), wide.SQLText()) +} + +func TestDecimalSQLTextRejects(t *testing.T) { + t.Parallel() + + for _, s := range []string{"", "1.5", "#12", "#" + strings.Repeat("g", 64), strings.Repeat("a", 65)} { + assert.False(t, bqsql.IsSQLText(s), s) + + _, err := bqsql.DecodeSQLText(s, bqsql.KindNumeric) + require.ErrorIs(t, err, bqsql.ErrDecimal) + } + + _, err := bqsql.DecodeSQLText(dec(t, bqsql.KindBigNumeric, bigMax).SQLText(), bqsql.KindNumeric) + require.ErrorIs(t, err, bqsql.ErrDecimal) +} + +func TestParseNumericText(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + in string + want string + fail bool + }{ + {"plain", "123.45", "123.45", false}, + {"commas", "1,234,567.891", "1234567.891", false}, + {"space", " 12 ", "12", false}, + {"signspace", "- 12.3", "-12.3", false}, + {"trailsign", "12.3-", "-12.3", false}, + {"plussign", "+5", "5", false}, + {"exp", "1.5e2", "150", false}, + {"expneg", "15E-1", "1.5", false}, + {"round", "0.0000000005", "0.000000001", false}, + {"onlycommas", ",,,.1234", "", true}, + {"midspace", "1 23.4 5", "", true}, + {"nodigits", " e1 ", "", true}, + {"twosigns", " - 12.3 - ", "", true}, + {"currency", "$12.34", "", true}, + {"commaafter", "1.2,3", "", true}, + {"empty", "", "", true}, + {"over", "1e30", "", true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + d, err := bqsql.ParseNumericText(bqsql.KindNumeric, tt.in) + if tt.fail { + require.ErrorIs(t, err, bqsql.ErrDecimal) + + return + } + + require.NoError(t, err) + assert.Equal(t, tt.want, d.String()) + }) + } +} + +func TestDecimalMath(t *testing.T) { + t.Parallel() + + n, b := bqsql.KindNumeric, bqsql.KindBigNumeric + + tests := []struct { + name string + fn string + x, y string + want string + kind bqsql.Kind + }{ + {"sqrt4", "sqrt", "4", "", "2", n}, + {"sqrt2", "sqrt", "2", "", "1.414213562", n}, + {"sqrt0", "sqrt", "0", "", "0", n}, + {"sqrtbig", "sqrt", "2", "", "1.41421356237309504880168872420969807857", b}, + {"exp1", "exp", "1", "", "2.718281828", n}, + {"exp0", "exp", "0", "", "1", n}, + {"expneg", "exp", "-1", "", "0.367879441", n}, + {"expunder", "exp", "-500", "", "0", n}, + {"ln10", "ln", "10", "", "2.302585093", n}, + {"ln1", "ln", "1", "", "0", n}, + {"lnbig", "ln", "2", "", "0.69314718055994530941723212145817656808", b}, + {"log10", "log10", "1000", "", "3", n}, + {"log10frac", "log10", "0.001", "", "-3", n}, + {"log2", "log", "8", "2", "3", n}, + {"log100", "log", "100", "10", "2", n}, + {"pow", "pow", "2", "10", "1024", n}, + {"powneg", "pow", "2", "-2", "0.25", n}, + {"powfrac", "pow", "2", "0.5", "1.414213562", n}, + {"powzero", "pow", "0", "0", "1", n}, + {"powzerobase", "pow", "0", "5", "0", n}, + {"pownegbase", "pow", "-2", "3", "-8", n}, + {"powunder", "pow", "10", "-30", "0", n}, + {"powbig", "pow", "2", "0.5", "1.41421356237309504880168872420969807857", b}, + {"intdiv", "intdiv", "7.5", "2", "3", n}, + {"intdivneg", "intdiv", "-7.5", "2", "-3", n}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + x := dec(t, tt.kind, tt.x) + + var ( + got bqsql.Decimal + err error + ) + + switch tt.fn { + case "sqrt": + got, err = x.Sqrt() + case "exp": + got, err = x.Exp() + case "ln": + got, err = x.Ln() + case "log10": + got, err = x.Log10() + case "log": + got, err = x.Log(dec(t, tt.kind, tt.y)) + case "pow": + got, err = x.Pow(dec(t, tt.kind, tt.y)) + default: + got, err = x.IntDiv(dec(t, tt.kind, tt.y)) + } + + require.NoError(t, err) + assert.Equal(t, tt.want, got.String()) + }) + } +} + +func TestDecimalMathErrors(t *testing.T) { + t.Parallel() + + n := bqsql.KindNumeric + neg, zero, two := dec(t, n, "-1"), dec(t, n, "0"), dec(t, n, "2") + + tests := []struct { + run func() error + name string + }{ + {func() error { + _, err := neg.Sqrt() + + return err + }, "sqrtneg"}, + {func() error { + _, err := zero.Ln() + + return err + }, "lnzero"}, + {func() error { + _, err := neg.Log10() + + return err + }, "log10neg"}, + {func() error { + _, err := two.Log(dec(t, n, "1")) + + return err + }, "logbase1"}, + {func() error { + _, err := neg.Log(two) + + return err + }, "logneg"}, + {func() error { + _, err := dec(t, n, "100").Exp() + + return err + }, "expover"}, + {func() error { + _, err := neg.Pow(dec(t, n, "0.5")) + + return err + }, "powneg"}, + {func() error { + _, err := zero.Pow(neg) + + return err + }, "powzero"}, + {func() error { + _, err := dec(t, n, "10").Pow(dec(t, n, "40")) + + return err + }, "powover"}, + {func() error { + _, err := two.IntDiv(zero) + + return err + }, "intdivzero"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + require.ErrorIs(t, tt.run(), bqsql.ErrDecimal) + }) + } +} + +func TestSQLiteValueBoundary(t *testing.T) { + t.Parallel() + + n := bqsql.Field{Name: "n", Type: "NUMERIC"} + b := bqsql.Field{Name: "b", Type: "BIGNUMERIC"} + + enc := bqsql.ToSQLite(b, "0.00000000000000000000000000000000000001") + txt, ok := enc.(string) + require.True(t, ok) + assert.True(t, bqsql.IsSQLText(txt)) + + back, err := bqsql.FromSQLite(b, txt) + require.NoError(t, err) + assert.Equal(t, "0.00000000000000000000000000000000000001", back) + + for _, bad := range []any{float64(1.5), int64(2), "1.5", []byte("x")} { + _, err = bqsql.FromSQLite(n, bad) + require.ErrorIs(t, err, bqsql.ErrValue) + } + + nested := bqsql.Field{Name: "a", Type: "NUMERIC", Mode: bqsql.ModeRepeated} + text, ok := bqsql.ToSQLite(nested, []any{"1.5", "-2"}).(string) + require.True(t, ok) + assert.NotContains(t, text, "1.5") + + got, err := bqsql.FromSQLite(nested, text) + require.NoError(t, err) + assert.Equal(t, []any{"1.5", "-2"}, got) + assert.JSONEq(t, `["1.5","-2"]`, bqsql.JSONText(nested, []any{"1.5", "-2"})) +} diff --git a/services/gcpbigquery/bqsql/decimal_format.go b/services/gcpbigquery/bqsql/decimal_format.go new file mode 100644 index 0000000000..6d9a568b55 --- /dev/null +++ b/services/gcpbigquery/bqsql/decimal_format.go @@ -0,0 +1,218 @@ +package bqsql + +import ( + "fmt" + "math/big" + "strconv" + "strings" +) + +const ( + fmtDecimalTag = "\x01" + defaultFormatPrec = 6 + sciLowExp = -4 + minExpDigits = 2 + maxFormatPrec = 1000 +) + +type decFormatSpec struct { + width int + prec int + minus bool + plus bool + space bool + zero bool + sharp bool +} + +func parseDecimalFlags(flags string) decFormatSpec { + sp := decFormatSpec{prec: defaultFormatPrec} + + i := 0 + for ; i < len(flags) && strings.IndexByte("-+ #0", flags[i]) >= 0; i++ { + switch flags[i] { + case '-': + sp.minus = true + case '+': + sp.plus = true + case ' ': + sp.space = true + case '#': + sp.sharp = true + case '0': + sp.zero = true + } + } + + w, rest, hasDot := strings.Cut(flags[i:], ".") + sp.width, _ = strconv.Atoi(w) + + if hasDot { + sp.prec, _ = strconv.Atoi(rest) + } + + return sp +} + +// formatDecimal prints one FORMAT argument tagged by dec_fmt; %f, %e and %g are computed on exact digits. +func formatDecimal(spec byte, flags, tagged string) (string, error) { + kind := KindNumeric + if strings.HasPrefix(tagged, "B") { + kind = KindBigNumeric + } + + d, err := ParseDecimal(kind, tagged[1:]) + if err != nil { + return "", decFail(err) + } + + sp := parseDecimalFlags(flags) + + switch spec { + case 's': + return fmt.Sprintf("%"+flags+"s", d.String()), nil + case 't', 'T': + txt := d.String() + if !strings.Contains(txt, ".") { + txt += ".0" + } + + if spec == 'T' { + txt = kind.RESTName() + ` "` + txt + `"` + } + + return fmt.Sprintf("%"+flags+"s", txt), nil + case 'f', 'F': + body, ferr := fixedBody(d, min(sp.prec, maxFormatPrec), sp.sharp) + + return padDecimal(d.Sign() < 0, body, sp), ferr + case 'e', 'E': + return padDecimal(d.Sign() < 0, sciBody(d, sp.prec, sp.sharp, spec == 'E'), sp), nil + case 'g', 'G': + return padDecimal(d.Sign() < 0, generalBody(d, sp, spec == 'G'), sp), nil + } + + return "", errBQ("Invalid format specifier %%%c for %s", spec, kind.RESTName()) +} + +func padDecimal(neg bool, body string, sp decFormatSpec) string { + sign := "" + + switch { + case neg: + sign = "-" + case sp.plus: + sign = "+" + case sp.space: + sign = " " + } + + pad := max(min(sp.width, maxFormatPrec)-len(sign)-len(body), 0) + + switch { + case sp.minus: + return sign + body + strings.Repeat(" ", pad) + case sp.zero: + return sign + strings.Repeat("0", pad) + body + } + + return strings.Repeat(" ", pad) + sign + body +} + +// fixedBody renders |d| in decimal notation with exactly prec fractional digits, rounding half away from zero. +func fixedBody(d Decimal, prec int, sharp bool) (string, error) { + r, err := d.Round(prec, RoundHalfAwayFromZero) + if err != nil { + return "", decFail(err) + } + + abs, _ := r.Abs() + whole, frac, _ := strings.Cut(abs.String(), ".") + frac += strings.Repeat("0", max(prec-len(frac), 0)) + + switch { + case prec > 0: + return whole + "." + frac, nil + case sharp: + return whole + ".", nil + } + + return whole, nil +} + +// sciDigits returns prec+1 significant digits of |d| rounded half away from zero and the decimal exponent. +func sciDigits(d Decimal, prec int) (string, int) { + n := new(big.Int).Abs(d.unscaled()) + want := prec + 1 + + if n.Sign() == 0 { + return strings.Repeat("0", want), 0 + } + + sig := n.String() + exp := len(sig) - 1 - decScale(d.kind) + + if len(sig) > want { + q := divRound(n, pow10(len(sig)-want)).String() + if len(q) > want { + q = q[:want] + exp++ + } + + return q, exp + } + + return sig + strings.Repeat("0", want-len(sig)), exp +} + +func sciBody(d Decimal, prec int, sharp, upper bool) string { + digits, exp := sciDigits(d, prec) + + return sciText(digits, exp, sharp, upper) +} + +func sciText(digits string, exp int, sharp, upper bool) string { + body := digits[:1] + if len(digits) > 1 || sharp { + body += "." + digits[1:] + } + + mark, sign := "e", "+" + if upper { + mark = "E" + } + + if exp < 0 { + sign, exp = "-", -exp + } + + e := strconv.Itoa(exp) + if len(e) < minExpDigits { + e = strings.Repeat("0", minExpDigits-len(e)) + e + } + + return body + mark + sign + e +} + +func generalBody(d Decimal, sp decFormatSpec, upper bool) string { + p := max(sp.prec, 1) + digits, exp := sciDigits(d, p-1) + + if exp < sciLowExp || exp >= p { + if !sp.sharp { + digits = strings.TrimRight(digits, "0") + if digits == "" { + digits = "0" + } + } + + return sciText(digits, exp, sp.sharp, upper) + } + + body, _ := fixedBody(d, p-1-exp, sp.sharp) + if sp.sharp || !strings.Contains(body, ".") { + return body + } + + return strings.TrimSuffix(strings.TrimRight(body, "0"), ".") +} diff --git a/services/gcpbigquery/bqsql/decimal_math.go b/services/gcpbigquery/bqsql/decimal_math.go new file mode 100644 index 0000000000..a135eb8800 --- /dev/null +++ b/services/gcpbigquery/bqsql/decimal_math.go @@ -0,0 +1,270 @@ +package bqsql + +import ( + "fmt" + "math" + "math/big" +) + +const ( + mathPrec = 640 + expLimit = 200 + expSeriesCap = 400 + powExactLimit = 256 + powBitLimit = 4096 + halvings = 16 + logSeedIters = 8 + halfDivisor = 2 +) + +func (d Decimal) rat() *big.Rat { + return new(big.Rat).SetFrac(d.unscaled(), pow10(decScale(d.kind))) +} + +func (d Decimal) bigFloat() *big.Float { + return new(big.Float).SetPrec(mathPrec).SetRat(d.rat()) +} + +func decimalFromFloat(k Kind, f *big.Float, expr string, args ...any) (Decimal, error) { + r, _ := f.Rat(nil) + n := divRound(new(big.Int).Mul(r.Num(), pow10(decScale(k))), r.Denom()) + + return newDecimal(k, n, expr, args...) +} + +func decErr(format string, args ...any) error { + return fmt.Errorf("%w: %s", ErrDecimal, fmt.Sprintf(format, args...)) +} + +// Sqrt returns the square root rounded half away from zero; negative input is an error. +func (d Decimal) Sqrt() (Decimal, error) { + if d.Sign() < 0 { + return Decimal{}, decErr("an invalid argument to SQRT: %s", d.String()) + } + + scaled := new(big.Int).Mul(d.unscaled(), pow10(decScale(d.kind))) + r := new(big.Int).Sqrt(scaled) + rem := new(big.Int).Sub(scaled, new(big.Int).Mul(r, r)) + + if rem.Cmp(r) > 0 { + r.Add(r, big.NewInt(1)) + } + + return newDecimal(d.kind, r, "SQRT(%s)", d.String()) +} + +func expFloat(x *big.Float) *big.Float { + div := new(big.Float).SetPrec(mathPrec).SetInt(new(big.Int).Lsh(big.NewInt(1), halvings)) + r := new(big.Float).SetPrec(mathPrec).Quo(x, div) + sum := new(big.Float).SetPrec(mathPrec).SetInt64(1) + term := new(big.Float).SetPrec(mathPrec).SetInt64(1) + eps := new(big.Float).SetPrec(mathPrec).SetMantExp(big.NewFloat(1), -mathPrec) + + for i := 1; i < expSeriesCap; i++ { + term.Mul(term, r) + term.Quo(term, new(big.Float).SetPrec(mathPrec).SetInt64(int64(i))) + sum.Add(sum, term) + + if new(big.Float).Abs(term).Cmp(eps) < 0 { + break + } + } + + for range halvings { + sum.Mul(sum, sum) + } + + return sum +} + +// Exp returns e^d; huge results overflow and tiny ones underflow to zero. +func (d Decimal) Exp() (Decimal, error) { + f := d.Float64() + switch { + case f > expLimit: + return Decimal{}, decOverflow(d.kind, "EXP(%s)", d.String()) + case f < -expLimit: + return Decimal{n: new(big.Int), kind: decKind(d.kind)}, nil + } + + return decimalFromFloat(d.kind, expFloat(d.bigFloat()), "EXP(%s)", d.String()) +} + +func lnFloat(x *big.Float) *big.Float { + seed, _ := x.Float64() + y := new(big.Float).SetPrec(mathPrec).SetFloat64(math.Log(seed)) + two := new(big.Float).SetPrec(mathPrec).SetInt64(halfDivisor) + + for range logSeedIters { + e := expFloat(y) + num := new(big.Float).SetPrec(mathPrec).Sub(x, e) + den := new(big.Float).SetPrec(mathPrec).Add(x, e) + y.Add(y, new(big.Float).SetPrec(mathPrec).Mul(two, num.Quo(num, den))) + } + + return y +} + +// Ln returns the natural logarithm; non-positive input is an error. +func (d Decimal) Ln() (Decimal, error) { + if d.Sign() <= 0 { + return Decimal{}, decErr("an invalid argument to LN: %s", d.String()) + } + + return decimalFromFloat(d.kind, lnFloat(d.bigFloat()), "LN(%s)", d.String()) +} + +// Log10 returns the base-10 logarithm; non-positive input is an error. +func (d Decimal) Log10() (Decimal, error) { + if d.Sign() <= 0 { + return Decimal{}, decErr("an invalid argument to LOG10: %s", d.String()) + } + + ten := new(big.Float).SetPrec(mathPrec).SetInt64(decimalBase) + q := new(big.Float).SetPrec(mathPrec).Quo(lnFloat(d.bigFloat()), lnFloat(ten)) + + return decimalFromFloat(d.kind, q, "LOG10(%s)", d.String()) +} + +// Log returns the logarithm of d in the given base; d, base <= 0 and base = 1 are errors. +func (d Decimal) Log(base Decimal) (Decimal, error) { + one := unitDecimal(base.kind) + if d.Sign() <= 0 || base.Sign() <= 0 || base.Cmp(one) == 0 { + return Decimal{}, decErr("an invalid argument to LOG: %s, %s", d.String(), base.String()) + } + + k := KindNumeric + if d.kind == KindBigNumeric || base.kind == KindBigNumeric { + k = KindBigNumeric + } + + q := new(big.Float).SetPrec(mathPrec).Quo(lnFloat(d.bigFloat()), lnFloat(base.bigFloat())) + + return decimalFromFloat(k, q, "LOG(%s, %s)", d.String(), base.String()) +} + +func (d Decimal) isInteger() bool { + return new(big.Int).Rem(d.unscaled(), pow10(decScale(d.kind))).Sign() == 0 +} + +func ratPow(x *big.Rat, n int64) (*big.Rat, bool) { + neg := n < 0 + if neg { + n = -n + } + + res := new(big.Rat).SetInt64(1) + base := new(big.Rat).Set(x) + + for ; n > 0; n >>= 1 { + if n&1 == 1 { + res.Mul(res, base) + } + + if res.Num().BitLen() > powBitLimit || res.Denom().BitLen() > powBitLimit { + return nil, false + } + + base.Mul(base, base) + + if n > 1 && (base.Num().BitLen() > powBitLimit || base.Denom().BitLen() > powBitLimit) { + return nil, false + } + } + + if neg { + res.Inv(res) + } + + return res, true +} + +// Pow returns d^e. Underflow yields zero; a negative base with fractional exponent and 0^negative are errors. +func (d Decimal) Pow(e Decimal) (Decimal, error) { + k := KindNumeric + if d.kind == KindBigNumeric || e.kind == KindBigNumeric { + k = KindBigNumeric + } + + expr := fmt.Sprintf("POW(%s, %s)", d.String(), e.String()) + + switch { + case d.Sign() == 0 && e.Sign() < 0, d.Sign() < 0 && !e.isInteger(): + return Decimal{}, decErr("an invalid argument to POW: %s, %s", d.String(), e.String()) + case d.Sign() == 0: + return powZeroBase(k, e) + } + + if r, ok := d.powExact(e); ok { + v := divRound(new(big.Int).Mul(r.Num(), pow10(decScale(k))), r.Denom()) + + return newDecimal(k, v, "%s", expr) + } + + return d.powSeries(e, k, expr) +} + +// powExact computes d^e as an exact rational for small integer exponents. +func (d Decimal) powExact(e Decimal) (*big.Rat, bool) { + if !e.isInteger() { + return nil, false + } + + n := new(big.Int).Div(e.unscaled(), pow10(decScale(e.kind))) + if !n.IsInt64() || n.CmpAbs(big.NewInt(powExactLimit)) > 0 { + return nil, false + } + + return ratPow(d.rat(), n.Int64()) +} + +func (d Decimal) powSeries(e Decimal, k Kind, expr string) (Decimal, error) { + ax := new(big.Float).SetPrec(mathPrec).Abs(d.bigFloat()) + prod := new(big.Float).SetPrec(mathPrec).Mul(e.bigFloat(), lnFloat(ax)) + + f, _ := prod.Float64() + if f > expLimit { + return Decimal{}, decOverflow(k, "%s", expr) + } + + if f < -expLimit { + return Decimal{n: new(big.Int), kind: k}, nil + } + + res := expFloat(prod) + if d.Sign() < 0 && !e.isEven() { + res.Neg(res) + } + + return decimalFromFloat(k, res, "%s", expr) +} + +func (d Decimal) isEven() bool { + whole := new(big.Int).Div(d.unscaled(), pow10(decScale(d.kind))) + + return whole.Bit(0) == 0 +} + +func powZeroBase(k Kind, e Decimal) (Decimal, error) { + if e.Sign() == 0 { + return unitDecimal(k), nil + } + + return Decimal{n: new(big.Int), kind: k}, nil +} + +// IntDiv returns the integer quotient truncated toward zero; a zero divisor is an error. +func (d Decimal) IntDiv(o Decimal) (Decimal, error) { + k, x, y, err := widest(d, o) + if err != nil { + return Decimal{}, err + } + + if y.Sign() == 0 { + return Decimal{}, decErr("division by zero: DIV(%s, %s)", d.String(), o.String()) + } + + q := new(big.Int).Quo(x, y) + + return newDecimal(k, q.Mul(q, pow10(decScale(k))), "DIV(%s, %s)", d.String(), o.String()) +} diff --git a/services/gcpbigquery/bqsql/decimal_test.go b/services/gcpbigquery/bqsql/decimal_test.go new file mode 100644 index 0000000000..aecabc3a1a --- /dev/null +++ b/services/gcpbigquery/bqsql/decimal_test.go @@ -0,0 +1,465 @@ +package bqsql_test + +import ( + "math" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/gcpbigquery/bqsql" +) + +const ( + numMax = "99999999999999999999999999999.999999999" + bigMax = "578960446186580977117854925043439539266.34992332820282019728792003956564819967" + bigOver = "578960446186580977117854925043439539266.34992332820282019728792003956564819968" + bigUnder = "-578960446186580977117854925043439539266.34992332820282019728792003956564819969" + bigMin = "-578960446186580977117854925043439539266.34992332820282019728792003956564819968" +) + +func dec(t *testing.T, k bqsql.Kind, s string) bqsql.Decimal { + t.Helper() + + d, err := bqsql.ParseDecimal(k, s) + require.NoError(t, err) + + return d +} + +func TestDecimalParseFormat(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + in string + want string + kind bqsql.Kind + }{ + {"int", "42", "42", bqsql.KindNumeric}, + {"trim", "1.500000000", "1.5", bqsql.KindNumeric}, + {"neg", "-0.25", "-0.25", bqsql.KindNumeric}, + {"negzero", "-0.0", "0", bqsql.KindNumeric}, + {"negtiny", "-0.0000000004", "0", bqsql.KindNumeric}, + {"plus", "+7", "7", bqsql.KindNumeric}, + {"leadpoint", ".5", "0.5", bqsql.KindNumeric}, + {"trailpoint", "5.", "5", bqsql.KindNumeric}, + {"exp", "1.5e3", "1500", bqsql.KindNumeric}, + {"expneg", "25E-2", "0.25", bqsql.KindNumeric}, + {"space", " 3.14 ", "3.14", bqsql.KindNumeric}, + {"halfup", "0.0000000005", "0.000000001", bqsql.KindNumeric}, + {"halfupneg", "-0.0000000005", "-0.000000001", bqsql.KindNumeric}, + {"halfdown", "0.0000000004999", "0", bqsql.KindNumeric}, + {"max", numMax, numMax, bqsql.KindNumeric}, + {"min", "-" + numMax, "-" + numMax, bqsql.KindNumeric}, + {"hugeneg", "1e-999", "0", bqsql.KindNumeric}, + {"bigmax", bigMax, bigMax, bqsql.KindBigNumeric}, + {"bigmin", bigMin, bigMin, bqsql.KindBigNumeric}, + { + "bigfrac", "0.123456789012345678901234567890123456785", + "0.12345678901234567890123456789012345679", bqsql.KindBigNumeric, + }, + {"bigsmall", "1e-38", "0.00000000000000000000000000000000000001", bqsql.KindBigNumeric}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, tt.want, dec(t, tt.kind, tt.in).String()) + }) + } +} + +func TestDecimalParseErrors(t *testing.T) { + t.Parallel() + + long := strings.Repeat("9", 600) + + tests := []struct { + name string + in string + kind bqsql.Kind + }{ + {"empty", "", bqsql.KindNumeric}, + {"blank", " ", bqsql.KindNumeric}, + {"point", ".", bqsql.KindNumeric}, + {"sign", "-", bqsql.KindNumeric}, + {"text", "abc", bqsql.KindNumeric}, + {"nan", "NaN", bqsql.KindNumeric}, + {"inf", "Infinity", bqsql.KindNumeric}, + {"twopoints", "1.2.3", bqsql.KindNumeric}, + {"noexp", "1e", bqsql.KindNumeric}, + {"badexp", "1e+x", bqsql.KindNumeric}, + {"hugeexp", "1e99999", bqsql.KindNumeric}, + {"toolong", long, bqsql.KindNumeric}, + {"over", "100000000000000000000000000000", bqsql.KindNumeric}, + {"overneg", "-1e29", bqsql.KindNumeric}, + {"expover", "1e400", bqsql.KindNumeric}, + {"bigover", bigOver, bqsql.KindBigNumeric}, + {"bigunder", bigUnder, bqsql.KindBigNumeric}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + _, err := bqsql.ParseDecimal(tt.kind, tt.in) + require.ErrorIs(t, err, bqsql.ErrDecimal) + }) + } +} + +func TestDecimalArithmetic(t *testing.T) { + t.Parallel() + + n, b := bqsql.KindNumeric, bqsql.KindBigNumeric + + tests := []struct { + name string + op string + x, y string + want string + kind bqsql.Kind + }{ + {"add", "+", "0.1", "0.2", "0.3", n}, + {"addneg", "+", "-0.1", "0.05", "-0.05", n}, + { + "add38", "+", "12345678901234567890123456789.123456789", "0.000000001", + "12345678901234567890123456789.12345679", n, + }, + {"sub", "-", "0.3", "0.1", "0.2", n}, + {"subzero", "-", "1.5", "1.5", "0", n}, + {"mul", "*", "0.1", "0.1", "0.01", n}, + {"mulround", "*", "0.000000001", "0.5", "0.000000001", n}, + {"mulrounddown", "*", "0.000000001", "0.4", "0", n}, + {"mulroundneg", "*", "-0.000000001", "0.5", "-0.000000001", n}, + {"quothird", "/", "1", "3", "0.333333333", n}, + {"quotwothird", "/", "2", "3", "0.666666667", n}, + {"quoneg", "/", "-1", "3", "-0.333333333", n}, + {"quohalf", "/", "1", "2", "0.5", n}, + {"mod", "%", "7.5", "2", "1.5", n}, + {"modneg", "%", "-7.5", "2", "-1.5", n}, + {"modnegdiv", "%", "7.5", "-2", "1.5", n}, + {"bigquo", "/", "1", "3", "0.33333333333333333333333333333333333333", b}, + {"bigmul", "*", "1e19", "1e19", "100000000000000000000000000000000000000", b}, + {"mixed", "+", "0.1", "0.2", "0.3", b}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + x, y := dec(t, tt.kind, tt.x), dec(t, tt.kind, tt.y) + + var ( + got bqsql.Decimal + err error + ) + + switch tt.op { + case "+": + got, err = x.Add(y) + case "-": + got, err = x.Sub(y) + case "*": + got, err = x.Mul(y) + case "/": + got, err = x.Quo(y) + default: + got, err = x.Mod(y) + } + + require.NoError(t, err) + assert.Equal(t, tt.want, got.String()) + assert.Equal(t, tt.kind, got.Kind()) + }) + } +} + +func TestDecimalMixedKindPromotes(t *testing.T) { + t.Parallel() + + tiny := dec(t, bqsql.KindBigNumeric, "0.00000000000000000000000000000000000001") + got, err := dec(t, bqsql.KindNumeric, "1.5").Add(tiny) + require.NoError(t, err) + assert.Equal(t, bqsql.KindBigNumeric, got.Kind()) + assert.Equal(t, "1.50000000000000000000000000000000000001", got.String()) +} + +func TestDecimalErrors(t *testing.T) { + t.Parallel() + + maxN := dec(t, bqsql.KindNumeric, numMax) + one := dec(t, bqsql.KindNumeric, "0.000000001") + zero := dec(t, bqsql.KindNumeric, "0") + bmax := dec(t, bqsql.KindBigNumeric, bigMax) + bmin := dec(t, bqsql.KindBigNumeric, bigMin) + + tests := []struct { + run func() error + name string + msg string + }{ + {func() error { + _, err := maxN.Add(one) + + return err + }, "addover", "numeric overflow: " + numMax + " + 0.000000001"}, + {func() error { + _, err := maxN.Mul(maxN) + + return err + }, "mulover", "numeric overflow"}, + {func() error { + _, err := bmin.Neg() + + return err + }, "negover", "BIGNUMERIC overflow"}, + {func() error { + _, err := bmin.Abs() + + return err + }, "absover", "BIGNUMERIC overflow"}, + {func() error { + _, err := bmax.Add(bmax) + + return err + }, "bigaddover", "BIGNUMERIC overflow"}, + {func() error { + _, err := one.Quo(zero) + + return err + }, "divzero", "division by zero: 0.000000001 / 0"}, + {func() error { + _, err := one.Mod(zero) + + return err + }, "modzero", "division by zero"}, + {func() error { + _, err := bmax.As(bqsql.KindNumeric) + + return err + }, "narrow", "numeric overflow"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + err := tt.run() + require.ErrorIs(t, err, bqsql.ErrDecimal) + assert.Contains(t, err.Error(), tt.msg) + }) + } +} + +func TestDecimalNegAbsSignCmp(t *testing.T) { + t.Parallel() + + x := dec(t, bqsql.KindNumeric, "-2.5") + neg, err := x.Neg() + require.NoError(t, err) + assert.Equal(t, "2.5", neg.String()) + + abs, err := x.Abs() + require.NoError(t, err) + assert.Equal(t, "2.5", abs.String()) + assert.Equal(t, -1, x.Sign()) + assert.Equal(t, 0, dec(t, bqsql.KindNumeric, "0").Sign()) + assert.Equal(t, 1, neg.Sign()) + + assert.Negative(t, x.Cmp(neg)) + assert.Positive(t, neg.Cmp(x)) + assert.Zero(t, neg.Cmp(dec(t, bqsql.KindBigNumeric, "2.5"))) + above := dec(t, bqsql.KindBigNumeric, "1.00000000000000000000000000000000000001") + assert.Negative(t, dec(t, bqsql.KindNumeric, "1").Cmp(above)) + + z, err := dec(t, bqsql.KindNumeric, "0").Neg() + require.NoError(t, err) + assert.Equal(t, "0", z.String()) +} + +func TestDecimalRounding(t *testing.T) { + t.Parallel() + + away, even := bqsql.RoundHalfAwayFromZero, bqsql.RoundHalfEven + + tests := []struct { + name string + in string + want string + digits int + mode bqsql.RoundMode + }{ + {"away", "2.5", "3", 0, away}, + {"awayneg", "-2.5", "-3", 0, away}, + {"even", "2.5", "2", 0, even}, + {"even3", "3.5", "4", 0, even}, + {"evenneg", "-2.5", "-2", 0, even}, + {"evenabove", "2.50001", "3", 0, even}, + {"two", "1.125", "1.13", 2, away}, + {"twoneg", "-1.125", "-1.13", 2, away}, + {"eventwo", "1.125", "1.12", 2, even}, + {"tens", "1250", "1300", -2, away}, + {"tensneg", "-1250", "-1300", -2, away}, + {"tenseven", "1250", "1200", -2, even}, + {"wide", "1.5", "1.5", 20, away}, + {"tiny", "0.4", "0", -400, away}, + {"tonegzero", "-0.4", "0", 0, away}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + got, err := dec(t, bqsql.KindNumeric, tt.in).Round(tt.digits, tt.mode) + require.NoError(t, err) + assert.Equal(t, tt.want, got.String()) + }) + } + + _, err := dec(t, bqsql.KindNumeric, "99999999999999999999999999999.5").Round(0, away) + require.ErrorIs(t, err, bqsql.ErrDecimal) +} + +func TestDecimalTruncCeilFloor(t *testing.T) { + t.Parallel() + + tests := []struct { + in string + trunc1 string + ceil, floor string + }{ + {"2.75", "2.7", "3", "2"}, + {"-2.75", "-2.7", "-2", "-3"}, + {"5", "5", "5", "5"}, + {"-0.5", "-0.5", "0", "-1"}, + {"0.5", "0.5", "1", "0"}, + } + + for _, tt := range tests { + t.Run(tt.in, func(t *testing.T) { + t.Parallel() + + d := dec(t, bqsql.KindNumeric, tt.in) + assert.Equal(t, tt.trunc1, d.Trunc(1).String()) + + c, err := d.Ceil() + require.NoError(t, err) + assert.Equal(t, tt.ceil, c.String()) + + f, err := d.Floor() + require.NoError(t, err) + assert.Equal(t, tt.floor, f.String()) + }) + } + + assert.Equal(t, "0", dec(t, bqsql.KindNumeric, "0.5").Trunc(-500).String()) +} + +func TestDecimalConversions(t *testing.T) { + t.Parallel() + + i, err := bqsql.DecimalFromInt(bqsql.KindNumeric, math.MinInt64) + require.NoError(t, err) + assert.Equal(t, "-9223372036854775808", i.String()) + + back, err := i.Int64() + require.NoError(t, err) + assert.Equal(t, int64(math.MinInt64), back) + + r, err := dec(t, bqsql.KindNumeric, "2.5").Int64() + require.NoError(t, err) + assert.Equal(t, int64(3), r) + + r, err = dec(t, bqsql.KindNumeric, "-2.5").Int64() + require.NoError(t, err) + assert.Equal(t, int64(-3), r) + + _, err = dec(t, bqsql.KindNumeric, "9223372036854775807.5").Int64() + require.ErrorIs(t, err, bqsql.ErrDecimal) + + f, err := bqsql.DecimalFromFloat(bqsql.KindNumeric, 0.1) + require.NoError(t, err) + assert.Equal(t, "0.1", f.String()) + + f, err = bqsql.DecimalFromFloat(bqsql.KindBigNumeric, 0.1) + require.NoError(t, err) + assert.Equal(t, "0.10000000000000000555111512312578270212", f.String()) + + f, err = bqsql.DecimalFromFloat(bqsql.KindNumeric, -1e-10) + require.NoError(t, err) + assert.Equal(t, "0", f.String()) + + for _, bad := range []float64{math.NaN(), math.Inf(1), math.Inf(-1), 1e30} { + _, err = bqsql.DecimalFromFloat(bqsql.KindNumeric, bad) + require.ErrorIs(t, err, bqsql.ErrDecimal) + } + + assert.InDelta(t, 0.3, dec(t, bqsql.KindNumeric, "0.3").Float64(), 0) + assert.InDelta(t, -1.5e20, dec(t, bqsql.KindNumeric, "-150000000000000000000").Float64(), 0) + + wide, err := dec(t, bqsql.KindNumeric, "1.5").As(bqsql.KindBigNumeric) + require.NoError(t, err) + assert.Equal(t, bqsql.KindBigNumeric, wide.Kind()) + + narrow, err := dec(t, bqsql.KindBigNumeric, "0.0000000005").As(bqsql.KindNumeric) + require.NoError(t, err) + assert.Equal(t, "0.000000001", narrow.String()) +} + +func TestDecimalConstrain(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + in string + want string + p, s int + kind bqsql.Kind + fail bool + }{ + {"round", "1.125", "1.13", 5, 2, bqsql.KindNumeric, false}, + {"fits", "999.99", "999.99", 5, 2, bqsql.KindNumeric, false}, + {"over", "1000", "", 5, 2, bqsql.KindNumeric, true}, + {"roundover", "999.995", "", 5, 2, bqsql.KindNumeric, true}, + {"scale0", "2.5", "3", 3, 0, bqsql.KindNumeric, false}, + {"negover", "-1000", "", 5, 2, bqsql.KindNumeric, true}, + {"badscale", "1", "", 5, 10, bqsql.KindNumeric, true}, + {"badprec", "1", "", 40, 9, bqsql.KindNumeric, true}, + {"badzero", "1", "", 0, 0, bqsql.KindNumeric, true}, + {"precbelowscale", "1", "", 2, 3, bqsql.KindNumeric, true}, + {"bigok", "1.5", "1.5", 76, 38, bqsql.KindBigNumeric, false}, + {"bigover", "1000", "", 40, 38, bqsql.KindBigNumeric, true}, + {"bigscale", "1", "", 10, 39, bqsql.KindBigNumeric, true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + got, err := dec(t, tt.kind, tt.in).Constrain(tt.p, tt.s) + if tt.fail { + require.ErrorIs(t, err, bqsql.ErrDecimal) + + return + } + + require.NoError(t, err) + assert.Equal(t, tt.want, got.String()) + }) + } +} + +func TestDecimalZeroValue(t *testing.T) { + t.Parallel() + + var z bqsql.Decimal + + assert.Equal(t, "0", z.String()) + assert.Equal(t, bqsql.KindNumeric, z.Kind()) + assert.Zero(t, z.Sign()) + assert.InDelta(t, 0.0, z.Float64(), 0) +} diff --git a/services/gcpbigquery/bqsql/exec.go b/services/gcpbigquery/bqsql/exec.go index d1726fde85..ed09b9a779 100644 --- a/services/gcpbigquery/bqsql/exec.go +++ b/services/gcpbigquery/bqsql/exec.go @@ -133,13 +133,12 @@ func affinity(t Type) string { switch t.Kind { case KindInt, KindBool: return litInteger - case KindFloat, KindNumeric, KindBigNumeric: + case KindFloat: return "REAL" case KindBytes: return "BLOB" - case KindUnknown, KindString, KindTimestamp, KindDate, KindTime, KindDatetime, KindJSON, KindGeography, - KindInterval, - KindStruct, KindArray: + case KindUnknown, KindString, KindNumeric, KindBigNumeric, KindTimestamp, KindDate, KindTime, KindDatetime, + KindJSON, KindGeography, KindInterval, KindStruct, KindArray: return "TEXT" } diff --git a/services/gcpbigquery/bqsql/interval.go b/services/gcpbigquery/bqsql/interval.go index 57db2078b2..e281f42dc6 100644 --- a/services/gcpbigquery/bqsql/interval.go +++ b/services/gcpbigquery/bqsql/interval.go @@ -775,7 +775,7 @@ func temporalDiff(op string, l, r *gx) (*gx, bool, error) { func intervalArithmetic(op string, l, r *gx) (*gx, bool, error) { li, ri := l.typ.Kind == KindInterval, r.typ.Kind == KindInterval - fn, known := map[string]string{"+": "add", "-": "sub", "*": "mul", "/": "div"}[op] + fn, known := map[string]string{"+": decAdd, "-": decSub, "*": decMul, "/": decDiv}[op] if !known || li && ri && op != "+" && op != "-" || (li != ri) && (op == "+" || op == "-") || !li && op == "/" { return nil, true, invalid("Operator %s is not supported for INTERVAL operands", op) diff --git a/services/gcpbigquery/bqsql/numeric_engine_test.go b/services/gcpbigquery/bqsql/numeric_engine_test.go new file mode 100644 index 0000000000..1bf7be178d --- /dev/null +++ b/services/gcpbigquery/bqsql/numeric_engine_test.go @@ -0,0 +1,388 @@ +package bqsql_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/gcpbigquery/bqsql" +) + +func numericCatalog(t *testing.T) *fakeCatalog { + t.Helper() + + fs := fieldsJSON(t, `[ + {"name":"id","type":"INTEGER"}, + {"name":"n","type":"NUMERIC"}, + {"name":"b","type":"BIGNUMERIC"}, + {"name":"g","type":"STRING"}, + {"name":"f","type":"FLOAT"}, + {"name":"arr","type":"NUMERIC","mode":"REPEATED"}, + {"name":"rec","type":"RECORD","fields":[{"name":"x","type":"NUMERIC"},{"name":"y","type":"BIGNUMERIC"}]} + ]`) + + rows := rowsJSON(t, fs, `[ + {"id":1,"n":"0.1","b":"0.00000000000000000000000000000000000001","g":"a","f":0.5, + "arr":["1.5","2.25"],"rec":{"x":"3.5","y":"4"}}, + {"id":2,"n":"0.2","b":"12345678901234567890123456789012345678.12345678901234567890123456789012345678", + "g":"a","f":1.5,"arr":[],"rec":{"x":"-1","y":"-2.5"}}, + {"id":3,"n":"-0.3","b":"-5","g":"b","f":2.5,"arr":["7"],"rec":null}, + {"id":4,"n":null,"b":null,"g":"b","f":null,"arr":[],"rec":null}, + {"id":5,"n":"0.1","b":"5","g":"b","f":0.25,"arr":[],"rec":null} + ]`) + + return &fakeCatalog{tables: map[string]*bqsql.TableData{ + "ds.nums": {Ref: bqsql.TableRef{Project: "p", Dataset: "ds", Table: "nums"}, Fields: fs, Rows: rows}, + }} +} + +func TestNumericQueries(t *testing.T) { + t.Parallel() + + tests := []fnCase{ + {"add", "SELECT NUMERIC '0.1' + NUMERIC '0.2'", [][]any{{"0.3"}}}, + {"third", "SELECT NUMERIC '1' / NUMERIC '3'", [][]any{{"0.333333333"}}}, + { + "bigthird", + "SELECT BIGNUMERIC '1' / BIGNUMERIC '3'", + [][]any{{"0.33333333333333333333333333333333333333"}}, + }, + {"eq", "SELECT NUMERIC '0.1' + NUMERIC '0.2' = NUMERIC '0.3'", [][]any{{"true"}}}, + {"wide", "SELECT NUMERIC '99999999999999999999999999999.999999999' - NUMERIC '0.000000001'", + [][]any{{"99999999999999999999999999999.999999998"}}}, + { + "intmix", + "SELECT 1 + NUMERIC '0.5', NUMERIC '0.5' * 3, 10 / NUMERIC '4'", + [][]any{{"1.5", "1.5", "2.5"}}, + }, + {"floatlit", "SELECT NUMERIC '1.5' + 1.25", [][]any{{"2.75"}}}, + {"mixkinds", "SELECT NUMERIC '0.1' + BIGNUMERIC '0.00000000000000000000000000000000000001'", + [][]any{{"0.10000000000000000000000000000000000001"}}}, + {"neg", "SELECT -NUMERIC '1.5', -(NUMERIC '0')", [][]any{{"-1.5", "0"}}}, + {"cmp", "SELECT NUMERIC '1.5' > 1, NUMERIC '1.5' < 2, NUMERIC '2' >= 2, NUMERIC '2' != 2", + [][]any{{"true", "true", "true", "false"}}}, + { + "safe", + "SELECT SAFE_DIVIDE(NUMERIC '1', NUMERIC '0'), SAFE_ADD(NUMERIC '99999999999999999999999999999', " + + "NUMERIC '1e28'), SAFE_NEGATE(NUMERIC '2')", + [][]any{{nil, nil, "-2"}}}, + { + "round", + "SELECT ROUND(NUMERIC '2.5'), ROUND(NUMERIC '-2.5'), ROUND(NUMERIC '1.125', 2), ROUND(NUMERIC '2.5', 0, " + + "'ROUND_HALF_EVEN'), ROUND(NUMERIC '1250', -2)", + [][]any{{"3", "-3", "1.13", "2", "1300"}}}, + { + "trunc", + "SELECT TRUNC(NUMERIC '2.75'), TRUNC(NUMERIC '-2.75', 1), CEIL(NUMERIC '2.1'), FLOOR(NUMERIC '-2.1'), " + + "CEILING(NUMERIC '-0.5')", + [][]any{{"2", "-2.7", "3", "-3", "0"}}}, + { + "absmod", + "SELECT ABS(NUMERIC '-3.5'), SIGN(NUMERIC '-3.5'), MOD(NUMERIC '7.5', NUMERIC '2'), DIV(NUMERIC '7.5', " + + "NUMERIC '2'), MOD(7, NUMERIC '2.5')", + [][]any{{"3.5", "-1", "1.5", "3", "2"}}}, + { + "powers", + "SELECT POW(NUMERIC '2', NUMERIC '10'), SQRT(NUMERIC '2'), POWER(NUMERIC '2', 3), EXP(NUMERIC '0'), " + + "LN(NUMERIC '1'), LOG10(NUMERIC '1000'), LOG(NUMERIC '8', 2)", + [][]any{{"1024", "1.414213562", "8", "1", "0", "3", "3"}}}, + { + "greatest", + "SELECT GREATEST(NUMERIC '1.5', 2, NUMERIC '0.5'), LEAST(NUMERIC '1.5', 2, NUMERIC '0.5'), " + + "GREATEST(NUMERIC '1', NULL)", + [][]any{{"2", "0.5", nil}}}, + { + "casts", + "SELECT CAST('1.5' AS NUMERIC), CAST(NUMERIC '1.5' AS STRING), CAST(NUMERIC '2.5' AS INT64), " + + "CAST(1 AS BIGNUMERIC), CAST(0.125 AS NUMERIC)", + [][]any{{"1.5", "1.5", "3", "1", "0.125"}}}, + { + "castnarrow", + "SELECT CAST(BIGNUMERIC '0.0000000005' AS NUMERIC), CAST(NUMERIC '1.5' AS FLOAT64), " + + "SAFE_CAST('x' AS NUMERIC), SAFE_CAST('1e2' AS BIGNUMERIC)", + [][]any{{"0.000000001", "1.5", nil, "100"}}}, + { + "params", + "SELECT CAST(1.125 AS NUMERIC(5, 2)), CAST('1.234567891234' AS BIGNUMERIC(10, 3))", + [][]any{{"1.13", "1.235"}}, + }, + {"parse", "SELECT PARSE_NUMERIC('1,234.5'), PARSE_BIGNUMERIC(' - 12.5 '), PARSE_NUMERIC('1e2')", + [][]any{{"1234.5", "-12.5", "100"}}}, + { + "format", + "SELECT FORMAT('%f|%.2f|%t|%T|%10.1f', NUMERIC '1.5', NUMERIC '2.345', NUMERIC '1', BIGNUMERIC '1.5', " + + "NUMERIC '-3.25')", + [][]any{{"1.500000|2.35|1.0|BIGNUMERIC \"1.5\"| -3.3"}}}, + { + "json", + "SELECT TO_JSON_STRING(NUMERIC '1.5'), TO_JSON_STRING(STRUCT(NUMERIC '1.5' AS a, 'x' AS b)), " + + "TO_JSON_STRING([NUMERIC '1', NUMERIC '2.5'])", + [][]any{{"1.5", `{"a":1.5,"b":"x"}`, "[1,2.5]"}}}, + { + "ifcase", + "SELECT IF(TRUE, 1, NUMERIC '2.5'), CASE WHEN FALSE THEN 1 ELSE NUMERIC '2.5' END, COALESCE(NULL, " + + "NUMERIC '1.5'), IFNULL(NULL, 1) + NUMERIC '0.5', NULLIF(NUMERIC '1', 1)", + [][]any{{"1", "2.5", "1.5", "1.5", nil}}}, + {"union", "SELECT 1 AS v UNION ALL SELECT NUMERIC '2.5' ORDER BY v", [][]any{{"1"}, {"2.5"}}}, + { + "in", + "SELECT NUMERIC '1.5' IN (1, NUMERIC '1.5'), NUMERIC '1' BETWEEN 0 AND NUMERIC '2', " + + "3 IN UNNEST([NUMERIC '3'])", + [][]any{{"true", "true", "true"}}}, + { + "arrays", + "SELECT ARRAY[1, 2.5], ARRAY_LENGTH([NUMERIC '1', NUMERIC '2']), [NUMERIC '1', " + + "NUMERIC '2'][OFFSET(1)]", + [][]any{{[]map[string]any{{"v": "1"}, {"v": "2.5"}}, "2", "2"}}}, + {"castarray", "SELECT CAST([1, 2] AS ARRAY)[OFFSET(1)] / 4", [][]any{{"0.5"}}}, + {"genarray", "SELECT GENERATE_ARRAY(NUMERIC '0', NUMERIC '1', NUMERIC '0.5')", + [][]any{{[]map[string]any{{"v": "0"}, {"v": "0.5"}, {"v": "1"}}}}}, + {"struct", "SELECT STRUCT(NUMERIC '1.5' AS a).a + 1", [][]any{{"2.5"}}}, + { + "unnest", + "SELECT x + NUMERIC '0.5' FROM UNNEST([NUMERIC '1', NUMERIC '2']) AS x ORDER BY 1", + [][]any{{"1.5"}, {"2.5"}}, + }, + {"stddev", "SELECT STDDEV_POP(x) FROM UNNEST([NUMERIC '1', NUMERIC '3']) AS x", [][]any{{"1.0"}}}, + { + "variance", + "SELECT VAR_SAMP(x), VAR_POP(x), VARIANCE(x) FROM UNNEST([NUMERIC '1', NUMERIC '2', NUMERIC '3', " + + "NUMERIC '4']) AS x", + [][]any{{"1.6666666666666667", "1.25", "1.6666666666666667"}}}, + { + "varexact", + "SELECT VAR_POP(x) FROM UNNEST([NUMERIC '99999999999999999999999999999.999999999', " + + "NUMERIC '99999999999999999999999999999.999999997']) AS x", + [][]any{{"1e-18"}}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + res, err := runSQL(t, numericCatalog(t), tt.sql) + require.NoError(t, err) + assert.Equal(t, tt.want, wireRows(res)) + }) + } +} + +func TestNumericFormat(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + args string + want string + }{ + {"e", "'%e', NUMERIC '392.65'", "3.926500e+02"}, + {"upper", "'%E', NUMERIC '392.65'", "3.926500E+02"}, + {"g", "'%g', NUMERIC '392.65'", "392.65"}, + {"gexp", "'%g', NUMERIC '39265000'", "3.9265e+07"}, + {"gsmall", "'%g|%g', NUMERIC '0.0001', NUMERIC '0.00001'", "0.0001|1e-05"}, + {"gzero", "'%g', NUMERIC '0'", "0"}, + {"sharp", "'%#g', NUMERIC '1.5'", "1.50000"}, + {"prec", "'%.3e', BIGNUMERIC '12345678901234567890.123456789012345678'", "1.235e+19"}, + {"carry", "'%.2e', NUMERIC '9.999'", "1.00e+01"}, + {"neg", "'%e', NUMERIC '-0.5'", "-5.000000e-01"}, + {"f", "'%f', NUMERIC '392.65'", "392.650000"}, + {"fwide", "'%.12f', NUMERIC '1.5'", "1.500000000000"}, + { + "fflags", + "'%+.2f|%08.2f|%-8.1f|', NUMERIC '1.005', NUMERIC '-1.5', NUMERIC '2.25'", + "+1.01|-0001.50|2.3 |", + }, + {"fzero", "'%.0f|%#.0f', NUMERIC '2.5', NUMERIC '2.5'", "3|3."}, + { + "digits", + "'%.30f', BIGNUMERIC '0.12345678901234567890123456789012345678'", + "0.123456789012345678901234567890", + }, + {"tt", "'%t|%T', NUMERIC '12', NUMERIC '1.25'", "12.0|NUMERIC \"1.25\""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + res, err := runSQL(t, numericCatalog(t), "SELECT FORMAT("+tt.args+")") + require.NoError(t, err) + assert.Equal(t, [][]any{{tt.want}}, wireRows(res)) + }) + } +} + +func TestNumericTables(t *testing.T) { + t.Parallel() + + tests := []fnCase{ + { + "order", + "SELECT id FROM nums WHERE n IS NOT NULL ORDER BY n, id", + [][]any{{"3"}, {"1"}, {"5"}, {"2"}}, + }, + {"orderdesc", "SELECT id FROM nums ORDER BY b DESC, id", [][]any{{"2"}, {"5"}, {"1"}, {"3"}, {"4"}}}, + {"group", "SELECT n, COUNT(*) FROM nums WHERE n IS NOT NULL GROUP BY n ORDER BY n", + [][]any{{"-0.3", "1"}, {"0.1", "2"}, {"0.2", "1"}}}, + { + "distinct", + "SELECT DISTINCT n FROM nums WHERE n IS NOT NULL ORDER BY n", + [][]any{{"-0.3"}, {"0.1"}, {"0.2"}}, + }, + { + "sum", + "SELECT SUM(n), AVG(n), MIN(n), MAX(n), COUNT(DISTINCT n), ANY_VALUE(g) FROM nums WHERE g = 'a'", + [][]any{{"0.3", "0.15", "0.1", "0.2", "2", "a"}}}, + {"sumall", "SELECT SUM(n), AVG(n) FROM nums", [][]any{{"0.1", "0.025"}}}, + { + "bigsum", + "SELECT SUM(b) FROM nums WHERE id <= 2", + [][]any{{"12345678901234567890123456789012345678.12345678901234567890123456789012345679"}}, + }, + {"emptysum", "SELECT SUM(n) FROM nums WHERE id > 100", [][]any{{nil}}}, + {"groupsum", "SELECT g, SUM(n) FROM nums GROUP BY g ORDER BY g", [][]any{{"a", "0.3"}, {"b", "-0.2"}}}, + { + "window", + "SELECT id, " + + "SUM(n) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) FROM nums WHERE n IS NOT NULL ORDER BY id", + [][]any{{"1", "0.1"}, {"2", "0.3"}, {"3", "-0.1"}, {"5", "-0.2"}}}, + { + "winavg", + "SELECT id, AVG(n) OVER () FROM nums WHERE id <= 2 ORDER BY id", + [][]any{{"1", "0.15"}, {"2", "0.15"}}, + }, + { + "lag", + "SELECT id, LAG(n) OVER (ORDER BY id) FROM nums WHERE id <= 2 ORDER BY id", + [][]any{{"1", nil}, {"2", "0.1"}}, + }, + {"join", "SELECT a.id, c.id FROM nums a JOIN nums c ON a.n = c.n AND a.id < c.id", [][]any{{"1", "5"}}}, + {"arrayagg", "SELECT ARRAY_AGG(n ORDER BY n) FROM nums WHERE n IS NOT NULL", + [][]any{{[]map[string]any{{"v": "-0.3"}, {"v": "0.1"}, {"v": "0.1"}, {"v": "0.2"}}}}}, + {"nested", "SELECT arr, rec FROM nums WHERE id = 1", + [][]any{{ + []map[string]any{{"v": "1.5"}, {"v": "2.25"}}, + map[string]any{"f": []map[string]any{{"v": "3.5"}, {"v": "4"}}}, + }}}, + { + "nestedmath", + "SELECT rec.x + rec.y, (SELECT SUM(a) FROM UNNEST(arr) AS a) FROM nums WHERE id = 1", + [][]any{{"7.5", "3.75"}}, + }, + {"mixfloat", "SELECT n + f FROM nums WHERE id = 1", [][]any{{"0.6"}}}, + {"bigmix", "SELECT n + b FROM nums WHERE id = 3", [][]any{{"-5.3"}}}, + {"compare", "SELECT id FROM nums WHERE n > 0.1 OR n < 0 ORDER BY id", [][]any{{"2"}, {"3"}}}, + { + "between", + "SELECT id FROM nums WHERE n BETWEEN 0.1 AND 0.2 ORDER BY id", + [][]any{{"1"}, {"2"}, {"5"}}, + }, + {"in", "SELECT id FROM nums WHERE n IN (0.1, 0.2) ORDER BY id", [][]any{{"1"}, {"2"}, {"5"}}}, + { + "case", + "SELECT CASE n WHEN 0.1 THEN 'x' ELSE 'y' END FROM nums WHERE id IN (1, 3) ORDER BY id", + [][]any{{"x"}, {"y"}}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + res, err := runSQL(t, numericCatalog(t), tt.sql) + require.NoError(t, err) + assert.Equal(t, tt.want, wireRows(res)) + }) + } +} + +func TestNumericErrors(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + sql string + msg string + }{ + { + "overflow", + "SELECT NUMERIC '99999999999999999999999999999.999999999' + NUMERIC '1'", + "numeric overflow", + }, + {"mulover", "SELECT NUMERIC '1e20' * NUMERIC '1e20'", "numeric overflow"}, + {"divzero", "SELECT NUMERIC '1' / NUMERIC '0'", "division by zero: 1 / 0"}, + {"bigover", "SELECT BIGNUMERIC '5e38' + BIGNUMERIC '5e38'", "BIGNUMERIC overflow"}, + {"castover", "SELECT CAST(BIGNUMERIC '1e30' AS NUMERIC)", "numeric overflow"}, + {"badstr", "SELECT CAST('abc' AS NUMERIC)", "invalid NUMERIC value"}, + {"nanfloat", "SELECT CAST(IEEE_DIVIDE(1, 0) AS NUMERIC)", "cannot convert"}, + {"constrain", "SELECT CAST(1000 AS NUMERIC(5, 2))", "out of range"}, + {"sqrtneg", "SELECT SQRT(NUMERIC '-1')", "invalid argument to SQRT"}, + {"ordinal", "SELECT ROUND(1.5, 0, 'ROUND_HALF_EVEN')", "rounding mode"}, + {"badmode", "SELECT ROUND(NUMERIC '1.5', 0, 'X')", "rounding mode"}, + {"fmtd", "SELECT FORMAT('%d', NUMERIC '1')", "Invalid format specifier"}, + { + "sumover", + "SELECT SUM(x) FROM UNNEST([NUMERIC '99999999999999999999999999999', " + + "NUMERIC '99999999999999999999999999999']) AS x", + "numeric overflow", + }, + {"castbool", "SELECT CAST(TRUE AS NUMERIC)", "Invalid cast"}, + { + "rangeframe", + "SELECT SUM(id) OVER (ORDER BY n RANGE BETWEEN 1 PRECEDING AND CURRENT ROW) FROM nums", + "RANGE window frame offsets", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + _, err := runSQL(t, numericCatalog(t), tt.sql) + require.Error(t, err) + assert.Contains(t, err.Error(), tt.msg) + }) + } +} + +func TestNumericScriptsAndRoutines(t *testing.T) { + t.Parallel() + + tests := []fnCase{ + {"rollup", "SELECT g, SUM(n) FROM nums GROUP BY ROLLUP(g) ORDER BY g NULLS FIRST", + [][]any{{nil, "0.1"}, {"a", "0.3"}, {"b", "-0.2"}}}, + {"having", "SELECT g FROM nums GROUP BY g HAVING SUM(n) > 0 ORDER BY g", [][]any{{"a"}}}, + { + "lagdefault", + "SELECT LAG(n, 1, 0) OVER (ORDER BY id) FROM nums WHERE id <= 2 ORDER BY id", + [][]any{{"0"}, {"0.1"}}, + }, + { + "pivot", + "SELECT * FROM (SELECT g, n FROM nums WHERE n IS NOT NULL) PIVOT (SUM(n) FOR g IN ('a', 'b'))", + [][]any{{"0.3", "-0.2"}}}, + { + "structarr", + "SELECT s.x * 2 FROM UNNEST([STRUCT(NUMERIC '1.5' AS x), STRUCT(NUMERIC '2' AS x)]) AS s ORDER BY 1", + [][]any{{"3"}, {"4"}}}, + {"quantiles", "SELECT APPROX_QUANTILES(x, 2) FROM UNNEST([NUMERIC '3', NUMERIC '1', NUMERIC '2']) AS x", + [][]any{{[]map[string]any{{"v": "1"}, {"v": "2"}, {"v": "3"}}}}}, + {"distinctunion", "SELECT NUMERIC '1.0' UNION DISTINCT SELECT NUMERIC '1'", [][]any{{"1"}}}, + {"exceptall", "SELECT n FROM nums WHERE id = 1 EXCEPT DISTINCT SELECT NUMERIC '0.1'", [][]any{}}, + { + "hll", + "SELECT HLL_COUNT.EXTRACT(HLL_COUNT.INIT(x)) FROM UNNEST([NUMERIC '1', NUMERIC '1', NUMERIC '2']) AS x", + [][]any{{"2"}}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + res, err := runSQL(t, numericCatalog(t), tt.sql) + require.NoError(t, err) + assert.Equal(t, tt.want, wireRows(res)) + }) + } +} diff --git a/services/gcpbigquery/bqsql/parser_expr.go b/services/gcpbigquery/bqsql/parser_expr.go index 5159fa499e..99db08b13f 100644 --- a/services/gcpbigquery/bqsql/parser_expr.go +++ b/services/gcpbigquery/bqsql/parser_expr.go @@ -1,6 +1,8 @@ package bqsql import ( + "fmt" + "strconv" "strings" ) @@ -1071,17 +1073,67 @@ func (p *parser) typeSpec() (Type, error) { return Type{}, syntaxErr(p.toks[p.i-1].pos, "unknown type %q", name) } + t := scalar(k) + if p.acceptPunct("(") { - for !p.acceptPunct(")") { - if p.peek().kind == tkEOF { - return Type{}, p.unexpected("expected )") + nums, perr := p.typeParams() + if perr != nil { + return Type{}, perr + } + + if isDec(t) { + if perr = decimalParams(&t, nums); perr != nil { + return Type{}, syntaxErr(p.toks[p.i-1].pos, "%v", perr) } + } + } - p.i++ + return t, nil +} + +const ( + maxTypeParam = 255 + maxDecimalParam = 2 +) + +// typeParams consumes the parenthesised parameters of a type up to the closing parenthesis. +func (p *parser) typeParams() ([]int, error) { + var nums []int + + for !p.acceptPunct(")") { + tok := p.peek() + if tok.kind == tkEOF { + return nil, p.unexpected("expected )") + } + + if n, err := strconv.Atoi(tok.text); err == nil && n >= 0 && n <= maxTypeParam { + nums = append(nums, n) } + + p.i++ } - return scalar(k), nil + return nums, nil +} + +// decimalParams records NUMERIC(P[, S]) or BIGNUMERIC(P[, S]) on t after validating the ranges. +func decimalParams(t *Type, nums []int) error { + if len(nums) == 0 || len(nums) > maxDecimalParam { + return fmt.Errorf("%w: %s takes (precision[, scale])", ErrDecimal, t.Kind.RESTName()) + } + + p, s := nums[0], 0 + if len(nums) == maxDecimalParam { + s = nums[1] + } + + if err := checkDecimalParams(t.Kind, p, s); err != nil { + return err + } + + t.Prec, t.Scale = p, s + + return nil } func (p *parser) arrayType() (Type, error) { diff --git a/services/gcpbigquery/bqsql/sqlvalues.go b/services/gcpbigquery/bqsql/sqlvalues.go index 8b71a0ddd4..3169fb13ef 100644 --- a/services/gcpbigquery/bqsql/sqlvalues.go +++ b/services/gcpbigquery/bqsql/sqlvalues.go @@ -24,7 +24,7 @@ func ToSQLite(f Field, stored any) driver.Value { if k == KindStruct || strings.EqualFold(f.Mode, ModeRepeated) { var buf bytes.Buffer - writeJSON(&buf, f, stored) + writeJSON(&buf, f, stored, false) return buf.String() } @@ -34,6 +34,15 @@ func ToSQLite(f Field, stored any) driver.Value { return scalarToSQLite(k, s) } +// JSONText renders a stored record or repeated value as JSON text with decimals as plain strings. +func JSONText(f Field, stored any) string { + var buf bytes.Buffer + + writeJSON(&buf, f, stored, true) + + return buf.String() +} + func scalarToSQLite(k Kind, s string) driver.Value { switch k { case KindInt: @@ -45,9 +54,12 @@ func scalarToSQLite(k Kind, s string) driver.Value { return f case KindNumeric, KindBigNumeric: - f, _ := strconv.ParseFloat(s, bitSize) + d, err := ParseDecimal(k, s) + if err != nil { + return nil + } - return f + return d.SQLText() case KindBool: if s == litTrueX { return int64(1) @@ -67,7 +79,7 @@ func scalarToSQLite(k Kind, s string) driver.Value { return s } -func writeJSON(buf *bytes.Buffer, f Field, stored any) { +func writeJSON(buf *bytes.Buffer, f Field, stored any, plain bool) { if strings.EqualFold(f.Mode, ModeRepeated) { arr, _ := stored.([]any) elem := f @@ -80,7 +92,7 @@ func writeJSON(buf *bytes.Buffer, f Field, stored any) { buf.WriteByte(',') } - writeJSON(buf, elem, e) + writeJSON(buf, elem, e, plain) } buf.WriteByte(']') @@ -96,16 +108,16 @@ func writeJSON(buf *bytes.Buffer, f Field, stored any) { k, _ := KindOf(f.Type) if k == KindStruct { - writeJSONRecord(buf, f.Fields, stored) + writeJSONRecord(buf, f.Fields, stored, plain) return } s, _ := stored.(string) - writeJSONScalar(buf, k, s) + writeJSONScalar(buf, k, s, plain) } -func writeJSONRecord(buf *bytes.Buffer, fields []Field, stored any) { +func writeJSONRecord(buf *bytes.Buffer, fields []Field, stored any, plain bool) { rec, _ := stored.([]any) buf.WriteByte('{') @@ -124,13 +136,13 @@ func writeJSONRecord(buf *bytes.Buffer, fields []Field, stored any) { v = rec[i] } - writeJSON(buf, fl, v) + writeJSON(buf, fl, v, plain) } buf.WriteByte('}') } -func writeJSONScalar(buf *bytes.Buffer, k Kind, s string) { +func writeJSONScalar(buf *bytes.Buffer, k Kind, s string, plain bool) { switch k { case KindInt, KindBool: buf.WriteString(s) @@ -144,8 +156,17 @@ func writeJSONScalar(buf *bytes.Buffer, k Kind, s string) { } buf.WriteString(strconv.FormatFloat(f, 'g', -1, bitSize)) - case KindUnknown, KindString, KindBytes, KindTimestamp, KindDate, KindTime, KindDatetime, KindNumeric, - KindBigNumeric, KindJSON, KindGeography, KindInterval, KindStruct, KindArray: + case KindNumeric, KindBigNumeric: + txt := litNull + if d, err := ParseDecimal(k, s); err == nil && plain { + txt = `"` + d.String() + `"` + } else if err == nil { + txt = `"` + d.SQLText() + `"` + } + + buf.WriteString(txt) + case KindUnknown, KindString, KindBytes, KindTimestamp, KindDate, KindTime, KindDatetime, + KindJSON, KindGeography, KindInterval, KindStruct, KindArray: q, _ := json.Marshal(s, jsonx.V1()) buf.Write(q) } @@ -273,9 +294,7 @@ func scalarFromSQLite(k Kind, v any) (any, error) { case KindBool: return storedBool(v) case KindNumeric, KindBigNumeric: - if fl, ok := v.(float64); ok { - return FormatNumeric(fl), nil - } + return decimalFromSQLite(k, v) case KindBytes: if b, ok := v.([]byte); ok { return base64.StdEncoding.EncodeToString(b), nil @@ -294,3 +313,17 @@ func scalarFromSQLite(k Kind, v any) (any, error) { return scalarStored(k, v) } + +func decimalFromSQLite(k Kind, v any) (any, error) { + s, ok := v.(string) + if !ok { + return nil, valueErr("expected an encoded %s value, got %T", k.RESTName(), v) + } + + d, err := DecodeSQLText(s, k) + if err != nil { + return nil, valueErr("invalid %s value", k.RESTName()) + } + + return d.String(), nil +} diff --git a/services/gcpbigquery/bqsql/types.go b/services/gcpbigquery/bqsql/types.go index 6a22283132..dbb3137e90 100644 --- a/services/gcpbigquery/bqsql/types.go +++ b/services/gcpbigquery/bqsql/types.go @@ -4,6 +4,7 @@ package bqsql import ( "errors" "fmt" + "strconv" "strings" ) @@ -41,6 +42,8 @@ type Column struct { type Type struct { Elem *Type Fields []Column + Prec int + Scale int Kind Kind } @@ -143,6 +146,9 @@ func (f Field) SQLType() Type { t = Type{Kind: KindStruct, Fields: FieldColumns(f.Fields)} } else { t = scalar(k) + if isDec(t) { + t.Prec, t.Scale = f.decimalParams() + } } if strings.EqualFold(f.Mode, ModeRepeated) { @@ -152,6 +158,20 @@ func (f Field) SQLType() Type { return t } +func (f Field) decimalParams() (int, int) { + p, err := strconv.Atoi(f.Precision) + if err != nil || p <= 0 || p > maxTypeParam { + return 0, 0 + } + + s, _ := strconv.Atoi(f.Scale) + if s < 0 || s > p { + return 0, 0 + } + + return p, s +} + // FieldColumns converts schema fields into typed columns. func FieldColumns(fs []Field) []Column { cols := make([]Column, len(fs)) @@ -173,6 +193,10 @@ func TypeField(name string, t Type) Field { f.Type = t.Kind.RESTName() + if isDec(t) && t.Prec > 0 { + f.Precision, f.Scale = strconv.Itoa(t.Prec), strconv.Itoa(t.Scale) + } + if t.Kind == KindStruct { f.Fields = ColumnFields(t.Fields) } @@ -245,6 +269,33 @@ func normalizeField(f *Field) error { f.Fields = nil + return normalizeDecimalParams(f, k) +} + +func normalizeDecimalParams(f *Field, k Kind) error { + if !isDec(scalar(k)) { + f.Precision, f.Scale = "", "" + + return nil + } + + if f.Precision == "" && f.Scale == "" { + return nil + } + + p, perr := strconv.Atoi(f.Precision) + s, serr := strconv.Atoi(f.Scale) + + if f.Scale == "" { + s, serr = 0, nil + } + + if perr != nil || serr != nil || checkDecimalParams(k, p, s) != nil { + return fmt.Errorf("%w: invalid precision %q and scale %q for field %q", ErrSchema, f.Precision, f.Scale, f.Name) + } + + f.Precision, f.Scale = strconv.Itoa(p), strconv.Itoa(s) + return nil } diff --git a/services/gcpbigquery/bqsql/udf.go b/services/gcpbigquery/bqsql/udf.go index 41345b5998..99c4f918d6 100644 --- a/services/gcpbigquery/bqsql/udf.go +++ b/services/gcpbigquery/bqsql/udf.go @@ -53,6 +53,7 @@ func registerUDFs() { addIntervalUDFs(defs) addSearchUDFs(defs) addCastUDFs(defs) + addDecimalUDFs(defs) for name, d := range defs { register("bq_"+name, d, d.fn) @@ -60,6 +61,8 @@ func registerUDFs() { } registerAggregates() + registerDecimalAggregates() + registerDecimalMoments() }) } diff --git a/services/gcpbigquery/bqsql/udf_cast.go b/services/gcpbigquery/bqsql/udf_cast.go index 9a9049aff9..57714b06ac 100644 --- a/services/gcpbigquery/bqsql/udf_cast.go +++ b/services/gcpbigquery/bqsql/udf_cast.go @@ -37,7 +37,7 @@ func udfCast(a []driver.Value) (driver.Value, error) { case KindBytes: return bytesOf(a[0]), nil case KindNumeric, KindBigNumeric: - return castNumeric(a[0]) + return nil, errBQ("unsupported cast to %s", target) case KindTimestamp, KindDate, KindDatetime, KindTime: return castTemporal(k, a[0]) case KindJSON: @@ -110,10 +110,6 @@ func castString(v driver.Value, src string) (driver.Value, error) { f, _ := toFloat(v) return strings.TrimSuffix(FormatFloat(f), ".0"), nil - case litNumeric, litBignumeric: - f, _ := toFloat(v) - - return FormatNumeric(f), nil case litTimestamp: return udfStringOf([]driver.Value{v}) case litDatetime, litTime: @@ -123,19 +119,6 @@ func castString(v driver.Value, src string) (driver.Value, error) { return toStr(v), nil } -func castNumeric(v driver.Value) (driver.Value, error) { - if n, ok := v.(int64); ok { - return float64(n), nil - } - - f, err := toFloat(v) - if err != nil { - return nil, errBQ("Invalid NUMERIC value: %s", toStr(v)) - } - - return f, nil -} - func castTemporal(k Kind, v driver.Value) (driver.Value, error) { t, from, err := parseAny(v) if err != nil { diff --git a/services/gcpbigquery/bqsql/udf_decimal.go b/services/gcpbigquery/bqsql/udf_decimal.go new file mode 100644 index 0000000000..c7db7e5e57 --- /dev/null +++ b/services/gcpbigquery/bqsql/udf_decimal.go @@ -0,0 +1,610 @@ +package bqsql + +import ( + "database/sql/driver" + "math" + "math/big" + "strings" + + sqlitedriver "modernc.org/sqlite" +) + +func decFail(err error) error { + return errBQ("%s", strings.TrimPrefix(err.Error(), ErrDecimal.Error()+": ")) +} + +func decKindArg(v driver.Value) Kind { + if n, ok := v.(int64); ok && n == 1 { + return KindBigNumeric + } + + return KindNumeric +} + +func decArg(v driver.Value, k Kind) (Decimal, error) { + s, ok := v.(string) + if !ok { + return Decimal{}, errBQ("expected a NUMERIC value") + } + + d, err := DecodeSQLText(s, k) + if err != nil { + return Decimal{}, decFail(err) + } + + return d, nil +} + +func decOut(d Decimal, err error) (driver.Value, error) { + if err != nil { + return nil, decFail(err) + } + + return d.SQLText(), nil +} + +func decUnary(op func(Decimal) (Decimal, error)) udfFn { + return func(a []driver.Value) (driver.Value, error) { + if a[0] == nil { + return nil, nil + } + + k := decKindArg(a[len(a)-1]) + + x, err := decArg(a[0], k) + if err != nil { + return nil, err + } + + return decOut(op(x)) + } +} + +func decBinary(op func(x, y Decimal) (Decimal, error)) udfFn { + return func(a []driver.Value) (driver.Value, error) { + if a[0] == nil || a[1] == nil { + return nil, nil + } + + k := decKindArg(a[argc2]) + + x, err := decArg(a[0], k) + if err != nil { + return nil, err + } + + y, err := decArg(a[1], k) + if err != nil { + return nil, err + } + + return decOut(op(x, y)) + } +} + +const maxDigitsArg = 1000 + +func clampDigits(n int64) int { return int(max(min(n, maxDigitsArg), -maxDigitsArg)) } + +func decRound(a []driver.Value) (driver.Value, error) { + if anyNull(a[:argc2]) { + return nil, nil //nolint:nilnil // NULL in, NULL out + } + + k := decKindArg(a[argc4-1]) + + x, err := decArg(a[0], k) + if err != nil { + return nil, err + } + + digits, _ := a[1].(int64) + mode := RoundHalfAwayFromZero + + if m, _ := a[argc2].(int64); m == 1 { + mode = RoundHalfEven + } + + return decOut(x.Round(clampDigits(digits), mode)) +} + +func decTrunc(a []driver.Value) (driver.Value, error) { + if anyNull(a[:argc2]) { + return nil, nil //nolint:nilnil // NULL in, NULL out + } + + x, err := decArg(a[0], decKindArg(a[argc2])) + if err != nil { + return nil, err + } + + digits, _ := a[1].(int64) + + return x.Trunc(clampDigits(digits)).SQLText(), nil +} + +func decFromInt(a []driver.Value) (driver.Value, error) { + if a[0] == nil { + return nil, nil //nolint:nilnil // NULL in, NULL out + } + + n, err := toInt(a[0]) + if err != nil { + return nil, err + } + + return decOut(DecimalFromInt(decKindArg(a[1]), n)) +} + +func decFromFloat(a []driver.Value) (driver.Value, error) { + if a[0] == nil { + return nil, nil //nolint:nilnil // NULL in, NULL out + } + + f, err := toFloat(a[0]) + if err != nil { + return nil, err + } + + return decOut(DecimalFromFloat(decKindArg(a[1]), f)) +} + +func decFromStr(parse func(Kind, string) (Decimal, error)) udfFn { + return func(a []driver.Value) (driver.Value, error) { + if a[0] == nil { + return nil, nil + } + + return decOut(parse(decKindArg(a[1]), toStr(a[0]))) + } +} + +func decConvert(a []driver.Value) (driver.Value, error) { + if a[0] == nil { + return nil, nil //nolint:nilnil // NULL in, NULL out + } + + k := decKindArg(a[1]) + + d, err := DecodeSQLText(toStr(a[0]), KindBigNumeric) + if err != nil { + return nil, decFail(err) + } + + return decOut(d.As(k)) +} + +func decConstrain(a []driver.Value) (driver.Value, error) { + if a[0] == nil { + return nil, nil //nolint:nilnil // NULL in, NULL out + } + + d, err := decArg(a[0], decKindArg(a[argc4-1])) + if err != nil { + return nil, err + } + + p, _ := a[1].(int64) + s, _ := a[argc2].(int64) + + return decOut(d.Constrain(int(p), int(s))) +} + +func decToFloat(a []driver.Value) (driver.Value, error) { + if a[0] == nil { + return nil, nil //nolint:nilnil // NULL in, NULL out + } + + d, err := decArg(a[0], KindBigNumeric) + if err != nil { + return nil, err + } + + return d.Float64(), nil +} + +func decToInt(a []driver.Value) (driver.Value, error) { + if a[0] == nil { + return nil, nil //nolint:nilnil // NULL in, NULL out + } + + d, err := decArg(a[0], KindBigNumeric) + if err != nil { + return nil, err + } + + n, err := d.Int64() + if err != nil { + return nil, decFail(err) + } + + return n, nil +} + +func decToStr(a []driver.Value) (driver.Value, error) { + if a[0] == nil { + return nil, nil //nolint:nilnil // NULL in, NULL out + } + + d, err := decArg(a[0], KindBigNumeric) + if err != nil { + return nil, err + } + + return d.String(), nil +} + +func decSign(x Decimal) (Decimal, error) { + return DecimalFromInt(x.Kind(), int64(x.Sign())) +} + +func decNeg(x Decimal) (Decimal, error) { return x.Neg() } + +func decAbs(x Decimal) (Decimal, error) { return x.Abs() } + +func decCeil(x Decimal) (Decimal, error) { return x.Ceil() } + +func decFloor(x Decimal) (Decimal, error) { return x.Floor() } + +func decSqrt(x Decimal) (Decimal, error) { return x.Sqrt() } + +func decExp(x Decimal) (Decimal, error) { return x.Exp() } + +func decLn(x Decimal) (Decimal, error) { return x.Ln() } + +func decLog10(x Decimal) (Decimal, error) { return x.Log10() } + +func decGenerateArray(a []driver.Value) (driver.Value, error) { + if anyNull(a[:argc3]) { + return nil, nil //nolint:nilnil // NULL in, NULL out + } + + k := decKindArg(a[argc3]) + + lo, err := decArg(a[0], k) + if err != nil { + return nil, err + } + + hi, err := decArg(a[1], k) + if err != nil { + return nil, err + } + + step, err := decArg(a[argc2], k) + if err != nil { + return nil, err + } + + return decGenerate(lo, hi, step) +} + +const ( + maxGenerated = 1_000_000 + squaredScale = 2 * bigNumericScale +) + +func decGenerate(lo, hi, step Decimal) (driver.Value, error) { + if step.Sign() == 0 { + return nil, errBQ("Sequence step in the series can't be 0.") + } + + var sb strings.Builder + + sb.WriteByte('[') + + n := 0 + + for cur, ok := lo, inSeries(lo, hi, step); ok; { + if n >= maxGenerated { + return nil, errBQ("A generated array is too large") + } + + if n > 0 { + sb.WriteByte(',') + } + + sb.WriteString(`"` + cur.SQLText() + `"`) + + n++ + + next, err := cur.Add(step) + ok = err == nil && inSeries(next, hi, step) + cur = next + } + + sb.WriteByte(']') + + return sb.String(), nil +} + +func inSeries(cur, hi, step Decimal) bool { + if step.Sign() > 0 { + return cur.Cmp(hi) <= 0 + } + + return cur.Cmp(hi) >= 0 +} + +func decJSON(a []driver.Value) (driver.Value, error) { + if a[0] == nil { + return "null", nil + } + + d, err := decArg(a[0], KindBigNumeric) + if err != nil { + return nil, err + } + + return d.String(), nil +} + +func addDecimalUDFs(d map[string]udfDef) { + d["dec_add"] = udfDef{n: argc3, fn: decBinary(Decimal.Add)} + d["dec_sub"] = udfDef{n: argc3, fn: decBinary(Decimal.Sub)} + d["dec_mul"] = udfDef{n: argc3, fn: decBinary(Decimal.Mul)} + d["dec_div"] = udfDef{n: argc3, fn: decBinary(Decimal.Quo)} + d["dec_mod"] = udfDef{n: argc3, fn: decBinary(Decimal.Mod)} + d["dec_intdiv"] = udfDef{n: argc3, fn: decBinary(Decimal.IntDiv)} + d["dec_pow"] = udfDef{n: argc3, fn: decBinary(Decimal.Pow)} + d["dec_log"] = udfDef{n: argc3, fn: decBinary(Decimal.Log)} + d["dec_neg"] = udfDef{n: argc2, fn: decUnary(decNeg)} + d["dec_abs"] = udfDef{n: argc2, fn: decUnary(decAbs)} + d["dec_sign"] = udfDef{n: argc2, fn: decUnary(decSign)} + d["dec_ceil"] = udfDef{n: argc2, fn: decUnary(decCeil)} + d["dec_floor"] = udfDef{n: argc2, fn: decUnary(decFloor)} + d["dec_sqrt"] = udfDef{n: argc2, fn: decUnary(decSqrt)} + d["dec_exp"] = udfDef{n: argc2, fn: decUnary(decExp)} + d["dec_ln"] = udfDef{n: argc2, fn: decUnary(decLn)} + d["dec_log10"] = udfDef{n: argc2, fn: decUnary(decLog10)} + d["dec_round"] = udfDef{n: argc4, fn: decRound} + d["dec_trunc"] = udfDef{n: argc3, fn: decTrunc} + d["dec_from_int"] = udfDef{n: argc2, fn: decFromInt} + d["dec_from_float"] = udfDef{n: argc2, fn: decFromFloat} + d["dec_from_str"] = udfDef{n: argc2, fn: decFromStr(ParseDecimal)} + d["dec_parse"] = udfDef{n: argc2, fn: decFromStr(ParseNumericText)} + d["dec_convert"] = udfDef{n: argc2, fn: decConvert} + d["dec_constrain"] = udfDef{n: argc4, fn: decConstrain} + d["dec_to_float"] = udfDef{n: 1, fn: decToFloat} + d["dec_to_int"] = udfDef{n: 1, fn: decToInt} + d["dec_to_str"] = udfDef{n: 1, fn: decToStr} + d["dec_json"] = udfDef{n: 1, fn: decJSON} + d["dec_fmt"] = udfDef{n: argc2, fn: decFmt} + d["dec_json_nested"] = udfDef{n: 1, fn: decJSONNested} + d["dec_generate_array"] = udfDef{n: argc4, fn: decGenerateArray} +} + +type decAgg struct { + sum *big.Int + n int64 + kind Kind + avg bool +} + +func (a *decAgg) Step(_ *sqlitedriver.FunctionContext, args []driver.Value) error { + return a.apply(args, false) +} + +func (a *decAgg) WindowInverse(_ *sqlitedriver.FunctionContext, args []driver.Value) error { + return a.apply(args, true) +} + +func (a *decAgg) apply(args []driver.Value, remove bool) error { + if args[0] == nil { + return nil + } + + v, err := decodeScaled(toStr(args[0])) + if err != nil { + return decFail(err) + } + + if remove { + a.sum.Sub(a.sum, v) + a.n-- + + return nil + } + + a.sum.Add(a.sum, v) + a.n++ + + return nil +} + +func (a *decAgg) WindowValue(*sqlitedriver.FunctionContext) (driver.Value, error) { + if a.n == 0 { + return nil, nil //nolint:nilnil // an empty group has no sum + } + + var ( + d Decimal + err error + ) + + if a.avg { + den := big.NewInt(a.n) + if a.kind == KindNumeric { + den.Mul(den, pow10(narrowShift)) + } + + d, err = newDecimal(a.kind, divRound(new(big.Int).Set(a.sum), den), "AVG") + } else { + d, err = decimalFromScaled(a.kind, new(big.Int).Set(a.sum), "SUM") + } + + if err != nil { + return nil, decFail(err) + } + + return d.SQLText(), nil +} + +func (a *decAgg) Final(*sqlitedriver.FunctionContext) {} + +func registerDecimalAggregates() { + for name, spec := range map[string]struct { + kind Kind + avg bool + }{ + "bq_dec_sum_n": {KindNumeric, false}, "bq_dec_sum_b": {KindBigNumeric, false}, + "bq_dec_avg_n": {KindNumeric, true}, "bq_dec_avg_b": {KindBigNumeric, true}, + } { + sqlitedriver.MustRegisterFunction(name, &sqlitedriver.FunctionImpl{ + NArgs: 1, + MakeAggregate: func(sqlitedriver.FunctionContext) (sqlitedriver.AggregateFunction, error) { + return &decAgg{avg: spec.avg, kind: spec.kind, sum: new(big.Int)}, nil + }, + }) + } +} + +func decFmt(a []driver.Value) (driver.Value, error) { + if a[0] == nil { + return nil, nil //nolint:nilnil // NULL in, NULL out + } + + k := decKindArg(a[1]) + + d, err := decArg(a[0], k) + if err != nil { + return nil, err + } + + return fmtDecimalTag + decFlagLetter(k) + d.String(), nil +} + +func decFlagLetter(k Kind) string { + if k == KindBigNumeric { + return "B" + } + + return "N" +} + +// decJSONNested rewrites every encoded decimal string inside JSON text into a bare JSON number. +func decJSONNested(a []driver.Value) (driver.Value, error) { + if a[0] == nil { + return nil, nil //nolint:nilnil // NULL in, NULL out + } + + src := toStr(a[0]) + + var sb strings.Builder + + for i := 0; i < len(src); i++ { + if src[i] != '"' { + sb.WriteByte(src[i]) + + continue + } + + end := i + 1 + for end < len(src) && src[end] != '"' { + if src[end] == '\\' { + end++ + } + + end++ + } + + if end >= len(src) { + sb.WriteString(src[i:]) + + break + } + + inner := src[i+1 : end] + + if IsSQLText(inner) { + d, err := DecodeSQLText(inner, KindBigNumeric) + if err != nil { + return nil, decFail(err) + } + + sb.WriteString(d.String()) + } else { + sb.WriteString(src[i : end+1]) + } + + i = end + } + + return sb.String(), nil +} + +// decMomentAgg keeps exact power sums so VARIANCE and STDDEV of decimals only round once, on the final FLOAT64. +type decMomentAgg struct { + sum *big.Int + sumSq *big.Int + n int64 + sample bool + root bool +} + +func (a *decMomentAgg) Step(_ *sqlitedriver.FunctionContext, args []driver.Value) error { + return a.apply(args, 1) +} + +func (a *decMomentAgg) WindowInverse(_ *sqlitedriver.FunctionContext, args []driver.Value) error { + return a.apply(args, -1) +} + +func (a *decMomentAgg) apply(args []driver.Value, sign int64) error { + if args[0] == nil { + return nil + } + + v, err := decodeScaled(toStr(args[0])) + if err != nil { + return decFail(err) + } + + a.sum.Add(a.sum, new(big.Int).Mul(v, big.NewInt(sign))) + a.sumSq.Add(a.sumSq, new(big.Int).Mul(new(big.Int).Mul(v, v), big.NewInt(sign))) + a.n += sign + + return nil +} + +func (a *decMomentAgg) WindowValue(*sqlitedriver.FunctionContext) (driver.Value, error) { + denom := a.n + if a.sample { + denom-- + } + + if a.n <= 0 || denom <= 0 { + return nil, nil //nolint:nilnil // too few rows + } + + num := new(big.Int).Mul(a.sumSq, big.NewInt(a.n)) + num.Sub(num, new(big.Int).Mul(a.sum, a.sum)) + + den := new(big.Int).Mul(big.NewInt(a.n), big.NewInt(denom)) + den.Mul(den, pow10(squaredScale)) + + v, _ := new(big.Rat).SetFrac(num, den).Float64() + if a.root { + return math.Sqrt(v), nil + } + + return v, nil +} + +func (a *decMomentAgg) Final(*sqlitedriver.FunctionContext) {} + +func registerDecimalMoments() { + for name, spec := range map[string][2]bool{ + "bq_dec_stddev_samp": {true, true}, "bq_dec_stddev_pop": {false, true}, "bq_dec_var_samp": {true, false}, + "bq_dec_var_pop": {false, false}, + } { + sample, root := spec[0], spec[1] + + sqlitedriver.MustRegisterFunction(name, &sqlitedriver.FunctionImpl{ + NArgs: 1, + MakeAggregate: func(sqlitedriver.FunctionContext) (sqlitedriver.AggregateFunction, error) { + return &decMomentAgg{sum: new(big.Int), sumSq: new(big.Int), sample: sample, root: root}, nil + }, + }) + } +} diff --git a/services/gcpbigquery/bqsql/udf_json.go b/services/gcpbigquery/bqsql/udf_json.go index 5d52d43200..eb75622d4b 100644 --- a/services/gcpbigquery/bqsql/udf_json.go +++ b/services/gcpbigquery/bqsql/udf_json.go @@ -226,7 +226,7 @@ func udfFormat(a []driver.Value) (driver.Value, error) { return nil, errBQ("Too few arguments to FORMAT") } - out, err := formatOne(spec, flags, args[0]) + out, err := formatArg(spec, flags, args[0]) if err != nil { return nil, err } @@ -239,6 +239,14 @@ func udfFormat(a []driver.Value) (driver.Value, error) { return sb.String(), nil } +func formatArg(spec byte, flags string, v driver.Value) (string, error) { + if txt, ok := v.(string); ok && strings.HasPrefix(txt, fmtDecimalTag) { + return formatDecimal(spec, flags, txt[len(fmtDecimalTag):]) + } + + return formatOne(spec, flags, v) +} + func formatOne(spec byte, flags string, v driver.Value) (string, error) { if v == nil { if spec == 'T' || spec == 't' { diff --git a/services/gcpbigquery/bqsql/values.go b/services/gcpbigquery/bqsql/values.go index 08d77c7208..2c057f343b 100644 --- a/services/gcpbigquery/bqsql/values.go +++ b/services/gcpbigquery/bqsql/values.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "math" - "math/big" "strconv" "strings" "time" @@ -21,7 +20,6 @@ const ( DateLayout = "2006-01-02" DatetimeLayout = "2006-01-02T15:04:05.000000" TimeLayout = "15:04:05.000000" - numericScale = 9 microsPerSecond = 1e6 nanosPerMicroUnit = 1e3 nanosPerSecondF = 1e9 @@ -102,6 +100,10 @@ func parseSingle(f Field, v any, o ParseOptions) (any, error) { k, _ := KindOf(f.Type) s, err := scalarStored(k, v) + if err == nil && isDec(scalar(k)) { + s, err = constrainStored(f, k, s) + } + if err != nil { return nil, fmt.Errorf("field %s: %w", f.Name, err) } @@ -153,7 +155,7 @@ func scalarStored(k Kind, v any) (string, error) { case KindBytes: return storedBytes(v) case KindNumeric, KindBigNumeric: - return storedNumeric(v) + return storedDecimal(k, v) case KindTimestamp, KindDate, KindTime, KindDatetime: return storedTemporal(k, v) case KindJSON: @@ -329,23 +331,36 @@ func storedBytes(v any) (string, error) { } } -func storedNumeric(v any) (string, error) { - s, ok := numberText(v) - if !ok { - return "", valueErr("cannot use %T as NUMERIC", v) +func constrainStored(f Field, k Kind, s string) (string, error) { + p, sc := f.decimalParams() + if p == 0 { + return s, nil } - r, ok := new(big.Rat).SetString(s) - if !ok { - return "", valueErr("invalid NUMERIC value %q", s) + d, err := ParseDecimal(k, s) + if err == nil { + d, err = d.Constrain(p, sc) + } + + if err != nil { + return "", valueErr("value %s does not fit %s(%d, %d)", s, k.RESTName(), p, sc) } - return trimDecimal(r.FloatString(numericScale)), nil + return d.String(), nil } -// FormatNumeric renders f as a NUMERIC with scale 9 and no trailing zeros. -func FormatNumeric(f float64) string { - return trimDecimal(strconv.FormatFloat(f, 'f', numericScale, bitSize)) +func storedDecimal(k Kind, v any) (string, error) { + s, ok := numberText(v) + if !ok { + return "", valueErr("cannot use %T as %s", v, k.RESTName()) + } + + d, err := ParseDecimal(k, s) + if err != nil { + return "", valueErr("invalid %s value %q", k.RESTName(), clip(s)) + } + + return d.String(), nil } func trimDecimal(s string) string { @@ -692,3 +707,72 @@ func storedInterval(v any) (string, error) { return iv.String(), nil } + +// 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 NormalizeRows(fields []Field, rows [][]any) { + if !fieldsHaveDecimal(fields) { + return + } + + for _, row := range rows { + for i := range min(len(row), len(fields)) { + row[i] = normalizeCell(fields[i], row[i]) + } + } +} + +func fieldsHaveDecimal(fields []Field) bool { + for _, f := range fields { + k, _ := KindOf(f.Type) + if isDec(scalar(k)) || k == KindStruct && fieldsHaveDecimal(f.Fields) { + return true + } + } + + return false +} + +func normalizeCell(f Field, v any) any { + if v == nil { + return nil + } + + if strings.EqualFold(f.Mode, ModeRepeated) { + arr, ok := v.([]any) + if !ok { + return v + } + + elem := f + elem.Mode = ModeNullable + + for i := range arr { + arr[i] = normalizeCell(elem, arr[i]) + } + + return arr + } + + k, _ := KindOf(f.Type) + + switch { + case k == KindStruct: + rec, ok := v.([]any) + if !ok { + return v + } + + for i := range min(len(rec), len(f.Fields)) { + rec[i] = normalizeCell(f.Fields[i], rec[i]) + } + + return rec + case isDec(scalar(k)): + if s, err := storedDecimal(k, v); err == nil { + return s + } + } + + return v +} diff --git a/services/gcpbigquery/jobs_extract.go b/services/gcpbigquery/jobs_extract.go index 51570d3759..07e7a1df87 100644 --- a/services/gcpbigquery/jobs_extract.go +++ b/services/gcpbigquery/jobs_extract.go @@ -383,9 +383,7 @@ func jsonCell(f bqsql.Field, v any) jsontext.Value { k, _ := bqsql.KindOf(f.Type) if k == bqsql.KindStruct || f.Mode == bqsql.ModeRepeated { - text, _ := bqsql.ToSQLite(f, v).(string) - - return jsontext.Value(text) + return jsontext.Value(bqsql.JSONText(f, v)) } s, _ := v.(string) diff --git a/services/gcpbigquery/persistence.go b/services/gcpbigquery/persistence.go index 490de32736..82db65e2a2 100644 --- a/services/gcpbigquery/persistence.go +++ b/services/gcpbigquery/persistence.go @@ -6,6 +6,7 @@ import ( "github.com/blackbirdworks/gopherstack/pkgs/logger" "github.com/blackbirdworks/gopherstack/pkgs/persistence" + "github.com/blackbirdworks/gopherstack/services/gcpbigquery/bqsql" ) // snapshotVersion must be bumped when a change to Dataset, Table or Job would make an older snapshot unsafe to decode. @@ -108,6 +109,12 @@ func normalizeDataset(d *Dataset) { if t.Rows == nil { t.Rows = [][]any{} } + + bqsql.NormalizeRows(t.Schema, t.Rows) + + for i := range t.History { + bqsql.NormalizeRows(t.History[i].Schema, t.History[i].Rows) + } } } diff --git a/services/gcpbigquery/sdk_numeric_test.go b/services/gcpbigquery/sdk_numeric_test.go new file mode 100644 index 0000000000..5ef75acdee --- /dev/null +++ b/services/gcpbigquery/sdk_numeric_test.go @@ -0,0 +1,456 @@ +package gcpbigquery_test + +import ( + "bytes" + "math/big" + "strings" + "testing" + + "cloud.google.com/go/bigquery" + "github.com/iskorotkov/avro/v2/ocf" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/pkgs/parquetio" +) + +const ( + bigMaxText = "578960446186580977117854925043439539266.34992332820282019728792003956564819967" + bigMinText = "-578960446186580977117854925043439539266.34992332820282019728792003956564819968" + tinyText = "0.00000000000000000000000000000000000001" + bigHalfText = "12345678901234567890123456789012345678.5" + wideNumeric = "12345678901234567890123456789.123456789" + wideBig = "12345678901234567890123456789012.12345678901234567890123456789012345678" +) + +func ratOf(t *testing.T, s string) *big.Rat { + t.Helper() + + r, ok := new(big.Rat).SetString(s) + require.True(t, ok, s) + + return r +} + +func requireRats(t *testing.T, row []bigquery.Value, want ...string) { + t.Helper() + + require.Len(t, row, len(want)) + + for i, w := range want { + if w == "" { + assert.Nil(t, row[i], "column %d", i) + + continue + } + + got, ok := row[i].(*big.Rat) + require.True(t, ok, "column %d is %T", i, row[i]) + assert.Zero(t, got.Cmp(ratOf(t, w)), "column %d: got %s want %s", i, got.FloatString(40), w) + } +} + +func TestSDKNumericExactness(t *testing.T) { + t.Parallel() + + env := newSDK(t) + + tests := []struct { + name string + sql string + want []string + }{ + {"point3", "SELECT NUMERIC '0.1' + NUMERIC '0.2'", []string{"0.3"}}, + { + "third", + "SELECT NUMERIC '1' / NUMERIC '3', NUMERIC '2' / NUMERIC '3'", + []string{"0.333333333", "0.666666667"}, + }, + { + "digits38", + "SELECT NUMERIC '12345678901234567890123456789.123456789' + NUMERIC '0.000000001'", + []string{"12345678901234567890123456789.12345679"}, + }, + { + "floatloses", + "SELECT NUMERIC '99999999999999999999999999999.999999999' - NUMERIC '0.000000001'", + []string{"99999999999999999999999999999.999999998"}, + }, + { + "bigthird", + "SELECT BIGNUMERIC '1' / BIGNUMERIC '3'", + []string{"0.33333333333333333333333333333333333333"}, + }, + {"extremes", "SELECT BIGNUMERIC '" + bigMaxText + "', BIGNUMERIC '" + bigMinText + "'", + []string{bigMaxText, bigMinText}}, + { + "bigsum", + "SELECT BIGNUMERIC '1e38' + BIGNUMERIC '1e-38'", + []string{"100000000000000000000000000000000000000.00000000000000000000000000000000000001"}, + }, + { + "casts", + "SELECT CAST('1.5' AS NUMERIC), CAST(NUMERIC '1.5' AS BIGNUMERIC), CAST(BIGNUMERIC '0.5' AS NUMERIC)", + []string{"1.5", "1.5", "0.5"}}, + {"castnum", "SELECT CAST(2 AS NUMERIC) * NUMERIC '0.5', SAFE_CAST('x' AS NUMERIC)", []string{"1", ""}}, + { + "safe", + "SELECT SAFE_DIVIDE(NUMERIC '1', NUMERIC '0'), SAFE_ADD(NUMERIC '1', NUMERIC '2')", + []string{"", "3"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + rows := env.rows(t, tt.sql) + require.Len(t, rows, 1) + requireRats(t, rows[0], tt.want...) + }) + } +} + +func TestSDKNumericErrors(t *testing.T) { + t.Parallel() + + env := newSDK(t) + + tests := []struct { + name string + sql string + msg string + }{ + { + "overflow", + "SELECT NUMERIC '99999999999999999999999999999.999999999' + NUMERIC '1'", + "numeric overflow", + }, + {"divzero", "SELECT NUMERIC '1' / NUMERIC '0'", "division by zero"}, + {"bigover", "SELECT BIGNUMERIC '" + bigMaxText + "' + BIGNUMERIC '1'", "BIGNUMERIC overflow"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + job, err := env.client.Query(tt.sql).Run(t.Context()) + require.NoError(t, err) + + st, err := job.Wait(t.Context()) + if err == nil { + err = st.Err() + } + + require.Error(t, err) + assert.Contains(t, err.Error(), tt.msg) + }) + } +} + +func TestSDKNumericTable(t *testing.T) { + t.Parallel() + + env := newSDK(t) + ctx := t.Context() + ds := env.dataset(t, "nm") + + schema := bigquery.Schema{ + {Name: "id", Type: bigquery.IntegerFieldType}, + {Name: "g", Type: bigquery.StringFieldType}, + {Name: "n", Type: bigquery.NumericFieldType}, + {Name: "b", Type: bigquery.BigNumericFieldType}, + } + tbl := ds.Table("t") + require.NoError(t, tbl.Create(ctx, &bigquery.TableMetadata{Schema: schema})) + + put := func(id int64, g, n, b string) *bigquery.ValuesSaver { + return &bigquery.ValuesSaver{ + Schema: schema, InsertID: g + n, + Row: []bigquery.Value{id, g, ratOf(t, n), ratOf(t, b)}, + } + } + + require.NoError(t, tbl.Inserter().Put(ctx, []*bigquery.ValuesSaver{ + put(1, "a", "0.1", "0.00000000000000000000000000000000000001"), + put(2, "a", "0.2", "12345678901234567890123456789012345678.5"), + put(3, "b", "-0.3", "-5"), + put(4, "b", "0.1", "5"), + })) + + rows := env.rows(t, "SELECT n, b FROM nm.t ORDER BY id") + require.Len(t, rows, 4) + requireRats(t, rows[0], "0.1", "0.00000000000000000000000000000000000001") + requireRats(t, rows[1], "0.2", "12345678901234567890123456789012345678.5") + + rows = env.rows(t, "SELECT n FROM nm.t ORDER BY n DESC, id") + require.Len(t, rows, 4) + + for i, w := range []string{"0.2", "0.1", "0.1", "-0.3"} { + requireRats(t, rows[i], w) + } + + rows = env.rows(t, "SELECT g, SUM(n), AVG(n), MIN(b), MAX(b), COUNT(DISTINCT n) FROM nm.t GROUP BY g ORDER BY g") + require.Len(t, rows, 2) + assert.Equal(t, "a", rows[0][0]) + requireRats(t, rows[0][1:5], "0.3", "0.15", tinyText, bigHalfText) + requireRats(t, rows[1][1:5], "-0.2", "-0.1", "-5", "5") + assert.Equal(t, int64(2), rows[0][5]) + assert.Equal(t, int64(2), rows[1][5]) + + rows = env.rows(t, "SELECT n, COUNT(*) FROM nm.t GROUP BY n ORDER BY n") + require.Len(t, rows, 3) + requireRats(t, rows[2][:1], "0.2") + assert.Equal(t, int64(2), rows[1][1]) + + rows = env.rows(t, "SELECT SUM(b) OVER (PARTITION BY g ORDER BY id) FROM nm.t ORDER BY id") + require.Len(t, rows, 4) + requireRats(t, rows[3], "0") + requireRats(t, rows[2], "-5") + + rows = env.rows(t, "SELECT a.id FROM nm.t a JOIN nm.t c ON a.n = c.n AND a.id < c.id") + require.Len(t, rows, 1) + assert.Equal(t, int64(1), rows[0][0]) +} + +func TestSDKNumericParameters(t *testing.T) { + t.Parallel() + + env := newSDK(t) + + rows := env.rows(t, "SELECT @n + NUMERIC '0.2', @b + BIGNUMERIC '1', @arr, @n = NUMERIC '0.1'", + bigquery.QueryParameter{Name: "n", Value: big.NewRat(1, 10)}, + bigquery.QueryParameter{Name: "b", Value: &bigquery.QueryParameterValue{ + Type: bigquery.StandardSQLDataType{TypeKind: "BIGNUMERIC"}, + Value: bigquery.BigNumericString(ratOf(t, "0.00000000000000000000000000000000000001")), + }}, + bigquery.QueryParameter{Name: "arr", Value: []*big.Rat{big.NewRat(1, 4), big.NewRat(3, 1)}}, + ) + require.Len(t, rows, 1) + requireRats(t, rows[0][:2], "0.3", "1.00000000000000000000000000000000000001") + + arr, ok := rows[0][2].([]bigquery.Value) + require.True(t, ok) + require.Len(t, arr, 2) + requireRats(t, []bigquery.Value{arr[0], arr[1]}, "0.25", "3") + assert.Equal(t, true, rows[0][3]) +} + +func TestSDKNumericDML(t *testing.T) { + t.Parallel() + + env := newSDK(t) + env.dataset(t, "dm") + + env.exec(t, "CREATE TABLE dm.t (id INT64, price NUMERIC(10, 2), wide BIGNUMERIC)") + env.exec(t, "INSERT INTO dm.t VALUES (1, 1.125, 1), "+ + "(2, NUMERIC '2.5', BIGNUMERIC '0.123456789012345678901234567890123456789')") + env.exec(t, "UPDATE dm.t SET price = price * 3, wide = wide + 1 WHERE id = 1") + env.exec(t, "CREATE TABLE dm.copy AS SELECT id, price + NUMERIC '0.005' AS p, wide FROM dm.t") + + rows := env.rows(t, "SELECT price, wide FROM dm.t ORDER BY id") + require.Len(t, rows, 2) + requireRats(t, rows[0], "3.39", "2") + requireRats(t, rows[1], "2.5", "0.12345678901234567890123456789012345679") + + rows = env.rows(t, "SELECT p FROM dm.copy ORDER BY id") + requireRats(t, rows[0], "3.395") + + job, err := env.client.Query("INSERT INTO dm.t (id, price) VALUES (3, 1000000000)").Run(t.Context()) + require.NoError(t, err) + + st, err := job.Wait(t.Context()) + if err == nil { + err = st.Err() + } + + require.Error(t, err) + assert.Contains(t, err.Error(), "out of range") +} + +func TestSDKNumericLoads(t *testing.T) { + t.Parallel() + + env := newSDK(t) + ds := env.dataset(t, "ld") + + const avroSchema = `{"type":"record","name":"r","fields":[ + {"name":"id","type":"long"}, + {"name":"n","type":{"type":"bytes","logicalType":"decimal","precision":38,"scale":9}}, + {"name":"b","type":{"type":"bytes","logicalType":"decimal","precision":70,"scale":38}}]}` + + var avroBuf bytes.Buffer + + enc, err := ocf.NewEncoder(avroSchema, &avroBuf) + require.NoError(t, err) + require.NoError(t, enc.Encode(map[string]any{ + "id": int64(1), "n": ratOf(t, "12345678901234567890123456789.123456789"), + "b": ratOf(t, "12345678901234567890123456789012.12345678901234567890123456789012345678"), + })) + require.NoError(t, enc.Close()) + + var pq bytes.Buffer + + require.NoError(t, parquetio.Write(&pq, + []parquetio.Column{{Name: "id", Type: "bigint"}, {Name: "n", Type: "decimal(38,9)"}}, + [][]any{{int64(1), "12345678901234567890123456789.123456789"}}, "")) + + env.objects.data["bkt/a.avro"] = avroBuf.Bytes() + env.objects.data["bkt/a.parquet"] = pq.Bytes() + env.objects.data["bkt/a.csv"] = []byte("id,n,b\n1,\"1234.5\"," + tinyText + "\n2,-0.000000001,5e3\n") + env.objects.data["bkt/a.json"] = []byte(`{"id":1,"n":0.1,"b":"1e-38"}` + "\n" + + `{"id":2,"n":"7","b":123456789012345678901234567890.1}` + "\n") + + numSchema := bigquery.Schema{ + {Name: "id", Type: bigquery.IntegerFieldType}, + {Name: "n", Type: bigquery.NumericFieldType}, + {Name: "b", Type: bigquery.BigNumericFieldType}, + } + + tests := []struct { + name string + uri string + format bigquery.DataFormat + schema bigquery.Schema + want [][]string + }{ + {"avro", "gs://bkt/a.avro", bigquery.Avro, nil, + [][]string{{wideNumeric, wideBig}}}, + {"parquet", "gs://bkt/a.parquet", bigquery.Parquet, bigquery.Schema{numSchema[0], numSchema[1]}, + [][]string{{"12345678901234567890123456789.123456789"}}}, + {"csv", "gs://bkt/a.csv", bigquery.CSV, numSchema, + [][]string{{"1234.5", "0.00000000000000000000000000000000000001"}, {"-0.000000001", "5000"}}}, + {"json", "gs://bkt/a.json", bigquery.JSON, numSchema, + [][]string{{"0.1", "0.00000000000000000000000000000000000001"}, {"7", "123456789012345678901234567890.1"}}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ref := bigquery.NewGCSReference(tt.uri) + ref.SourceFormat = tt.format + ref.Schema = tt.schema + + if tt.format == bigquery.CSV { + ref.SkipLeadingRows = 1 + } + + job, runErr := ds.Table(tt.name).LoaderFrom(ref).Run(t.Context()) + require.NoError(t, runErr) + + status, waitErr := job.Wait(t.Context()) + require.NoError(t, waitErr) + require.NoError(t, status.Err()) + + sel := "SELECT n, b FROM ld." + tt.name + " ORDER BY id" + if tt.name == "parquet" { + sel = "SELECT n FROM ld.parquet ORDER BY id" + } + + rows := env.rows(t, sel) + require.Len(t, rows, len(tt.want)) + + for i, w := range tt.want { + requireRats(t, rows[i], w...) + } + }) + } +} + +func TestSDKNumericAvroExtractExact(t *testing.T) { + t.Parallel() + + env := newSDK(t) + ds := env.dataset(t, "ex") + + env.exec(t, "CREATE TABLE ex.src AS SELECT NUMERIC '12345678901234567890123456789.123456789' AS n, "+ + "BIGNUMERIC '12345678901234567890123456789012345678.12345678901234567890123456789012345678' AS b") + + ref := bigquery.NewGCSReference("gs://b/p.avro") + ref.DestinationFormat = bigquery.Avro + require.NoError(t, runExtract(t, ds, ref, false).Err()) + + in := bigquery.NewGCSReference("gs://b/p.avro") + in.SourceFormat = bigquery.Avro + + job, err := ds.Table("back").LoaderFrom(in).Run(t.Context()) + require.NoError(t, err) + + status, err := job.Wait(t.Context()) + require.NoError(t, err) + require.NoError(t, status.Err()) + + rows := env.rows(t, "SELECT n, b FROM ex.back") + require.Len(t, rows, 1) + requireRats(t, rows[0], "12345678901234567890123456789.123456789", + "12345678901234567890123456789012345678.12345678901234567890123456789012345678") +} + +func TestSDKNumericScriptsAndRoutines(t *testing.T) { + t.Parallel() + + env := newSDK(t) + + tests := []struct { + name string + sql string + want []string + }{ + { + "script", + "DECLARE x NUMERIC DEFAULT NUMERIC '1.5'; SET x = x + 1; SELECT x, x * 2;", + []string{"2.5", "5"}, + }, + {"scriptint", "DECLARE x NUMERIC(5, 2) DEFAULT 1; SET x = x / 3; SELECT x;", []string{"0.33"}}, + { + "udf", + "CREATE TEMP FUNCTION f(x NUMERIC) RETURNS NUMERIC AS (x * 2); SELECT f(1), f(NUMERIC '0.25');", + []string{"2", "0.5"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + rows := env.rows(t, tt.sql) + require.Len(t, rows, 1) + requireRats(t, rows[0], tt.want...) + }) + } +} + +func TestSDKNumericSnapshotLegacyRows(t *testing.T) { + t.Parallel() + + env := newSDK(t) + env.dataset(t, "old") + env.exec(t, "CREATE TABLE old.t AS SELECT 7 AS id, NUMERIC '1.5' AS n, BIGNUMERIC '2.25' AS b, "+ + "[NUMERIC '0.5'] AS arr, STRUCT(NUMERIC '3.75' AS x) AS st") + + data := env.backend.Snapshot(t.Context()) + + for _, from := range []string{`"1.5"`, `"2.25"`, `"0.5"`, `"3.75"`} { + require.Contains(t, string(data), from) + } + + legacy := string(data) + + for from, to := range map[string]string{ + `"1.5"`: `"1.500000000"`, `"2.25"`: `"2.250000000"`, `"0.5"`: `"5e-1"`, `"3.75"`: `"+3.75"`, + } { + legacy = strings.ReplaceAll(legacy, from, to) + } + + other := newSDK(t) + require.NoError(t, other.backend.Restore(t.Context(), []byte(legacy))) + + rows := other.rows(t, "SELECT n + 1, b * 2, arr[OFFSET(0)] + 1, st.x + 1, n = NUMERIC '1.5' FROM old.t") + require.Len(t, rows, 1) + requireRats(t, rows[0][:4], "2.5", "4.5", "1.5", "4.75") + assert.Equal(t, true, rows[0][4]) + + rows = other.rows(t, "SELECT n, b FROM old.t") + requireRats(t, rows[0], "1.5", "2.25") +} From 49f79c7c809abefcc261c26e25c1e4519134e0ca Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 16:44:00 -0600 Subject: [PATCH 3/9] fix(gcpbigquery): decimals never reach clients encoded; mixed INT64 and NUMERIC joins, IN and IS DISTINCT FROM compare by value Concatenation, LIKE, array-to-string, casts of arrays and structs, FORMAT and error messages could return the internal decimal encoding, and a string that resembled it could be decoded as a decimal. USING joins and IN subqueries between INT64 and NUMERIC columns matched nothing, IS DISTINCT FROM a literal was always true and ARRAY_CONCAT dropped decimal elements. Combining a decimal with a string, bytes, boolean, struct or array is a type error. SEARCH reads decimals inside structs as their decimal text. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- services/gcpbigquery/PARITY.md | 5 +- services/gcpbigquery/bqsql/compile.go | 15 +- services/gcpbigquery/bqsql/compile_decimal.go | 239 ++++++-- services/gcpbigquery/bqsql/compile_expr.go | 99 +++- services/gcpbigquery/bqsql/compile_func.go | 14 +- services/gcpbigquery/bqsql/decimal_format.go | 12 +- .../gcpbigquery/bqsql/decimal_fuzz_test.go | 91 +++ .../gcpbigquery/bqsql/decimal_oracle_test.go | 534 ++++++++++++++++++ .../bqsql/numeric_aggregate_test.go | 316 +++++++++++ .../bqsql/numeric_coercion_test.go | 265 +++++++++ .../gcpbigquery/bqsql/numeric_leak_test.go | 190 +++++++ services/gcpbigquery/bqsql/pivot.go | 28 +- services/gcpbigquery/bqsql/search.go | 3 + services/gcpbigquery/bqsql/udf_decimal.go | 81 +-- .../bqsql/udf_decimal_internal_test.go | 88 +++ services/gcpbigquery/bqsql/udf_json.go | 4 +- services/gcpbigquery/extract_shard_test.go | 3 +- .../gcpbigquery/sdk_numeric_egress_test.go | 352 ++++++++++++ 18 files changed, 2213 insertions(+), 126 deletions(-) create mode 100644 services/gcpbigquery/bqsql/decimal_fuzz_test.go create mode 100644 services/gcpbigquery/bqsql/decimal_oracle_test.go create mode 100644 services/gcpbigquery/bqsql/numeric_aggregate_test.go create mode 100644 services/gcpbigquery/bqsql/numeric_coercion_test.go create mode 100644 services/gcpbigquery/bqsql/numeric_leak_test.go create mode 100644 services/gcpbigquery/bqsql/udf_decimal_internal_test.go create mode 100644 services/gcpbigquery/sdk_numeric_egress_test.go diff --git a/services/gcpbigquery/PARITY.md b/services/gcpbigquery/PARITY.md index 04f92a9591..b3df0a1bf5 100644 --- a/services/gcpbigquery/PARITY.md +++ b/services/gcpbigquery/PARITY.md @@ -60,7 +60,7 @@ items_still_open: - "Unsupported functions: RANGE values, ML.*, GEOGRAPHY beyond the implemented ST_* set (use_spheroid => TRUE, make_valid => TRUE, ST_UNION, ST_BUFFER and the other constructors and aggregates), SEARCH over a table reference or a tuple, JSON constructors and mutators beyond JSON_VALUE/JSON_QUERY/PARSE_JSON/TO_JSON_STRING, FORMAT patterns beyond %s %d %i %f %g %e %t %T %x %o, collation." - "ST_MAKELINE does not snap sufficiently short edges together (geography_functions ST_MAKELINE constraints; snap radius not stated there). Overlap detection of edges beyond the first 1024 only collapses repeated identical edges, and detection off the equator and meridians uses a floating-point tolerance, not an exact predicate. The error text for an edge of 180 degrees or more is emulator wording." - "SEARCH NO_OP_ANALYZER: the page's example SEARCH(R'\"foo bar\"', R'\"foo Bar\"', analyzer=>'NO_OP_ANALYZER') is TRUE with the comment 'analysis is case-insensitive', while its 'Foobar' vs 'foobar' example is FALSE; the emulator keeps NO_OP case-sensitive and returns FALSE for the first. SEARCH also reads upper-case AND/OR inside a double-quoted phrase as logical operators (the page's SEARCH(R'foo bar', R'\"foo AND (bar OR baz)\"') is TRUE, commented as a logical match); the rule for phrases that really contain those words is not documented, so 'Clyde and Bonnie' matches the query \"Bonnie AND Clyde\"." - - "NUMERIC and BIGNUMERIC: a RANGE window frame with an offset over a NUMERIC or BIGNUMERIC ORDER BY key is rejected as unsupported (SQLite applies the offset to the encoded text); Parquet export writes BIGNUMERIC as STRING because pkgs/parquetio caps DECIMAL precision at 38 (the exporting-data page's BIGNUMERIC type mapping was not read)." + - "NUMERIC and BIGNUMERIC: a RANGE window frame with an offset over a NUMERIC or BIGNUMERIC ORDER BY key is rejected as unsupported (SQLite applies the offset to the encoded text); Parquet export writes BIGNUMERIC as STRING because pkgs/parquetio caps DECIMAL precision at 38 (the exporting-data page's BIGNUMERIC type mapping was not read); a scalar function that has no decimal implementation, including the string functions (UPPER, LENGTH, SUBSTR, TRIM and the like), runs on the FLOAT64 conversion of a NUMERIC or BIGNUMERIC argument where BigQuery reports no matching signature; STRUCT equality and IN over structs do not coerce an INT64 or FLOAT64 field to NUMERIC; insertAll, load and DML round a value with more fraction digits than the scale half away from zero (NUMERIC scale 9, BIGNUMERIC scale 38) and the streaming and load pages read do not say whether BigQuery rounds or rejects it; a Parquet load without a schema reads DECIMAL columns as STRING (autodetect types by value)." - "Jobs: no slot or priority scheduling, no query cache, anonymous result tables are not created, script expression evaluations are not recorded as EXPRESSION child jobs, and execution holds the backend write lock (jobs_async.go runLocked), so jobs.cancel and jobTimeoutMs stop a job before it executes and a script between statements, not a plain statement in flight." - "Load: Datastore and Firestore backups, nested CSV and column-name flexibility options are not supported. External tables: GOOGLE_SHEETS, DATASTORE_BACKUP, BIGTABLE and DELTA_LAKE sources and WITH CONNECTION need services the emulator does not have. External tables and CREATE EXTERNAL TABLE read Cloud Storage while the backend lock is held (external.go readExternalRows). The NDJSON TIMESTAMP and CSV float rendering of extract have not been checked against the live service." leaks: {status: clean, note: "Background resources are the HTTP listener and the job workers; Shutdown joins both (Backend.Close cancels and waits for unfinished jobs). goleak runs in TestMain."} @@ -126,6 +126,9 @@ Pass 2026-11-21: NUMERIC and BIGNUMERIC are exact decimals end to end (bqsql/dec - CAST of NUMERIC to INT64 rounds half away from zero; the conversion page does not describe it. AVG of NUMERIC rounds half away from zero at the result scale. - FORMAT %f, %e and %g of NUMERIC print exact digits with ties away from zero; %t prints a whole value with ".0" and %T as NUMERIC "1.25" or BIGNUMERIC "1.25" as the format table shows. - A NUMERIC literal or string with more fraction digits than the scale rounds half away from zero, as CAST of STRING does. +- NUMERIC or BIGNUMERIC combined with STRING, BYTES, BOOL, STRUCT or ARRAY in an operator, comparison, BETWEEN, IN, CASE, IF, COALESCE, IFNULL, NULLIF, GREATEST, LEAST, UNION or array literal fails at compile time ("No matching signature ..." or "Incompatible types ..."), as does LIKE, `||` and ARRAY_TO_STRING over a decimal and CAST of an ARRAY or STRUCT to STRING; the wording is ours. +- SUM reports overflow only when the exact total leaves the range; a partial sum that would overflow and later cancels is not an error (the order BigQuery adds in is not documented). +- FORMAT of a STRUCT or ARRAY holding decimals prints the TO_JSON_STRING form, and SEARCH over such a value matches the canonical decimal text of each decimal. - Parameterised NUMERIC(P, S) values on insertAll, load and DML are rounded to S and fail with the emulator's message when more than P digits remain. - HLL_COUNT.INIT hashes the decimal's internal encoding, so NUMERIC and BIGNUMERIC sketches of equal values agree with each other, not with BigQuery. diff --git a/services/gcpbigquery/bqsql/compile.go b/services/gcpbigquery/bqsql/compile.go index 0e1ddbd86f..b74be3f487 100644 --- a/services/gcpbigquery/bqsql/compile.go +++ b/services/gcpbigquery/bqsql/compile.go @@ -382,6 +382,10 @@ func (c *compiler) compileSetOp(s *setExpr, outer *scope) (*compiledQuery, *selO cols := make([]Column, len(left.cols)) for i := range cols { + if derr := decMix(&gx{typ: left.cols[i].Type}, &gx{typ: right.cols[i].Type}); derr != nil { + return nil, nil, derr + } + cols[i] = Column{Name: left.cols[i].Name, Type: commonType(left.cols[i].Type, right.cols[i].Type)} } @@ -1122,10 +1126,17 @@ func (c *compiler) usingJoin(f *fromItem, sc *scope, nLeft int) (string, error) return "", invalid("USING column %s must exist on both sides of the join", u) } - conds = append(conds, l.sql+" = "+r.sql) + lg, rg := &gx{sql: l.sql, typ: l.typ}, &gx{sql: r.sql, typ: r.typ} + + if err := decMix(lg, rg); err != nil { + return "", err + } + + lg, rg, t := unifyPair(lg, rg) + conds = append(conds, lg.sql+" = "+rg.sql) if f.joinType == litRight || f.joinType == "FULL" { - l.sql = "COALESCE(" + l.sql + ", " + r.sql + ")" + l.sql, l.typ = "COALESCE("+lg.sql+", "+rg.sql+")", t } r.hidden = true diff --git a/services/gcpbigquery/bqsql/compile_decimal.go b/services/gcpbigquery/bqsql/compile_decimal.go index 755b142d80..121d382d91 100644 --- a/services/gcpbigquery/bqsql/compile_decimal.go +++ b/services/gcpbigquery/bqsql/compile_decimal.go @@ -5,6 +5,8 @@ import ( "strings" ) +const jsonEachValue = `"value"` + func isDec(t Type) bool { return t.Kind == KindNumeric || t.Kind == KindBigNumeric } func decFlag(t Type) string { @@ -26,30 +28,80 @@ func decCall(name string, args ...string) string { func toType(g *gx, t Type) *gx { switch { case isDec(t) && g.typ.Kind == KindInt: - if g.lit != nil && g.lit.kind == nInt { - if d, err := ParseDecimal(t.Kind, g.lit.str); err == nil { - return &gx{sql: quoteStr(d.SQLText()), typ: t, lit: g.lit} - } - } - - return &gx{sql: decCall("from_int", g.sql, decFlag(t)), typ: t} + return intToDec(g, t) case isDec(t) && g.typ.Kind == KindFloat: - if g.floatLiteral() { - if d, err := ParseDecimal(t.Kind, g.lit.str); err == nil { - return &gx{sql: quoteStr(d.SQLText()), typ: t} - } - } - - return &gx{sql: decCall("from_float", g.sql, decFlag(t)), typ: t} + return floatToDec(g, t) case isDec(t) && isDec(g.typ): return &gx{sql: g.sql, typ: t, lit: g.lit} case t.Kind == KindFloat && isDec(g.typ): return &gx{sql: decCall("to_float", g.sql), typ: t} + case t.Kind == KindArray && g.typ.Kind == KindArray && t.Elem != nil && g.typ.Elem != nil && + (isDec(*t.Elem) || isDec(*g.typ.Elem)): + return coerceDecArray(g, t) } return g } +func intToDec(g *gx, t Type) *gx { + if g.lit != nil && g.lit.kind == nInt { + if d, err := ParseDecimal(t.Kind, g.lit.str); err == nil { + return &gx{sql: quoteStr(d.SQLText()), typ: t, lit: g.lit} + } + } + + return &gx{sql: decCall("from_int", g.sql, decFlag(t)), typ: t} +} + +func floatToDec(g *gx, t Type) *gx { + if g.floatLiteral() { + if d, err := ParseDecimal(t.Kind, g.lit.str); err == nil { + return &gx{sql: quoteStr(d.SQLText()), typ: t} + } + } + + return &gx{sql: decCall("from_float", g.sql, decFlag(t)), typ: t} +} + +// coerceDecArray converts the elements of array g to the element type of t when either side is a decimal. +func coerceDecArray(g *gx, t Type) *gx { + from := *g.typ.Elem + if isDec(from) && isDec(*t.Elem) { + return &gx{sql: g.sql, typ: t} + } + + el := toType(&gx{sql: jsonEachValue, typ: from}, *t.Elem) + if el.sql == jsonEachValue { + return g + } + + return &gx{ + sql: "(CASE WHEN " + g.sql + " IS NULL THEN NULL ELSE (SELECT json_group_array(" + el.sql + + ") FROM json_each(" + g.sql + ")) END)", + typ: t, + } +} + +func hasDecDeep(gs []*gx) bool { + for _, g := range gs { + if containsDec(g.typ) { + return true + } + } + + return false +} + +func hasDecArray(gs []*gx) bool { + for _, g := range gs { + if g.typ.Kind == KindArray && g.typ.Elem != nil && isDec(*g.typ.Elem) { + return true + } + } + + return false +} + func hasDec(gs []*gx) bool { for _, g := range gs { if isDec(g.typ) { @@ -68,7 +120,7 @@ func unifyAll(gs []*gx) (Type, []*gx) { t = commonType(t, g.typ) } - if !hasDec(gs) { + if !hasDec(gs) && !hasDecArray(gs) { return t, gs } @@ -98,26 +150,66 @@ func unifyPair(l, r *gx) (*gx, *gx, Type) { return out[0], out[1], t } +func decOperand(t Type) bool { + return t.Kind == KindUnknown || t.Kind == KindInt || t.Kind == KindFloat || isDec(t) +} + +// decMix rejects a decimal combined with a type it does not coerce to. +func decMix(gs ...*gx) error { + if !hasDec(gs) { + return nil + } + + for _, g := range gs { + if !decOperand(g.typ) { + return invalid("Incompatible types %s and %s", firstDecType(gs).Kind.SQLName(), g.typ.Kind.SQLName()) + } + } + + return nil +} + +func firstDecType(gs []*gx) Type { + for _, g := range gs { + if isDec(g.typ) { + return g.typ + } + } + + return Type{} +} + +func noSignature(what string, l, r *gx) error { + return invalid( + "No matching signature for %s for argument types: %s, %s", what, l.typ.Kind.SQLName(), r.typ.Kind.SQLName(), + ) +} + // decOperator compiles an operator with at least one decimal operand; ok is false for operators that are not numeric. -func decOperator(op string, l, r *gx) (*gx, bool) { +func decOperator(op string, l, r *gx) (*gx, bool, error) { switch op { - case "=", "!=", "<", ">", "<=", ">=": - l2, r2, _ := unifyPair(l, r) - - return &gx{sql: "(" + l2.sql + " " + op + " " + r2.sql + ")", typ: scalar(KindBool)}, true - case "+", "-", "*", "/": + case "=", "!=", "<", ">", "<=", ">=", "+", "-", "*", "/": default: - return nil, false + return nil, false, nil + } + + if !decOperand(l.typ) || !decOperand(r.typ) { + return nil, false, noSignature("operator "+op, l, r) } l2, r2, t := unifyPair(l, r) + + if op != "+" && op != "-" && op != "*" && op != "/" { + return &gx{sql: "(" + l2.sql + " " + op + " " + r2.sql + ")", typ: scalar(KindBool)}, true, nil + } + if !isDec(t) { - return nil, false + return nil, false, nil } fn := map[string]string{"+": decAdd, "-": decSub, "*": decMul, "/": decDiv}[op] - return &gx{sql: decCall(fn, l2.sql, r2.sql, decFlag(t)), typ: t}, true + return &gx{sql: decCall(fn, l2.sql, r2.sql, decFlag(t)), typ: t}, true, nil } // constrainDec enforces NUMERIC(P, S) on g when the target type is parameterised. @@ -266,6 +358,10 @@ func decUnaryFn(udf string, safe bool, args []*gx) (*gx, bool, error) { } func decExtreme(udf string, args []*gx) (*gx, bool, error) { + if err := decMix(args...); err != nil { + return nil, false, err + } + ct, us := unifyAll(args) if !isDec(ct) { return nil, false, nil @@ -290,6 +386,10 @@ func decPair(name string, safe bool, args []*gx) (*gx, bool, error) { return nil, false, nil } + if err := decMix(args...); err != nil { + return nil, false, err + } + l, r, t := unifyPair(args[0], args[1]) if !isDec(t) { return nil, false, nil @@ -353,7 +453,7 @@ func decGenerateArraySQL(args []*gx) (*gx, bool, error) { // decCallArgs routes a scalar call with decimal arguments: it returns the finished expression, or the arguments // the generic function should receive (decimals decoded to FLOAT64, or FORMAT's tagged strings). func decCallArgs(udf string, safe bool, args []*gx) ([]*gx, *gx, error) { - if !hasDec(args) { + if !hasDecDeep(args) { if udf == "round" && len(args) > arityTwo { return nil, nil, invalid("ROUND rounding mode requires a NUMERIC or BIGNUMERIC argument") } @@ -361,8 +461,20 @@ func decCallArgs(udf string, safe bool, args []*gx) ([]*gx, *gx, error) { return args, nil, nil } - if udf == "format" { - return formatArgs(args), nil, nil + switch udf { + case "format": + return nil, formatDecimalCall(args), nil + case "array_to_string": + return nil, nil, invalid("No matching signature for function ARRAY_TO_STRING for argument types: %s", + args[0].typ.Kind.SQLName()) + case "array_concat": + _, us := unifyAll(args) + + return us, nil, nil + } + + if !hasDec(args) { + return args, nil, nil } g, ok, err := decFunction(udf, safe, args) @@ -373,18 +485,77 @@ func decCallArgs(udf string, safe bool, args []*gx) ([]*gx, *gx, error) { return floatArgs(args), nil, nil } -// formatArgs tags decimal FORMAT arguments with their kind so the formatter can print them exactly. -func formatArgs(args []*gx) []*gx { - out := make([]*gx, len(args)) +// formatDecimalCall compiles FORMAT with decimal arguments: a mask tells the runtime which arguments are encoded. +func formatDecimalCall(args []*gx) *gx { + sqls := make([]string, len(args)) + mask := make([]byte, 0, len(args)) for i, g := range args { - out[i] = g - if isDec(g.typ) { - out[i] = &gx{sql: decCall("fmt", g.sql, decFlag(g.typ)), typ: scalar(KindString)} + sqls[i] = g.sql + + if i == 0 { + continue + } + + switch g.typ.Kind { + case KindNumeric: + mask = append(mask, 'N') + case KindBigNumeric: + mask = append(mask, 'B') + default: + mask = append(mask, '-') + + if containsDec(g.typ) { + sqls[i] = decimalJSON(g, false) + } } } - return out + return &gx{ + sql: "bq_format_dec(" + quoteStr(string(mask)) + ", " + strings.Join(sqls, ", ") + ")", + typ: scalar(KindString), + } +} + +// decimalJSON renders a value that is or contains decimals as JSON text, decimals as numbers or, when quote, strings. +func decimalJSON(g *gx, quote bool) string { + switch { + case isDec(g.typ): + if quote { + return "json_quote(" + decCall("to_str", g.sql) + ")" + } + + return "json(" + decCall("to_str", g.sql) + ")" + case g.typ.Kind == KindArray && g.typ.Elem != nil && containsDec(g.typ): + el := decimalJSONMember(&gx{sql: jsonEachValue, typ: *g.typ.Elem}, jsonEachValue, quote) + + return "(CASE WHEN " + g.sql + " IS NULL THEN NULL ELSE (SELECT json_group_array(" + el + + ") FROM json_each(" + g.sql + ")) END)" + case g.typ.Kind == KindStruct && containsDec(g.typ): + parts := make([]string, 0, argc2*len(g.typ.Fields)) + + for _, f := range g.typ.Fields { + path := `'$."` + strings.ReplaceAll(strings.ReplaceAll(f.Name, `\`, `\\`), `"`, `\"`) + `"'` + m := decimalJSONMember( + &gx{sql: "json_extract(" + g.sql + ", " + path + ")", typ: f.Type}, + g.sql+" -> "+path, + quote, + ) + parts = append(parts, quoteStr(f.Name), m) + } + + return "(CASE WHEN " + g.sql + " IS NULL THEN NULL ELSE json_object(" + strings.Join(parts, ", ") + ") END)" + } + + return g.sql +} + +func decimalJSONMember(g *gx, raw string, quote bool) string { + if !containsDec(g.typ) { + return "(" + raw + ")" + } + + return decimalJSON(g, quote) } func containsDec(t Type) bool { diff --git a/services/gcpbigquery/bqsql/compile_expr.go b/services/gcpbigquery/bqsql/compile_expr.go index 3387e6a5e9..872faefc95 100644 --- a/services/gcpbigquery/bqsql/compile_expr.go +++ b/services/gcpbigquery/bqsql/compile_expr.go @@ -15,6 +15,9 @@ func commonType(a, b Type) Type { return a case a.IsNumeric() && b.IsNumeric(): return numericCommon(a, b) + case a.Kind == KindArray && b.Kind == KindArray && a.Elem != nil && b.Elem != nil && + (isDec(*a.Elem) || isDec(*b.Elem)): + return arrayOf(commonType(*a.Elem, *b.Elem)) } return a @@ -462,8 +465,8 @@ func (c *compiler) binary(n *node, sc *scope) (*gx, error) { } if isDec(l.typ) || isDec(r.typ) { - if g, ok := decOperator(op, l, r); ok { - return g, nil + if g, ok, derr := decOperator(op, l, r); ok || derr != nil { + return g, derr } if op == "+" || op == "-" || op == "*" || op == "/" { @@ -502,8 +505,14 @@ func (c *compiler) arithmetic(op string, l, r *gx) (*gx, error) { return &gx{sql: "bq_div(" + l.sql + ", " + r.sql + ")", typ: t}, nil case "||": + if isDec(l.typ) || isDec(r.typ) { + return nil, noSignature("operator ||", l, r) + } + if l.typ.Kind == KindArray { - return &gx{sql: "bq_array_concat(" + l.sql + ", " + r.sql + ")", typ: l.typ}, nil + t, us := unifyAll([]*gx{l, r}) + + return &gx{sql: "bq_array_concat(" + us[0].sql + ", " + us[1].sql + ")", typ: t}, nil } t := scalar(KindString) @@ -585,6 +594,10 @@ func (c *compiler) caseExpr(n *node, sc *scope) (*gx, error) { results = append(results, e) } + if err := decMix(results...); err != nil { + return nil, err + } + typ, results := unifyAll(results) var sb strings.Builder @@ -593,6 +606,10 @@ func (c *compiler) caseExpr(n *node, sc *scope) (*gx, error) { if op != nil { ws := append([]*gx{op}, whens...) + if err := decMix(ws...); err != nil { + return nil, err + } + _, ws = unifyAll(ws) op, whens = ws[0], ws[1:] @@ -621,6 +638,10 @@ func (c *compiler) cast(n *node, sc *scope) (*gx, error) { to := *n.castTo fn := "bq_cast" + if containsDec(a.typ) && !isDec(a.typ) && to.Kind == KindString { + return nil, invalid("Invalid cast from %s to %s", a.typ.Kind.SQLName(), to.Kind.SQLName()) + } + if isDec(to) || isDec(a.typ) { if len(n.args) > 1 { return nil, unsupported("CAST ... FORMAT with NUMERIC or BIGNUMERIC") @@ -727,18 +748,26 @@ func (c *compiler) predicate(n *node, sc *scope) (*gx, error) { } if n.kind == nBetween && hasDec(args) { + if g := firstNonNumeric(args); g != nil { + return nil, noSignature("BETWEEN", args[0], g) + } + _, args = unifyAll(args) } switch n.kind { case nLike: + if hasDec(args) { + return nil, noSignature("operator LIKE", args[0], args[1]) + } + return &gx{sql: "(" + not + "bq_like(" + args[0].sql + ", " + args[1].sql + "))", typ: boolT}, nil case nBetween: lo, hi := coerceLiteral(args[1], args[0].typ), coerceLiteral(args[2], args[0].typ) return &gx{sql: "(" + args[0].sql + " " + not + "BETWEEN " + lo.sql + " AND " + hi.sql + ")", typ: boolT}, nil case nIs: - return isPredicate(n, args), nil + return isPredicate(n, args) case nIn: return c.inPredicate(n, args, sc) case nNull, nInt, nFloat, nString, nBytes, nBool, nTyped, nParam, nPath, nStar, nUnary, nBinary, nCall, nCase, @@ -749,7 +778,17 @@ func (c *compiler) predicate(n *node, sc *scope) (*gx, error) { return nil, invalid("unsupported predicate") } -func isPredicate(n *node, args []*gx) *gx { +func firstNonNumeric(gs []*gx) *gx { + for _, g := range gs { + if !decOperand(g.typ) { + return g + } + } + + return nil +} + +func isPredicate(n *node, args []*gx) (*gx, error) { not := "" if n.not { not = "NOT " @@ -763,10 +802,18 @@ func isPredicate(n *node, args []*gx) *gx { op = "IS" } - return &gx{sql: "(" + args[0].sql + " " + op + " " + args[1].sql + ")", typ: boolT} + if hasDec(args) { + if g := firstNonNumeric(args); g != nil { + return nil, noSignature("IS DISTINCT FROM", args[0], g) + } + + _, args = unifyAll(args) + } + + return &gx{sql: "(" + args[0].sql + " " + op + " " + args[1].sql + ")", typ: boolT}, nil } - return &gx{sql: "(" + args[0].sql + " IS " + not + n.name + ")", typ: boolT} + return &gx{sql: "(" + args[0].sql + " IS " + not + n.name + ")", typ: boolT}, nil } func (c *compiler) inPredicate(n *node, args []*gx, sc *scope) (*gx, error) { @@ -779,12 +826,18 @@ func (c *compiler) inPredicate(n *node, args []*gx, sc *scope) (*gx, error) { switch { case n.name == litUnnest: - if el := args[1].typ.Elem; el != nil && isDec(*el) { - args[0] = toType(args[0], *el) + val := &gx{sql: jsonEachValue} + if el := args[1].typ.Elem; el != nil { + val.typ = *el + } + + if isDec(val.typ) || isDec(args[0].typ) { + t, us := unifyAll([]*gx{args[0], val}) + args[0], val = us[0], toType(val, t) } return &gx{ - sql: "(" + args[0].sql + " " + op + " (SELECT \"value\" FROM json_each(" + args[1].sql + ")))", + sql: "(" + args[0].sql + " " + op + " (SELECT " + val.sql + " FROM json_each(" + args[1].sql + ")))", typ: boolT, }, nil case n.query != nil: @@ -797,14 +850,25 @@ func (c *compiler) inPredicate(n *node, args []*gx, sc *scope) (*gx, error) { return nil, invalid("Subquery of type IN must have only one output column") } - if isDec(cq.cols[0].Type) { - args[0] = toType(args[0], cq.cols[0].Type) + if isDec(cq.cols[0].Type) || isDec(args[0].typ) { + col := &gx{sql: quoteIdent(cq.aliases[0]), typ: cq.cols[0].Type} + t, us := unifyAll([]*gx{args[0], col}) + args[0], col = us[0], toType(col, t) + + return &gx{ + sql: "(" + args[0].sql + " " + op + " (SELECT " + col.sql + " FROM (" + cq.sql + ")))", + typ: boolT, + }, nil } return &gx{sql: "(" + args[0].sql + " " + op + " (" + cq.sql + "))", typ: boolT}, nil } if hasDec(args) { + if g := firstNonNumeric(args); g != nil { + return nil, noSignature("IN", args[0], g) + } + _, args = unifyAll(args) } @@ -862,6 +926,10 @@ func (c *compiler) arrayLit(n *node, sc *scope) (*gx, error) { items[i] = g } + if err := decMix(items...); err != nil { + return nil, err + } + elem, items := unifyAll(items) if n.elemType != nil { elem = *n.elemType @@ -963,6 +1031,10 @@ func coerceTo(g *gx, target Type) *gx { switch { case isDec(target) || target.Kind == KindFloat && isDec(g.typ): return constrainDec(toType(g, target), target) + case isDec(g.typ) && (target.Kind == KindString || target.Kind == KindInt): + if out, err := decCast(g, target, false); err == nil { + return out + } case arrayNeedsCoerce(g.typ, target): elem := coerceTo(&gx{sql: `"_ce"."value"`, typ: *g.typ.Elem}, *target.Elem) @@ -991,5 +1063,6 @@ func arrayNeedsCoerce(from, to Type) bool { return false } - return to.Elem.Kind == KindStruct || isDec(*to.Elem) && (from.Elem.Kind != to.Elem.Kind || to.Elem.Prec > 0) + return to.Elem.Kind == KindStruct || isDec(*to.Elem) && (from.Elem.Kind != to.Elem.Kind || to.Elem.Prec > 0) || + isDec(*from.Elem) && !isDec(*to.Elem) } diff --git a/services/gcpbigquery/bqsql/compile_func.go b/services/gcpbigquery/bqsql/compile_func.go index f4e40cf09c..76ed568b32 100644 --- a/services/gcpbigquery/bqsql/compile_func.go +++ b/services/gcpbigquery/bqsql/compile_func.go @@ -257,6 +257,10 @@ func addMiscFuncs(t map[string]*fnDef) { } if hasDec(a) { + if err = decMix(a...); err != nil { + return nil, err + } + _, u := unifyAll(a) return &gx{sql: "NULLIF(" + u[0].sql + ", " + u[1].sql + ")", typ: u[0].typ}, nil @@ -394,6 +398,10 @@ func genIf(c *compiler, n *node, sc *scope) (*gx, error) { return nil, err } + if err = decMix(a[1:]...); err != nil { + return nil, err + } + typ, res := unifyAll(a[1:]) return &gx{ @@ -408,6 +416,10 @@ func genCoalesce(c *compiler, n *node, sc *scope) (*gx, error) { return nil, err } + if err = decMix(a...); err != nil { + return nil, err + } + typ, a := unifyAll(a) parts := make([]string, len(a)) @@ -433,7 +445,7 @@ func genToJSONString(c *compiler, n *node, sc *scope) (*gx, error) { switch x.typ.Kind { case KindStruct, KindArray: if containsDec(x.typ) { - return &gx{sql: "bq_dec_json_nested(json(" + x.sql + "))", typ: scalar(KindString)}, nil + return &gx{sql: "CAST(" + decimalJSON(x, false) + " AS TEXT)", typ: scalar(KindString)}, nil } return &gx{sql: "CAST(json(" + x.sql + ") AS TEXT)", typ: scalar(KindString)}, nil diff --git a/services/gcpbigquery/bqsql/decimal_format.go b/services/gcpbigquery/bqsql/decimal_format.go index 6d9a568b55..417f18fb37 100644 --- a/services/gcpbigquery/bqsql/decimal_format.go +++ b/services/gcpbigquery/bqsql/decimal_format.go @@ -8,7 +8,6 @@ import ( ) const ( - fmtDecimalTag = "\x01" defaultFormatPrec = 6 sciLowExp = -4 minExpDigits = 2 @@ -54,14 +53,11 @@ func parseDecimalFlags(flags string) decFormatSpec { return sp } -// formatDecimal prints one FORMAT argument tagged by dec_fmt; %f, %e and %g are computed on exact digits. -func formatDecimal(spec byte, flags, tagged string) (string, error) { - kind := KindNumeric - if strings.HasPrefix(tagged, "B") { - kind = KindBigNumeric - } +// formatDecimal prints one decimal FORMAT argument; %f, %e and %g are computed on exact digits. +func formatDecimal(spec byte, flags string, arg decFormatArg) (string, error) { + kind := arg.kind - d, err := ParseDecimal(kind, tagged[1:]) + d, err := ParseDecimal(kind, arg.text) if err != nil { return "", decFail(err) } diff --git a/services/gcpbigquery/bqsql/decimal_fuzz_test.go b/services/gcpbigquery/bqsql/decimal_fuzz_test.go new file mode 100644 index 0000000000..4549c38dee --- /dev/null +++ b/services/gcpbigquery/bqsql/decimal_fuzz_test.go @@ -0,0 +1,91 @@ +package bqsql_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/gcpbigquery/bqsql" +) + +func FuzzParseDecimal(f *testing.F) { + for _, s := range []string{"0", "-1.5", "1e9", "1e-40", ".5", "5.", "+7", "1E+3", "", "x", bigMax, bigMin, "1e99999"} { + f.Add(s, true) + } + + f.Fuzz(func(t *testing.T, s string, big bool) { + k := bqsql.KindNumeric + if big { + k = bqsql.KindBigNumeric + } + + d, err := bqsql.ParseDecimal(k, s) + if err != nil { + require.ErrorIs(t, err, bqsql.ErrDecimal) + + return + } + + again, err := bqsql.ParseDecimal(k, d.String()) + require.NoError(t, err) + assert.Zero(t, d.Cmp(again)) + assert.Equal(t, d.String(), again.String()) + + back, err := bqsql.DecodeSQLText(d.SQLText(), k) + require.NoError(t, err) + assert.Equal(t, d.String(), back.String()) + assert.True(t, bqsql.IsSQLText(d.SQLText())) + }) +} + +func FuzzDecodeSQLText(f *testing.F) { + f.Add("#" + strings.Repeat("0", 64)) + f.Add("#" + strings.Repeat("f", 64)) + f.Add("#8" + strings.Repeat("0", 63)) + f.Add("#8" + strings.Repeat("F", 63)) + f.Add("") + + f.Fuzz(func(t *testing.T, s string) { + d, err := bqsql.DecodeSQLText(s, bqsql.KindBigNumeric) + if err != nil { + return + } + + assert.True(t, bqsql.IsSQLText(s)) + assert.Equal(t, s, d.SQLText(), "an accepted encoding is canonical") + }) +} + +func TestDecimalSQLTextCaseAndBoundaries(t *testing.T) { + t.Parallel() + + upper := strings.ToUpper(dec(t, bqsql.KindNumeric, "255").SQLText()[1:]) + _, err := bqsql.DecodeSQLText("#"+upper, bqsql.KindNumeric) + require.ErrorIs(t, err, bqsql.ErrDecimal) + assert.False(t, bqsql.IsSQLText("#"+upper)) + assert.False(t, bqsql.IsSQLText(strings.ToUpper(dec(t, bqsql.KindNumeric, "1").SQLText()))) + + ulp := "0.00000000000000000000000000000000000001" + ordered := []string{bigMin, "-" + ulp, "0", ulp, bigMax} + + prev := "" + + for i, s := range ordered { + enc := dec(t, bqsql.KindBigNumeric, s).SQLText() + assert.Len(t, enc, 65) + + if i > 0 { + assert.Less(t, prev, enc, s) + } + + prev = enc + } + + assert.Equal(t, "#"+strings.Repeat("0", 64), dec(t, bqsql.KindBigNumeric, bigMin).SQLText()) + assert.Equal(t, "#"+strings.Repeat("f", 64), dec(t, bqsql.KindBigNumeric, bigMax).SQLText()) + assert.Equal(t, dec(t, bqsql.KindNumeric, "1.5").SQLText(), dec(t, bqsql.KindBigNumeric, "1.5").SQLText()) + assert.Equal(t, dec(t, bqsql.KindNumeric, "0").SQLText(), dec(t, bqsql.KindNumeric, "-0").SQLText()) + assert.Equal(t, "#8"+strings.Repeat("0", 63), dec(t, bqsql.KindNumeric, "0").SQLText()) +} diff --git a/services/gcpbigquery/bqsql/decimal_oracle_test.go b/services/gcpbigquery/bqsql/decimal_oracle_test.go new file mode 100644 index 0000000000..98d447040d --- /dev/null +++ b/services/gcpbigquery/bqsql/decimal_oracle_test.go @@ -0,0 +1,534 @@ +package bqsql_test + +import ( + "math/big" + "math/rand/v2" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/gcpbigquery/bqsql" +) + +type oracleKind struct { + min, max *big.Int + scale int + kind bqsql.Kind +} + +func oracleKinds() map[string]oracleKind { + p10 := func(n int) *big.Int { return new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(n)), nil) } + lim := new(big.Int).Lsh(big.NewInt(1), 255) + + return map[string]oracleKind{ + "numeric": { + min: new(big.Int).Neg(new(big.Int).Sub(p10(38), big.NewInt(1))), + max: new(big.Int).Sub(p10(38), big.NewInt(1)), scale: 9, kind: bqsql.KindNumeric, + }, + "bignumeric": { + min: new(big.Int).Neg(lim), max: new(big.Int).Sub(lim, big.NewInt(1)), scale: 38, + kind: bqsql.KindBigNumeric, + }, + } +} + +func ratOf(t *testing.T, s string) *big.Rat { + t.Helper() + + r, ok := new(big.Rat).SetString(s) + require.True(t, ok, s) + + return r +} + +func roundHalfAway(r *big.Rat) *big.Int { + num, den := new(big.Int).Set(r.Num()), r.Denom() + neg := num.Sign() < 0 + num.Abs(num) + + q, rem := new(big.Int).QuoRem(num, den, new(big.Int)) + if rem.Lsh(rem, 1).Cmp(den) >= 0 { + q.Add(q, big.NewInt(1)) + } + + if neg { + q.Neg(q) + } + + return q +} + +func (k oracleKind) unscaled(r *big.Rat) (*big.Int, bool) { + n := roundHalfAway( + new(big.Rat).Mul(r, new(big.Rat).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(k.scale)), nil))), + ) + + return n, n.Cmp(k.min) >= 0 && n.Cmp(k.max) <= 0 +} + +func (k oracleKind) canonical(n *big.Int) string { + r := new(big.Rat).SetFrac(n, new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(k.scale)), nil)) + s := r.FloatString(k.scale) + + if strings.Contains(s, ".") { + s = strings.TrimRight(strings.TrimRight(s, "0"), ".") + } + + if s == "-0" { + return "0" + } + + return s +} + +func truncRat(r *big.Rat) *big.Rat { + return new(big.Rat).SetInt(new(big.Int).Quo(r.Num(), r.Denom())) +} + +func floorRat(r *big.Rat) *big.Rat { + q := new(big.Int).Div(r.Num(), r.Denom()) + + return new(big.Rat).SetInt(q) +} + +type binOracle struct { + got func(a, b bqsql.Decimal) (bqsql.Decimal, error) + want func(a, b *big.Rat) (*big.Rat, bool) + name string +} + +func binOracles() []binOracle { + return []binOracle{ + {bqsql.Decimal.Add, func(a, b *big.Rat) (*big.Rat, bool) { return new(big.Rat).Add(a, b), true }, "add"}, + {bqsql.Decimal.Sub, func(a, b *big.Rat) (*big.Rat, bool) { return new(big.Rat).Sub(a, b), true }, "sub"}, + {bqsql.Decimal.Mul, func(a, b *big.Rat) (*big.Rat, bool) { return new(big.Rat).Mul(a, b), true }, "mul"}, + {bqsql.Decimal.Quo, func(a, b *big.Rat) (*big.Rat, bool) { + if b.Sign() == 0 { + return nil, false + } + + return new(big.Rat).Quo(a, b), true + }, "quo"}, + {bqsql.Decimal.Mod, func(a, b *big.Rat) (*big.Rat, bool) { + if b.Sign() == 0 { + return nil, false + } + + q := truncRat(new(big.Rat).Quo(a, b)) + + return new(big.Rat).Sub(a, new(big.Rat).Mul(q, b)), true + }, "mod"}, + {bqsql.Decimal.IntDiv, func(a, b *big.Rat) (*big.Rat, bool) { + if b.Sign() == 0 { + return nil, false + } + + return truncRat(new(big.Rat).Quo(a, b)), true + }, "intdiv"}, + } +} + +func checkBinary(t *testing.T, name string, ok oracleKind, op binOracle, as, bs string) { + t.Helper() + + a, err := bqsql.ParseDecimal(ok.kind, as) + require.NoError(t, err, as) + + b, err := bqsql.ParseDecimal(ok.kind, bs) + require.NoError(t, err, bs) + + ra, rb := ratOf(t, a.String()), ratOf(t, b.String()) + want, valid := op.want(ra, rb) + got, gerr := op.got(a, b) + + if !valid { + require.Error(t, gerr, "%s %s %s %s", name, op.name, as, bs) + + return + } + + n, inRange := ok.unscaled(want) + if !inRange { + require.Error(t, gerr, "%s %s(%s, %s) should overflow", name, op.name, as, bs) + assert.ErrorIs(t, gerr, bqsql.ErrDecimal) + + return + } + + require.NoError(t, gerr, "%s %s(%s, %s)", name, op.name, as, bs) + assert.Equal(t, ok.canonical(n), got.String(), "%s %s(%s, %s)", name, op.name, as, bs) + assert.Equal(t, ok.kind, got.Kind()) +} + +func oracleHardInputs() map[string][]string { + return map[string][]string{ + "numeric": { + "0", "1", "-1", "0.5", "-0.5", "0.000000001", "-0.000000001", "0.0000000005", "0.000000005", "2.5", "-2.5", + "0.3333333333", "99999999999999999999999999999.999999999", "-99999999999999999999999999999.999999999", + "99999999999999999999999999999.999999998", "1e20", "-1e-9", "123456789.123456789", "3", "-3", "7", "-7", + "0.1", "0.2", "1e19", "4.5", "-4.5", "1.0000000005", "-1.0000000005", + }, + "bignumeric": { + "0", "1", "-1", "0.5", "-0.5", "0.00000000000000000000000000000000000001", + "-0.00000000000000000000000000000000000001", "0.000000000000000000000000000000000000005", + "578960446186580977117854925043439539266.34992332820282019728792003956564819967", + "-578960446186580977117854925043439539266.34992332820282019728792003956564819968", + "578960446186580977117854925043439539266.34992332820282019728792003956564819966", + "-578960446186580977117854925043439539266.34992332820282019728792003956564819967", + "1e19", "1e20", "-1e19", "3", "-3", "7", "-7", "2.5", "-2.5", "0.33333333333333333333333333333333333333", + "99999999999999999999999999999999999999.99999999999999999999999999999999999999", "12345678901234567890.5", + }, + } +} + +func TestDecimalOracleHardCases(t *testing.T) { + t.Parallel() + + for name, ok := range oracleKinds() { + inputs := oracleHardInputs()[name] + + for _, op := range binOracles() { + t.Run(name+"/"+op.name, func(t *testing.T) { + t.Parallel() + + for _, a := range inputs { + for _, b := range inputs { + checkBinary(t, name, ok, op, a, b) + } + } + }) + } + } +} + +func oracleRandom(r *rand.Rand, ok oracleKind) string { + maxInt := 29 + if ok.scale == 38 { + maxInt = 38 + } + + intDigits := r.IntN(maxInt + 1) + if r.IntN(4) == 0 { + intDigits = r.IntN(4) + } + + digits := func(n int) string { + b := make([]byte, n) + for i := range b { + b[i] = byte('0' + r.IntN(10)) + } + + return string(b) + } + + s := "0" + if intDigits > 0 { + s = digits(intDigits) + } + + if frac := r.IntN(ok.scale + 1); frac > 0 { + s += "." + digits(frac) + } + + if r.IntN(2) == 0 { + s = "-" + s + } + + return s +} + +func TestDecimalOracleRandom(t *testing.T) { + t.Parallel() + + for name, ok := range oracleKinds() { + for _, op := range binOracles() { + t.Run(name+"/"+op.name, func(t *testing.T) { + t.Parallel() + + r := rand.New(rand.NewPCG(7, uint64(len(op.name)))) + + for range 600 { + checkBinary(t, name, ok, op, oracleRandom(r, ok), oracleRandom(r, ok)) + } + }) + } + } +} + +func TestDecimalOracleUnary(t *testing.T) { + t.Parallel() + + type unary struct { + got func(d bqsql.Decimal) (bqsql.Decimal, error) + want func(r *big.Rat) *big.Rat + name string + } + + ops := []unary{ + {bqsql.Decimal.Neg, func(r *big.Rat) *big.Rat { return new(big.Rat).Neg(r) }, "neg"}, + {bqsql.Decimal.Abs, func(r *big.Rat) *big.Rat { return new(big.Rat).Abs(r) }, "abs"}, + {func(d bqsql.Decimal) (bqsql.Decimal, error) { return d.Trunc(0), nil }, truncRat, "trunc0"}, + {bqsql.Decimal.Floor, floorRat, "floor"}, + {bqsql.Decimal.Ceil, func(r *big.Rat) *big.Rat { + return new(big.Rat).Neg(floorRat(new(big.Rat).Neg(r))) + }, "ceil"}, + { + func(d bqsql.Decimal) (bqsql.Decimal, error) { return d.Round(0, bqsql.RoundHalfAwayFromZero) }, + func(r *big.Rat) *big.Rat { + return new(big.Rat).SetInt(roundHalfAway(r)) + }, + "round0", + }, + } + + for name, ok := range oracleKinds() { + for _, op := range ops { + t.Run(name+"/"+op.name, func(t *testing.T) { + t.Parallel() + + for _, in := range oracleHardInputs()[name] { + d, err := bqsql.ParseDecimal(ok.kind, in) + require.NoError(t, err) + + want := op.want(ratOf(t, d.String())) + n, inRange := ok.unscaled(want) + got, gerr := op.got(d) + + if !inRange { + require.Error(t, gerr, "%s(%s)", op.name, in) + + continue + } + + require.NoError(t, gerr, "%s(%s)", op.name, in) + assert.Equal(t, ok.canonical(n), got.String(), "%s(%s)", op.name, in) + } + }) + } + } +} + +func TestDecimalOracleRound(t *testing.T) { + t.Parallel() + + for name, ok := range oracleKinds() { + t.Run(name, func(t *testing.T) { + t.Parallel() + + for _, in := range oracleHardInputs()[name] { + for digits := -40; digits <= ok.scale+2; digits++ { + d, err := bqsql.ParseDecimal(ok.kind, in) + require.NoError(t, err) + + unit := new(big.Rat).SetFrac(big.NewInt(1), big.NewInt(1)) + if digits >= 0 { + unit.SetFrac(big.NewInt(1), new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(digits)), nil)) + } else { + unit.SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(-digits)), nil)) + } + + scaled := new(big.Rat).Quo(ratOf(t, d.String()), unit) + want := new(big.Rat).Mul(new(big.Rat).SetInt(roundHalfAway(scaled)), unit) + wn, inRange := ok.unscaled(want) + got, gerr := d.Round(digits, bqsql.RoundHalfAwayFromZero) + + if !inRange { + require.Error(t, gerr, "ROUND(%s,%d)", in, digits) + + continue + } + + require.NoError(t, gerr, "ROUND(%s,%d)", in, digits) + assert.Equal(t, ok.canonical(wn), got.String(), "ROUND(%s,%d)", in, digits) + + tr := new(big.Rat).Mul(truncRat(new(big.Rat).Quo(ratOf(t, d.String()), unit)), unit) + tn, _ := ok.unscaled(tr) + assert.Equal(t, ok.canonical(tn), d.Trunc(digits).String(), "TRUNC(%s,%d)", in, digits) + } + } + }) + } +} + +func TestDecimalRangeBoundaries(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + text string + kind bqsql.Kind + valid bool + }{ + {"numeric max", "99999999999999999999999999999.999999999", bqsql.KindNumeric, true}, + {"numeric over", "100000000000000000000000000000", bqsql.KindNumeric, false}, + {"numeric min", "-99999999999999999999999999999.999999999", bqsql.KindNumeric, true}, + {"numeric under", "-100000000000000000000000000000", bqsql.KindNumeric, false}, + {"numeric round up to over", "99999999999999999999999999999.9999999995", bqsql.KindNumeric, false}, + {"big max", bigMax, bqsql.KindBigNumeric, true}, + {"big over", bigOver, bqsql.KindBigNumeric, false}, + {"big min", bigMin, bqsql.KindBigNumeric, true}, + {"big under", bigUnder, bqsql.KindBigNumeric, false}, + { + "big documented max", + "5.7896044618658097711785492504343953926634992332820282019728792003956564819967E+38", + bqsql.KindBigNumeric, + true, + }, + { + "big documented min", + "-5.7896044618658097711785492504343953926634992332820282019728792003956564819968E+38", + bqsql.KindBigNumeric, + true, + }, + { + "big documented over", + "5.7896044618658097711785492504343953926634992332820282019728792003956564819968E+38", + bqsql.KindBigNumeric, + false, + }, + {"big round up to over", bigMax + "5", bqsql.KindBigNumeric, false}, + {"exp small", "1.5e-9", bqsql.KindNumeric, true}, + {"exp neg", "-12E+3", bqsql.KindNumeric, true}, + {"exp huge", "1e999", bqsql.KindNumeric, false}, + {"exp over bound", "1e1025", bqsql.KindNumeric, false}, + {"exp tiny", "1e-1000", bqsql.KindNumeric, true}, + {"over scale rounds", "0.0000000005", bqsql.KindNumeric, true}, + {"leading plus", "+1.5", bqsql.KindNumeric, true}, + {"bare dot", ".", bqsql.KindNumeric, false}, + {"dot only digits", ".5", bqsql.KindNumeric, true}, + {"trailing dot", "5.", bqsql.KindNumeric, true}, + {"two dots", "1.2.3", bqsql.KindNumeric, false}, + {"double sign", "--1", bqsql.KindNumeric, false}, + {"empty exponent", "1e", bqsql.KindNumeric, false}, + {"hex", "0x10", bqsql.KindNumeric, false}, + {"inf", "inf", bqsql.KindNumeric, false}, + {"nan", "NaN", bqsql.KindNumeric, false}, + {"underscore", "1_000", bqsql.KindNumeric, false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + d, err := bqsql.ParseDecimal(tt.kind, tt.text) + if !tt.valid { + require.Error(t, err) + + return + } + + require.NoError(t, err) + + if tt.name == "big max" || tt.name == "big min" || tt.name == "numeric max" { + assert.Equal(t, tt.text, d.String()) + } + }) + } + + d, err := bqsql.ParseDecimal(bqsql.KindBigNumeric, bigMax) + require.NoError(t, err) + + _, err = d.Add(dec(t, bqsql.KindBigNumeric, "0.00000000000000000000000000000000000001")) + require.Error(t, err) + + m, err := bqsql.ParseDecimal(bqsql.KindBigNumeric, bigMin) + require.NoError(t, err) + + _, err = m.Neg() + require.Error(t, err, "negating the minimum overflows") + + _, err = m.Abs() + require.Error(t, err) + + _, err = m.Sub(dec(t, bqsql.KindBigNumeric, "0.00000000000000000000000000000000000001")) + require.Error(t, err) +} + +func TestDecimalCanonicalString(t *testing.T) { + t.Parallel() + + tests := []struct { + in string + want string + kind bqsql.Kind + }{ + {"-0", "0", bqsql.KindNumeric}, + {"-0.0000000001", "0", bqsql.KindNumeric}, + {"1.500", "1.5", bqsql.KindNumeric}, + {"100", "100", bqsql.KindNumeric}, + {"0.000000001", "0.000000001", bqsql.KindNumeric}, + {"1e2", "100", bqsql.KindNumeric}, + {"-1.0E-1", "-0.1", bqsql.KindNumeric}, + {"00012.3400", "12.34", bqsql.KindBigNumeric}, + { + "-0.00000000000000000000000000000000000001", + "-0.00000000000000000000000000000000000001", + bqsql.KindBigNumeric, + }, + } + + for _, tt := range tests { + t.Run(tt.in, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, tt.want, dec(t, tt.kind, tt.in).String()) + }) + } +} + +func TestDecimalConstrainOracle(t *testing.T) { + t.Parallel() + + tests := []struct { + in string + want string + p, s int + kind bqsql.Kind + wantErr bool + }{ + {"1.125", "1.13", 5, 2, bqsql.KindNumeric, false}, + {"-1.125", "-1.13", 5, 2, bqsql.KindNumeric, false}, + {"999.995", "", 5, 2, bqsql.KindNumeric, true}, + {"999.994", "999.99", 5, 2, bqsql.KindNumeric, false}, + {"-999.995", "", 5, 2, bqsql.KindNumeric, true}, + {"12345", "12345", 5, 0, bqsql.KindNumeric, false}, + {"123456", "", 5, 0, bqsql.KindNumeric, true}, + {"0.5", "1", 1, 0, bqsql.KindNumeric, false}, + {"9.5", "", 1, 0, bqsql.KindNumeric, true}, + {"1", "1", 38, 9, bqsql.KindNumeric, false}, + {"1", "", 39, 9, bqsql.KindNumeric, true}, + {"1", "", 9, 9, bqsql.KindNumeric, true}, + {"0.1", "", 10, 10, bqsql.KindNumeric, true}, + {"0.1", "0.1", 9, 9, bqsql.KindNumeric, false}, + {"1", "", 10, 12, bqsql.KindNumeric, true}, + { + "1.00000000000000000000000000000000000005", + "1.00000000000000000000000000000000000005", + 76, + 38, + bqsql.KindBigNumeric, + false, + }, + {"1", "1", 76, 38, bqsql.KindBigNumeric, false}, + {"1", "", 77, 38, bqsql.KindBigNumeric, true}, + } + + for _, tt := range tests { + t.Run(tt.in+"/"+strconv.Itoa(tt.p)+"_"+strconv.Itoa(tt.s), func(t *testing.T) { + t.Parallel() + + got, err := dec(t, tt.kind, tt.in).Constrain(tt.p, tt.s) + if tt.wantErr { + require.Error(t, err) + + return + } + + require.NoError(t, err) + assert.Equal(t, tt.want, got.String()) + }) + } +} diff --git a/services/gcpbigquery/bqsql/numeric_aggregate_test.go b/services/gcpbigquery/bqsql/numeric_aggregate_test.go new file mode 100644 index 0000000000..50a6e05fb3 --- /dev/null +++ b/services/gcpbigquery/bqsql/numeric_aggregate_test.go @@ -0,0 +1,316 @@ +package bqsql_test + +import ( + "fmt" + "math/big" + "math/rand/v2" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/gcpbigquery/bqsql" +) + +type frameCase struct { + lo, hi func(i int) int + sql string +} + +func frameCases() []frameCase { + const unb = 1 << 30 + + return []frameCase{ + {func(i int) int { return i - 1 }, func(i int) int { return i }, "ROWS BETWEEN 1 PRECEDING AND CURRENT ROW"}, + { + func(i int) int { return i - 2 }, + func(i int) int { return i + 1 }, + "ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING", + }, + { + func(int) int { return -unb }, + func(i int) int { return i }, + "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW", + }, + { + func(i int) int { return i }, + func(int) int { return unb }, + "ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING", + }, + { + func(i int) int { return i + 1 }, + func(i int) int { return i + 3 }, + "ROWS BETWEEN 1 FOLLOWING AND 3 FOLLOWING", + }, + { + func(i int) int { return i - 3 }, + func(i int) int { return i - 1 }, + "ROWS BETWEEN 3 PRECEDING AND 1 PRECEDING", + }, + { + func(int) int { return -unb }, + func(int) int { return unb }, + "ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING", + }, + } +} + +func windowCatalog(t *testing.T, vals []string, nullEvery int) *fakeCatalog { + t.Helper() + + fs := fieldsJSON( + t, + `[{"name":"id","type":"INTEGER"},{"name":"n","type":"NUMERIC"},{"name":"b","type":"BIGNUMERIC"}]`, + ) + + var sb strings.Builder + + sb.WriteString("[") + + for i, v := range vals { + if i > 0 { + sb.WriteString(",") + } + + cell := `"` + v + `"` + if nullEvery > 0 && i%nullEvery == nullEvery-1 { + cell = "null" + } + + fmt.Fprintf(&sb, `{"id":%d,"n":%s,"b":%s}`, i, cell, cell) + } + + sb.WriteString("]") + + return &fakeCatalog{tables: map[string]*bqsql.TableData{ + "ds.w": { + Ref: bqsql.TableRef{Project: "p", Dataset: "ds", Table: "w"}, + Fields: fs, + Rows: rowsJSON(t, fs, sb.String()), + }, + }} +} + +func windowValue(r *rand.Rand) string { + digits := func(n int) string { + b := make([]byte, n) + for i := range b { + b[i] = byte('0' + r.IntN(10)) + } + + return string(b) + } + + s := "0" + if n := r.IntN(25); n > 0 { + s = digits(n) + } + + if f := r.IntN(10); f > 0 { + s += "." + digits(f) + } + + if r.IntN(2) == 0 { + s = "-" + s + } + + return s +} + +func TestNumericWindowFramesMatchBruteForce(t *testing.T) { + t.Parallel() + + r := rand.New(rand.NewPCG(11, 13)) + nk := oracleKinds()["numeric"] + vals := make([]string, 40) + + for i := range vals { + vals[i] = windowValue(r) + } + + for _, nullEvery := range []int{0, 3} { + cat := windowCatalog(t, vals, nullEvery) + + for _, fc := range frameCases() { + t.Run(fmt.Sprintf("%d/%s", nullEvery, fc.sql), func(t *testing.T) { + t.Parallel() + + sql := "SELECT id, SUM(n) OVER (ORDER BY id " + fc.sql + "), AVG(n) OVER (ORDER BY id " + fc.sql + + "), SUM(b) OVER (ORDER BY id " + fc.sql + ") FROM w ORDER BY id" + + res, err := runSQL(t, cat, sql) + require.NoError(t, err) + + got := wireRows(res) + require.Len(t, got, len(vals)) + + for i := range vals { + sum, cnt := new(big.Rat), 0 + + for j := max(fc.lo(i), 0); j <= min(fc.hi(i), len(vals)-1); j++ { + if nullEvery > 0 && j%nullEvery == nullEvery-1 { + continue + } + + sum.Add(sum, ratOf(t, vals[j])) + + cnt++ + } + + if cnt == 0 { + assert.Equal(t, []any{strconv.Itoa(i), nil, nil, nil}, got[i], "row %d", i) + + continue + } + + sn, _ := nk.unscaled(sum) + avg, _ := nk.unscaled(new(big.Rat).Quo(sum, big.NewRat(int64(cnt), 1))) + bk := oracleKinds()["bignumeric"] + sb, _ := bk.unscaled(sum) + + assert.Equal( + t, + []any{strconv.Itoa(i), nk.canonical(sn), nk.canonical(avg), bk.canonical(sb)}, + got[i], + "row %d frame %s", + i, + fc.sql, + ) + } + }) + } + } +} + +func TestNumericAggregateEdges(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + sql string + err string + want [][]any + }{ + { + "avg tie up", + "SELECT AVG(x) FROM UNNEST([NUMERIC '0.000000001', NUMERIC '0']) x", + "", + [][]any{{"0.000000001"}}, + }, + { + "avg tie down", + "SELECT AVG(x) FROM UNNEST([NUMERIC '-0.000000001', NUMERIC '0']) x", + "", + [][]any{{"-0.000000001"}}, + }, + { + "avg third", + "SELECT AVG(x) FROM UNNEST([NUMERIC '1', NUMERIC '1', NUMERIC '2']) x", + "", + [][]any{{"1.333333333"}}, + }, + { + "avg big", + "SELECT AVG(x) FROM UNNEST([BIGNUMERIC '1', BIGNUMERIC '1', BIGNUMERIC '2']) x", + "", + [][]any{{"1.33333333333333333333333333333333333333"}}, + }, + {"empty", "SELECT SUM(x), AVG(x) FROM UNNEST(ARRAY[]) x", "", [][]any{{nil, nil}}}, + { + "all null", + "SELECT SUM(x), AVG(x), MIN(x), MAX(x) FROM UNNEST([CAST(NULL AS NUMERIC)]) x", + "", + [][]any{{nil, nil, nil, nil}}, + }, + { + "skips null", + "SELECT SUM(x), AVG(x), COUNT(x) FROM UNNEST([NUMERIC '1', NULL, NUMERIC '2']) x", + "", + [][]any{{"3", "1.5", "2"}}, + }, + {"distinct", "SELECT SUM(DISTINCT x), AVG(DISTINCT x), COUNT(DISTINCT x) " + + "FROM UNNEST([NUMERIC '1', NUMERIC '1.0', NUMERIC '2']) x", "", [][]any{{"3", "1.5", "2"}}}, + { + "overflow", + "SELECT SUM(x) FROM UNNEST([NUMERIC '99999999999999999999999999999.999999999', NUMERIC '0.000000001']) x", + "numeric overflow", + nil, + }, + { + "big overflow", + "SELECT SUM(x) FROM UNNEST([BIGNUMERIC '" + bigMax + "', BIGNUMERIC '1']) x", + "BIGNUMERIC overflow", + nil, + }, + { + "minmax type", + "SELECT MIN(x), MAX(x) FROM UNNEST([NUMERIC '1.5', NUMERIC '-2']) x", + "", + [][]any{{"-2", "1.5"}}, + }, + { + "count distinct kinds", + "SELECT COUNT(DISTINCT x) FROM UNNEST([CAST(NUMERIC '1.5' AS BIGNUMERIC), BIGNUMERIC '1.5', BIGNUMERIC '2']) x", + "", + [][]any{{"2"}}, + }, + { + "count distinct union", + "SELECT COUNT(DISTINCT x) FROM (SELECT NUMERIC '1.5' AS x UNION ALL SELECT BIGNUMERIC '1.5' UNION ALL SELECT 1.5)", + "", + [][]any{{"1"}}, + }, + {"sum int numeric", "SELECT SUM(x) FROM UNNEST([1, 2, 3]) x", "", [][]any{{"6"}}}, + { + "stddev", + "SELECT STDDEV(x), VARIANCE(x) FROM UNNEST([NUMERIC '2', NUMERIC '4']) x", + "", + [][]any{{"1.4142135623730951", "2.0"}}, + }, + {"stddev single", "SELECT STDDEV(x), STDDEV_POP(x) FROM UNNEST([NUMERIC '2']) x", "", [][]any{{nil, "0.0"}}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + res, err := runSQL(t, numericCatalog(t), tt.sql) + if tt.err != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.err) + + return + } + + require.NoError(t, err) + assert.Equal(t, tt.want, wireRows(res)) + }) + } +} + +func TestNormalizeRowsLegacyCells(t *testing.T) { + t.Parallel() + + fs := fieldsJSON(t, `[ + {"name":"n","type":"NUMERIC"}, + {"name":"b","type":"BIGNUMERIC"}, + {"name":"arr","type":"NUMERIC","mode":"REPEATED"}, + {"name":"rec","type":"RECORD","fields":[{"name":"x","type":"NUMERIC"},{"name":"s","type":"STRING"}]} + ]`) + + rows := [][]any{ + {float64(0.1), "2.250000000", []any{float64(1.5), "2", nil}, []any{int64(3), "7"}}, + {"5e-1", float64(1e21), []any{}, []any{"x", "keep"}}, + {nil, nil, nil, nil}, + } + + bqsql.NormalizeRows(fs, rows) + + assert.Equal(t, [][]any{ + {"0.1", "2.25", []any{"1.5", "2", nil}, []any{"3", "7"}}, + {"0.5", "1000000000000000000000", []any{}, []any{"x", "keep"}}, + {nil, nil, nil, nil}, + }, rows) +} diff --git a/services/gcpbigquery/bqsql/numeric_coercion_test.go b/services/gcpbigquery/bqsql/numeric_coercion_test.go new file mode 100644 index 0000000000..40744b2f8d --- /dev/null +++ b/services/gcpbigquery/bqsql/numeric_coercion_test.go @@ -0,0 +1,265 @@ +package bqsql_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNonNumericQueriesUnchanged(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + sql string + typ string + want []any + }{ + {"float add", "SELECT 0.1 + 0.2", "FLOAT", []any{"0.30000000000000004"}}, + {"int div", "SELECT 1 / 3", "FLOAT", []any{"0.3333333333333333"}}, + {"int div exact", "SELECT 7 / 2", "FLOAT", []any{"3.5"}}, + {"neg int div", "SELECT -7 / 2", "FLOAT", []any{"-3.5"}}, + {"float mul", "SELECT 0.1 * 3", "FLOAT", []any{"0.30000000000000004"}}, + {"float sub", "SELECT 10 - 0.5", "FLOAT", []any{"9.5"}}, + {"float one", "SELECT 2 * 0.5", "FLOAT", []any{"1.0"}}, + {"exp literal", "SELECT 1e2 + 1", "FLOAT", []any{"101.0"}}, + {"int mul", "SELECT 2 * 3", "INTEGER", []any{"6"}}, + {"int sub", "SELECT 9223372036854775807 - 1", "INTEGER", []any{"9223372036854775806"}}, + {"div fn", "SELECT DIV(7, 2)", "INTEGER", []any{"3"}}, + {"mod fn", "SELECT MOD(7, -2)", "INTEGER", []any{"1"}}, + {"int float eq", "SELECT 7 = 7.0", "BOOLEAN", []any{"true"}}, + {"abs", "SELECT ABS(-2.5)", "FLOAT", []any{"2.5"}}, + {"round", "SELECT ROUND(2.5)", "FLOAT", []any{"3.0"}}, + {"sqrt", "SELECT SQRT(2)", "FLOAT", []any{"1.4142135623730951"}}, + {"greatest", "SELECT GREATEST(1, 2.5)", "FLOAT", []any{"2.5"}}, + {"if", "SELECT IF(TRUE, 1, 2.5)", "FLOAT", []any{"1.0"}}, + {"coalesce", "SELECT COALESCE(1, 2.5)", "FLOAT", []any{"1.0"}}, + {"case", "SELECT CASE WHEN TRUE THEN 1 ELSE 2.5 END", "FLOAT", []any{"1.0"}}, + {"in", "SELECT 1 IN (1.0, 2)", "BOOLEAN", []any{"true"}}, + {"between", "SELECT 2 BETWEEN 1 AND 2.5", "BOOLEAN", []any{"true"}}, + {"sum float", "SELECT SUM(x) FROM UNNEST([0.1, 0.2]) x", "FLOAT", []any{"0.30000000000000004"}}, + {"sum int", "SELECT SUM(x) FROM UNNEST([1, 2, 4]) x", "INTEGER", []any{"7"}}, + {"avg int", "SELECT AVG(x) FROM UNNEST([1, 2, 4]) x", "FLOAT", []any{"2.3333333333333335"}}, + {"array literal", "SELECT ARRAY_LENGTH([1, 2.5])", "INTEGER", []any{"2"}}, + {"concat", "SELECT 5 || 'x'", "STRING", []any{"5x"}}, + {"like", "SELECT 'abc' LIKE 'a%'", "BOOLEAN", []any{"true"}}, + {"distinct from", "SELECT 1 IS DISTINCT FROM 1.0", "BOOLEAN", []any{"false"}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + res, err := runSQL(t, numericCatalog(t), tt.sql) + require.NoError(t, err) + require.Len(t, res.Fields, 1) + assert.Equal(t, tt.typ, res.Fields[0].Type) + assert.Equal(t, [][]any{tt.want}, wireRows(res)) + }) + } +} + +func TestNumericMixedComparisons(t *testing.T) { + t.Parallel() + + tests := []fnCase{ + {"int column join", "SELECT x.id, y.id FROM nums x JOIN nums y ON x.id = y.b", [][]any{{"5", "5"}}}, + {"using join", "SELECT x.id FROM nums x JOIN (SELECT id AS b FROM nums) y USING (b)", [][]any{{"5"}}}, + {"using join count", "SELECT COUNT(*) FROM nums x JOIN nums y USING (n)", [][]any{{"6"}}}, + { + "using full join", + "SELECT x.id, b FROM nums x FULL JOIN (SELECT id AS b FROM nums) y USING (b) WHERE b >= 5", + [][]any{{"2", "12345678901234567890123456789012345678.12345678901234567890123456789012345678"}, {"5", "5"}}, + }, + {"in subquery int in numeric", "SELECT id FROM nums WHERE id IN (SELECT b FROM nums)", [][]any{{"5"}}}, + {"in subquery numeric in int", "SELECT id FROM nums WHERE b IN (SELECT id FROM nums)", [][]any{{"5"}}}, + {"in unnest ints", "SELECT id FROM nums WHERE b IN UNNEST([5, 3]) ORDER BY id", [][]any{{"5"}}}, + { + "in unnest decimals", + "SELECT id FROM nums WHERE id IN UNNEST([NUMERIC '5', NUMERIC '3']) ORDER BY id", + [][]any{{"3"}, {"5"}}, + }, + {"exists", "SELECT id FROM nums o WHERE EXISTS (SELECT 1 FROM nums i WHERE i.id = o.b)", [][]any{{"5"}}}, + {"intersect", "SELECT id AS v FROM nums INTERSECT DISTINCT SELECT b FROM nums", [][]any{{"5"}}}, + { + "except", + "SELECT id AS v FROM nums WHERE id IN (3, 5) EXCEPT DISTINCT SELECT b FROM nums ORDER BY v", + [][]any{{"3"}}, + }, + { + "union distinct", + "SELECT id AS v FROM nums WHERE id = 5 UNION DISTINCT SELECT b FROM nums WHERE id = 5", + [][]any{{"5"}}, + }, + { + "group mixed", + "SELECT v, COUNT(*) FROM (SELECT id AS v FROM nums UNION ALL SELECT b FROM nums WHERE id = 5) " + + "GROUP BY v ORDER BY v LIMIT 5", + [][]any{{"1", "1"}, {"2", "1"}, {"3", "1"}, {"4", "1"}, {"5", "2"}}, + }, + {"order mixed", "SELECT id FROM nums ORDER BY b - id", [][]any{{"4"}, {"3"}, {"1"}, {"5"}, {"2"}}}, + {"eq float column", "SELECT id FROM nums WHERE n = f", [][]any{}}, + { + "between mixed", + "SELECT id FROM nums WHERE b BETWEEN id - 1 AND id + 1 AND b IS NOT NULL ORDER BY id", + [][]any{{"1"}, {"5"}}, + }, + {"greatest mixed", "SELECT GREATEST(n, b) FROM nums WHERE id = 3", [][]any{{"-0.3"}}}, + {"if mixed", "SELECT IF(id > 3, id, n) FROM nums WHERE id IN (1, 5) ORDER BY id", [][]any{{"0.1"}, {"5"}}}, + {"coalesce default", "SELECT COALESCE(n, 0) FROM nums WHERE id = 4", [][]any{{"0"}}}, + { + "distinct from", + "SELECT n IS DISTINCT FROM 0.1, n IS NOT DISTINCT FROM 0.1 FROM nums ORDER BY id", + [][]any{{"false", "true"}, {"true", "false"}, {"true", "false"}, {"true", "false"}, {"false", "true"}}, + }, + {"array concat", "SELECT SUM(x) FROM UNNEST(ARRAY_CONCAT([1], [NUMERIC '1.5'])) x", [][]any{{"2.5"}}}, + { + "array concat operator", + "SELECT ARRAY_LENGTH([1.5] || [NUMERIC '2.5']), (SELECT SUM(x) FROM UNNEST([1.5] || [NUMERIC '2.5']) x)", + [][]any{{"2", "4.0"}}, + }, + { + "array concat column", + "SELECT (SELECT SUM(x) FROM UNNEST(ARRAY_CONCAT([1], arr)) x) FROM nums WHERE id = 1", + [][]any{{"4.75"}}, + }, + {"array if", "SELECT (SELECT SUM(x) FROM UNNEST(IF(FALSE, [1], [NUMERIC '2.5'])) x)", [][]any{{"2.5"}}}, + { + "unpivot", + "SELECT * FROM (SELECT id, n FROM nums WHERE id = 1) UNPIVOT (v FOR c IN (id, n)) ORDER BY c", + [][]any{{"1", "id"}, {"0.1", "n"}}, + }, + {"search struct", "SELECT SEARCH(rec, '3.5'), SEARCH(rec, '4'), SEARCH(rec, '99') FROM nums WHERE id = 1", + [][]any{{"true", "true", "false"}}}, + { + "search array", + "SELECT SEARCH(arr, '1.5'), SEARCH(arr, '1.50') FROM nums WHERE id = 1", + [][]any{{"true", "false"}}, + }, + { + "format nested", + "SELECT FORMAT('%s|%t', arr, rec) FROM nums WHERE id = 1", + [][]any{{`[1.5,2.25]|{"x":3.5,"y":4}`}}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + res, err := runSQL(t, numericCatalog(t), tt.sql) + require.NoError(t, err) + assert.Equal(t, tt.want, wireRows(res)) + }) + } +} + +func TestNumericIncompatibleOperandsError(t *testing.T) { + t.Parallel() + + tests := []struct{ name, sql string }{ + {"eq string", "SELECT n = 'x' FROM nums"}, + {"lt string column", "SELECT n < g FROM nums"}, + {"add string", "SELECT n + 'x' FROM nums"}, + {"concat operator", "SELECT n || 'x' FROM nums"}, + {"like", "SELECT n LIKE '%1%' FROM nums"}, + {"between", "SELECT n BETWEEN 'a' AND 'b' FROM nums"}, + {"in list", "SELECT n IN ('a') FROM nums"}, + {"distinct from", "SELECT n IS DISTINCT FROM 'x' FROM nums"}, + {"if", "SELECT IF(id > 1, 'x', n) FROM nums"}, + {"case", "SELECT CASE WHEN id = 1 THEN g ELSE n END FROM nums"}, + {"coalesce", "SELECT COALESCE(g, n) FROM nums"}, + {"nullif", "SELECT NULLIF(g, n) FROM nums"}, + {"greatest", "SELECT GREATEST('a', n) FROM nums"}, + {"union", "SELECT g AS v FROM nums UNION ALL SELECT n FROM nums"}, + {"array literal", "SELECT ['x', n] FROM nums"}, + {"array to string", "SELECT ARRAY_TO_STRING(arr, ',') FROM nums"}, + {"cast array", "SELECT CAST(arr AS STRING) FROM nums"}, + {"cast struct", "SELECT CAST(rec AS STRING) FROM nums"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + _, err := runSQL(t, numericCatalog(t), tt.sql) + require.Error(t, err) + assert.NotRegexp(t, encodedDecimal, err.Error()) + }) + } +} + +func TestNumericAdversarialMath(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + sql string + err string + want string + }{ + { + "pow huge", + "SELECT POW(NUMERIC '99999999999999999999999999999.999999999', NUMERIC '99999999999')", + "overflow", + "", + }, + {"pow huge big", "SELECT POW(BIGNUMERIC '" + bigMax + "', BIGNUMERIC '" + bigMax + "')", "overflow", ""}, + {"pow tiny", "SELECT POW(NUMERIC '0.000000001', NUMERIC '99999999999')", "", "0"}, + { + "pow negative huge", + "SELECT POW(NUMERIC '-99999999999999999999999999999', NUMERIC '99999999999')", + "overflow", + "", + }, + {"pow exact limit", "SELECT POW(NUMERIC '1.000000001', NUMERIC '256')", "", "1.000000256"}, + {"pow over limit", "SELECT POW(NUMERIC '10', NUMERIC '257')", "overflow", ""}, + {"pow fractional", "SELECT POW(NUMERIC '2', NUMERIC '0.5')", "", "1.414213562"}, + {"pow negative base", "SELECT POW(NUMERIC '-2', NUMERIC '0.5')", "invalid argument", ""}, + {"exp huge", "SELECT EXP(NUMERIC '99999999999999999999999999999')", "overflow", ""}, + {"exp very negative", "SELECT EXP(NUMERIC '-99999999999999999999999999999')", "", "0"}, + {"exp 200", "SELECT EXP(NUMERIC '201')", "overflow", ""}, + { + "ln tiny", + "SELECT LN(BIGNUMERIC '0.00000000000000000000000000000000000001')", + "", + "-87.49823353377373599268367527800583988884", + }, + {"log10 big", "SELECT LOG10(BIGNUMERIC '" + bigMax + "')", "", ""}, + {"sqrt big", "SELECT SQRT(BIGNUMERIC '" + bigMax + "')", "", ""}, + { + "round huge digits", + "SELECT ROUND(NUMERIC '1.5', 9223372036854775807), ROUND(NUMERIC '1.5', -9223372036854775807)", + "", + "", + }, + {"trunc huge digits", "SELECT TRUNC(NUMERIC '1.5', 9223372036854775807)", "", "1.5"}, + { + "generate huge", + "SELECT ARRAY_LENGTH(GENERATE_ARRAY(NUMERIC '0', NUMERIC '1000000000', NUMERIC '0.000000001'))", + "too large", + "", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + res, err := runSQL(t, numericCatalog(t), tt.sql) + if tt.err != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.err) + + return + } + + require.NoError(t, err) + + if tt.want != "" { + assert.Equal(t, tt.want, wireRows(res)[0][0]) + } + }) + } +} diff --git a/services/gcpbigquery/bqsql/numeric_leak_test.go b/services/gcpbigquery/bqsql/numeric_leak_test.go new file mode 100644 index 0000000000..1478da5e5f --- /dev/null +++ b/services/gcpbigquery/bqsql/numeric_leak_test.go @@ -0,0 +1,190 @@ +package bqsql_test + +import ( + "fmt" + "regexp" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/gcpbigquery/bqsql" +) + +var encodedDecimal = regexp.MustCompile(`#[0-9a-f]{64}`) + +const lookalike = "#8000000000000000000000000000000070d8f2fc87ca26b70e4f336000000000" + +func leakCatalog(t *testing.T) *fakeCatalog { + t.Helper() + + fs := fieldsJSON(t, `[ + {"name":"id","type":"INTEGER"}, + {"name":"n","type":"NUMERIC"}, + {"name":"b","type":"BIGNUMERIC"}, + {"name":"s","type":"STRING"}, + {"name":"arr","type":"NUMERIC","mode":"REPEATED"}, + {"name":"rec","type":"RECORD","fields":[ + {"name":"x","type":"NUMERIC"},{"name":"y","type":"BIGNUMERIC"},{"name":"s","type":"STRING"}]}, + {"name":"recs","type":"RECORD","mode":"REPEATED","fields":[ + {"name":"x","type":"NUMERIC"},{"name":"tag","type":"STRING"}]} + ]`) + + rows := rowsJSON(t, fs, `[ + {"id":1,"n":"1.5","b":"0.00000000000000000000000000000000000001","s":"`+lookalike+`","arr":["2.5","3"], + "rec":{"x":"4.25","y":"5","s":"`+lookalike+`"},"recs":[{"x":"6.5","tag":"a"},{"x":"7","tag":"b"}]}, + {"id":2,"n":"-2","b":"-7.5","s":"plain","arr":[],"rec":null,"recs":[]}, + {"id":3,"n":null,"b":null,"s":null,"arr":[],"rec":null,"recs":[]} + ]`) + + return &fakeCatalog{tables: map[string]*bqsql.TableData{ + "ds.t": {Ref: bqsql.TableRef{Project: "p", Dataset: "ds", Table: "t"}, Fields: fs, Rows: rows}, + }} +} + +func TestNumericNeverLeaksEncoding(t *testing.T) { + t.Parallel() + + queries := []string{ + "SELECT n, b, arr, rec, recs FROM t", + "SELECT * FROM t", + "SELECT TO_JSON_STRING(n), TO_JSON_STRING(b), TO_JSON_STRING(arr), TO_JSON_STRING(rec), TO_JSON_STRING(recs) FROM t", + "SELECT TO_JSON_STRING(STRUCT(n, b, s, arr)) FROM t", + "SELECT TO_JSON_STRING([STRUCT(n AS a), STRUCT(b AS a)]) FROM t", + "SELECT FORMAT('%s|%t|%T', n, n, b) FROM t", + "SELECT FORMAT('%s|%t|%T', arr, rec, recs) FROM t", + "SELECT FORMAT('%s %s', s, n) FROM t", + "SELECT CAST(n AS STRING), CAST(b AS STRING) FROM t", + "SELECT CAST(arr AS STRING) FROM t", + "SELECT CAST(rec AS STRING) FROM t", + "SELECT CAST(arr AS ARRAY), CAST(arr AS ARRAY), CAST(arr AS ARRAY) FROM t", + "SELECT CAST(rec AS STRUCT) FROM t", + "SELECT CAST(recs AS ARRAY>) FROM t", + "SELECT n || 'x' FROM t", + "SELECT s || CAST(n AS STRING) FROM t", + "SELECT CONCAT(s, n) FROM t", + "SELECT CONCAT(s, CAST(b AS STRING)) FROM t", + "SELECT STRING_AGG(n) FROM t", + "SELECT STRING_AGG(CAST(n AS STRING), ',') FROM t", + "SELECT ARRAY_TO_STRING(arr, ',') FROM t", + "SELECT ARRAY_TO_STRING([n], ',') FROM t", + "SELECT ARRAY_TO_STRING(ARRAY(SELECT CAST(a AS STRING) FROM UNNEST(arr) a), ',') FROM t", + "SELECT n LIKE '%1%' FROM t", + "SELECT n = s FROM t", + "SELECT n < s FROM t", + "SELECT n IS DISTINCT FROM s FROM t", + "SELECT s IN (n) FROM t", + "SELECT n BETWEEN s AND s FROM t", + "SELECT IF(id > 1, s, n) FROM t", + "SELECT COALESCE(s, n) FROM t", + "SELECT IFNULL(s, n) FROM t", + "SELECT NULLIF(s, n) FROM t", + "SELECT CASE WHEN id = 1 THEN n ELSE s END FROM t", + "SELECT n AS v FROM t UNION ALL SELECT s FROM t", + "SELECT s AS v FROM t UNION DISTINCT SELECT n FROM t", + "SELECT ['x', n] FROM t", + "SELECT GREATEST(s, n) FROM t", + "SELECT SEARCH(rec, '4.25'), SEARCH(arr, '2.5'), SEARCH(recs, '6.5') FROM t", + "SELECT UPPER(n), LENGTH(n), SUBSTR(b, 1, 5), TRIM(n), REPLACE(n, '1', '2') FROM t", + "SELECT ARRAY_CONCAT(arr, [1, 2]), [1] || arr, ARRAY_REVERSE(arr) FROM t", + "SELECT x FROM t, UNNEST(arr) AS x", + "SELECT r.x, r.tag FROM t, UNNEST(recs) AS r", + "SELECT ARRAY(SELECT AS STRUCT n, b) FROM t", + "SELECT STRUCT(n, b, arr) FROM t", + "SELECT MIN(n), MAX(b), SUM(n), AVG(b), ANY_VALUE(n), ARRAY_AGG(n) FROM t", + "SELECT APPROX_TOP_COUNT(n, 2), APPROX_QUANTILES(b, 2) FROM t", + "SELECT rec, COUNT(*) FROM t GROUP BY rec", + "SELECT DISTINCT arr FROM t", + "SELECT n, LAG(n, 1, 0) OVER (ORDER BY id), FIRST_VALUE(b) OVER (ORDER BY id) FROM t", + "SELECT * FROM (SELECT id, n, b FROM t) UNPIVOT (v FOR c IN (id, n, b))", + "SELECT ERROR(CAST(n AS STRING)) FROM t WHERE id = 1", + "SELECT CAST(s AS NUMERIC) FROM t", + "SELECT PARSE_NUMERIC(s) FROM t", + "SELECT s, TO_JSON_STRING(STRUCT(s, n AS n2)), UPPER(s) FROM t", + "SELECT TO_JSON_STRING(STRUCT(rec.s AS s, n AS n)) FROM t", + } + + for _, sql := range queries { + t.Run(sql, func(t *testing.T) { + t.Parallel() + + res, err := runSQL(t, leakCatalog(t), sql) + if err != nil { + assert.NotRegexp(t, encodedDecimal, err.Error()) + + return + } + + var sb strings.Builder + + fmt.Fprint(&sb, wireRows(res)) + + for _, r := range res.Rows { + fmt.Fprint(&sb, r) + } + + body := sb.String() + + if encodedDecimal.MatchString(body) { + assert.Contains(t, body, lookalike, "only a genuine STRING may carry the lookalike text") + assert.Equal(t, 0, countOutsideStrings(body), "an encoded decimal reached the client: %s", body) + } + }) + } +} + +func countOutsideStrings(body string) int { + rest := regexp.MustCompile(regexpQuote(lookalike)).ReplaceAllString(body, "") + + return len(encodedDecimal.FindAllString(rest, -1)) +} + +func regexpQuote(s string) string { return regexp.QuoteMeta(s) } + +func TestStringLookalikeIsNotADecimal(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + sql string + want [][]any + }{ + {"column", "SELECT s FROM t WHERE id = 1", [][]any{{lookalike}}}, + { + "upper", + "SELECT UPPER(s) FROM t WHERE id = 1", + [][]any{{"#8000000000000000000000000000000070D8F2FC87CA26B70E4F336000000000"}}, + }, + { + "json struct", + "SELECT TO_JSON_STRING(STRUCT(n, s)) FROM t WHERE id = 1", + [][]any{{`{"n":1.5,"s":"` + lookalike + `"}`}}, + }, + { + "json nested record", + "SELECT TO_JSON_STRING(rec) FROM t WHERE id = 1", + [][]any{{`{"x":4.25,"y":5,"s":"` + lookalike + `"}`}}, + }, + {"format", "SELECT FORMAT('%s|%s', s, n) FROM t WHERE id = 1", [][]any{{lookalike + "|1.5"}}}, + {"format control", "SELECT FORMAT('%s|%s', '\\x01N1', n) FROM t WHERE id = 1", [][]any{{"\x01N1|1.5"}}}, + {"concat", "SELECT s || 'x' FROM t WHERE id = 1", [][]any{{lookalike + "x"}}}, + {"group", "SELECT s, COUNT(*) FROM t WHERE id = 1 GROUP BY s", [][]any{{lookalike, "1"}}}, + {"nested string", "SELECT rec.s FROM t WHERE id = 1", [][]any{{lookalike}}}, + { + "typed cast", + "SELECT CAST(NUMERIC '1' AS STRING) = '1', s = '" + lookalike + "' FROM t WHERE id = 1", + [][]any{{"true", "true"}}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + res, err := runSQL(t, leakCatalog(t), tt.sql) + require.NoError(t, err) + assert.Equal(t, tt.want, wireRows(res)) + }) + } +} diff --git a/services/gcpbigquery/bqsql/pivot.go b/services/gcpbigquery/bqsql/pivot.go index 948d2d5970..b506973072 100644 --- a/services/gcpbigquery/bqsql/pivot.go +++ b/services/gcpbigquery/bqsql/pivot.go @@ -516,20 +516,41 @@ func (c *compiler) unpivotSQL(spec *pivotSpec, cols []*colInfo, base string) ([] return nil, "", err } + valTypes := make([]Type, len(spec.valueCols)) + for i, vc := range spec.valueCols { - out = append(out, selectedCol{vc, byName[strings.ToLower(spec.sets[0].cols[i])].typ}) + valTypes[i] = unpivotValueType(spec, byName, i) + out = append(out, selectedCol{vc, valTypes[i]}) } out = append(out, selectedCol{spec.nameCol, nameTyp}) parts := make([]string, len(spec.sets)) for i, set := range spec.sets { - parts[i] = c.unpivotMember(spec, set, byName, other, base, nameTyp) + parts[i] = c.unpivotMember(spec, set, byName, other, base, nameTyp, valTypes) } return out, "SELECT * FROM (" + strings.Join(parts, " UNION ALL ") + ")", nil } +// unpivotValueType is the type of value column i: the first column set's type, widened when decimals are mixed in. +func unpivotValueType(spec *pivotSpec, byName map[string]*colInfo, i int) Type { + first := byName[strings.ToLower(spec.sets[0].cols[i])].typ + gs := make([]*gx, len(spec.sets)) + + for j, set := range spec.sets { + gs[j] = &gx{typ: byName[strings.ToLower(set.cols[i])].typ} + } + + if !hasDec(gs) { + return first + } + + t, _ := unifyAll(gs) + + return t +} + func unpivotNameType(spec *pivotSpec) (Type, error) { typ := scalar(KindString) @@ -569,6 +590,7 @@ func unpivotNameType(spec *pivotSpec) (Type, error) { func (c *compiler) unpivotMember( spec *pivotSpec, set unpivotSet, byName map[string]*colInfo, other []*colInfo, base string, nameTyp Type, + valTypes []Type, ) string { sel := make([]string, 0, len(other)+len(set.cols)+1) @@ -580,7 +602,7 @@ func (c *compiler) unpivotMember( for i, name := range set.cols { col := byName[strings.ToLower(name)] - sel = append(sel, col.sql+" AS "+quoteIdent(spec.valueCols[i])) + sel = append(sel, toType(&gx{sql: col.sql, typ: col.typ}, valTypes[i]).sql+" AS "+quoteIdent(spec.valueCols[i])) conds = append(conds, col.sql+" IS NOT NULL") } diff --git a/services/gcpbigquery/bqsql/search.go b/services/gcpbigquery/bqsql/search.go index 887ec314b4..9faebb3de3 100644 --- a/services/gcpbigquery/bqsql/search.go +++ b/services/gcpbigquery/bqsql/search.go @@ -782,6 +782,9 @@ func genSearch(c *compiler, n *node, sc *scope) (*gx, error) { sqls[1] = quoteStr(tagString) case KindStruct, KindArray: sqls[0], sqls[1] = "CAST(json("+data.sql+") AS TEXT)", quoteStr(tagJSON) + if containsDec(data.typ) { + sqls[0] = "CAST(" + decimalJSON(data, true) + " AS TEXT)" + } case KindJSON: sqls[1] = quoteStr(tagJSONType) case KindUnknown, KindInt, KindFloat, KindBool, KindBytes, KindTimestamp, KindDate, KindTime, KindDatetime, diff --git a/services/gcpbigquery/bqsql/udf_decimal.go b/services/gcpbigquery/bqsql/udf_decimal.go index c7db7e5e57..0a4d1c8ff9 100644 --- a/services/gcpbigquery/bqsql/udf_decimal.go +++ b/services/gcpbigquery/bqsql/udf_decimal.go @@ -4,6 +4,7 @@ import ( "database/sql/driver" "math" "math/big" + "slices" "strings" sqlitedriver "modernc.org/sqlite" @@ -369,8 +370,7 @@ func addDecimalUDFs(d map[string]udfDef) { d["dec_to_int"] = udfDef{n: 1, fn: decToInt} d["dec_to_str"] = udfDef{n: 1, fn: decToStr} d["dec_json"] = udfDef{n: 1, fn: decJSON} - d["dec_fmt"] = udfDef{n: argc2, fn: decFmt} - d["dec_json_nested"] = udfDef{n: 1, fn: decJSONNested} + d["format_dec"] = udfDef{n: -1, fn: udfFormatDec} d["dec_generate_array"] = udfDef{n: argc4, fn: decGenerateArray} } @@ -459,78 +459,39 @@ func registerDecimalAggregates() { } } -func decFmt(a []driver.Value) (driver.Value, error) { - if a[0] == nil { - return nil, nil //nolint:nilnil // NULL in, NULL out - } - - k := decKindArg(a[1]) - - d, err := decArg(a[0], k) - if err != nil { - return nil, err - } - - return fmtDecimalTag + decFlagLetter(k) + d.String(), nil +// decFormatArg is a decoded decimal handed to the FORMAT implementation; its Go type cannot collide with any SQL value. +type decFormatArg struct { + text string + kind Kind } -func decFlagLetter(k Kind) string { - if k == KindBigNumeric { - return "B" +func udfFormatDec(a []driver.Value) (driver.Value, error) { + if len(a) < argc2 { + return nil, errBQ("Too few arguments to FORMAT") } - return "N" -} - -// decJSONNested rewrites every encoded decimal string inside JSON text into a bare JSON number. -func decJSONNested(a []driver.Value) (driver.Value, error) { - if a[0] == nil { - return nil, nil //nolint:nilnil // NULL in, NULL out - } - - src := toStr(a[0]) - - var sb strings.Builder - - for i := 0; i < len(src); i++ { - if src[i] != '"' { - sb.WriteByte(src[i]) + mask := toStr(a[0]) + args := slices.Clone(a[1:]) + for j := range len(mask) { + if j+1 >= len(args) || mask[j] == '-' || args[j+1] == nil { continue } - end := i + 1 - for end < len(src) && src[end] != '"' { - if src[end] == '\\' { - end++ - } - - end++ - } - - if end >= len(src) { - sb.WriteString(src[i:]) - - break + k := KindNumeric + if mask[j] == 'B' { + k = KindBigNumeric } - inner := src[i+1 : end] - - if IsSQLText(inner) { - d, err := DecodeSQLText(inner, KindBigNumeric) - if err != nil { - return nil, decFail(err) - } - - sb.WriteString(d.String()) - } else { - sb.WriteString(src[i : end+1]) + d, err := decArg(args[j+1], k) + if err != nil { + return nil, err } - i = end + args[j+1] = decFormatArg{text: d.String(), kind: k} } - return sb.String(), nil + return udfFormat(args) } // decMomentAgg keeps exact power sums so VARIANCE and STDDEV of decimals only round once, on the final FLOAT64. diff --git a/services/gcpbigquery/bqsql/udf_decimal_internal_test.go b/services/gcpbigquery/bqsql/udf_decimal_internal_test.go new file mode 100644 index 0000000000..47385bc7c1 --- /dev/null +++ b/services/gcpbigquery/bqsql/udf_decimal_internal_test.go @@ -0,0 +1,88 @@ +package bqsql + +import ( + "database/sql/driver" + "math/big" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestDecimalFunctionsRejectMalformedArguments(t *testing.T) { + t.Parallel() + + defs := map[string]udfDef{} + addDecimalUDFs(defs) + + good := mustDecimal(t, "1.5").SQLText() + pool := []driver.Value{ + nil, "", "x", "#", good[:64], good + "0", "#" + good[1:] + "", []byte("blob"), int64(1), int64(0), int64(-1), + float64(1.5), float64(-1e300), good, int64(1 << 62), + } + + for name, d := range defs { + t.Run(name, func(t *testing.T) { + t.Parallel() + + arities := []int{int(d.n)} + if d.n < 0 { + arities = []int{1, 2, 3, 4, 5} + } + + for _, n := range arities { + for _, first := range pool { + for _, second := range pool { + args := make([]driver.Value, n) + for i := range args { + args[i] = pool[(i+1)%len(pool)] + } + + args[0] = first + if n > 1 { + args[1] = second + } + + assert.NotPanics(t, func() { _, _ = d.fn(args) }, "%s(%v)", name, args) + } + } + } + }) + } +} + +func mustDecimal(t *testing.T, s string) Decimal { + t.Helper() + + d, err := ParseDecimal(KindNumeric, s) + if err != nil { + t.Fatal(err) + } + + return d +} + +func TestDecimalAggregatesRejectMalformedArguments(t *testing.T) { + t.Parallel() + + for _, avg := range []bool{false, true} { + a := &decAgg{sum: new(big.Int), avg: avg, kind: KindNumeric} + + for _, v := range []driver.Value{nil, "x", []byte("b"), int64(3), float64(1), mustDecimal(t, "1").SQLText()} { + assert.NotPanics(t, func() { + _ = a.Step(nil, []driver.Value{v}) + _ = a.WindowInverse(nil, []driver.Value{v}) + _, _ = a.WindowValue(nil) + }) + } + } + + m := &decMomentAgg{sum: new(big.Int), sumSq: new(big.Int)} + + for _, v := range []driver.Value{nil, "x", int64(1), mustDecimal(t, "2").SQLText()} { + assert.NotPanics(t, func() { + _ = m.Step(nil, []driver.Value{v}) + _, _ = m.WindowValue(nil) + _ = m.WindowInverse(nil, []driver.Value{v}) + }) + } +} diff --git a/services/gcpbigquery/bqsql/udf_json.go b/services/gcpbigquery/bqsql/udf_json.go index eb75622d4b..4bc0072eca 100644 --- a/services/gcpbigquery/bqsql/udf_json.go +++ b/services/gcpbigquery/bqsql/udf_json.go @@ -240,8 +240,8 @@ func udfFormat(a []driver.Value) (driver.Value, error) { } func formatArg(spec byte, flags string, v driver.Value) (string, error) { - if txt, ok := v.(string); ok && strings.HasPrefix(txt, fmtDecimalTag) { - return formatDecimal(spec, flags, txt[len(fmtDecimalTag):]) + if da, ok := v.(decFormatArg); ok { + return formatDecimal(spec, flags, da) } return formatOne(spec, flags, v) diff --git a/services/gcpbigquery/extract_shard_test.go b/services/gcpbigquery/extract_shard_test.go index 84266fa562..d167f7b158 100644 --- a/services/gcpbigquery/extract_shard_test.go +++ b/services/gcpbigquery/extract_shard_test.go @@ -80,8 +80,7 @@ func TestExtractShardingAndUris(t *testing.T) { env := newSDK(t) ds := env.dataset(t, "ex") - _, err := env.client.Query("CREATE TABLE ex.src AS " + rows).Run(t.Context()) - require.NoError(t, err) + env.exec(t, "CREATE TABLE ex.src AS "+rows) env.backend.SetExtractShardBytes(tt.shard) diff --git a/services/gcpbigquery/sdk_numeric_egress_test.go b/services/gcpbigquery/sdk_numeric_egress_test.go new file mode 100644 index 0000000000..783569a63c --- /dev/null +++ b/services/gcpbigquery/sdk_numeric_egress_test.go @@ -0,0 +1,352 @@ +package gcpbigquery_test + +import ( + "bytes" + "io" + "math/big" + "net/http" + "regexp" + "strings" + "testing" + + "cloud.google.com/go/bigquery" + "github.com/iskorotkov/avro/v2/ocf" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/pkgs/testclient" +) + +var encodedDecimalText = regexp.MustCompile(`#[0-9a-f]{64}`) + +func httpJSON(t *testing.T, env *sdkEnv, method, path, body string) (int, string) { + t.Helper() + + var rd io.Reader + if body != "" { + rd = strings.NewReader(body) + } + + req, err := http.NewRequestWithContext(t.Context(), method, env.url+path, rd) + require.NoError(t, err) + + req.Header.Set("Content-Type", "application/json") + + resp, err := testclient.New(t).Do(req) + require.NoError(t, err) + + defer resp.Body.Close() + + out, err := io.ReadAll(resp.Body) + require.NoError(t, err) + + return resp.StatusCode, string(out) +} + +func jsonString(s string) string { + return `"` + strings.ReplaceAll(strings.ReplaceAll(s, `\`, `\\`), `"`, `\"`) + `"` +} + +func TestSDKNumericEgressNeverEncoded(t *testing.T) { + t.Parallel() + + env := newSDK(t) + ds := env.dataset(t, "eg") + + env.exec(t, "CREATE TABLE eg.src AS SELECT 1 AS id, NUMERIC '1.5' AS n, "+ + "BIGNUMERIC '0.00000000000000000000000000000000000001' AS b, [NUMERIC '2.5', NUMERIC '3'] AS arr, "+ + "STRUCT(NUMERIC '4.25' AS x, BIGNUMERIC '5' AS y) AS rec, [STRUCT(NUMERIC '6.5' AS x, 'a' AS tag)] AS recs") + + queries := []string{ + "SELECT * FROM eg.src", + "SELECT n + 1, b * 2, arr, rec, recs FROM eg.src", + "SELECT TO_JSON_STRING(rec), TO_JSON_STRING(recs), FORMAT('%s', arr), FORMAT('%T', n) FROM eg.src", + "SELECT MIN(n), MAX(b), SUM(n), AVG(b), ARRAY_AGG(n) FROM eg.src", + "DECLARE x NUMERIC DEFAULT NUMERIC '1.5'; SET x = x + 1; SELECT x, [x], STRUCT(x AS v);", + "SELECT x, [x, x * 2] FROM UNNEST([NUMERIC '1', NUMERIC '2']) x", + "SELECT n IS NULL, CAST(n AS STRING), CAST(b AS STRING), CAST(n AS FLOAT64) FROM eg.src", + "CREATE TEMP FUNCTION f(x NUMERIC) RETURNS NUMERIC AS (x * 2); SELECT f(n), f(1) FROM eg.src", + "SELECT @p, [@p], STRUCT(@p AS v)", + } + + for _, q := range queries { + t.Run(q, func(t *testing.T) { + t.Parallel() + + body := `{"query":` + jsonString(q) + `,"useLegacySql":false,` + + `"queryParameters":[{"name":"p","parameterType":{"type":"NUMERIC"},"parameterValue":{"value":"7.25"}}],` + + `"parameterMode":"NAMED"}` + if !strings.Contains(q, "@p") { + body = `{"query":` + jsonString(q) + `,"useLegacySql":false}` + } + + code, out := httpJSON(t, env, http.MethodPost, "/projects/"+sdkProject+"/queries", body) + assert.Equal(t, http.StatusOK, code, out) + assert.NotRegexp(t, encodedDecimalText, out) + }) + } + + t.Run("tabledata", func(t *testing.T) { + t.Parallel() + + code, out := httpJSON(t, env, http.MethodGet, "/projects/"+sdkProject+"/datasets/eg/tables/src/data", "") + assert.Equal(t, http.StatusOK, code) + assert.NotRegexp(t, encodedDecimalText, out) + assert.Contains(t, out, `"1.5"`) + assert.Contains(t, out, `"0.00000000000000000000000000000000000001"`) + }) + + t.Run("extract", func(t *testing.T) { + t.Parallel() + + for name, format := range map[string]bigquery.DataFormat{ + "json": bigquery.JSON, + } { + ref := bigquery.NewGCSReference("gs://b/" + name + ".out") + ref.DestinationFormat = format + require.NoError(t, runExtract(t, ds, ref, false).Err(), name) + } + + for name, data := range env.objects.data { + assert.False(t, encodedDecimalText.Match(data), name) + } + + assert.Contains(t, string(env.objects.data["b/json.out"]), "0.00000000000000000000000000000000000001") + }) +} + +func TestSDKNumericFlatExtracts(t *testing.T) { + t.Parallel() + + env := newSDK(t) + ds := env.dataset(t, "pq") + + env.exec(t, "CREATE TABLE pq.src AS SELECT NUMERIC '1.5' AS n, "+ + "BIGNUMERIC '0.00000000000000000000000000000000000001' AS b") + + csv := bigquery.NewGCSReference("gs://b/p.csv") + csv.DestinationFormat = bigquery.CSV + require.NoError(t, runExtract(t, ds, csv, false).Err()) + assert.Contains(t, string(env.objects.data["b/p.csv"]), "1.5,0.00000000000000000000000000000000000001") + + av := bigquery.NewGCSReference("gs://b/p.avro") + av.DestinationFormat = bigquery.Avro + require.NoError(t, runExtract(t, ds, av, false).Err()) + + dec, err := ocf.NewDecoder(bytes.NewReader(env.objects.data["b/p.avro"])) + require.NoError(t, err) + + var rec map[string]any + + require.True(t, dec.HasNext()) + require.NoError(t, dec.Decode(&rec)) + assert.Zero(t, rec["b"].(*big.Rat).Cmp(ratOf(t, tinyText))) + assert.Zero(t, rec["n"].(*big.Rat).Cmp(ratOf(t, "1.5"))) + assert.Contains(t, string(env.objects.data["b/p.avro"]), `"scale":38`) + + ref := bigquery.NewGCSReference("gs://b/p.parquet") + ref.DestinationFormat = bigquery.Parquet + require.NoError(t, runExtract(t, ds, ref, false).Err()) + assert.False(t, encodedDecimalText.Match(env.objects.data["b/p.parquet"])) + + in := bigquery.NewGCSReference("gs://b/p.parquet") + in.SourceFormat = bigquery.Parquet + in.Schema = bigquery.Schema{ + {Name: "n", Type: bigquery.NumericFieldType}, {Name: "b", Type: bigquery.BigNumericFieldType}, + } + + job, err := ds.Table("back").LoaderFrom(in).Run(t.Context()) + require.NoError(t, err) + + status, err := job.Wait(t.Context()) + require.NoError(t, err) + require.NoError(t, status.Err()) + + rows := env.rows(t, "SELECT n, b FROM pq.back") + require.Len(t, rows, 1) + requireRats(t, rows[0], "1.5", tinyText) +} + +func TestSDKNumericInsertAllValues(t *testing.T) { + t.Parallel() + + env := newSDK(t) + env.dataset(t, "ia") + + env.exec(t, "CREATE TABLE ia.t (id INT64, n NUMERIC, p NUMERIC(5, 2), b BIGNUMERIC)") + + tests := []struct { + name string + row string + want string + failed bool + }{ + {"number", `{"id":1,"n":1.5,"p":1.25,"b":2.5}`, "1.5", false}, + {"string", `{"id":2,"n":"1234.5","p":"3","b":"1e-38"}`, "1234.5", false}, + {"exponent", `{"id":3,"n":"1.5e3","p":1e1,"b":"5E-1"}`, "1500", false}, + {"over scale", `{"id":4,"n":"0.0000000005","p":"1.005","b":"0.5"}`, "0.000000001", false}, + {"bad text", `{"id":5,"n":"abc"}`, "", true}, + {"overflow", `{"id":6,"n":"100000000000000000000000000000"}`, "", true}, + {"precision", `{"id":7,"p":"1000"}`, "", true}, + {"bool", `{"id":8,"n":true}`, "", true}, + {"encoded text", `{"id":9,"n":"#8000000000000000000000000000000070d8f2fc87ca26b70e4f336000000000"}`, "", true}, + } + + for _, tt := range tests { + code, out := httpJSON(t, env, http.MethodPost, "/projects/"+sdkProject+"/datasets/ia/tables/t/insertAll", + `{"rows":[{"json":`+tt.row+`}]}`) + require.Equal(t, http.StatusOK, code, tt.name+out) + assert.NotRegexp(t, encodedDecimalText, out, tt.name) + + if tt.failed { + assert.Contains(t, out, `"insertErrors"`, tt.name) + assert.Contains(t, out, `"index":0`, tt.name) + + continue + } + + assert.NotContains(t, out, `"insertErrors"`, tt.name) + } + + rows := env.rows(t, "SELECT id, n, p FROM ia.t ORDER BY id") + require.Len(t, rows, 4) + requireRats(t, rows[0][1:], "1.5", "1.25") + requireRats(t, rows[1][1:], "1234.5", "3") + requireRats(t, rows[2][1:], "1500", "10") + requireRats(t, rows[3][1:], "0.000000001", "1.01") +} + +func TestSDKNumericSchemaParameters(t *testing.T) { + t.Parallel() + + env := newSDK(t) + ds := env.dataset(t, "sp") + + schema := bigquery.Schema{ + {Name: "n", Type: bigquery.NumericFieldType, Precision: 10, Scale: 2}, + {Name: "b", Type: bigquery.BigNumericFieldType, Precision: 40, Scale: 20}, + {Name: "plain", Type: bigquery.NumericFieldType}, + } + require.NoError(t, ds.Table("t").Create(t.Context(), &bigquery.TableMetadata{Schema: schema})) + + md, err := ds.Table("t").Metadata(t.Context()) + require.NoError(t, err) + require.Len(t, md.Schema, 3) + assert.Equal(t, int64(10), md.Schema[0].Precision) + assert.Equal(t, int64(2), md.Schema[0].Scale) + assert.Equal(t, int64(40), md.Schema[1].Precision) + assert.Equal(t, int64(20), md.Schema[1].Scale) + assert.Zero(t, md.Schema[2].Precision) + + bad := bigquery.Schema{{Name: "n", Type: bigquery.NumericFieldType, Precision: 50, Scale: 2}} + require.Error(t, ds.Table("bad").Create(t.Context(), &bigquery.TableMetadata{Schema: bad})) +} + +func TestSDKNumericMixedDMLAndDynamicSQL(t *testing.T) { + t.Parallel() + + env := newSDK(t) + env.dataset(t, "dm") + + env.exec(t, "CREATE TABLE dm.t (id INT64, n NUMERIC, b BIGNUMERIC)") + env.exec(t, "INSERT INTO dm.t VALUES (1, 1, 1), (2, 2.5, 3), (3, 5, 5), (4, NULL, 4)") + env.exec(t, "UPDATE dm.t SET n = n * id + id / 4 WHERE n = id OR b = id") + env.exec(t, "DELETE FROM dm.t WHERE b = n AND id = 3") + env.exec(t, "MERGE dm.t T USING (SELECT 2 AS k, NUMERIC '9.5' AS v) S ON T.n = S.k OR T.b = S.k "+ + "WHEN MATCHED THEN UPDATE SET n = S.v WHEN NOT MATCHED THEN INSERT (id, n, b) VALUES (S.k, S.v, S.k)") + + rows := env.rows(t, "SELECT id, n FROM dm.t ORDER BY id, n") + require.Len(t, rows, 4) + requireRats(t, rows[0][1:], "1.25") + requireRats(t, rows[1][1:], "2.5") + requireRats(t, rows[2][1:], "9.5") + assert.Nil(t, rows[3][1]) + + rows = env.rows(t, "EXECUTE IMMEDIATE 'SELECT ? + NUMERIC \"1\", @named' USING NUMERIC '2.5', NUMERIC '3' AS named") + require.Len(t, rows, 1) + requireRats(t, rows[0], "3.5", "3") + + rows = env.rows(t, "SELECT @s.x + 1, @s.y", + bigquery.QueryParameter{Name: "s", Value: struct { + X *big.Rat `bigquery:"x"` + Y string `bigquery:"y"` + }{X: big.NewRat(1, 4), Y: "lit"}}) + require.Len(t, rows, 1) + requireRats(t, rows[0][:1], "1.25") + assert.Equal(t, "lit", rows[0][1]) +} + +func TestSDKNumericSnapshotRoundTripLossless(t *testing.T) { + t.Parallel() + + env := newSDK(t) + env.dataset(t, "rt") + env.exec(t, "CREATE TABLE rt.t AS SELECT BIGNUMERIC '"+bigMaxText+"' AS hi, BIGNUMERIC '"+bigMinText+"' AS lo, "+ + "BIGNUMERIC '"+tinyText+"' AS tiny, [BIGNUMERIC '"+tinyText+"'] AS arr, "+ + "STRUCT(NUMERIC '"+wideNumeric+"' AS x) AS rec") + + data := env.backend.Snapshot(t.Context()) + assert.NotRegexp(t, encodedDecimalText, string(data)) + assert.Contains(t, string(data), tinyText) + + other := newSDK(t) + require.NoError(t, other.backend.Restore(t.Context(), data)) + + rows := other.rows(t, "SELECT hi, lo, tiny, rec.x FROM rt.t") + require.Len(t, rows, 1) + requireRats(t, rows[0], bigMaxText, bigMinText, tinyText, wideNumeric) + + job, err := other.client.Query("SELECT hi + tiny FROM rt.t").Run(t.Context()) + require.NoError(t, err) + + st, err := job.Wait(t.Context()) + if err == nil { + err = st.Err() + } + + require.Error(t, err, "the maximum plus one unit overflows after a restore too") + assert.Contains(t, err.Error(), "BIGNUMERIC overflow") +} + +func TestSDKNumericViewsCTEsAndTableFunctions(t *testing.T) { + t.Parallel() + + env := newSDK(t) + env.dataset(t, "vw") + + env.exec(t, "CREATE TABLE vw.t AS SELECT 1 AS id, NUMERIC '1.5' AS n, BIGNUMERIC '2.25' AS b "+ + "UNION ALL SELECT 2, NUMERIC '-0.5', BIGNUMERIC '3'") + env.exec(t, "CREATE VIEW vw.v AS SELECT id, n * 2 AS n2, b FROM vw.t") + env.exec(t, "CREATE TABLE FUNCTION vw.tf(lim NUMERIC) AS SELECT id, n FROM vw.t WHERE n > lim") + env.exec(t, "CREATE FUNCTION vw.f(x NUMERIC, y BIGNUMERIC) RETURNS BIGNUMERIC AS (x + y)") + + tests := []struct { + name string + sql string + want [][]string + }{ + {"view", "SELECT n2 + 1, b FROM vw.v WHERE id = 1", [][]string{{"4", "2.25"}}}, + {"view compare", "SELECT n2 FROM vw.v WHERE n2 = id + 2", [][]string{{"3"}}}, + { + "cte", + "WITH c AS (SELECT n AS m, id FROM vw.t) SELECT SUM(m), MAX(m) FROM c WHERE m > id - 2", + [][]string{{"1.5", "1.5"}}, + }, + {"tvf", "SELECT SUM(n) FROM vw.tf(0)", [][]string{{"1.5"}}}, + {"tvf int arg", "SELECT SUM(n) FROM vw.tf(-1)", [][]string{{"1"}}}, + {"udf", "SELECT vw.f(n, b) FROM vw.t WHERE id = 1", [][]string{{"3.75"}}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + rows := env.rows(t, tt.sql) + require.Len(t, rows, len(tt.want)) + + for i, w := range tt.want { + requireRats(t, rows[i], w...) + } + }) + } +} From 05652fe528c89acca5534ee96830c6404cdba197 Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 16:51:10 -0600 Subject: [PATCH 4/9] fix(timestreamquery): integer overflow is not rendered wrapped, typeof escapes type names, outer joins keep their scanned range An integer result that overflowed was printed as a wrapped BIGINT, and a 32-bit overflow kept the INTEGER type. A row field name containing a quote broke the typeof rewrite. ON predicates of outer joins narrowed the reported temporal range of the preserved side. Spatial coverage reads the table's partition key through the write service. Rate-limit state is pruned. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- internal/app/timestream_query_sdk_test.go | 67 +++ internal/app/timestream_source.go | 28 +- services/timestreamquery/PARITY.md | 4 +- services/timestreamquery/query_execution.go | 6 + services/timestreamquery/ts_infer.go | 2 +- .../ts_infer_robust_internal_test.go | 131 ++++++ services/timestreamquery/ts_prune.go | 6 +- services/timestreamquery/ts_render.go | 5 + services/timestreamquery/ts_result.go | 54 ++- .../timestreamquery/ts_static_types_test.go | 411 ++++++++++++++++++ 10 files changed, 707 insertions(+), 7 deletions(-) create mode 100644 services/timestreamquery/ts_infer_robust_internal_test.go create mode 100644 services/timestreamquery/ts_static_types_test.go diff --git a/internal/app/timestream_query_sdk_test.go b/internal/app/timestream_query_sdk_test.go index c2b2a50aa6..fd5c6ace3f 100644 --- a/internal/app/timestream_query_sdk_test.go +++ b/internal/app/timestream_query_sdk_test.go @@ -573,3 +573,70 @@ func TestTimestreamQuery_SDK_ScheduledQueryWritesTarget(t *testing.T) { assert.EqualValues(t, 2, desc.ScheduledQuery.LastRunSummary.ExecutionStats.RecordsIngested) assert.EqualValues(t, 2, desc.ScheduledQuery.LastRunSummary.ExecutionStats.QueryResultRows) } + +func TestTimestreamQuery_SDK_InsightsUsePartitionKey(t *testing.T) { + t.Parallel() + + tests := []struct { + key twtypes.PartitionKey + name string + query string + note string + wantKey []string + wantCov float64 + }{ + { + name: "dimension key", + key: twtypes.PartitionKey{Type: twtypes.PartitionKeyTypeDimension, Name: aws.String("host")}, + query: "SELECT * FROM pkdb.m WHERE host = 'h1'", + wantKey: []string{"host"}, wantCov: 0.5, note: "constrained", + }, + { + name: "measure key", + key: twtypes.PartitionKey{Type: twtypes.PartitionKeyTypeMeasure}, + query: "SELECT * FROM pkdb.m WHERE measure_name = 'cpu'", + wantKey: []string{"measure_name"}, wantCov: 1, note: "all measures are cpu", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + t0 := time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC) + env := newTimestreamEnv(t, t0) + + _, err := env.write.CreateDatabase( + t.Context(), + &twsdk.CreateDatabaseInput{DatabaseName: aws.String("pkdb")}, + ) + require.NoError(t, err) + + _, err = env.write.CreateTable(t.Context(), &twsdk.CreateTableInput{ + DatabaseName: aws.String("pkdb"), TableName: aws.String("m"), + Schema: &twtypes.Schema{CompositePartitionKey: []twtypes.PartitionKey{tc.key}}, + }) + require.NoError(t, err) + + _, err = env.write.WriteRecords(t.Context(), &twsdk.WriteRecordsInput{ + DatabaseName: aws.String("pkdb"), TableName: aws.String("m"), + Records: []twtypes.Record{ + single("cpu", "1", twtypes.MeasureValueTypeDouble, t0.Add(-time.Minute), dim("host", "h1")), + single("cpu", "2", twtypes.MeasureValueTypeDouble, t0.Add(-time.Minute), dim("host", "h2")), + }, + }) + require.NoError(t, err) + + out, err := env.query.Query(t.Context(), &tqsdk.QueryInput{ + QueryString: aws.String(tc.query), + QueryInsights: &tqtypes.QueryInsights{Mode: tqtypes.QueryInsightsModeEnabledWithRateControl}, + }) + require.NoError(t, err) + require.NotNil(t, out.QueryInsightsResponse.QuerySpatialCoverage) + + cov := out.QueryInsightsResponse.QuerySpatialCoverage.Max + assert.Equal(t, tc.wantKey, cov.PartitionKey) + assert.InDelta(t, tc.wantCov, cov.Value, 0.001, tc.note) + }) + } +} diff --git a/internal/app/timestream_source.go b/internal/app/timestream_source.go index 34cc986bbb..7b923bf72c 100644 --- a/internal/app/timestream_source.go +++ b/internal/app/timestream_source.go @@ -24,8 +24,9 @@ type timestreamRecordSource struct { } var ( - _ timestreamquerybackend.RecordSource = (*timestreamRecordSource)(nil) - _ timestreamquerybackend.SchemaSource = (*timestreamRecordSource)(nil) + _ timestreamquerybackend.RecordSource = (*timestreamRecordSource)(nil) + _ timestreamquerybackend.SchemaSource = (*timestreamRecordSource)(nil) + _ timestreamquerybackend.PartitionKeySource = (*timestreamRecordSource)(nil) ) func newTimestreamRecordSource(h *timestreamwritebackend.Handler) *timestreamRecordSource { @@ -69,6 +70,29 @@ func (s *timestreamRecordSource) TableShapes(region, database, table string) []t return out } +// TablePartitionKeys returns the table's customer-defined partition key: dimension names, or measure_name for a +// measure key, in schema order. +func (s *timestreamRecordSource) TablePartitionKeys(region, database, table string) []string { + tbl, err := s.handler.BackendFor(region).DescribeTable(database, table) + if err != nil || tbl.Schema == nil { + return nil + } + + keys := make([]string, 0, len(tbl.Schema.CompositePartitionKey)) + + for _, pk := range tbl.Schema.CompositePartitionKey { + if pk.Type == timestreamwritebackend.PartitionKeyTypeMeasure { + keys = append(keys, "measure_name") + + continue + } + + keys = append(keys, pk.Name) + } + + return keys +} + func (s *timestreamRecordSource) ListDatabases(region string) []string { dbs := s.handler.BackendFor(region).ListDatabases() names := make([]string, 0, len(dbs)) diff --git a/services/timestreamquery/PARITY.md b/services/timestreamquery/PARITY.md index 6634208b98..762ba94cfe 100644 --- a/services/timestreamquery/PARITY.md +++ b/services/timestreamquery/PARITY.md @@ -40,8 +40,8 @@ families: gaps: [] items_still_open: - "Static type inference (ts_infer.go) types every select-list expression before execution, but a query using a construct it cannot parse or type keeps the older value-based column typing (and syntactic boolean/interval typing, ts_boolean.go) for the affected columns: positional ? and named @parameters (PrepareQuery), AT TIME ZONE, TABLESAMPLE, recursive CTEs, transform() over a timeseries (the engine has no implementation), and any function without a return-type rule (SQLite built-ins outside the Timestream function list); an empty result of such a column still reports VARCHAR" - - "Unverified against the service: integer literals are typed INTEGER when they fit 32 bits else BIGINT (supported-data-types.html lists int and bigint but not which a literal gets), and typeof() prints array(T), row(name T, ...) and timeseries(T) for nested types where the page gives only the notations array[T,...], row(T,...) and timeseries[row(timestamp, T,...)]" - - "QueryInsights QuerySpatialCoverage reports the table's partition key as measure_name unless the RecordSource implements PartitionKeySource (TablePartitionKeys); internal/app's timestreamRecordSource (internal/app/timestream_source.go) does not implement it yet, so a table with a customer-defined partition key is not measured on that key" + - "Unverified against the service: integer literals are typed INTEGER when they fit 32 bits else BIGINT (supported-data-types.html lists int and bigint but not which a literal gets; the SDK ScalarType enum has INTEGER, appended after UNKNOWN, so the service does emit it for something, and no recorded real response in the repo or the documentation shows a literal's ColumnInfo), and typeof() prints array(T), row(name T, ...) and timeseries(T) for nested types where the page gives only the notations array[T,...], row(T,...) and timeseries[row(timestamp, T,...)]" + - "Integer overflow is not an error: a 32-bit INTEGER result that overflows is widened to BIGINT and a 64-bit overflow (SQLite promotes it to a float) is reported as DOUBLE, where the service fails the query; CAST(double AS bigint) truncates (SQLite) rather than rounding, and TRY_CAST of an unparsable string yields 0 rather than NULL" structural_gaps: - "CreateScheduledQuery KmsKeyId is stored and echoed, but there is no at-rest encryption layer to apply it to." diff --git a/services/timestreamquery/query_execution.go b/services/timestreamquery/query_execution.go index c41bd86fa3..075ddd9405 100644 --- a/services/timestreamquery/query_execution.go +++ b/services/timestreamquery/query_execution.go @@ -366,6 +366,12 @@ func (b *InMemoryBackend) admitInsights(region, mode string) error { b.mu.Lock("admitInsights") defer b.mu.Unlock() + for r, last := range b.insightsLast { + if now.Sub(last) >= time.Second { + delete(b.insightsLast, r) + } + } + if last, ok := b.insightsLast[region]; ok && now.Sub(last) < time.Second { return fmt.Errorf("%w: query insights is limited to 1 query per second", ErrThrottling) } diff --git a/services/timestreamquery/ts_infer.go b/services/timestreamquery/ts_infer.go index a7705e81ec..d94764c6b4 100644 --- a/services/timestreamquery/ts_infer.go +++ b/services/timestreamquery/ts_infer.go @@ -651,7 +651,7 @@ func (inf *inferrer) inferCall(n *node, sc *scope) tsType { func (inf *inferrer) inferTypeof(n *node, arg tsType) tsType { if arg.known() { inf.edit("(CASE WHEN 0 THEN ", n.start, n.start+len(n.name)) - inf.closeEdit(" ELSE '"+arg.typeofName()+"' END)", n.end) + inf.closeEdit(" ELSE '"+strings.ReplaceAll(arg.typeofName(), "'", "''")+"' END)", n.end) } return scalar(tyVarchar) diff --git a/services/timestreamquery/ts_infer_robust_internal_test.go b/services/timestreamquery/ts_infer_robust_internal_test.go new file mode 100644 index 0000000000..eb6fc57cdc --- /dev/null +++ b/services/timestreamquery/ts_infer_robust_internal_test.go @@ -0,0 +1,131 @@ +package timestreamquery + +import ( + "strconv" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func abusiveQueries() map[string]string { + return map[string]string{ + "1mb string": "SELECT '" + strings.Repeat("a", 1<<20) + "'", + "1mb unterminated": "SELECT '" + strings.Repeat("a", 1<<20), + "1mb ident": "SELECT " + strings.Repeat("a", 1<<20), + "thousands of items": "SELECT " + strings.Repeat("1,", 20000) + "1", + "many unions": strings.Repeat("SELECT 1 UNION ALL ", 5000) + "SELECT 1", + "deep case": "SELECT " + strings.Repeat( + "CASE WHEN true THEN ", + 3000, + ) + "1" + strings.Repeat( + " END", + 3000, + ), + "deep arrays": "SELECT " + strings.Repeat("ARRAY[", 3000) + "1" + strings.Repeat("]", 3000), + "deep calls": "SELECT " + strings.Repeat("abs(", 3000) + "1" + strings.Repeat(")", 3000), + "deep unary": "SELECT " + strings.Repeat("-", 100000) + "1", + "deep not": "SELECT " + strings.Repeat("NOT ", 100000) + "true", + "deep ctes": strings.Repeat( + "WITH a AS (", + 3000, + ) + "SELECT 1" + strings.Repeat( + ") SELECT * FROM a", + 3000, + ), + "huge numeric": "SELECT " + strings.Repeat("9", 5000) + ", 1e999999, 0x, 1e, .e1", + "nul bytes": "SELECT '\x00', \"\x00\", \x00 FROM \x00", + "unicode": "SELECT '日本語', \"ключ\", 😀 FROM t", + "invalid utf8": "SELECT '\xff\xfe', \xc3\x28", + "unterminated quoted": `SELECT "abc`, + "unterminated comment": "SELECT 1 /* never closed", + "comment only": "-- nothing", + "block comment only": "/* nothing */", + "line comment at end": "SELECT 1 --", + "many lambdas": "SELECT " + strings.Repeat( + "filter(ARRAY[1], x -> ", + 2000, + ) + "true" + strings.Repeat( + ")", + 2000, + ), + "huge in list": "SELECT 1 IN (" + strings.Repeat("1,", 50000) + "1)", + "huge between chain": "SELECT " + strings.Repeat("1 BETWEEN 0 AND ", 2000) + "2", + "operators": "SELECT " + strings.Repeat("1 + ", 50000) + "1", + "parens balance": strings.Repeat(")", 50000), + "lone quote": "'", + "empty": "", + "only semicolons": ";;;;", + "interval junk": "SELECT 1d2h3m, 99999999999999999999d, interval '' day", + "cast garbage": "SELECT cast(1 as ), cast( as bigint), cast(1 as array(array(array(", + "deep row type": "SELECT cast(1 as " + strings.Repeat( + "array(", + 3000, + ) + "bigint" + strings.Repeat( + ")", + 3000, + ) + ")", + "dollar quote": "SELECT $$ -- x $$, $a$ /* y */ $a$", + "comment markers adj": "SELECT 1-/**/-1, 1/-/*x*/-1", + "backslash": `SELECT '\', "\\" -- \`, + "non-ascii whitespace": "SELECT 1 + 2", + "identifier like names": `SELECT typeof_x, "typeof"(1), ts_filter, filter_x FROM t`, + } +} + +func TestAnnotateAbusiveQueriesDoNotPanicOrHang(t *testing.T) { + t.Parallel() + + for name, q := range abusiveQueries() { + t.Run(name, func(t *testing.T) { + t.Parallel() + + start := time.Now() + + assert.NotPanics(t, func() { + _ = stripSQLComments(q) + _, _ = parseSQL(q) + _ = buildAnnotation(q, loadedSet{}, time.Time{}, nil) + }) + assert.Less(t, time.Since(start), 10*time.Second) + }) + } +} + +func FuzzAnnotateQuery(f *testing.F) { + for _, s := range []string{ + "SELECT 1", "SELECT a, count(*) FROM t WHERE time > ago(1h) GROUP BY a", "SELECT 'x' -- c", + "SELECT /* c */ CASE WHEN a THEN 1 END", + "WITH a AS (SELECT 1) SELECT * FROM a", "SELECT filter(ARRAY[1], x -> x > 0)", `SELECT "a--b"`, + } { + f.Add(s) + } + + f.Fuzz(func(_ *testing.T, q string) { + _ = stripSQLComments(q) + _, _ = parseSQL(q) + _ = buildAnnotation(q, loadedSet{}, time.Time{}, nil) + }) +} + +func TestAdmitInsightsLimiterStaysBounded(t *testing.T) { + t.Parallel() + + now := time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC) + b := NewInMemoryBackend("000000000000", "us-east-1") + b.SetClock(func() time.Time { return now }) + + for i := range 100 { + require.NoError(t, b.admitInsights("region-"+strconv.Itoa(i), insightsModeEnabled)) + } + + require.ErrorIs(t, b.admitInsights("region-0", insightsModeEnabled), ErrThrottling) + require.NoError(t, b.admitInsights("region-0", insightsModeDisabled), "queries without insights are never limited") + + now = now.Add(time.Second) + + require.NoError(t, b.admitInsights("region-0", insightsModeEnabled)) + assert.Len(t, b.insightsLast, 1) +} diff --git a/services/timestreamquery/ts_prune.go b/services/timestreamquery/ts_prune.go index 3dbebd38d7..5cb76368a5 100644 --- a/services/timestreamquery/ts_prune.go +++ b/services/timestreamquery/ts_prune.go @@ -79,7 +79,7 @@ func collectInstances(r *relation, tables loadedSet, insts *[]tableInst, conds * collectInstances(r.left, tables, insts, conds) collectInstances(r.right, tables, insts, conds) - if r.on != nil { + if r.on != nil && (r.joinType == "INNER" || r.joinType == "CROSS") { *conds = append(*conds, splitAnd(r.on)...) } case relSubquery, relUnnest, relValues: @@ -496,6 +496,10 @@ func temporalRange(scan pruneScan, recs []SourceRecord, now time.Time) int64 { if lo == nil && len(recs) > 0 { first := recs[0].Time.UnixNano() + for _, r := range recs[1:] { + first = min(first, r.Time.UnixNano()) + } + lo = &first } diff --git a/services/timestreamquery/ts_render.go b/services/timestreamquery/ts_render.go index 14b9ff8d7b..55d5c2d544 100644 --- a/services/timestreamquery/ts_render.go +++ b/services/timestreamquery/ts_render.go @@ -6,6 +6,7 @@ import ( "encoding/json/jsontext" "encoding/json/v2" "fmt" + "math" "strconv" "strings" "time" @@ -106,6 +107,10 @@ func renderInt(v any) Datum { case int64: return ScalarDatum(strconv.FormatInt(x, 10)) case float64: + if x != math.Trunc(x) || x >= twoPow63 || x < -twoPow63 { + return renderDouble(x) + } + return ScalarDatum(strconv.FormatInt(int64(x), 10)) case bool: if x { diff --git a/services/timestreamquery/ts_result.go b/services/timestreamquery/ts_result.go index 0119d8c737..c9e1561836 100644 --- a/services/timestreamquery/ts_result.go +++ b/services/timestreamquery/ts_result.go @@ -14,6 +14,8 @@ var ( reTSText = regexp.MustCompile(`^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.(\d{3}|\d{9})$`) ) +const twoPow63 = float64(1 << 63) + const ( kwNull = "null" kwTrue = "true" @@ -156,7 +158,8 @@ func readRows(rows *sql.Rows, plan []tsType) (*resultSet, error) { var static tsType if i < len(plan) { - static = plan[i] + static = reconcileStatic(plan[i], col) + plan[i] = static } info, typ, isStatic := columnFor(columnName(n, i), ctypes[i].DatabaseTypeName(), static, col) @@ -183,6 +186,55 @@ func readRows(rows *sql.Rows, plan []tsType) (*resultSet, error) { return rs, nil } +// reconcileStatic keeps a numeric static type only while every value fits it; otherwise it widens the type +// (32-bit overflow, a float SQLite overflowed to) or returns the zero type so value-based typing applies. +func reconcileStatic(t tsType, col []any) tsType { + switch t.kind { + case tyInteger, tyBigint: + return reconcileIntegral(t, col) + case tyDouble: + for _, v := range col { + if s, ok := v.(string); ok { + if _, err := strconv.ParseFloat(s, 64); err != nil { + return tsType{} + } + } + } + default: + } + + return t +} + +func reconcileIntegral(t tsType, col []any) tsType { + out := t + + for _, v := range col { + var n float64 + + switch x := v.(type) { + case int64: + n = float64(x) + case float64: + if x != math.Trunc(x) || x >= twoPow63 || x < -twoPow63 { + return scalar(tyDouble) + } + + n = x + case string, []byte: + return tsType{} + default: + continue + } + + if out.kind == tyInteger && (n > math.MaxInt32 || n < math.MinInt32) { + out = scalar(tyBigint) + } + } + + return out +} + func scanAll(rows *sql.Rows, width int) ([][]any, error) { var raw [][]any diff --git a/services/timestreamquery/ts_static_types_test.go b/services/timestreamquery/ts_static_types_test.go new file mode 100644 index 0000000000..8733abfb9a --- /dev/null +++ b/services/timestreamquery/ts_static_types_test.go @@ -0,0 +1,411 @@ +package timestreamquery_test + +import ( + "regexp" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/timestreamquery" +) + +func corpusBackend(t *testing.T) *timestreamquery.InMemoryBackend { + t.Helper() + + now := fnNow() + mk := func(m time.Duration, name, typ, v, host, region string) timestreamquery.SourceRecord { + return timestreamquery.SourceRecord{ + Time: now.Add(-m), + MeasureName: name, + MeasureValueType: typ, + MeasureValue: v, + Dimensions: []timestreamquery.SourceDimension{ + {Name: "hostname", Value: host}, + {Name: "region", Value: region}, + }, + } + } + + src := &memSource{tables: map[string][]timestreamquery.SourceRecord{"db.t": { + mk(20*time.Minute, "cpu_utilization", "DOUBLE", "10.5", "a", "us-east-1"), + mk(10*time.Minute, "cpu_utilization", "DOUBLE", "20", "a", "us-east-1"), + mk(5*time.Minute, "cpu_utilization", "DOUBLE", "30", "b", "eu-west-1"), + mk(5*time.Minute, "mem", "BIGINT", "7", "b", "eu-west-1"), + }}} + + b := timestreamquery.NewInMemoryBackend("000000000000", "us-east-1") + b.SetClock(fnNow) + b.SetRecordSource(src) + + return b +} + +func runCorpus(t *testing.T, q string) ([]string, [][]string) { + t.Helper() + + page, err := corpusBackend(t).QueryWithOptions(t.Context(), timestreamquery.QueryOptions{QueryString: q}) + require.NoError(t, err, q) + + types := make([]string, 0, len(page.Columns)) + for _, c := range page.Columns { + types = append(types, renderType(c.Type)) + } + + rows := make([][]string, 0, len(page.Rows)) + + for _, r := range page.Rows { + row := make([]string, 0, len(r.Data)) + for _, d := range r.Data { + row = append(row, renderDatum(d)) + } + + rows = append(rows, row) + } + + return types, rows +} + +func TestQuery_StaticTypeCorpus(t *testing.T) { + t.Parallel() + + const cpu = " FROM db.t WHERE measure_name = 'cpu_utilization'" + + tests := []struct { + name string + query string + types string + first string + }{ + {"count", "SELECT count(*), sum(measure_value::bigint), avg(measure_value::double) FROM db.t", + "BIGINT,BIGINT,DOUBLE", "4|7|20.166666666666668"}, + {"group", "SELECT hostname, count(*) c FROM db.t GROUP BY hostname ORDER BY c DESC", "VARCHAR,BIGINT", "b|2"}, + { + "bin", + "SELECT bin(time, 1m) AS b, avg(measure_value::double) AS a" + cpu + + " AND time > ago(1h) GROUP BY bin(time, 1m) ORDER BY b", + "TIMESTAMP,DOUBLE", + "2026-10-31 11:40:00.000000000|10.5", + }, + { + "case varchar", + "SELECT CASE WHEN measure_value::double > 15 THEN 'high' ELSE 'low' END" + cpu + " ORDER BY time", + "VARCHAR", + "low", + }, + { + "case int", + "SELECT CASE WHEN measure_value::double > 15 THEN 1 ELSE 0 END" + cpu + " ORDER BY time", + "INTEGER", + "0", + }, + {"date_trunc", "SELECT date_trunc('hour', time), count(*) FROM db.t GROUP BY 1", "TIMESTAMP,BIGINT", + "2026-10-31 11:00:00.000000000|4"}, + { + "timeseries", + "SELECT hostname, create_time_series(time, measure_value::double)" + cpu + " GROUP BY hostname ORDER BY 1", + "VARCHAR,timeseries(DOUBLE)", + "", + }, + { + "interpolate unnest", + "SELECT hostname, time, value FROM (SELECT hostname, " + + "INTERPOLATE_LINEAR(CREATE_TIME_SERIES(time, measure_value::double), " + + "SEQUENCE(ago(1h), now(), 10m)) AS ts" + cpu + " GROUP BY hostname) " + + "CROSS JOIN UNNEST(ts) AS u (time, value) ORDER BY 1, 2", + "VARCHAR,TIMESTAMP,DOUBLE", + "a|2026-10-31 11:40:00.000000000|10.5", + }, + {"percentile", "SELECT approx_percentile(measure_value::double, 0.9), approx_distinct(hostname)" + cpu, + "DOUBLE,BIGINT", "30.0|2"}, + {"cte join", "WITH a AS (SELECT hostname, avg(measure_value::double) av" + cpu + " GROUP BY hostname), " + + "b AS (SELECT hostname, count(*) n FROM db.t GROUP BY hostname) " + + "SELECT a.hostname, a.av, b.n FROM a JOIN b ON a.hostname = b.hostname ORDER BY 1", + "VARCHAR,DOUBLE,BIGINT", "a|15.25|2"}, + { + "window", + "SELECT row_number() OVER (PARTITION BY hostname ORDER BY time), " + + "lag(measure_value::double) OVER (ORDER BY time)" + cpu + " ORDER BY time", + "BIGINT,DOUBLE", + "1|", + }, + {"multi measure columns", "SELECT measure_value::bigint, measure_value::double FROM db.t LIMIT 1", + "BIGINT,DOUBLE", ""}, + { + "strings", + "SELECT upper(hostname), length(hostname), concat(hostname, '-', region), split(region, '-') FROM db.t LIMIT 1", + "VARCHAR,BIGINT,VARCHAR,array(VARCHAR)", + "A|1|a-us-east-1|[us, east, 1]", + }, + { + "casts", + "SELECT cast(1 AS double), cast('5' AS bigint), cast(time AS date), cast(1 AS varchar)" + cpu + " LIMIT 1", + "DOUBLE,BIGINT,DATE,VARCHAR", + "1.0|5|2026-10-31|1", + }, + { + "predicates", + "SELECT hostname IN ('a'), hostname LIKE 'a%', hostname IS NOT NULL, NOT (hostname = 'a') FROM db.t LIMIT 1", + "BOOLEAN,BOOLEAN,BOOLEAN,BOOLEAN", + "true|true|true|false", + }, + {"union widen", "SELECT 1 AS a UNION ALL SELECT 2.5 ORDER BY 1", "DOUBLE", "1.0"}, + {"union varchar", "SELECT hostname FROM db.t UNION SELECT region FROM db.t ORDER BY 1", "VARCHAR", "a"}, + { + "typeof", + "SELECT typeof(1), typeof(1.5), typeof(time), typeof(count(*)), typeof(ARRAY[1.5]) FROM db.t LIMIT 1", + "VARCHAR,VARCHAR,VARCHAR,VARCHAR,VARCHAR", + "integer|double|timestamp|bigint|array(double)", + }, + { + "arrays", + "SELECT ARRAY[1, 2], ARRAY['a'], ARRAY[1.5, 2], sequence(1, 5, 2)", + "array(INTEGER),array(VARCHAR),array(DOUBLE),array(INTEGER)", + "[1, 2]|[a]|[1.5, 2.0]|[1, 3, 5]", + }, + {"time arithmetic", "SELECT time - ago(1h), time + 1h, now() - time FROM db.t LIMIT 1", + "INTERVAL_DAY_TO_SECOND,TIMESTAMP,INTERVAL_DAY_TO_SECOND", ""}, + { + "integer widening", + "SELECT 1 + CAST(2 AS bigint), 1 + 1.5, 7 / 2, 7.0 / 2, 2147483648", + "BIGINT,DOUBLE,INTEGER,DOUBLE,BIGINT", + "3|2.5|3|3.5|2147483648", + }, + {"int32 overflow widens", "SELECT 2147483647 + 1", "BIGINT", "2147483648"}, + {"bigint overflow is not wrapped", "SELECT 9223372036854775807 + 1", "DOUBLE", "9.223372036854776E18"}, + {"empty result", "SELECT hostname, time, measure_value::double" + cpu + " AND hostname = 'zzz'", + "VARCHAR,TIMESTAMP,DOUBLE", ""}, + { + "empty aggregate", + "SELECT count(*), max(measure_value::double) FROM db.t WHERE hostname = 'zzz'", + "BIGINT,DOUBLE", + "0|", + }, + {"null", "SELECT null, cast(null AS bigint), coalesce(null, 1)", "UNKNOWN,BIGINT,INTEGER", "||1"}, + {"scalar subquery", "SELECT hostname, (SELECT count(*) FROM db.t) FROM db.t LIMIT 1", "VARCHAR,BIGINT", "a|4"}, + {"comments", "SELECT /* x */ 1 -- y\n, '-- not a comment'", "INTEGER,VARCHAR", "1|-- not a comment"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + types, rows := runCorpus(t, tc.query) + assert.Equal(t, tc.types, strings.Join(types, ",")) + + if tc.first != "" { + require.NotEmpty(t, rows) + assert.Equal(t, tc.first, strings.Join(rows[0], "|")) + } + }) + } +} + +var ( + reCorpusInt = regexp.MustCompile(`^-?\d+$`) + reCorpusDbl = regexp.MustCompile(`^(-?\d+\.\d+(E-?\d+)?|NaN|-?Infinity)$`) + reCorpusBool = regexp.MustCompile(`^(true|false)$`) + reCorpusTS = regexp.MustCompile(`^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{9}$`) + reCorpusDate = regexp.MustCompile(`^\d{4}-\d\d-\d\d$`) +) + +// Every function with a fixed declared return type must produce a value of that storage class at runtime. +func TestQuery_FunctionReturnTypesMatchRuntime(t *testing.T) { + t.Parallel() + + groups := []struct { + typ string + re *regexp.Regexp + exprs []string + }{ + { + "BIGINT", + reCorpusInt, + []string{ + "count(*)", + "count_if(true)", + "approx_distinct(hostname)", + "length('abc')", + "strpos('abc', 'b')", + "cardinality(ARRAY[1])", + "json_array_length('[1]')", + "year(now())", + "month(now())", + "day(now())", + "hour(now())", + "minute(now())", + "second(now())", + "quarter(now())", + "week(now())", + "day_of_week(now())", + "day_of_year(now())", + "date_diff('second', now(), now())", + "to_milliseconds(now())", + "to_nanoseconds(now())", + "codepoint('a')", + "levenshtein_distance('a', 'b')", + "bitwise_and(5, 3)", + "row_number() OVER (ORDER BY time)", + "rank() OVER (ORDER BY time)", + "dense_rank() OVER (ORDER BY time)", + "ntile(2) OVER (ORDER BY time)", + "array_position(ARRAY[1, 2], 2)", + "sum(1)", + "extract(year FROM now())", + }, + }, + {"DOUBLE", reCorpusDbl, []string{ + "avg(measure_value::double)", "stddev(measure_value::double)", "variance(measure_value::double)", "sqrt(4)", + "ln(1)", "exp(0)", "power(2, 3)", "to_unixtime(now())", "pi()", "rand()", "log10(100)", "sin(0)", "cbrt(8)", + "radians(180)", "degrees(1)", "percent_rank() OVER (ORDER BY time)", "cume_dist() OVER (ORDER BY time)", + "avg(1)", "sum(1.5)", "ceil(1.2)", "floor(1.7)", "round(1.5)", "round(measure_value::double, 1)", + "approx_percentile(measure_value::double, 0.5)", "geometric_mean(measure_value::double)", "abs(-1.5)", + }}, + { + "BOOLEAN", + reCorpusBool, + []string{ + "contains(ARRAY[1], 1)", + "regexp_like('a', 'a')", + "starts_with('ab', 'a')", + "any_match(ARRAY[1], x -> x > 0)", + "bool_and(true)", + "bool_or(false)", + "'a' LIKE 'a%'", + "1 IN (1, 2)", + "1 BETWEEN 0 AND 2", + "null IS NULL", + }, + }, + {"TIMESTAMP", reCorpusTS, []string{ + "now()", "ago(1h)", "from_unixtime(1)", "from_milliseconds(1)", "date_parse('2020-01-01', '%Y-%m-%d')", + "date_trunc('hour', now())", "date_add('day', 1, now())", "bin(now(), 1h)", "max(time)", "min(time)", + "timestamp '2020-01-01 00:00:00'", "current_timestamp", + }}, + {"DATE", reCorpusDate, []string{"current_date", "date '2020-01-01'", "cast(now() AS date)"}}, + {"VARCHAR", regexp.MustCompile(`.*`), []string{ + "lower('A')", "upper('a')", "trim(' a ')", "replace('abc', 'b', 'x')", "substr('abc', 2)", + "date_format(now(), '%Y')", "format_datetime(now(), 'yyyy')", "to_iso8601(now())", + "json_format(json_parse('[1]'))", "typeof(1)", "regexp_extract('a1', '[0-9]')", "lpad('a', 3, 'x')", + "split_part('a,b', ',', 1)", "concat('a', 'b')", "chr(65)", "cast(1 AS varchar)", "arbitrary(hostname)", + "min_by(hostname, time)", "json_extract_scalar('{\"a\":1}', '$.a')", + }}, + } + + b := corpusBackend(t) + + for _, g := range groups { + for _, expr := range g.exprs { + t.Run(g.typ+"/"+expr, func(t *testing.T) { + t.Parallel() + + page, err := b.QueryWithOptions(t.Context(), timestreamquery.QueryOptions{ + QueryString: "SELECT " + expr + " FROM db.t WHERE measure_name = 'cpu_utilization'", + }) + require.NoError(t, err) + require.Len(t, page.Columns, 1) + require.NotEmpty(t, page.Rows) + + assert.Equal( + t, + g.typ, + renderType(page.Columns[0].Type), + "declared type must survive the runtime values", + ) + + for _, r := range page.Rows { + if r.Data[0].ScalarValue != nil { + assert.Regexp(t, g.re, *r.Data[0].ScalarValue) + } + } + }) + } + } +} + +func TestQuery_TypeofEscapesRowFieldNames(t *testing.T) { + t.Parallel() + + _, rows := runCorpus(t, `SELECT typeof(CAST(ROW(1) AS ROW("a'b" bigint)))`) + if assert.NotEmpty(t, rows) { + assert.Equal(t, []string{"row(a'b bigint)"}, rows[0]) + } +} + +func TestQuery_InsightsTemporalRangeNeverNarrowerThanScan(t *testing.T) { + t.Parallel() + + const ( + minute = int64(time.Minute) + data = 20 * minute + ) + + tests := []struct { + name string + query string + want int64 + }{ + {"between ago and now", "SELECT * FROM db.t WHERE time BETWEEN ago(1h) AND now()", 60 * minute}, + {"gt and le", "SELECT * FROM db.t WHERE time > ago(30m) AND time <= ago(10m)", 20 * minute}, + {"no predicate scans the data extent", "SELECT * FROM db.t", data}, + {"or of ranges is not narrowed", "SELECT * FROM db.t WHERE time > ago(5m) OR hostname = 'a'", data}, + {"negated predicate", "SELECT * FROM db.t WHERE NOT (time > ago(5m))", data}, + {"not between", "SELECT * FROM db.t WHERE time NOT BETWEEN ago(5m) AND now()", data}, + {"non literal bound", "SELECT * FROM db.t WHERE time > (SELECT min(time) FROM db.t)", data}, + {"cte predicate", "WITH w AS (SELECT * FROM db.t WHERE time > ago(10m)) SELECT * FROM w", 10 * minute}, + { + "derived column is not the table time", + "SELECT * FROM (SELECT hostname AS time FROM db.t) WHERE time > 'x'", + data, + }, + { + "left join on predicate does not prune the preserved side", + "SELECT * FROM db.t a LEFT JOIN db.t b ON a.hostname = b.hostname AND a.time > ago(10m) WHERE b.time > ago(5m)", + data, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + b := corpusBackend(t) + + page, err := b.QueryWithOptions(t.Context(), timestreamquery.QueryOptions{ + QueryString: tc.query, InsightsMode: "ENABLED_WITH_RATE_CONTROL", + }) + require.NoError(t, err) + require.NotNil(t, page.Insights) + require.NotNil(t, page.Insights.TemporalRange) + assert.Equal(t, tc.want, page.Insights.TemporalRange.Max.Value) + }) + } +} + +func TestQuery_InsightsUnsortedRecordsUseOldest(t *testing.T) { + t.Parallel() + + now := fnNow() + rec := func(ago time.Duration) timestreamquery.SourceRecord { + return timestreamquery.SourceRecord{ + Time: now.Add(-ago), + MeasureName: "m", + MeasureValueType: "BIGINT", + MeasureValue: "1", + } + } + + b := timestreamquery.NewInMemoryBackend("000000000000", "us-east-1") + b.SetClock(fnNow) + b.SetRecordSource(&memSource{tables: map[string][]timestreamquery.SourceRecord{ + "db.t": {rec(time.Minute), rec(30 * time.Minute), rec(5 * time.Minute)}, + }}) + + page, err := b.QueryWithOptions(t.Context(), timestreamquery.QueryOptions{ + QueryString: "SELECT * FROM db.t", InsightsMode: "ENABLED_WITH_RATE_CONTROL", + }) + require.NoError(t, err) + assert.Equal(t, int64(30*time.Minute), page.Insights.TemporalRange.Max.Value) +} From 4a6da1d156af76f1e048e88ca1bf42549d3a8c9d Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 17:12:54 -0600 Subject: [PATCH 5/9] test(azure): private transport for the Functions test client Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- services/azurefunctions/helpers_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/azurefunctions/helpers_test.go b/services/azurefunctions/helpers_test.go index 87b38fd984..84ba7184f7 100644 --- a/services/azurefunctions/helpers_test.go +++ b/services/azurefunctions/helpers_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/require" + "github.com/blackbirdworks/gopherstack/pkgs/testclient" "github.com/blackbirdworks/gopherstack/services/azurefunctions" ) @@ -34,7 +35,7 @@ func newEnv(t *testing.T, withRuntime bool) *env { azurefunctions.Settings{Domain: testDomain, Port: azurefunctions.DefaultPort, StartupTimeout: 20 * time.Second}, ) - e := &env{backend: b, client: &http.Client{Timeout: 30 * time.Second}} + e := &env{backend: b, client: &http.Client{Transport: testclient.New(t).Transport, Timeout: 30 * time.Second}} if withRuntime { e.rt = newFakeRuntime() From 3ffec8aabdebdf8d84bec8347d380dc8952366ca Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 17:12:55 -0600 Subject: [PATCH 6/9] test: no test client runs on the default transport; guard the pattern A test server's Close drops the default transport's idle connections, so a test client without its own transport can have its request broken by another test's teardown. The remaining bare clients use private transports and the test guard now rejects http.Client literals without a Transport. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- internal/app/cli_test.go | 2 +- internal/app/main_test.go | 5 +- ...nsibility_customresource_lifecycle_test.go | 7 +- ...urces_extensibility_customresource_test.go | 7 +- services/lambda/function_url_host_test.go | 3 +- services/lambdaweb/dataplane_test.go | 19 +++-- services/lambdaweb/docker_engine_test.go | 5 +- services/lambdaweb/logs_test.go | 4 +- services/lambdaweb/runtime_status_test.go | 3 +- services/lambdaweb/scaling_test.go | 5 +- services/lambdaweb/validation_test.go | 4 +- services/signin/routing_test.go | 7 +- services/sns/delivery_test.go | 3 +- services/sns/handler_test.go | 3 +- services/ssooidc/authorization_code_test.go | 15 +++- .../no_default_client_in_tests_guard_test.go | 77 ++++++++++++++++++- test/integration/lambda_url_test.go | 3 +- test/integration/lambdaweb_parity_test.go | 4 +- test/integration/s3_presigned_test.go | 2 +- test/integration/s3_realism_test.go | 4 +- test/terraform/terraform_test.go | 2 + 21 files changed, 149 insertions(+), 35 deletions(-) diff --git a/internal/app/cli_test.go b/internal/app/cli_test.go index 59c5e09539..a0d7a07795 100644 --- a/internal/app/cli_test.go +++ b/internal/app/cli_test.go @@ -3141,7 +3141,7 @@ func TestLocalstackCompatibilityEndpoints(t *testing.T) { waitForServerReady(t, port) - client := &http.Client{Timeout: 2 * time.Second} + client := &http.Client{Transport: testclient.New(t).Transport, Timeout: 2 * time.Second} tests := []struct { validate func(t *testing.T, body map[string]any) diff --git a/internal/app/main_test.go b/internal/app/main_test.go index 2f27b24373..ad7d306232 100644 --- a/internal/app/main_test.go +++ b/internal/app/main_test.go @@ -16,6 +16,8 @@ import ( "time" "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/pkgs/httpclient" ) func TestMultipleServersStartupAndShutdown(t *testing.T) { @@ -109,7 +111,8 @@ func startServerRetryingPort(t *testing.T, demo bool) (int, chan struct{}, chan // exits (delivering to errChan), or the deadline elapses. Matching the per-attempt account ID proves // the responder is this attempt's server, not another test's server that grabbed the port first. func waitForInstance(port int, accountID string, errChan <-chan error, timeout, interval time.Duration) (bool, error) { - client := &http.Client{Timeout: 1 * time.Second} + client := httpclient.New(1 * time.Second) + defer client.CloseIdleConnections() deadline := time.Now().Add(timeout) ticker := time.NewTicker(interval) defer ticker.Stop() diff --git a/services/cloudformation/resources_extensibility_customresource_lifecycle_test.go b/services/cloudformation/resources_extensibility_customresource_lifecycle_test.go index 67ced1c868..5c53018c76 100644 --- a/services/cloudformation/resources_extensibility_customresource_lifecycle_test.go +++ b/services/cloudformation/resources_extensibility_customresource_lifecycle_test.go @@ -11,6 +11,7 @@ import ( "github.com/stretchr/testify/require" "github.com/blackbirdworks/gopherstack/pkgs/jsonx" + "github.com/blackbirdworks/gopherstack/pkgs/testclient" "github.com/blackbirdworks/gopherstack/services/cloudformation" lambdabackend "github.com/blackbirdworks/gopherstack/services/lambda" ) @@ -64,7 +65,7 @@ func TestResourceCreator_CustomResource_DeleteEvent(t *testing.T) { "PhysicalResourceId": ev.PhysicalResourceID, } body, _ := json.Marshal(resp, jsonx.V1()) - client := &http.Client{Timeout: 2 * time.Second} + client := &http.Client{Transport: testclient.New(t).Transport, Timeout: 2 * time.Second} req, reqErr := http.NewRequestWithContext( ctx, http.MethodPut, @@ -159,7 +160,7 @@ func TestResourceCreator_CustomResource_UpdateEvent(t *testing.T) { "PhysicalResourceId": ev.PhysicalResourceID, } body, _ := json.Marshal(resp, jsonx.V1()) - client := &http.Client{Timeout: 2 * time.Second} + client := &http.Client{Transport: testclient.New(t).Transport, Timeout: 2 * time.Second} req, reqErr := http.NewRequestWithContext( ctx, http.MethodPut, @@ -268,7 +269,7 @@ func TestStack_CustomResource_UpdateStack_SendsUpdateEvent(t *testing.T) { "PhysicalResourceId": physID, } body, _ := json.Marshal(resp, jsonx.V1()) - client := &http.Client{Timeout: 2 * time.Second} + client := &http.Client{Transport: testclient.New(t).Transport, Timeout: 2 * time.Second} req, reqErr := http.NewRequestWithContext( ctx, http.MethodPut, diff --git a/services/cloudformation/resources_extensibility_customresource_test.go b/services/cloudformation/resources_extensibility_customresource_test.go index 2161711146..259b7f5cc2 100644 --- a/services/cloudformation/resources_extensibility_customresource_test.go +++ b/services/cloudformation/resources_extensibility_customresource_test.go @@ -14,6 +14,7 @@ import ( "github.com/blackbirdworks/gopherstack/pkgs/jsonx" "github.com/blackbirdworks/gopherstack/pkgs/page" + "github.com/blackbirdworks/gopherstack/pkgs/testclient" "github.com/blackbirdworks/gopherstack/services/cloudformation" lambdabackend "github.com/blackbirdworks/gopherstack/services/lambda" ) @@ -162,7 +163,7 @@ func TestResourceCreator_CustomResource_ResponseURL_RoundTrip(t *testing.T) { } body, _ := json.Marshal(resp, jsonx.V1()) - client := &http.Client{} + client := testclient.New(t) putReq, _ := http.NewRequestWithContext(t.Context(), http.MethodPut, url, newBytesReader(body)) putReq.ContentLength = int64(len(body)) @@ -365,7 +366,7 @@ func TestResourceCreator_CustomResource_FAILEDResponse(t *testing.T) { "PhysicalResourceId": "failing-resource-001", } body, _ := json.Marshal(resp, jsonx.V1()) - client := &http.Client{} + client := testclient.New(t) req, _ := http.NewRequestWithContext(t.Context(), http.MethodPut, url, newBytesReader(body)) req.ContentLength = int64(len(body)) res, err := client.Do(req) @@ -461,7 +462,7 @@ func TestStack_CustomResource_GetAtt_DataOutputs(t *testing.T) { }, } body, _ := json.Marshal(resp, jsonx.V1()) - client := &http.Client{} + client := testclient.New(t) req, _ := http.NewRequestWithContext(t.Context(), http.MethodPut, url, newBytesReader(body)) req.ContentLength = int64(len(body)) res, err := client.Do(req) diff --git a/services/lambda/function_url_host_test.go b/services/lambda/function_url_host_test.go index 77ca26b365..cd8fe69e91 100644 --- a/services/lambda/function_url_host_test.go +++ b/services/lambda/function_url_host_test.go @@ -22,6 +22,7 @@ import ( "github.com/blackbirdworks/gopherstack/pkgs/jsonx" "github.com/blackbirdworks/gopherstack/pkgs/portalloc" + "github.com/blackbirdworks/gopherstack/pkgs/testclient" "github.com/blackbirdworks/gopherstack/services/lambda" ) @@ -55,7 +56,7 @@ func runFakeRuntime(t *testing.T, port int, response string, events chan<- []byt go func() { defer close(done) - client := &http.Client{Timeout: 0} + client := &http.Client{Transport: testclient.New(t).Transport, Timeout: 0} for t.Context().Err() == nil { req, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, base+"next", nil) diff --git a/services/lambdaweb/dataplane_test.go b/services/lambdaweb/dataplane_test.go index b21cf13e47..1c5ea0e794 100644 --- a/services/lambdaweb/dataplane_test.go +++ b/services/lambdaweb/dataplane_test.go @@ -23,6 +23,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/blackbirdworks/gopherstack/pkgs/testclient" "github.com/blackbirdworks/gopherstack/services/lambdaweb" ) @@ -159,7 +160,8 @@ func newDataEnv(t *testing.T) *dataEnv { return &dataEnv{ testEnv: env, launcher: l, domain: aws.ToString(created.Endpoint.DomainName), - rev1: aws.ToString(created.Revision.RevisionId), http: &http.Client{Timeout: 30 * time.Second}, + rev1: aws.ToString(created.Revision.RevisionId), + http: &http.Client{Transport: testclient.New(t).Transport, Timeout: 30 * time.Second}, } } @@ -292,7 +294,10 @@ func TestDataPlane_EndpointStates(t *testing.T) { created := env.createFunction(t, "app") domain := aws.ToString(created.Endpoint.DomainName) - d := &dataEnv{testEnv: env, launcher: l, domain: domain, http: &http.Client{Timeout: 30 * time.Second}} + d := &dataEnv{ + testEnv: env, launcher: l, domain: domain, + http: &http.Client{Transport: testclient.New(t).Transport, Timeout: 30 * time.Second}, + } resp := d.get(t) assert.Equal(t, http.StatusConflict, resp.StatusCode, "a Pending endpoint is not served") @@ -375,7 +380,7 @@ func TestDataPlane_LatestRevisionFollowsNewest(t *testing.T) { testEnv: env, launcher: l, domain: aws.ToString(ep.DomainName), - http: &http.Client{Timeout: 30 * time.Second}, + http: &http.Client{Transport: testclient.New(t).Transport, Timeout: 30 * time.Second}, } newest := aws.ToString(env.createRevision(t).RevisionId) @@ -448,7 +453,7 @@ func TestDataPlane_MaxEnvironmentsCapacity(t *testing.T) { testEnv: env, launcher: l, domain: aws.ToString(created.Endpoint.DomainName), - http: &http.Client{Timeout: 30 * time.Second}, + http: &http.Client{Transport: testclient.New(t).Transport, Timeout: 30 * time.Second}, } var wg sync.WaitGroup @@ -557,7 +562,7 @@ func TestDataPlane_StubEngine(t *testing.T) { d := &dataEnv{ testEnv: env, domain: aws.ToString(created.Endpoint.DomainName), - http: &http.Client{Timeout: 30 * time.Second}, + http: &http.Client{Transport: testclient.New(t).Transport, Timeout: 30 * time.Second}, } resp := d.get(t) @@ -586,7 +591,7 @@ func TestDataPlane_RequestTimeout(t *testing.T) { testEnv: env, launcher: l, domain: aws.ToString(created.Endpoint.DomainName), - http: &http.Client{Timeout: 30 * time.Second}, + http: &http.Client{Transport: testclient.New(t).Transport, Timeout: 30 * time.Second}, } resp := d.get(t) @@ -625,7 +630,7 @@ func newIamEnv(t *testing.T) (*dataEnv, string) { d := &dataEnv{ testEnv: env, launcher: l, domain: aws.ToString(created.Endpoint.DomainName), - http: &http.Client{Timeout: 30 * time.Second}, + http: &http.Client{Transport: testclient.New(t).Transport, Timeout: 30 * time.Second}, } return d, aws.ToString(created.Revision.RevisionId) diff --git a/services/lambdaweb/docker_engine_test.go b/services/lambdaweb/docker_engine_test.go index 95ed7a8853..4dcb342d5c 100644 --- a/services/lambdaweb/docker_engine_test.go +++ b/services/lambdaweb/docker_engine_test.go @@ -16,6 +16,7 @@ import ( "github.com/blackbirdworks/gopherstack/pkgs/container" "github.com/blackbirdworks/gopherstack/pkgs/jsonx" + "github.com/blackbirdworks/gopherstack/pkgs/testclient" "github.com/blackbirdworks/gopherstack/services/lambdaweb" ) @@ -83,7 +84,7 @@ func TestDockerEngine_ServesRealApp(t *testing.T) { d := &dataEnv{ testEnv: env, domain: aws.ToString(created.Endpoint.DomainName), - http: &http.Client{Timeout: 2 * time.Minute}, + http: &http.Client{Transport: testclient.New(t).Transport, Timeout: 2 * time.Minute}, } resp := d.do(t, http.MethodGet, d.domain, "/ping", nil) @@ -144,7 +145,7 @@ func TestDockerEngine_ScalesOutAndToZero(t *testing.T) { d := &dataEnv{ testEnv: env, domain: aws.ToString(created.Endpoint.DomainName), - http: &http.Client{Timeout: 2 * time.Minute}, + http: &http.Client{Transport: testclient.New(t).Transport, Timeout: 2 * time.Minute}, } hosts := make(chan string, 2) diff --git a/services/lambdaweb/logs_test.go b/services/lambdaweb/logs_test.go index 892207222c..299cd3b38d 100644 --- a/services/lambdaweb/logs_test.go +++ b/services/lambdaweb/logs_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/require" "github.com/blackbirdworks/gopherstack/pkgs/jsonx" + "github.com/blackbirdworks/gopherstack/pkgs/testclient" "github.com/blackbirdworks/gopherstack/services/lambdaweb" ) @@ -50,7 +51,8 @@ func newLoggedEnv(t *testing.T, o logOpts) (*dataEnv, *fakeLogs) { return &dataEnv{ testEnv: env, launcher: l, domain: aws.ToString(created.Endpoint.DomainName), - rev1: aws.ToString(created.Revision.RevisionId), http: &http.Client{Timeout: 30 * time.Second}, + rev1: aws.ToString(created.Revision.RevisionId), + http: &http.Client{Transport: testclient.New(t).Transport, Timeout: 30 * time.Second}, }, logs } diff --git a/services/lambdaweb/runtime_status_test.go b/services/lambdaweb/runtime_status_test.go index b2df88b881..1459c964e4 100644 --- a/services/lambdaweb/runtime_status_test.go +++ b/services/lambdaweb/runtime_status_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/blackbirdworks/gopherstack/pkgs/testclient" "github.com/blackbirdworks/gopherstack/services/lambdaweb" ) @@ -101,7 +102,7 @@ func TestDataPlane_EnvironmentFailureStatus(t *testing.T) { d := &dataEnv{ testEnv: env, domain: aws.ToString(created.Endpoint.DomainName), - http: &http.Client{Timeout: 30 * time.Second}, + http: &http.Client{Transport: testclient.New(t).Transport, Timeout: 30 * time.Second}, } resp := d.get(t) diff --git a/services/lambdaweb/scaling_test.go b/services/lambdaweb/scaling_test.go index c42b0421a4..a1ab3fab89 100644 --- a/services/lambdaweb/scaling_test.go +++ b/services/lambdaweb/scaling_test.go @@ -11,6 +11,8 @@ import ( "github.com/aws/aws-sdk-go-v2/service/lambdaweb/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/pkgs/testclient" ) type scaleOpts struct { @@ -44,7 +46,8 @@ func newScaledEnv(t *testing.T, o scaleOpts) (*dataEnv, *fakeLauncher) { d := &dataEnv{ testEnv: env, launcher: l, domain: aws.ToString(created.Endpoint.DomainName), - rev1: aws.ToString(created.Revision.RevisionId), http: &http.Client{Timeout: 30 * time.Second}, + rev1: aws.ToString(created.Revision.RevisionId), + http: &http.Client{Transport: testclient.New(t).Transport, Timeout: 30 * time.Second}, } return d, l diff --git a/services/lambdaweb/validation_test.go b/services/lambdaweb/validation_test.go index 765565f28c..d18fa663a6 100644 --- a/services/lambdaweb/validation_test.go +++ b/services/lambdaweb/validation_test.go @@ -11,6 +11,8 @@ import ( lwsdk "github.com/aws/aws-sdk-go-v2/service/lambdaweb" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/pkgs/testclient" ) var ( @@ -148,7 +150,7 @@ func TestValidation_KeyDisabledAfterCreationFailsLaunch(t *testing.T) { keys.err.Store(&errNoKey) - d := &dataEnv{testEnv: env, launcher: l, domain: aws.ToString(created.Endpoint.DomainName), http: &http.Client{}} + d := &dataEnv{testEnv: env, launcher: l, domain: aws.ToString(created.Endpoint.DomainName), http: testclient.New(t)} resp := d.get(t) assert.Equal(t, http.StatusBadGateway, resp.StatusCode) diff --git a/services/signin/routing_test.go b/services/signin/routing_test.go index 12168eb09d..c36313523c 100644 --- a/services/signin/routing_test.go +++ b/services/signin/routing_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/blackbirdworks/gopherstack/pkgs/testclient" "github.com/blackbirdworks/gopherstack/services/signin" ) @@ -135,7 +136,10 @@ func TestAuthorizeEndpointIssuesCode(t *testing.T) { t.Parallel() f := newFixture(t) - hc := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + hc := &http.Client{ + Transport: testclient.New(t).Transport, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } q := "?client_id=" + testClient + "&redirect_uri=http://127.0.0.1:8080/callback&state=xyz" + "&code_challenge_method=S256&code_challenge=" + challenge() @@ -216,6 +220,7 @@ func TestAuthorizeRedirectTargets(t *testing.T) { f := newFixture(t) hc := &http.Client{ + Transport: testclient.New(t).Transport, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, } q := "?client_id=" + testClient + "&redirect_uri=" + url.QueryEscape(tt.redirect) + diff --git a/services/sns/delivery_test.go b/services/sns/delivery_test.go index 86399dfd39..0d7b88e71e 100644 --- a/services/sns/delivery_test.go +++ b/services/sns/delivery_test.go @@ -14,6 +14,7 @@ import ( "github.com/stretchr/testify/require" "github.com/blackbirdworks/gopherstack/pkgs/jsonx" + "github.com/blackbirdworks/gopherstack/pkgs/testclient" "github.com/blackbirdworks/gopherstack/services/sns" ) @@ -121,7 +122,7 @@ func TestSNSHTTPDelivery_Robustness(t *testing.T) { defer ts.Close() b := sns.NewInMemoryBackend() - b.SetHTTPDeliveryClient(&http.Client{Timeout: 5 * time.Second}) + b.SetHTTPDeliveryClient(&http.Client{Transport: testclient.New(t).Transport, Timeout: 5 * time.Second}) tp, err := b.CreateTopic("robustness-"+tt.name, nil) require.NoError(t, err) diff --git a/services/sns/handler_test.go b/services/sns/handler_test.go index 6fbe6392f7..024bd2ab08 100644 --- a/services/sns/handler_test.go +++ b/services/sns/handler_test.go @@ -15,6 +15,7 @@ import ( "github.com/stretchr/testify/require" "github.com/blackbirdworks/gopherstack/pkgs/jsonx" + "github.com/blackbirdworks/gopherstack/pkgs/testclient" "github.com/blackbirdworks/gopherstack/services/sns" ) @@ -281,7 +282,7 @@ func TestSNSHandler_Shutdown(t *testing.T) { }() b := sns.NewInMemoryBackend() - b.SetHTTPDeliveryClient(&http.Client{Timeout: 10 * time.Second}) + b.SetHTTPDeliveryClient(&http.Client{Transport: testclient.New(t).Transport, Timeout: 10 * time.Second}) h := sns.NewHandler(b) tp, err := b.CreateTopic("shutdown-"+tt.name, nil) diff --git a/services/ssooidc/authorization_code_test.go b/services/ssooidc/authorization_code_test.go index d1ff0015fa..70926745fa 100644 --- a/services/ssooidc/authorization_code_test.go +++ b/services/ssooidc/authorization_code_test.go @@ -11,6 +11,8 @@ import ( "github.com/aws/aws-sdk-go-v2/service/ssooidc" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/pkgs/testclient" ) const ( @@ -24,8 +26,15 @@ func s256(v string) string { return base64.RawURLEncoding.EncodeToString(sum[:]) } -func noRedirectClient() *http.Client { - return &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} +func noRedirectClient(t *testing.T) *http.Client { + t.Helper() + + return &http.Client{ + Transport: testclient.New(t).Transport, + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, + } } func (f fixture) authorize(t *testing.T, q url.Values) *http.Response { @@ -39,7 +48,7 @@ func (f fixture) authorize(t *testing.T, q url.Values) *http.Response { ) require.NoError(t, err) - resp, err := noRedirectClient().Do(req) + resp, err := noRedirectClient(t).Do(req) require.NoError(t, err) t.Cleanup(func() { _ = resp.Body.Close() }) diff --git a/test/guards/no_default_client_in_tests_guard_test.go b/test/guards/no_default_client_in_tests_guard_test.go index 66080c760d..3e116ffec7 100644 --- a/test/guards/no_default_client_in_tests_guard_test.go +++ b/test/guards/no_default_client_in_tests_guard_test.go @@ -1,6 +1,9 @@ package guards_test import ( + "go/ast" + "go/parser" + "go/token" "os" "path/filepath" "regexp" @@ -14,9 +17,14 @@ import ( var defaultTransportTestUse = regexp.MustCompile( `\bhttp\.(?:DefaultClient|DefaultTransport|Get\(|Post\(|Head\(|PostForm\()`) +var clientMention = regexp.MustCompile(`http\.Client\b`) + func defaultClientTestAllowlist() map[string]string { return map[string]string{ "pkgs/httpclient/httpclient_test.go": "proves clients are isolated from http.DefaultTransport", + "services/cognitoidp/localstack_alias_test.go": "TEMPORARY: fixed on the branch that merges first", + "services/cognitoidp/oauth_helpers_test.go": "TEMPORARY: fixed on the branch that merges first", + "services/cognitoidp/saml_federation_test.go": "TEMPORARY: fixed on the branch that merges first", "services/sns/leak_main_test.go": "TestMain restricts dialing; httpclient clones inherit it", "test/guards/http_transport_guard_test.go": "fixture strings", "test/guards/no_default_client_in_tests_guard_test.go": "fixture strings", @@ -34,8 +42,64 @@ func stripLineComments(src string) string { return strings.Join(lines, "\n") } +// bareClientLiterals reports http.Client literals without a Transport field and new(http.Client). +func bareClientLiterals(src string) []string { + if !clientMention.MatchString(src) { + return nil + } + + f, err := parser.ParseFile(token.NewFileSet(), "", src, 0) + if err != nil { + return nil + } + + isClient := func(e ast.Expr) bool { + sel, ok := e.(*ast.SelectorExpr) + if !ok || sel.Sel.Name != "Client" { + return false + } + + id, isID := sel.X.(*ast.Ident) + + return isID && id.Name == "http" + } + + var found []string + + ast.Inspect(f, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.CompositeLit: + if !isClient(x.Type) { + break + } + + hasTransport := false + + for _, el := range x.Elts { + if kv, ok := el.(*ast.KeyValueExpr); ok { + if k, isKey := kv.Key.(*ast.Ident); isKey && k.Name == "Transport" { + hasTransport = true + } + } + } + + if !hasTransport { + found = append(found, "http.Client literal without Transport") + } + case *ast.CallExpr: + if id, ok := x.Fun.(*ast.Ident); ok && id.Name == "new" && len(x.Args) == 1 && isClient(x.Args[0]) { + found = append(found, "new(http.Client)") + } + } + + return true + }) + + return found +} + func defaultClientTestUses(src string) []string { - return defaultTransportTestUse.FindAllString(stripLineComments(src), -1) + return append(defaultTransportTestUse.FindAllString(stripLineComments(src), -1), bareClientLiterals(src)...) } func TestDefaultClientTestUses(t *testing.T) { @@ -50,6 +114,10 @@ func TestDefaultClientTestUses(t *testing.T) { {name: "default_transport", src: "tr := http.DefaultTransport", want: 1}, {name: "get", src: "resp, err := http.Get(u)", want: 1}, {name: "post_form", src: "http.PostForm(u, v)", want: 1}, + {name: "bare_literal", src: "package p\nvar c = &http.Client{Timeout: 1}", want: 1}, + {name: "empty_literal", src: "package p\nvar c = http.Client{}", want: 1}, + {name: "new_client", src: "package p\nvar c = new(http.Client)", want: 1}, + {name: "literal_with_transport", src: "package p\nvar c = &http.Client{Transport: tr}", want: 0}, {name: "comment_only", src: "// http.Get(u) is banned", want: 0}, {name: "own_client", src: "resp, err := testclient.New(t).Get(u)", want: 0}, {name: "status_const", src: "http.StatusOK, http.MethodGet", want: 0}, @@ -66,7 +134,8 @@ func TestDefaultClientTestUses(t *testing.T) { // TestNoDefaultClientInTests keeps tests off http.DefaultTransport: httptest.Server.Close // closes its idle connections and breaks in-flight requests of parallel sibling tests. -// Use srv.Client(), pkgs/testclient or pkgs/httpclient. +// Use srv.Client(), testclient.New(t) (or testclient.New(t).Transport inside a custom http.Client) +// or httpclient.New. Also bans http.Client literals without a Transport. func TestNoDefaultClientInTests(t *testing.T) { t.Parallel() @@ -121,5 +190,7 @@ func TestNoDefaultClientInTests(t *testing.T) { } } - assert.Empty(t, offenders, "use srv.Client(), testclient.New(t) or httpclient.New") + assert.Empty(t, offenders, + "use testclient.New(t), or &http.Client{Transport: testclient.New(t).Transport, ...}; "+ + "srv.Client() for httptest servers") } diff --git a/test/integration/lambda_url_test.go b/test/integration/lambda_url_test.go index ed78d18226..070b06af84 100644 --- a/test/integration/lambda_url_test.go +++ b/test/integration/lambda_url_test.go @@ -19,6 +19,7 @@ import ( "github.com/blackbirdworks/gopherstack/pkgs/logger" "github.com/blackbirdworks/gopherstack/pkgs/portalloc/portalloctest" "github.com/blackbirdworks/gopherstack/pkgs/service" + "github.com/blackbirdworks/gopherstack/pkgs/testclient" lambdapkg "github.com/blackbirdworks/gopherstack/services/lambda" ) @@ -152,7 +153,7 @@ func TestLambdaFunctionURL_HTTPEndpoint(t *testing.T) { // The URL listener is running; an HTTP request should be handled // (may fail with invocation error since Docker isn't available, // but the listener itself should respond). - client := &http.Client{Timeout: 5 * time.Second} + client := &http.Client{Transport: testclient.New(t).Transport, Timeout: 5 * time.Second} req, err := http.NewRequestWithContext( t.Context(), http.MethodGet, diff --git a/test/integration/lambdaweb_parity_test.go b/test/integration/lambdaweb_parity_test.go index dde8bc51b5..4d84cbb61d 100644 --- a/test/integration/lambdaweb_parity_test.go +++ b/test/integration/lambdaweb_parity_test.go @@ -17,6 +17,8 @@ import ( s3types "github.com/aws/aws-sdk-go-v2/service/s3/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/pkgs/testclient" ) func lambdaWebSuffix() string { return strconv.FormatInt(time.Now().UnixNano(), 36) } @@ -205,7 +207,7 @@ func TestIntegration_LambdaWeb_Lifecycle(t *testing.T) { req.Host = host - resp, doErr := (&http.Client{Timeout: 10 * time.Second}).Do(req) + resp, doErr := (&http.Client{Transport: testclient.New(t).Transport, Timeout: 10 * time.Second}).Do(req) require.NoError(t, doErr) _ = resp.Body.Close() diff --git a/test/integration/s3_presigned_test.go b/test/integration/s3_presigned_test.go index fefaf8fe87..b89d38ae3a 100644 --- a/test/integration/s3_presigned_test.go +++ b/test/integration/s3_presigned_test.go @@ -98,7 +98,7 @@ func TestIntegration_S3_PresignedURLs(t *testing.T) { bytes.NewReader(content)) require.NoError(t, err) - httpClient := &http.Client{} + httpClient := testclient.New(t) resp, err := httpClient.Do(req) require.NoError(t, err) defer resp.Body.Close() diff --git a/test/integration/s3_realism_test.go b/test/integration/s3_realism_test.go index a7514a5be6..ef7b1be7a7 100644 --- a/test/integration/s3_realism_test.go +++ b/test/integration/s3_realism_test.go @@ -9,6 +9,8 @@ import ( smithyhttp "github.com/aws/smithy-go/transport/http" + "github.com/blackbirdworks/gopherstack/pkgs/testclient" + "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/aws/aws-sdk-go-v2/service/s3/types" @@ -189,7 +191,7 @@ func TestIntegration_S3_Realism_RequestIDs(t *testing.T) { url := endpoint + "/" + bucket t.Logf("Testing realism headers at: %s", url) - httpClient := &http.Client{Timeout: 10 * time.Second} + httpClient := &http.Client{Transport: testclient.New(t).Transport, Timeout: 10 * time.Second} req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) require.NoError(t, err) diff --git a/test/terraform/terraform_test.go b/test/terraform/terraform_test.go index 3656410958..0cb07a6454 100644 --- a/test/terraform/terraform_test.go +++ b/test/terraform/terraform_test.go @@ -3903,6 +3903,7 @@ func TestTerraform_APIGatewayManagementAPI(t *testing.T) { createReq.Header.Set("Content-Type", "application/x-www-form-urlencoded") createClient := &http.Client{ + Transport: testclient.New(t).Transport, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }, @@ -4090,6 +4091,7 @@ func TestTerraform_AppConfigData(t *testing.T) { setReq.Header.Set("Content-Type", "application/x-www-form-urlencoded") setClient := &http.Client{ + Transport: testclient.New(t).Transport, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }, From 34561321d480afd7f5dbac0280b97ba8e3581add Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 18:08:33 -0600 Subject: [PATCH 7/9] test(guards): drop the Cognito exemptions now that those clients have private transports Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- test/guards/no_default_client_in_tests_guard_test.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/test/guards/no_default_client_in_tests_guard_test.go b/test/guards/no_default_client_in_tests_guard_test.go index 3e116ffec7..e8a5fbed96 100644 --- a/test/guards/no_default_client_in_tests_guard_test.go +++ b/test/guards/no_default_client_in_tests_guard_test.go @@ -22,9 +22,6 @@ var clientMention = regexp.MustCompile(`http\.Client\b`) func defaultClientTestAllowlist() map[string]string { return map[string]string{ "pkgs/httpclient/httpclient_test.go": "proves clients are isolated from http.DefaultTransport", - "services/cognitoidp/localstack_alias_test.go": "TEMPORARY: fixed on the branch that merges first", - "services/cognitoidp/oauth_helpers_test.go": "TEMPORARY: fixed on the branch that merges first", - "services/cognitoidp/saml_federation_test.go": "TEMPORARY: fixed on the branch that merges first", "services/sns/leak_main_test.go": "TestMain restricts dialing; httpclient clones inherit it", "test/guards/http_transport_guard_test.go": "fixture strings", "test/guards/no_default_client_in_tests_guard_test.go": "fixture strings", From c623d047a173961aef05c3ecc71ba6cfca36b909 Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 18:30:00 -0600 Subject: [PATCH 8/9] docs: regenerate service READMEs Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- README.md | 2 +- services/gcpbigquery/README.md | 2 +- services/timestreamquery/README.md | 9 ++++----- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index b614d349b0..9f9d6934e1 100644 --- a/README.md +++ b/README.md @@ -748,7 +748,7 @@ Every service links to its own page with a coverage breakdown — audited operat | [RDS Data](services/rdsdata/README.md) | A | 7 | 4 structural gaps | | [Redshift](services/redshift/README.md) | A | 9 | 5 structural gaps | | [Redshift Data](services/redshiftdata/README.md) | A | 12 | 4 structural gaps; 1 deferred | -| [Timestream Query](services/timestreamquery/README.md) | A | 12 | 4 gaps; 1 structural gap | +| [Timestream Query](services/timestreamquery/README.md) | A | 12 | 3 gaps; 1 structural gap | | [Timestream Write](services/timestreamwrite/README.md) | A | 19 | 1 structural gap | ### Networking & Content Delivery diff --git a/services/gcpbigquery/README.md b/services/gcpbigquery/README.md index b5c8e4dfe8..5ec48ef163 100644 --- a/services/gcpbigquery/README.md +++ b/services/gcpbigquery/README.md @@ -20,7 +20,7 @@ - Unsupported functions: RANGE values, ML.*, GEOGRAPHY beyond the implemented ST_* set (use_spheroid => TRUE, make_valid => TRUE, ST_UNION, ST_BUFFER and the other constructors and aggregates), SEARCH over a table reference or a tuple, JSON constructors and mutators beyond JSON_VALUE/JSON_QUERY/PARSE_JSON/TO_JSON_STRING, FORMAT patterns beyond %s %d %i %f %g %e %t %T %x %o, collation. - ST_MAKELINE does not snap sufficiently short edges together (geography_functions ST_MAKELINE constraints; snap radius not stated there). Overlap detection of edges beyond the first 1024 only collapses repeated identical edges, and detection off the equator and meridians uses a floating-point tolerance, not an exact predicate. The error text for an edge of 180 degrees or more is emulator wording. - SEARCH NO_OP_ANALYZER: the page's example SEARCH(R'"foo bar"', R'"foo Bar"', analyzer=>'NO_OP_ANALYZER') is TRUE with the comment 'analysis is case-insensitive', while its 'Foobar' vs 'foobar' example is FALSE; the emulator keeps NO_OP case-sensitive and returns FALSE for the first. SEARCH also reads upper-case AND/OR inside a double-quoted phrase as logical operators (the page's SEARCH(R'foo bar', R'"foo AND (bar OR baz)"') is TRUE, commented as a logical match); the rule for phrases that really contain those words is not documented, so 'Clyde and Bonnie' matches the query "Bonnie AND Clyde". -- NUMERIC and BIGNUMERIC: a RANGE window frame with an offset over a NUMERIC or BIGNUMERIC ORDER BY key is rejected as unsupported, and Parquet export writes BIGNUMERIC as STRING (pkgs/parquetio caps DECIMAL precision at 38). +- NUMERIC and BIGNUMERIC: a RANGE window frame with an offset over a NUMERIC or BIGNUMERIC ORDER BY key is rejected as unsupported (SQLite applies the offset to the encoded text); Parquet export writes BIGNUMERIC as STRING because pkgs/parquetio caps DECIMAL precision at 38 (the exporting-data page's BIGNUMERIC type mapping was not read); a scalar function that has no decimal implementation, including the string functions (UPPER, LENGTH, SUBSTR, TRIM and the like), runs on the FLOAT64 conversion of a NUMERIC or BIGNUMERIC argument where BigQuery reports no matching signature; STRUCT equality and IN over structs do not coerce an INT64 or FLOAT64 field to NUMERIC; insertAll, load and DML round a value with more fraction digits than the scale half away from zero (NUMERIC scale 9, BIGNUMERIC scale 38) and the streaming and load pages read do not say whether BigQuery rounds or rejects it; a Parquet load without a schema reads DECIMAL columns as STRING (autodetect types by value). - Jobs: no slot or priority scheduling, no query cache, anonymous result tables are not created, script expression evaluations are not recorded as EXPRESSION child jobs, and execution holds the backend write lock (jobs_async.go runLocked), so jobs.cancel and jobTimeoutMs stop a job before it executes and a script between statements, not a plain statement in flight. - Load: Datastore and Firestore backups, nested CSV and column-name flexibility options are not supported. External tables: GOOGLE_SHEETS, DATASTORE_BACKUP, BIGTABLE and DELTA_LAKE sources and WITH CONNECTION need services the emulator does not have. External tables and CREATE EXTERNAL TABLE read Cloud Storage while the backend lock is held (external.go readExternalRows). The NDJSON TIMESTAMP and CSV float rendering of extract have not been checked against the live service. diff --git a/services/timestreamquery/README.md b/services/timestreamquery/README.md index d0970e470e..4c7348d0bf 100644 --- a/services/timestreamquery/README.md +++ b/services/timestreamquery/README.md @@ -9,17 +9,16 @@ | --- | --- | | PARITY entries audited | 12 (12 ok) | | Feature families | 2 (1 ok, 1 deferred) | -| Known gaps | 4 | +| Known gaps | 3 | | Structural gaps (can't be emulated) | 1 | | Deferred items | 0 | | Resource leaks | clean | ### Known gaps -- Query engine typeof: the engine is SQLite, so typeof returns SQLite storage names (integer/text/real/null) rather than the Timestream names listed in supported-data-types.html (bigint, double, varchar, boolean, timestamp, date, time, interval, unknown); values carry no static type at the UDF boundary (ts_funcs.go), so a correct typeof needs the static type inference the engine lacks -- Time-series lambdas: filter/reduce lambdas are recognised only when the body reads the element as p.value/p.time, so a lambda over a timeseries that never reads the element falls through to the stock engine -- Query engine: result ColumnInfo types for non-boolean expressions are inferred from values (BIGINT/DOUBLE/VARCHAR/TIMESTAMP) and an empty result reports VARCHAR for computed non-boolean columns. Boolean typing (ts_boolean.go) is syntactic: a CASE/CAST wrapping booleans, or a boolean function outside the known list, still reports its engine type. Plain column references keep their declared type. -- QueryInsightsResponse (Query and ExecuteScheduledQuery runs) carries OutputRows, OutputBytes and QueryTableCount but not QueryTemporalRange or QuerySpatialCoverage: both need time-predicate and partition-key pruning analysis the engine does not do (the dormant QuerySpatialCoverage float field in models.go is never set, so it cannot reach the wire; the SDK shape is a struct). ENABLED_WITH_RATE_CONTROL does not apply the 1 QPS rate limit, and an unknown QueryInsights.Mode is ignored rather than rejected. OutputBytes sums scalar value lengths only +- Static type inference (ts_infer.go) types every select-list expression before execution, but a query using a construct it cannot parse or type keeps the older value-based column typing (and syntactic boolean/interval typing, ts_boolean.go) for the affected columns: positional ? and named @parameters (PrepareQuery), AT TIME ZONE, TABLESAMPLE, recursive CTEs, transform() over a timeseries (the engine has no implementation), and any function without a return-type rule (SQLite built-ins outside the Timestream function list); an empty result of such a column still reports VARCHAR +- Unverified against the service: integer literals are typed INTEGER when they fit 32 bits else BIGINT (supported-data-types.html lists int and bigint but not which a literal gets; the SDK ScalarType enum has INTEGER, appended after UNKNOWN, so the service does emit it for something, and no recorded real response in the repo or the documentation shows a literal's ColumnInfo), and typeof() prints array(T), row(name T, ...) and timeseries(T) for nested types where the page gives only the notations array[T,...], row(T,...) and timeseries[row(timestamp, T,...)] +- Integer overflow is not an error: a 32-bit INTEGER result that overflows is widened to BIGINT and a 64-bit overflow (SQLite promotes it to a float) is reported as DOUBLE, where the service fails the query; CAST(double AS bigint) truncates (SQLite) rather than rounding, and TRY_CAST of an unparsable string yields 0 rather than NULL ### Structural gaps From 5c564abb7cf8274cfdb3a4abd3540d849abde0d8 Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 19:04:45 -0600 Subject: [PATCH 9/9] test(sns): prove non-blocking publish and prompt shutdown by ordering, not elapsed time Both tests compared elapsed time with a 500ms budget, which a loaded runner exceeds without anything blocking. The endpoint now stays blocked until Publish, or Shutdown, has returned. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- services/sns/delivery_test.go | 77 ++++++++++++++++++++++------------- services/sns/handler_test.go | 20 +++++---- 2 files changed, 61 insertions(+), 36 deletions(-) diff --git a/services/sns/delivery_test.go b/services/sns/delivery_test.go index 0d7b88e71e..19860b30a6 100644 --- a/services/sns/delivery_test.go +++ b/services/sns/delivery_test.go @@ -70,16 +70,16 @@ func TestSNSHTTPDelivery_Robustness(t *testing.T) { t.Parallel() tests := []struct { - serverFn func() (http.Handler, <-chan string) - name string - wantBody string - numSubs int - wantFastPub bool + serverFn func(release <-chan struct{}) (http.Handler, <-chan string) + name string + wantBody string + numSubs int + publishFirst bool }{ { name: "large_response_bounded", numSubs: 1, - serverFn: func() (http.Handler, <-chan string) { + serverFn: func(<-chan struct{}) (http.Handler, <-chan string) { received := make(chan string, 1) large := bytes.Repeat([]byte("x"), 2*1024*1024) h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -96,20 +96,19 @@ func TestSNSHTTPDelivery_Robustness(t *testing.T) { { name: "non_blocking_under_load", numSubs: 12, // more than snsMaxConcurrentDeliveries (8) - serverFn: func() (http.Handler, <-chan string) { - // Sleep briefly so that goroutines are still in-flight when we - // assert on elapsed time, but ensure the server completes well - // before any test timeout. This avoids the deadlock that occurs - // when httptest.Server.Close() (called via defer) waits for - // handlers that are blocked indefinitely. - h := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - time.Sleep(200 * time.Millisecond) + serverFn: func(release <-chan struct{}) (http.Handler, <-chan string) { + received := make(chan string, 12) + h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + <-release + body, _ := io.ReadAll(r.Body) + received <- string(body) w.WriteHeader(http.StatusOK) }) - return h, nil + return h, received }, - wantFastPub: true, + wantBody: "ping", + publishFirst: true, }, } @@ -117,9 +116,13 @@ func TestSNSHTTPDelivery_Robustness(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() - h, received := tt.serverFn() + release := make(chan struct{}) + var releaseOnce sync.Once + doRelease := func() { releaseOnce.Do(func() { close(release) }) } + + h, received := tt.serverFn(release) ts := newNotificationServer(h) - defer ts.Close() + t.Cleanup(ts.Close) b := sns.NewInMemoryBackend() b.SetHTTPDeliveryClient(&http.Client{Transport: testclient.New(t).Transport, Timeout: 5 * time.Second}) @@ -131,9 +134,8 @@ func TestSNSHTTPDelivery_Robustness(t *testing.T) { require.NoError(t, err) } - // Ensure goroutines are drained before the test exits to avoid leaks. t.Cleanup(func() { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + ctx, cancel := context.WithTimeout(context.WithoutCancel(t.Context()), 10*time.Second) defer cancel() done := make(chan struct{}) go func() { b.WaitDeliveries(); close(done) }() @@ -143,22 +145,39 @@ func TestSNSHTTPDelivery_Robustness(t *testing.T) { t.Errorf("WaitDeliveries timed out; goroutines may have leaked") } }) + t.Cleanup(doRelease) - start := time.Now() - _, err = b.Publish(tp.TopicArn, "ping", "", "", nil) - require.NoError(t, err) - elapsed := time.Since(start) + if !tt.publishFirst { + doRelease() + } - if tt.wantFastPub { - assert.Less(t, elapsed, 500*time.Millisecond, - "Publish must not block waiting for slow HTTP endpoints") + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + + publishErr := make(chan error, 1) + go func() { + _, perr := b.Publish(tp.TopicArn, "ping", "", "", nil) + publishErr <- perr + }() + + select { + case perr := <-publishErr: + require.NoError(t, perr) + case <-ctx.Done(): + require.FailNow(t, "Publish blocked waiting for slow HTTP endpoints") } - if tt.wantBody != "" { + doRelease() + + if tt.wantBody == "" { + return + } + + for range tt.numSubs { select { case got := <-received: assert.Equal(t, tt.wantBody, extractSNSHTTPMessage(got)) - case <-time.After(3 * time.Second): + case <-ctx.Done(): require.FailNow(t, "timed out waiting for HTTP delivery") } } diff --git a/services/sns/handler_test.go b/services/sns/handler_test.go index 024bd2ab08..40959b8d56 100644 --- a/services/sns/handler_test.go +++ b/services/sns/handler_test.go @@ -242,7 +242,7 @@ func TestSNSHandler_Shutdown(t *testing.T) { name string blockServer bool // server blocks until unblocked by cleanup cancelCtxFirst bool // cancel the context before calling Shutdown - wantFast bool // Shutdown should return in <500 ms + wantFast bool // Shutdown must return while delivery is still blocked wantDelivered bool // delivery must complete before Shutdown returns }{ { @@ -300,13 +300,19 @@ func TestSNSHandler_Shutdown(t *testing.T) { cancel() } - start := time.Now() - h.Shutdown(ctx) - elapsed := time.Since(start) + shutdownDone := make(chan struct{}) + go func() { + h.Shutdown(ctx) + close(shutdownDone) + }() + + failsafe, stop := context.WithTimeout(t.Context(), 30*time.Second) + defer stop() - if tt.wantFast { - assert.Less(t, elapsed, 500*time.Millisecond, - "Shutdown with cancelled context must return immediately") + select { + case <-shutdownDone: + case <-failsafe.Done(): + require.FailNow(t, "Shutdown did not return") } if tt.wantDelivered {