Skip to content

feat(core): add SSSQL optional branch pruning MVP#550

Merged
mk3008 merged 5 commits into
mainfrom
codex/issue-545-sssql-pruning-mvp
Mar 12, 2026
Merged

feat(core): add SSSQL optional branch pruning MVP#550
mk3008 merged 5 commits into
mainfrom
codex/issue-545-sssql-pruning-mvp

Conversation

@mk3008
Copy link
Copy Markdown
Owner

@mk3008 mk3008 commented Mar 11, 2026

Summary

  • add an MVP transformer that prunes supported truthful optional WHERE branches only when parameters are known absent
  • wire the pass into DynamicQueryBuilder via optionalConditionParameterStates and document the supported/no-op shapes
  • extend coverage to nested query blocks such as CTE bodies and derived-table subqueries

Verification

  • pnpm --filter rawsql-ts test -- tests/transformers/PruneOptionalConditionBranches.test.ts tests/transformers/DynamicQueryBuilder.test.ts
  • pnpm --filter rawsql-ts build
  • pnpm --filter rawsql-ts exec eslint src/transformers/PruneOptionalConditionBranches.ts src/transformers/DynamicQueryBuilder.ts tests/transformers/PruneOptionalConditionBranches.test.ts

Summary by CodeRabbit

  • New Features

    • Opt-in pruning of optional WHERE branches when parameters are marked absent (null/undefined treated as absent)
    • Extended filter support for scalar predicates and EXISTS-style predicates; parameter-state handling for pruning
  • Documentation

    • New guide describing optional-branch pruning usage, syntax, and opt-in parameters; minor front-matter cleanup
  • Tests

    • Comprehensive test suite covering pruning across queries, CTEs, subqueries, and integration scenarios
  • Chores

    • New changeset entry for a minor release

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 11, 2026

Warning

Rate limit exceeded

@mk3008 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 1 minutes and 56 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: cad8ee8e-2d58-4944-b75f-dcbd79aab825

📥 Commits

Reviewing files that changed from the base of the PR and between b05e4e9 and 8f0b4b5.

📒 Files selected for processing (2)
  • packages/core/src/transformers/PruneOptionalConditionBranches.ts
  • packages/core/tests/transformers/PruneOptionalConditionBranches.test.ts
📝 Walkthrough

Walkthrough

This PR implements an MVP optional-condition pruning transformer for SSSQL-style WHERE branches, adds the PruneOptionalConditionBranches module and its types/tests, integrates it into DynamicQueryBuilder with new options, and adds documentation and a changeset entry.

Changes

Cohort / File(s) Summary
Release Metadata
\.changeset/issue-545-sssql-pruning-mvp.md
Adds a changeset declaring a minor release for the MVP optional-condition pruning pass.
Documentation
docs/guide/sssql-optional-branch-pruning.md, docs/guide/querybuilding-recipes.md
Adds a new guide describing supported/unsupported optional-branch pruning shapes, opt-in parameters, known-absent semantics; fixes BOM in an existing guide.
Public API
packages/core/src/index.ts
Re-exports PruneOptionalConditionBranches to surface the transformer publicly.
Formatting
packages/core/src/parsers/SqlTokenizer.ts, packages/core/src/tokenReaders/CommandTokenReader.ts
Removes stray BOM and trailing blank lines; minor indentation/format tweaks only.
Core Transformer
packages/core/src/transformers/PruneOptionalConditionBranches.ts
New transformer that prunes OR-guarded WHERE branches when targeted parameters are known-absent; exports pruning types and pruning function; traverses nested queries and mutates AST.
Integration & Refactor
packages/core/src/transformers/DynamicQueryBuilder.ts
Integrates pruneOptionalConditionBranches into build flow, modularizes EXISTS handling/optimizers, adds FilterCondition* types, DynamicQueryBuilderOptions, and optionalConditionParameterStates support.
Tests
packages/core/tests/transformers/PruneOptionalConditionBranches.test.ts
Adds extensive tests covering scalar and EXISTS pruning, multiple branches, CTEs/derived tables, no-op cases, and DynamicQueryBuilder integration.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant DynamicQueryBuilder as DynamicQueryBuilder
    participant Parser as SelectQueryParser
    participant Pruner as PruneOptionalConditionBranches
    participant AST as QueryAST

    Client->>DynamicQueryBuilder: buildQuery(sqlTemplate, options, optionalConditionParameterStates)
    DynamicQueryBuilder->>Parser: parseQuery(sqlTemplate)
    Parser-->>AST: return AST
    DynamicQueryBuilder->>DynamicQueryBuilder: apply filters/sort/paging
    DynamicQueryBuilder->>Pruner: pruneOptionalConditionBranches(AST, pruningParameters)
    Note over Pruner,AST: traverse AST, detect OR branches guarded by targeted params
    Pruner->>AST: remove/mutate prunable branches
    Pruner-->>DynamicQueryBuilder: return pruned AST
    DynamicQueryBuilder->>DynamicQueryBuilder: apply unused-join/CTE optimizations
    DynamicQueryBuilder->>DynamicQueryBuilder: serialize AST -> SQL
    DynamicQueryBuilder-->>Client: return SQL
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

