Skip to content

Fix formatter comment handling around SQL expressions#884

Open
mk3008 wants to merge 1 commit into
mainfrom
codex/fix-comment-formatting
Open

Fix formatter comment handling around SQL expressions#884
mk3008 wants to merge 1 commit into
mainfrom
codex/fix-comment-formatting

Conversation

@mk3008

@mk3008 mk3008 commented Jun 11, 2026

Copy link
Copy Markdown
Owner

Summary

  • Fix SQL formatter comment handling around comma-prefixed expressions and value clauses.
  • Render comments after SELECT, ORDER BY, and GROUP BY list commas on dedicated lines in both before-comma and after-comma styles, while preserving first select-item inline comments.
  • Preserve comments before LIMIT/OFFSET values and avoid duplicated comments in function arguments, ORDER BY/GROUP BY items, and parenthesized WHERE predicates.
  • Add regression coverage for CASE select item comment indentation, before/after comma comment layout, and prior duplicate-comment expectations.

Verification

  • pnpm vitest run packages/core/tests/transformers/CommentStyle.comprehensive.test.ts packages/core/tests/transformers/SqlFormatter.comprehensive.test.ts packages/core/tests/transformers/SqlFormatter.case-comment-regression.test.ts packages/core/tests/transformers/SqlFormatter.comment-placement.test.ts packages/core/tests/transformers/SqlFormatter.comment-exact-transformation.test.ts packages/core/tests/transformers/SqlFormatter.comment-statement-invariance.property.test.ts packages/core/tests/transformers/SqlFormatter.values-comment-indentation.test.ts packages/core/tests/transformers/SqlFormatter.merge.test.ts
  • pnpm --filter rawsql-ts test
  • pnpm typecheck
  • Pre-commit hook: workspace typecheck, workspace tests, workspace build, workspace lint

Merge Readiness

  • No baseline exception requested.
  • Baseline exception requested and linked below.

Tracking issue: Not required
Scoped checks run: Focused formatter tests, pnpm --filter rawsql-ts test, pnpm typecheck, pre-commit workspace typecheck/test/build/lint
Why full baseline is not required: No exception requested; pre-commit ran the workspace gate successfully.

Self Review

Self-review workflow: self-review skill, two-cycle review after formatter-focused tests and the full pre-commit gate.
Self-review result: No blockers found; evidence covers the comment-loss, duplicate-comment, CASE indentation, and before/after comma layout regressions.
Concept-review workflow: No concept review required; this is a rawsql-ts formatter bug fix with no concept, package-boundary, CLI, or scaffold contract change.
Concept-review result: No concept or package-boundary violations found.

CLI Surface Migration

  • No migration packet required for this CLI change.
  • CLI/user-facing surface change and migration packet completed.

No-migration rationale: No CLI command, option, or public user-facing contract changed; formatter behavior is corrected.
Upgrade note: Not required.
Deprecation/removal plan or issue: Not required.
Docs/help/examples updated: Not required; changeset added for release notes.
Release/changeset wording: .changeset/fix-comment-formatting.md

Scaffold Contract Proof

  • No scaffold contract proof required for this PR.
  • Scaffold contract proof completed.

No-proof rationale: No scaffold templates, generation contracts, or scaffolded output changed.
Non-edit assertion: Not required.
Fail-fast input-contract proof: Not required.
Generated-output viability proof: Not required.

@coderabbitai

coderabbitai Bot commented Jun 11, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR fixes SQL formatter comment handling to eliminate duplicate comments in formatted output. Parser updates capture comments from LIMIT/OFFSET keywords and attach them to their values. Token printing logic deduplicates comments across nested components. Indentation rules adjust for SelectItem contexts. Comprehensive tests verify correct behavior across multiple SQL constructs.

Changes

SQL Formatter Comment Handling Fixes

Layer / File(s) Summary
LIMIT/OFFSET comment propagation
packages/core/src/parsers/LimitClauseParser.ts, packages/core/src/parsers/OffsetClauseParser.ts
LIMIT and OFFSET parsers now capture positioned comments from their keyword lexemes and propagate comments occurring after those keywords onto the respective value items as 'before' positioned comments.
Token printing comment deduplication
packages/core/src/parsers/SqlPrintTokenParser.ts
QualifiedName, ColumnReference, and ParenExpression visitors now compute whether parent components have their own comments and conditionally skip or filter nested comment propagation to prevent duplicate rendering in nested contexts.
SelectItem comment indentation
packages/core/src/transformers/SqlPrinter.ts
Leading block comment indentation for SelectItem contexts is adjusted by reducing computed indent level on blank lines and providing a dedicated SelectItem indentation rule that clamps to reviewable levels.
Test coverage and validation
packages/core/tests/transformers/CommentStyle.comprehensive.test.ts, packages/core/tests/transformers/SqlFormatter.comprehensive.test.ts
Five new block-style comment test cases verify correct placement for CASE items, function arguments, ORDER BY/GROUP BY lists, parenthesized WHERE predicates, and LIMIT/OFFSET values. Two existing test assertions updated to reflect eliminated duplicate comments.
Release notes
.changeset/fix-comment-formatting.md
Patch-level changeset documents fixes for comment deduplication and positioning across functions, comma-prefixed expressions, clauses, and CASE select items.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • mk3008/rawsql-ts#234: Updates SqlPrintTokenParser.ts comment propagation logic for ParenExpression with similar deduplication approach.
  • mk3008/rawsql-ts#221: Modifies SqlPrinter.ts leading-comment indentation and SelectItem-specific handling.
  • mk3008/rawsql-ts#220: Updates SqlPrintTokenParser.ts comment handling around parenthesized expressions.

