diff --git a/docs/preview.md b/docs/preview.md index b0898d75..bea75350 100644 --- a/docs/preview.md +++ b/docs/preview.md @@ -245,3 +245,99 @@ source cicd/vol/vendor-secrets/secrets.sh );" | perl -MTime::HiRes=time -pe 'printf "%.3f ", time' ``` + +## Recursive CTEs over provider queries + +Use `WITH RECURSIVE` with an anchor and one recursive term joined by +`UNION` or `UNION ALL`. The recursive term must reference its own CTE once. +`UNION` removes duplicate rows across iterations. `UNION ALL` retains them. +Multiple recursive definitions can appear alongside ordinary CTEs. Definitions +can read earlier CTEs. Mutual recursion is unsupported. + +```sql +WITH RECURSIVE nums(n) AS ( + SELECT 1 AS n + UNION ALL + SELECT n + 1 AS n FROM nums WHERE n < 4 +) +SELECT n FROM nums; +``` + +A run allows up to 1,024 recursive iterations and examines at most 100,000 +candidate rows, including duplicates. The whole main query waits for +recursion by default. When reads and effects can safely overlap, the +session can allow independent main-query work to start sooner. + +```sql +SELECT $recursive_allow_independent_work AS enabled; +SET recursive_allow_independent_work = true; +UNSET recursive_allow_independent_work; +``` + +### Traverse Google folders and list buckets by project + +Install the Google provider and use a credential with permission to list +folders, projects, and buckets in the target scope. Replace +`organizations/123` with your organization resource name. Use +`folders/123` as the seed to restrict the same query to a folder subtree. +The result includes buckets in projects directly under the seed and under +every reachable subfolder. + +```sql +WITH RECURSIVE containers(parent_name) AS ( + SELECT 'organizations/123' AS parent_name + UNION + SELECT f.name + FROM containers AS c + JOIN google.cloudresourcemanager.folders AS f ON f.parent = c.parent_name +), project_inventory AS ( + SELECT c.parent_name, p.projectId + FROM containers AS c + JOIN google.cloudresourcemanager.projects AS p ON p.parent = c.parent_name +) +SELECT p.parent_name, p.projectId, b.name AS bucket_name +FROM project_inventory AS p +JOIN google.storage.buckets AS b ON b.project = p.projectId; +``` + +For AWS Organizations, configure a provider alias for each organization +used for account discovery. Configure an alias or role for each account +used for bucket listing. A SQL row containing an account ID does not +dynamically select a provider alias. Queries can combine explicitly named +account aliases with `UNION ALL`. + +### Inventory buckets across two AWS organizations + +Configure `org_a` and `org_b` with each organization's discovery credentials +and the Organizations request region. Configure `member_a` and `member_b` +with credentials for the two member accounts being inventoried. Substitute +the real root IDs and account IDs below. This example traverses all OUs in +each organization and lists buckets for the two explicitly bound accounts. +To cover more accounts, add a member alias and bucket branch for each one. + +```sql +WITH RECURSIVE office_a(parent_id) AS ( + SELECT 'r-aaaa' AS parent_id + UNION + SELECT u.Id FROM office_a AS p + JOIN org_a.organizations.organizational_units_for_parents AS u ON u.ParentId = p.parent_id +), office_b(parent_id) AS ( + SELECT 'r-bbbb' AS parent_id + UNION + SELECT u.Id FROM office_b AS p + JOIN org_b.organizations.organizational_units_for_parents AS u ON u.ParentId = p.parent_id +), accounts_a AS ( + SELECT a.Id AS account_id FROM office_a AS p + JOIN org_a.organizations.accounts_for_parents AS a ON a.ParentId = p.parent_id +), accounts_b AS ( + SELECT a.Id AS account_id FROM office_b AS p + JOIN org_b.organizations.accounts_for_parents AS a ON a.ParentId = p.parent_id +) +SELECT 'org_a' AS org_alias, a.account_id, b.name AS bucket_name +FROM accounts_a AS a CROSS JOIN member_a.s3.buckets AS b +WHERE a.account_id = '111111111111' AND b.region = 'us-east-1' +UNION ALL +SELECT 'org_b' AS org_alias, a.account_id, b.name AS bucket_name +FROM accounts_b AS a CROSS JOIN member_b.s3.buckets AS b +WHERE a.account_id = '222222222222' AND b.region = 'us-east-1'; +``` diff --git a/go.mod b/go.mod index 32082e86..cace1b0c 100644 --- a/go.mod +++ b/go.mod @@ -25,7 +25,7 @@ require ( github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 github.com/spf13/viper v1.10.1 - github.com/stackql-labs/omnisdk v0.1.15-beta04 + github.com/stackql-labs/omnisdk v0.1.16-alpha01 github.com/stackql/go-suffix-map v0.0.1-alpha02 github.com/stackql/psql-wire v0.1.2-beta02 github.com/stackql/stackql-parser v0.0.17-alpha05 diff --git a/go.sum b/go.sum index d0d75580..53dde51a 100644 --- a/go.sum +++ b/go.sum @@ -327,8 +327,8 @@ github.com/spf13/viper v1.10.1 h1:nuJZuYpG7gTj/XqiUwg8bA0cp1+M2mC3J4g5luUYBKk= github.com/spf13/viper v1.10.1/go.mod h1:IGlFPqhNAPKRxohIzWpI5QEy4kuI7tcl5WvR+8qy1rU= github.com/spiffe/go-spiffe/v2 v2.7.0 h1:uXe1MflJoHw58wAUvxVlcM7WpKtijWG7I1UidcGh6g4= github.com/spiffe/go-spiffe/v2 v2.7.0/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U= -github.com/stackql-labs/omnisdk v0.1.15-beta04 h1:n6ad3JjC5fZx4LMp0+ejEFtqLps+YfAmfcyd1xuqSwQ= -github.com/stackql-labs/omnisdk v0.1.15-beta04/go.mod h1:76RVs6Uq5WIzFzsskvFiOToyxkELPbdNABFNgDR90d4= +github.com/stackql-labs/omnisdk v0.1.16-alpha01 h1:6x5RCF93NJf9+2VSY9vMGZ52RD+JwffeGrvNDbKI9RI= +github.com/stackql-labs/omnisdk v0.1.16-alpha01/go.mod h1:76RVs6Uq5WIzFzsskvFiOToyxkELPbdNABFNgDR90d4= github.com/stackql/go-suffix-map v0.0.1-alpha02 h1:JI4aiq/OfHW4a/BiNqK31NbyaR94zlUOhGZof3G/OUo= github.com/stackql/go-suffix-map v0.0.1-alpha02/go.mod h1:6BSMz4K/gIYfqdVRb7V8xL165wiPYyCjD9Kx7hLMd9Y= github.com/stackql/psql-wire v0.1.2-beta02 h1:7DfliBpyyCaUHVJ1Jxk37q3zVwVLyh6+FCHeM0/gbAQ= diff --git a/internal/stackql/handler/variables.go b/internal/stackql/handler/variables.go index e295cc2f..61a921f3 100644 --- a/internal/stackql/handler/variables.go +++ b/internal/stackql/handler/variables.go @@ -90,7 +90,12 @@ func (hc *standardHandlerContext) ResolveVariables(statement sqlparser.Statement resolved := map[string]sqlparser.Expr{} secretValues := map[string][]byte{} for name, path := range paths { - if value, exists := state.variables[strings.TrimPrefix(path, "variables.")]; exists { + key := strings.TrimPrefix(path, "variables.") + value, exists := state.variables[key] + if path == "variables."+recursiveIndependentVariable && !exists { + value, exists = false, true + } + if exists { literal, err := scalarVariableLiteral(value) if err != nil { return err @@ -99,7 +104,7 @@ func (hc *standardHandlerContext) ResolveVariables(statement sqlparser.Statement continue } parts := strings.Split(path, ".") - var value any = values + value = values if parts[0] == "secrets" { if len(parts) < 2 || state.store == nil { return fmt.Errorf("secret variable is unavailable") @@ -207,6 +212,11 @@ func (hc *standardHandlerContext) setSessionVariable(path string, rhs any) error if err := decoder.Decode(&value); err != nil { return err } + if name == recursiveIndependentVariable { + if _, boolean := value.(bool); !boolean { + return fmt.Errorf("%s requires a boolean", name) + } + } if _, err := scalarVariableLiteral(value); err != nil { return err } @@ -216,3 +226,13 @@ func (hc *standardHandlerContext) setSessionVariable(path string, rhs any) error state.variables[name] = value return nil } + +const recursiveIndependentVariable = "recursive_allow_independent_work" + +func (hc *standardHandlerContext) RecursiveIndependentWork() bool { + state := hc.providerSessionState() + state.mu.Lock() + defer state.mu.Unlock() + enabled, _ := state.variables[recursiveIndependentVariable].(bool) + return enabled +} diff --git a/internal/stackql/intrinsic/intrinsic.go b/internal/stackql/intrinsic/intrinsic.go index 53cc0fe5..1233587d 100644 --- a/internal/stackql/intrinsic/intrinsic.go +++ b/internal/stackql/intrinsic/intrinsic.go @@ -103,6 +103,9 @@ func GenerateStreamFunc( return execute, true } if node, isSelect := stmt.(*sqlparser.Select); isSelect { + if recursiveClause(node) != nil { + return statementReadFunc(ctx, node), true + } if action, handled := identitySelect(ctx, node); handled { return action, true } diff --git a/internal/stackql/intrinsic/recursive_reads.go b/internal/stackql/intrinsic/recursive_reads.go new file mode 100644 index 00000000..58b38723 --- /dev/null +++ b/internal/stackql/intrinsic/recursive_reads.go @@ -0,0 +1,288 @@ +package intrinsic + +import ( + "context" + "encoding/json" + "fmt" + "maps" + "strings" + + "github.com/stackql-labs/omnisdk/pkg/omnisdk" + "github.com/stackql/stackql-parser/go/vt/sqlparser" +) + +const ( + recursiveMaxIterations = 1024 + recursiveMaxRows = 100_000 +) + +type recursiveReadPlan derivedOpener + +func (p recursiveReadPlan) Open(ctx context.Context) (omnisdk.Rows, error) { + return p(ctx, nil) +} + +type frontierContextKey struct{ address string } + +func recursiveClause(stmt sqlparser.SelectStatement) *sqlparser.With { + if first := firstSelect(stmt); first != nil && first.With != nil && first.With.Recursive { + return first.With + } + return nil +} + +func planRecursiveRead(ctx queryContext, stmt sqlparser.SelectStatement, current string, depth int, + inherited map[string]omnisdk.Relation, +) ([]string, derivedOpener, error) { + cloned, err := sqlparser.Parse(statementSQL(stmt)) + if err != nil { + return nil, nil, err + } + main, ok := cloned.(sqlparser.SelectStatement) + if !ok || recursiveClause(main) == nil { + return nil, nil, fmt.Errorf("could not copy the recursive statement") + } + clause := recursiveClause(main) + index, err := findRecursiveDefinition(clause) + if err != nil { + return nil, nil, err + } + if index < 0 { + clause.Recursive = false + return planStatementRead(ctx, main, current, depth+1, inherited) + } + definition := clause.CTEs[index] + address := fmt.Sprintf("%somni_relations.sources.recursive_%d", UnstablePrefix, depth) + recursion, names, columns, err := planRecursiveDefinition( + ctx, definition, clause.CTEs[:index], current, depth, address, inherited) + if err != nil { + return nil, nil, err + } + clause.CTEs = append(clause.CTEs[:index:index], clause.CTEs[index+1:]...) + if len(clause.CTEs) == 0 { + firstSelect(main).With = nil + } + if _, err = recursiveReferences(main, definition.Name.GetRawVal(), address); err != nil { + return nil, nil, err + } + var outputs []string + independent := false + if session, configurable := ctx.(interface{ RecursiveIndependentWork() bool }); configurable { + independent = session.RecursiveIndependentWork() + } + plan, err := recursion.WithQuery(omnisdk.RecursiveQueryOptions{ + Address: address, Columns: columns, AllowIndependentWork: independent, + }, func(relation omnisdk.Relation) (omnisdk.Plan, error) { + relations := withRecursiveRelation(inherited, newOrderedRelation(relation, names)) + result, open, planErr := planStatementRead(ctx, main, current, depth+1, relations) + outputs = result + if planErr != nil { + return nil, planErr + } + return recursiveReadPlan(open), nil + }) + if err != nil { + return nil, nil, err + } + return outputs, func(runCtx context.Context, _ map[string]any) (omnisdk.Rows, error) { + return plan.Open(runCtx) + }, nil +} + +func findRecursiveDefinition(clause *sqlparser.With) (int, error) { + for i, definition := range clause.CTEs { + count, err := recursiveReferences(definition.Select, definition.Name.GetRawVal(), "") + if err != nil { + return -1, err + } + if count != 0 { + return i, nil + } + } + return -1, nil +} + +func planRecursiveDefinition(ctx queryContext, definition *sqlparser.CommonTableExpr, + prior []*sqlparser.CommonTableExpr, current string, depth int, address string, + inherited map[string]omnisdk.Relation, +) (omnisdk.RecursivePlan, []string, map[string]omnisdk.ColumnType, error) { + union, ok := definition.Select.(*sqlparser.Union) + if !ok || len(union.UnionSelects) != 1 || len(union.OrderBy) != 0 || union.Limit != nil || union.Lock != "" { + return nil, nil, nil, fmt.Errorf("recursive CTE requires an anchor UNION [ALL] a recursive term") + } + name := definition.Name.GetRawVal() + anchor, step := union.FirstStatement, union.UnionSelects[0].Statement + if count, err := recursiveReferences(anchor, name, ""); err != nil || count != 0 { + return nil, nil, nil, fmt.Errorf("recursive CTE %s cannot reference itself in the anchor", name) + } + if count, err := recursiveReferences(step, name, address); err != nil || count != 1 { + return nil, nil, nil, fmt.Errorf("recursive CTE %s requires one self-reference in the recursive term", name) + } + if err := attachRecursiveScope(anchor, prior); err != nil { + return nil, nil, nil, err + } + if err := attachRecursiveScope(step, prior); err != nil { + return nil, nil, nil, err + } + names, anchorOpen, err := planStatementRead(ctx, anchor, current, depth+1, inherited) + if err != nil { + return nil, nil, nil, err + } + projected := names + if len(definition.Columns) != 0 { + if len(definition.Columns) != len(names) { + return nil, nil, nil, fmt.Errorf("recursive CTE column count does not match its anchor") + } + projected = make([]string, len(names)) + for i, column := range definition.Columns { + projected[i] = column.GetRawVal() + } + } + columns, err := derivedColumns(projected) + if err != nil { + return nil, nil, nil, err + } + return compileRecursiveTerms(ctx, current, depth, inherited, address, step, projected, columns, + renameRecursiveOutput(anchorOpen, names, projected), strings.EqualFold(union.UnionSelects[0].Type, "union all")) +} + +func compileRecursiveTerms(ctx queryContext, current string, depth int, inherited map[string]omnisdk.Relation, + address string, step sqlparser.SelectStatement, names []string, columns map[string]omnisdk.ColumnType, + anchor derivedOpener, all bool, +) (omnisdk.RecursivePlan, []string, map[string]omnisdk.ColumnType, error) { + key := frontierContextKey{address} + openFrontier := func(ctx context.Context, _ map[string]any) (omnisdk.Rows, error) { + rows, ok := ctx.Value(key).([]omnisdk.Row) + if !ok { + return nil, fmt.Errorf("recursive frontier requires an active iteration") + } + return &materializedRelationRows{ctx: ctx, rows: rows}, nil + } + frontier, err := omnisdk.NewRelation(address, nil, columns, openFrontier) + if err != nil { + return nil, nil, nil, err + } + stepNames, stepOpen, err := planStatementRead(ctx, step, current, depth+1, + withRecursiveRelation(inherited, newOrderedRelation(frontier, names))) + if err != nil { + return nil, nil, nil, err + } + if len(stepNames) != len(names) { + return nil, nil, nil, fmt.Errorf("recursive CTE terms have different column counts") + } + stepOpen = renameRecursiveOutput(stepOpen, stepNames, names) + var distinct func(omnisdk.Row) (string, error) + if !all { + distinct = func(row omnisdk.Row) (string, error) { + values := make([]any, len(names)) + for i, name := range names { + values[i] = row[name] + } + serialized, marshalErr := json.Marshal(values) + return string(serialized), marshalErr + } + } + plan, err := omnisdk.NewRecursivePlan(recursiveReadPlan(anchor), + func(_ context.Context, rows []omnisdk.Row) (omnisdk.Plan, error) { + return recursiveReadPlan(func(runCtx context.Context, _ map[string]any) (omnisdk.Rows, error) { + return stepOpen(context.WithValue(runCtx, key, rows), nil) + }), nil + }, omnisdk.RecursiveOptions{MaxIterations: recursiveMaxIterations, MaxRows: recursiveMaxRows}, distinct) + return plan, names, columns, err +} + +func withRecursiveRelation( + inherited map[string]omnisdk.Relation, relation omnisdk.Relation, +) map[string]omnisdk.Relation { + relations := make(map[string]omnisdk.Relation, len(inherited)+1) + maps.Copy(relations, inherited) + relations[relation.Address()] = relation + return relations +} + +func attachRecursiveScope(stmt sqlparser.SelectStatement, prior []*sqlparser.CommonTableExpr) error { + first := firstSelect(stmt) + if first == nil || first.With != nil { + return fmt.Errorf("nested WITH in a recursive CTE term is unsupported") + } + if len(prior) != 0 { + first.With = &sqlparser.With{CTEs: prior} + } + return nil +} + +func recursiveReferences(stmt sqlparser.SelectStatement, name, address string) (int, error) { + count := 0 + seen := map[*sqlparser.AliasedTableExpr]bool{} + visit := func(node sqlparser.SQLNode) (bool, error) { + table, ok := node.(*sqlparser.AliasedTableExpr) + if !ok || seen[table] { + return true, nil + } + seen[table] = true + target, ok := table.Expr.(sqlparser.TableName) + if !ok || !target.Qualifier.IsEmpty() || !target.QualifierSecond.IsEmpty() || + !strings.EqualFold(target.Name.GetRawVal(), name) { + return true, nil + } + count++ + if address != "" { + provider, rest, _ := strings.Cut(address, ".") + service, resource, _ := strings.Cut(rest, ".") + if table.As.IsEmpty() { + table.As = target.Name + } + table.Expr = sqlparser.TableName{QualifierSecond: sqlparser.NewTableIdent(provider), + Qualifier: sqlparser.NewTableIdent(service), Name: sqlparser.NewTableIdent(resource)} + } + return false, nil + } + prior, err := recursiveReferencesInDefinitions(firstSelect(stmt), name, address) + if err != nil { + return 0, err + } + err = sqlparser.Walk(visit, stmt) + return prior + count, err +} + +func recursiveReferencesInDefinitions(first *sqlparser.Select, name, address string) (int, error) { + if first == nil || first.With == nil { + return 0, nil + } + count := 0 + for _, definition := range first.With.CTEs { + if strings.EqualFold(definition.Name.GetRawVal(), name) { + return 0, fmt.Errorf("nested CTE cannot shadow recursive name %s", name) + } + n, err := recursiveReferences(definition.Select, name, address) + if err != nil { + return 0, err + } + count += n + } + return count, nil +} + +type renamedRecursiveRows struct { + omnisdk.Rows + from, to []string +} + +func (rows *renamedRecursiveRows) Row() omnisdk.Row { + source := rows.Rows.Row() + row := make(omnisdk.Row, len(rows.to)) + for i, name := range rows.to { + row[name] = source[rows.from[i]] + } + return row +} + +func renameRecursiveOutput(open derivedOpener, from, to []string) derivedOpener { + return func(ctx context.Context, params map[string]any) (omnisdk.Rows, error) { + rows, err := open(ctx, params) + if err != nil { + return nil, err + } + return &renamedRecursiveRows{Rows: rows, from: from, to: to}, nil + } +} diff --git a/internal/stackql/intrinsic/statement_reads.go b/internal/stackql/intrinsic/statement_reads.go index 5bdafe22..1b315662 100644 --- a/internal/stackql/intrinsic/statement_reads.go +++ b/internal/stackql/intrinsic/statement_reads.go @@ -21,6 +21,9 @@ func planStatementRead( if depth >= derivedRelationMaxDepth { return nil, nil, fmt.Errorf("derived relations exceed nesting bound") } + if recursiveClause(stmt) != nil { + return planRecursiveRead(ctx, stmt, current, depth, inherited) + } switch node := stmt.(type) { case *sqlparser.ParenSelect: return planStatementRead(ctx, node.Select, current, depth+1, inherited) @@ -61,14 +64,13 @@ func planStatementRead( func planUnionRead( ctx queryContext, node *sqlparser.Union, current string, depth int, inherited map[string]omnisdk.Relation, ) ([]string, derivedOpener, error) { - statements := []sqlparser.SelectStatement{node.FirstStatement} - for _, branch := range node.UnionSelects { - statements = append(statements, branch.Statement) + statements, err := unionReadBranches(node) + if err != nil { + return nil, nil, err } names := make([][]string, len(statements)) opens := make([]derivedOpener, len(statements)) for i, statement := range statements { - var err error names[i], opens[i], err = planStatementRead(ctx, statement, current, depth+1, inherited) if err != nil { return nil, nil, err @@ -83,6 +85,31 @@ func planUnionRead( return names[0], open, nil } +// A WITH attached to the first SELECT scopes over the full UNION. +func unionReadBranches(node *sqlparser.Union) ([]sqlparser.SelectStatement, error) { + statements := []sqlparser.SelectStatement{node.FirstStatement} + first := firstSelect(node.FirstStatement) + for _, branch := range node.UnionSelects { + statement := branch.Statement + if first != nil && first.With != nil { + cloned, err := sqlparser.Parse(statementSQL(statement)) + if err != nil { + return nil, err + } + var ok bool + statement, ok = cloned.(sqlparser.SelectStatement) + if !ok { + return nil, fmt.Errorf("UNION branch must be a SELECT") + } + if scopeErr := attachRecursiveScope(statement, first.With.CTEs); scopeErr != nil { + return nil, scopeErr + } + } + statements = append(statements, statement) + } + return statements, nil +} + func openUnionRead( ctx queryContext, runCtx context.Context, node *sqlparser.Union, names [][]string, opens []derivedOpener, ) (omnisdk.Rows, error) { diff --git a/test/robot/functional/ProviderSessionLibrary.py b/test/robot/functional/ProviderSessionLibrary.py index 26ef3e25..b630c84e 100644 --- a/test/robot/functional/ProviderSessionLibrary.py +++ b/test/robot/functional/ProviderSessionLibrary.py @@ -22,6 +22,8 @@ def prepare_session_provider(self, binary, execution_platform="native", backend= self.aws_calls = [] self.view_calls = [] self.iac_calls = [] + self.recursive_calls = [] + self.recursive_gate = threading.Barrier(2) self.iac_widgets = {} self.concurrent_gate = None self.env = os.environ.copy() @@ -34,6 +36,18 @@ def log_message(self, *_): pass def do_GET(self): + if urlparse(self.path).path == "/recursive-tree": + parent = parse_qs(urlparse(self.path).query)["parent"][0] + owner.recursive_calls.append(parent) + if parent in ("a", "b"): + try: + owner.recursive_gate.wait(timeout=5) + except threading.BrokenBarrierError: + self.send_error(500, "recursive requests did not run concurrently") + return + children = {"root": ["a", "b"], "a": ["c"], "b": ["c"], "c": ["a"]} + self.iac_response([{"id": child} for child in children[parent]]) + return if urlparse(self.path).path == "/iac-widget": owner.iac_calls.append("read") identity = parse_qs(urlparse(self.path).query).get("id", [""])[0] @@ -770,6 +784,44 @@ def iac_inputs_file_errors_precede_provider_dispatch(self): assert result.returncode != 0 and "inputs_file:" in result.stderr, result.stderr assert len(self.calls) == before, "provider called before inputs loaded" + def recursive_provider_cte(self, sql): + path = self.root / "registry/src/widgets/v00.00.00000/services/things.yaml" + doc = json.loads(path.read_text()) + reference = "#/components/x-stackQL-resources/folders/methods/list" + doc["paths"]["/recursive-tree"] = {"get": { + "operationId": "list_folders", + "parameters": [{"name": "parent", "in": "query", "required": True, "schema": {"type": "string"}}], + "responses": {"200": {"content": {"application/json": {"schema": { + "type": "array", "items": {"type": "object", "properties": {"id": {"type": "string"}}} + }}}}}, + }} + doc["components"]["x-stackQL-resources"]["folders"] = { + "id": "widgets.things.folders", "name": "folders", + "methods": {"list": {"operation": {"$ref": "#/paths/~1recursive-tree/get"}, + "response": {"mediaType": "application/json", "openAPIDocKey": "200"}}}, + "sqlVerbs": {"select": [{"$ref": reference}]}, + } + path.write_text(json.dumps(doc)) + auth = ["--auth", json.dumps({"widgets": {"type": "bearer", "credentialsenvvar": "ROBOT_IAC_FIXTURE_TOKEN"}})] + self.env["ROBOT_IAC_FIXTURE_TOKEN"] = "recursive-fixture" + result = json.loads(self.run_sql(sql, [], auth).stdout) + assert sorted(row["id"] for row in result) == ["a", "b", "c", "root"], result + assert sorted(self.recursive_calls) == ["a", "b", "c", "root"], self.recursive_calls + + def multiple_recursive_ctes_feed_union(self, sql): + rows = json.loads(self.run_sql(sql, []).stdout) + assert sorted(int(row["n"]) for row in rows) == [1, 2, 11, 12], rows + + def recursive_option_round_trips(self, sql): + result = self.run_sql(sql, []).stdout + decoder = json.JSONDecoder() + flags = [] + while result.strip(): + rows, index = decoder.raw_decode(result.lstrip()) + flags.extend(str(row["enabled"]).lower() for row in rows) + result = result.lstrip()[index:] + assert flags in (["false", "true", "false"], ["0", "1", "0"]), flags + def install_iac_widget_fixture(self): path = self.root / "registry/src/widgets/v00.00.00000/services/things.yaml" doc = json.loads(path.read_text()) diff --git a/test/robot/functional/stackql_provider_sessions.robot b/test/robot/functional/stackql_provider_sessions.robot index c9e5a187..57a6db48 100644 --- a/test/robot/functional/stackql_provider_sessions.robot +++ b/test/robot/functional/stackql_provider_sessions.robot @@ -120,3 +120,12 @@ IaC Insert Prunes Omitted Resources ${expand} = Set Variable INSERT INTO stackql_preview.iac.run (collection, resources) VALUES ('robot-prune', '[{"key":"keep","provider":"widgets","address":"things.iac_widget","identity":"id","addressed_by":"id","desired":{"color":"keep"}},{"key":"drop","provider":"widgets","address":"things.iac_widget","identity":"id","addressed_by":"id","desired":{"color":"drop"}}]'); ${shrink} = Set Variable INSERT INTO stackql_preview.iac.run (collection, resources, prune) VALUES ('robot-prune', '[{"key":"keep","provider":"widgets","address":"things.iac_widget","identity":"id","addressed_by":"id","desired":{"color":"keep"}}]', 1) RETURNING status; IaC Insert Prunes Omitted Resources ${expand} ${shrink} + +Recursive Provider CTE Follows A Cycle With Concurrent Requests + Recursive Provider CTE WITH RECURSIVE asset_walk(id) AS (SELECT 'root' AS id UNION SELECT f.id FROM asset_walk t JOIN widgets.things.folders f ON f.parent = t.id), inventory AS (SELECT id FROM asset_walk) SELECT id FROM inventory; + +Recursive Main Work Option Is Readable And Resettable + Recursive Option Round Trips SELECT $recursive_allow_independent_work AS enabled; SET recursive_allow_independent_work = true; SELECT $recursive_allow_independent_work AS enabled; UNSET recursive_allow_independent_work; SELECT $recursive_allow_independent_work AS enabled; + +Multiple Recursive CTEs Feed Both Union Branches + Multiple Recursive CTEs Feed Union WITH RECURSIVE seq_a(n) AS (SELECT 1 AS n UNION ALL SELECT n + 1 AS n FROM seq_a WHERE n < 2), seq_b(n) AS (SELECT 11 AS n UNION ALL SELECT n + 1 AS n FROM seq_b WHERE n < 12), left_inventory AS (SELECT n FROM seq_a), right_inventory AS (SELECT n FROM seq_b) SELECT n FROM left_inventory UNION ALL SELECT n FROM right_inventory;