Poem

🐰 I hop through queries, snip and prune,
When params are absent, I clear the room.
OR-guards hidden, trimmed with delight,
Clean WHEREs by day, and tests by night. 🌿

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(core): add SSSQL optional branch pruning MVP' accurately describes the main change—introducing a new MVP feature for optional branch pruning in SSSQL queries.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/issue-545-sssql-pruning-mvp

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/core/src/transformers/DynamicQueryBuilder.ts`:
- Around line 344-346: In DynamicQueryBuilder, the current
isMultiColumnDefinitionArray check treats empty arrays as multi-column metadata
and skips handling, which causes predicates like { status: [] } to be swallowed;
update the checks around the two continue sites (the block containing
isMultiColumnDefinitionArray(value) and the similar block at 387-389) to require
a non-empty array for multi-column EXISTS metadata (e.g.,
isMultiColumnDefinitionArray(value) && value.length > 0) and, for ordinary keys
where the array is empty, do not continue silently but instead reject/throw a
clear error (or pass the empty array to SqlParamInjector’s validation) so empty
filters are not dropped. Ensure you reference the same logic path used to reach
SqlParamInjector so valid multi-column defs still short-circuit but empty arrays
are handled explicitly.
- Around line 134-140: The QueryBuildOptions.jsonb flag is declared but never
used; update the serialization branch that constructs PostgresJsonQueryBuilder
(and any call sites like buildQuery(sql, { serialize, jsonb })) to pass the
jsonb value through and have PostgresJsonQueryBuilder accept and honor it (e.g.,
add a constructor/option param jsonb: boolean and use it to switch between
JSON/JSONB serialization or to throw when jsonb is false and GROUP BY would be
used), or remove QueryBuildOptions.jsonb from the public API; specifically
modify the code that instantiates PostgresJsonQueryBuilder to include the jsonb
option and implement the behavior inside PostgresJsonQueryBuilder so the flag is
actually applied.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 55a79867-56f9-4330-ac85-dfd7a33cbc6c

📥 Commits

Reviewing files that changed from the base of the PR and between 88af074 and a7000ca.

📒 Files selected for processing (9)
  • .changeset/issue-545-sssql-pruning-mvp.md
  • docs/guide/querybuilding-recipes.md
  • docs/guide/sssql-optional-branch-pruning.md
  • packages/core/src/index.ts
  • packages/core/src/parsers/SqlTokenizer.ts
  • packages/core/src/tokenReaders/CommandTokenReader.ts
  • packages/core/src/transformers/DynamicQueryBuilder.ts
  • packages/core/src/transformers/PruneOptionalConditionBranches.ts
  • packages/core/tests/transformers/PruneOptionalConditionBranches.test.ts
💤 Files with no reviewable changes (1)
  • packages/core/src/tokenReaders/CommandTokenReader.ts

Comment on lines +134 to +140
serialize?: JsonMapping | boolean;
/**
* JSONB usage setting. Must be true (default) for PostgreSQL GROUP BY compatibility.
* Setting to false will throw an error as JSON type cannot be used in GROUP BY clauses.
* @default true
*/
jsonb?: boolean;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

jsonb is exposed but never applied.

The new QueryBuildOptions.jsonb flag is documented here, but the serialization branch never reads it. Calls like buildQuery(sql, { serialize: mapping, jsonb: false }) therefore behave exactly like the default path today, which makes this a misleading public API. Please either plumb the flag into PostgresJsonQueryBuilder or remove the option until it is implemented.

Also applies to: 304-308

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/transformers/DynamicQueryBuilder.ts` around lines 134 -
140, The QueryBuildOptions.jsonb flag is declared but never used; update the
serialization branch that constructs PostgresJsonQueryBuilder (and any call
sites like buildQuery(sql, { serialize, jsonb })) to pass the jsonb value
through and have PostgresJsonQueryBuilder accept and honor it (e.g., add a
constructor/option param jsonb: boolean and use it to switch between JSON/JSONB
serialization or to throw when jsonb is false and GROUP BY would be used), or
remove QueryBuildOptions.jsonb from the public API; specifically modify the code
that instantiates PostgresJsonQueryBuilder to include the jsonb option and
implement the behavior inside PostgresJsonQueryBuilder so the flag is actually
applied.