Poem

🐰 Comments once did dance and play,
Till duplicates showed up to stay,
With parsers fixed and printers wise,
Each comment now appears just twice! ✓
Block by block, the chaos fades,
And cleaner formatted text cascades.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: fixing formatter comment handling around SQL expressions, which is the primary focus of all file modifications.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The pull request description comprehensively covers all required sections with detailed information about changes, verification steps, merge readiness, and self-review.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/fix-comment-formatting

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/tests/transformers/CommentStyle.comprehensive.test.ts`:
- Around line 161-186: The test currently only checks presence of the comments
but should ensure they appear exactly once and directly adjacent to their
corresponding LIMIT/OFFSET parameters; update the assertions on
result.formattedSql (produced by formatter.format(query) where query =
SelectQueryParser.parse(sql).toSimpleQuery()) to (1) assert a single occurrence
of "page size" and "page offset" (e.g. count/indexOf checks) and (2) assert each
comment appears immediately before its parameter (e.g. assert the substring
"limit /* page size */ :limit" and "offset /* page offset */ :offset" or
equivalent regex matches) so duplication or misplacement will fail the test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2d8a697a-bd7f-4d4c-91ac-b2ee9e6f2335

📥 Commits

Reviewing files that changed from the base of the PR and between 536a9f4 and 2288ee3.

📒 Files selected for processing (7)
  • .changeset/fix-comment-formatting.md
  • packages/core/src/parsers/LimitClauseParser.ts
  • packages/core/src/parsers/OffsetClauseParser.ts
  • packages/core/src/parsers/SqlPrintTokenParser.ts
  • packages/core/src/transformers/SqlPrinter.ts
  • packages/core/tests/transformers/CommentStyle.comprehensive.test.ts
  • packages/core/tests/transformers/SqlFormatter.comprehensive.test.ts

Comment on lines +161 to +186
test('should preserve comments before LIMIT and OFFSET values', () => {
const formatter = new SqlFormatter({
exportComment: true,
commentStyle: 'block',
commaBreak: 'before',
indentSize: 4,
indentChar: ' ',
keywordCase: 'lower',
newline: '\n'
});
const sql = `
select *
from t
order by id
limit /* page size */
:limit
offset /* page offset */
:offset
`;

const query = SelectQueryParser.parse(sql).toSimpleQuery();
const result = formatter.format(query);

expect(result.formattedSql).toContain('page size');
expect(result.formattedSql).toContain('page offset');
});

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 | 🟡 Minor | ⚡ Quick win

Strengthen LIMIT/OFFSET assertions to catch duplication and misplacement.

Line 184 and Line 185 only verify presence. This still passes if comments are duplicated or moved away from the LIMIT/OFFSET values, which weakens this regression.

Suggested assertion tightening
-            expect(result.formattedSql).toContain('page size');
-            expect(result.formattedSql).toContain('page offset');
+            expect(result.formattedSql.match(/page size/g)).toHaveLength(1);
+            expect(result.formattedSql.match(/page offset/g)).toHaveLength(1);
+            expect(result.formattedSql).toMatch(/limit\s+\/\*\s*page size\s*\*\/\s*:limit/i);
+            expect(result.formattedSql).toMatch(/offset\s+\/\*\s*page offset\s*\*\/\s*:offset/i);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
test('should preserve comments before LIMIT and OFFSET values', () => {
const formatter = new SqlFormatter({
exportComment: true,
commentStyle: 'block',
commaBreak: 'before',
indentSize: 4,
indentChar: ' ',
keywordCase: 'lower',
newline: '\n'
});
const sql = `
select *
from t
order by id
limit /* page size */
:limit
offset /* page offset */
:offset
`;
const query = SelectQueryParser.parse(sql).toSimpleQuery();
const result = formatter.format(query);
expect(result.formattedSql).toContain('page size');
expect(result.formattedSql).toContain('page offset');
});
test('should preserve comments before LIMIT and OFFSET values', () => {
const formatter = new SqlFormatter({
exportComment: true,
commentStyle: 'block',
commaBreak: 'before',
indentSize: 4,
indentChar: ' ',
keywordCase: 'lower',
newline: '\n'
});
const sql = `
select *
from t
order by id
limit /* page size */
:limit
offset /* page offset */
:offset
`;
const query = SelectQueryParser.parse(sql).toSimpleQuery();
const result = formatter.format(query);
expect(result.formattedSql.match(/page size/g)).toHaveLength(1);
expect(result.formattedSql.match(/page offset/g)).toHaveLength(1);
expect(result.formattedSql).toMatch(/limit\s+\/\*\s*page size\s*\*\/\s*:limit/i);
expect(result.formattedSql).toMatch(/offset\s+\/\*\s*page offset\s*\*\/\s*:offset/i);
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/tests/transformers/CommentStyle.comprehensive.test.ts` around
lines 161 - 186, The test currently only checks presence of the comments but
should ensure they appear exactly once and directly adjacent to their
corresponding LIMIT/OFFSET parameters; update the assertions on
result.formattedSql (produced by formatter.format(query) where query =
SelectQueryParser.parse(sql).toSimpleQuery()) to (1) assert a single occurrence
of "page size" and "page offset" (e.g. count/indexOf checks) and (2) assert each
comment appears immediately before its parameter (e.g. assert the substring
"limit /* page size */ :limit" and "offset /* page offset */ :offset" or
equivalent regex matches) so duplication or misplacement will fail the test.

@mk3008 mk3008 force-pushed the codex/fix-comment-formatting branch from 2288ee3 to 4c2d0f4 Compare June 11, 2026 14:26
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