Comment on lines +344 to +346
if (this.isMultiColumnDefinitionArray(value)) {
continue;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Empty array filters get swallowed by the EXISTS-metadata check.

isMultiColumnDefinitionArray([]) is true, so a normal filter like { status: [] } hits this continue path and never reaches SqlParamInjector. That silently drops the predicate. Require a non-empty array for multi-column EXISTS metadata, and reject those arrays under ordinary keys instead of skipping them.

💡 Possible fix
-            if (this.isMultiColumnDefinitionArray(value)) {
-                continue;
-            }
+            if (this.isMultiColumnDefinitionArray(value)) {
+                throw new Error("Multi-column EXISTS definitions are only supported under '$exists' or '$notExists'.");
+            }
             cleanedFilters[key] = value as StateParameterValue;
@@
-        return Array.isArray(value) && value.every(entry => this.isMultiColumnDefinition(entry));
+        return Array.isArray(value) &&
+            value.length > 0 &&
+            value.every(entry => this.isMultiColumnDefinition(entry));

Also applies to: 387-389

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/transformers/DynamicQueryBuilder.ts` around lines 344 -
346, In DynamicQueryBuilder, the current isMultiColumnDefinitionArray check
treats empty arrays as multi-column metadata and skips handling, which causes
predicates like { status: [] } to be swallowed; update the checks around the two
continue sites (the block containing isMultiColumnDefinitionArray(value) and the
similar block at 387-389) to require a non-empty array for multi-column EXISTS
metadata (e.g., isMultiColumnDefinitionArray(value) && value.length > 0) and,
for ordinary keys where the array is empty, do not continue silently but instead
reject/throw a clear error (or pass the empty array to SqlParamInjector’s
validation) so empty filters are not dropped. Ensure you reference the same
logic path used to reach SqlParamInjector so valid multi-column defs still
short-circuit but empty arrays are handled explicitly.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (2)
packages/core/src/transformers/DynamicQueryBuilder.ts (2)

414-415: ⚠️ Potential issue | 🟠 Major

Empty arrays are still classified as multi-column EXISTS metadata.

Array.prototype.every() returns true for [], so isMultiColumnDefinitionArray([]) is true. That makes ordinary filters like { status: [] } hit the skip path at Line 371 and disappear instead of reaching normal validation/injection. Require a non-empty array here so only real EXISTS batches short-circuit.

💡 Suggested fix
     private isMultiColumnDefinitionArray(value: FilterConditionValue): value is MultiColumnExistsDefinition[] {
-        return Array.isArray(value) && value.every(entry => this.isMultiColumnDefinition(entry));
+        return Array.isArray(value) &&
+            value.length > 0 &&
+            value.every(entry => this.isMultiColumnDefinition(entry));
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/transformers/DynamicQueryBuilder.ts` around lines 414 -
415, The predicate isMultiColumnDefinitionArray treats empty arrays as valid
multi-column EXISTS metadata because Array.every([]) is true; update the check
in isMultiColumnDefinitionArray to require a non-empty array (e.g., ensure
Array.isArray(value) && value.length > 0 && value.every(...)) so only real
MultiColumnExistsDefinition batches short-circuit; touch the
isMultiColumnDefinitionArray function (and keep isMultiColumnDefinition as-is)
to add the non-empty requirement for FilterConditionValue /
MultiColumnExistsDefinition detection.

311-315: ⚠️ Potential issue | 🟠 Major

jsonb is still exposed but not applied.

This serialization path never reads options.jsonb, so buildQuery(sql, { serialize, jsonb: false }) behaves exactly like the default path even though the public API promises different behavior. Please either plumb the flag into PostgresJsonQueryBuilder here or remove it until it is implemented.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/transformers/DynamicQueryBuilder.ts` around lines 311 -
315, The JSON serialization branch ignores options.jsonb, so calls to
buildQuery(..., { serialize, jsonb: false }) don't change behavior; update the
path to pass the jsonb flag into the PostgresJsonQueryBuilder usage (either by
passing options.jsonb into PostgresJsonQueryBuilder's constructor or by
forwarding it as a third argument into PostgresJsonQueryBuilder.buildJsonQuery),
i.e. locate the block using options.serialize, QueryBuilder.buildSimpleQuery and
PostgresJsonQueryBuilder.buildJsonQuery and ensure the jsonb boolean from
options is plumbed through to PostgresJsonQueryBuilder so its behavior respects
options.jsonb (or remove options.jsonb from the public API until implemented).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/core/src/transformers/PruneOptionalConditionBranches.ts`:
- Around line 26-28: The current unwrapSingleOuterParen function only strips one
ParenExpression so deeply nested parentheses (e.g. ((...))) remain and prevent
downstream checks like isBinaryOperator and getGuardedParameterName from
matching; update unwrapSingleOuterParen to repeatedly unwrap while the node is a
ParenExpression (loop or recursion) until a non-ParenExpression ValueComponent
is returned so later logic in PruneOptionalConditionBranches sees the fully
unwrapped expression.

---

Duplicate comments:
In `@packages/core/src/transformers/DynamicQueryBuilder.ts`:
- Around line 414-415: The predicate isMultiColumnDefinitionArray treats empty
arrays as valid multi-column EXISTS metadata because Array.every([]) is true;
update the check in isMultiColumnDefinitionArray to require a non-empty array
(e.g., ensure Array.isArray(value) && value.length > 0 && value.every(...)) so
only real MultiColumnExistsDefinition batches short-circuit; touch the
isMultiColumnDefinitionArray function (and keep isMultiColumnDefinition as-is)
to add the non-empty requirement for FilterConditionValue /
MultiColumnExistsDefinition detection.
- Around line 311-315: The JSON serialization branch ignores options.jsonb, so
calls to buildQuery(..., { serialize, jsonb: false }) don't change behavior;
update the path to pass the jsonb flag into the PostgresJsonQueryBuilder usage
(either by passing options.jsonb into PostgresJsonQueryBuilder's constructor or
by forwarding it as a third argument into
PostgresJsonQueryBuilder.buildJsonQuery), i.e. locate the block using
options.serialize, QueryBuilder.buildSimpleQuery and
PostgresJsonQueryBuilder.buildJsonQuery and ensure the jsonb boolean from
options is plumbed through to PostgresJsonQueryBuilder so its behavior respects
options.jsonb (or remove options.jsonb from the public API until implemented).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6c5d5deb-4322-4b08-b45f-bbde0220154b

📥 Commits

Reviewing files that changed from the base of the PR and between a7000ca and b05e4e9.

📒 Files selected for processing (6)
  • .changeset/issue-545-sssql-pruning-mvp.md
  • docs/guide/querybuilding-recipes.md
  • docs/guide/sssql-optional-branch-pruning.md
  • packages/core/src/transformers/DynamicQueryBuilder.ts
  • packages/core/src/transformers/PruneOptionalConditionBranches.ts
  • packages/core/tests/transformers/PruneOptionalConditionBranches.test.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • .changeset/issue-545-sssql-pruning-mvp.md
  • docs/guide/querybuilding-recipes.md
  • packages/core/tests/transformers/PruneOptionalConditionBranches.test.ts
  • docs/guide/sssql-optional-branch-pruning.md

Comment thread packages/core/src/transformers/PruneOptionalConditionBranches.ts
@mk3008 mk3008 merged commit 777ce15 into main Mar 12, 2026
6 checks passed
@mk3008 mk3008 deleted the codex/issue-545-sssql-pruning-mvp branch March 12, 2026 00:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant