Skip to content

Fix inline comments mangling CREATE TABLE formatting#42

Merged
gmr merged 2 commits into
mainfrom
fix/create-table-inline-comments
Jul 8, 2026
Merged

Fix inline comments mangling CREATE TABLE formatting#42
gmr merged 2 commits into
mainfrom
fix/create-table-inline-comments

Conversation

@gmr

@gmr gmr commented Jul 8, 2026

Copy link
Copy Markdown
Owner

Problem

Reported in gmr/pgfmt#12. Inline -- ... comments on CREATE TABLE column definitions were mangled:

CREATE TABLE personnes (
    id INTEGER PRIMARY KEY, -- un type SERIAL aurait été bienvenu
    nom VARCHAR(100), -- nom de la colonne et type
    birthdate DATE CHECK (birthdate < CURRENT_DATE), --contrainte de colonne
    is_active BOOLEAN,
    UNIQUE (nom, birthdate) --contrainte de table
);

produced (aweber/river):

CREATE TABLE personnes (
    id                                      INTEGER      PRIMARY KEY,
    -- un type SERIAL aurait été bienvenu   ,
    nom                                     VARCHAR(100),
    -- nom de la colonne et type            ,
    birthdate                               DATE         CHECK (birthdate < CURRENT_DATE),
    --contrainte de colonne                 ,
    is_active                               BOOLEAN,
                                            UNIQUE (nom, birthdate)
);

Comments got column-alignment padding and a trailing comma (mangling the comment text and breaking idempotency), and the final comment (--contrainte de table) was dropped entirely.

Root cause

Two CST facts:

  1. Comments between columns parse as comment sibling nodes inside TableElementList, so flatten_list returned them alongside real TableElements and classify_table_element's catch-all arm turned each into a Column.
  2. A comment after the final element parses as a direct child of CreateStmt (before the closing paren), which the formatter never inspected.

Fix

format_create_table_stmt now groups each element with the comments that trail it (new group_table_elements helper) and scans the statement node's direct comment children, routing them by byte position (before the element list → leading; after → trailing on the last element). Both the river and left-aligned render branches emit comments at the end of the preceding element's line, after the comma; river style aligns them to a common column.

Result:

CREATE TABLE personnes (
    id        INTEGER      PRIMARY KEY,                      -- un type SERIAL aurait été bienvenu
    nom       VARCHAR(100),                                  -- nom de la colonne et type
    birthdate DATE         CHECK (birthdate < CURRENT_DATE), --contrainte de colonne
    is_active BOOLEAN,
              UNIQUE (nom, birthdate)                        --contrainte de table
);

Tests

  • Added create_table_inline_comments fixtures for river and mozilla styles.
  • Full suite passes; cargo fmt --check and cargo clippy -D warnings clean.
  • Verified idempotent across repeated passes.

Out of scope

CREATE FOREIGN TABLE shares the same pipeline and has the same latent bug — tracked in #41.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Improved CREATE TABLE formatting to preserve and correctly attach inline -- comments within column and constraint lists.
    • Enhanced comment boundary handling around the table element list so comments remain in the right place.
    • Improved alignment and rendering of trailing/extra attached comments for both single- and multi-line table elements.
  • Tests

    • Added fixture-based coverage for inline comment formatting for both River and Mozilla styles.
    • Added fixtures to validate comment boundaries and expected output.

Inline `-- ...` comments on column definitions were treated as bogus
columns: given alignment padding and a trailing comma (which mangled the
comment text and broke idempotency), and a comment after the last element
was dropped entirely.

Two CST facts drove the bug. Comments between columns parse as `comment`
sibling nodes inside `TableElementList`, so `flatten_list` returned them
alongside real `TableElement`s and `classify_table_element`'s catch-all
arm turned each into a `Column`. A comment after the final element parses
as a direct child of `CreateStmt` (before the closing paren), which the
formatter never inspected.

`format_create_table_stmt` now groups each element with the comments that
trail it (new `group_table_elements` helper) and also scans the statement
node's direct `comment` children, routing them by byte position. Both the
river and left-aligned render branches emit comments at the end of the
preceding element's line, after the comma; river style aligns them to a
common column.

Scoped to CREATE TABLE; CREATE FOREIGN TABLE has the same latent bug,
tracked in #41.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 8, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3da71a9a-4697-476d-a560-daa633cc7b3a

📥 Commits

Reviewing files that changed from the base of the PR and between 611517b and 4477ae9.

📒 Files selected for processing (6)
  • src/formatter/stmt.rs
  • tests/fixtures/mozilla/create_table_comment_boundaries.expected
  • tests/fixtures/mozilla/create_table_comment_boundaries.sql
  • tests/fixtures/river/create_table_comment_boundaries.expected
  • tests/fixtures/river/create_table_comment_boundaries.sql
  • tests/fixtures_test.rs
✅ Files skipped from review due to trivial changes (3)
  • tests/fixtures/mozilla/create_table_comment_boundaries.sql
  • tests/fixtures/river/create_table_comment_boundaries.expected
  • tests/fixtures_test.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/formatter/stmt.rs

📝 Walkthrough

Walkthrough

This PR updates CREATE TABLE formatting to preserve inline -- comments in river and non-river output, adds comment-boundary handling around table element lists, and includes new fixtures and tests for both dialect styles.

Changes

Inline Comment Preservation in CREATE TABLE Formatting

Layer / File(s) Summary
Comment grouping and rendering rewrite
src/formatter/stmt.rs
Adds group_table_elements, scans comments around the element list boundaries, and rewrites CREATE TABLE rendering to keep leading comments separate while carrying trailing comments through river and non-river output.
Fixtures and tests for comment boundaries
tests/fixtures/river/create_table_inline_comments.sql, tests/fixtures/river/create_table_inline_comments.expected, tests/fixtures/mozilla/create_table_inline_comments.sql, tests/fixtures/mozilla/create_table_inline_comments.expected, tests/fixtures/river/create_table_comment_boundaries.sql, tests/fixtures/river/create_table_comment_boundaries.expected, tests/fixtures/mozilla/create_table_comment_boundaries.sql, tests/fixtures/mozilla/create_table_comment_boundaries.expected, tests/fixtures_test.rs
Adds river and mozilla CREATE TABLE fixtures plus expected outputs for inline comments and comment boundary cases, and wires both cases into fixture-based tests.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related issues

Poem

A rabbit nibbled SQL so neat,
With comments lined in properీట్?
No stray notes fell away,
They hopped right into place today,
Hooray for tables sweet! 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main CREATE TABLE inline-comment formatting fix.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

@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 `@src/formatter/stmt.rs`:
- Around line 526-544: The comment handling in stmt.rs is routing any comment
after the table-element list into the last grouped table element, so update the
comment scan in the code around group_table_elements and elem_list to stop at
the end of OptTableElementList and keep later clauses out of the column list.
Also preserve source order for leading comments by collecting and emitting them
in the same order they appear before the list, instead of allowing later
processing to reorder them.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 195af3c7-b40d-47ff-88ed-74d59bbddecf

📥 Commits

Reviewing files that changed from the base of the PR and between a98ee3f and 611517b.

📒 Files selected for processing (6)
  • src/formatter/stmt.rs
  • tests/fixtures/mozilla/create_table_inline_comments.expected
  • tests/fixtures/mozilla/create_table_inline_comments.sql
  • tests/fixtures/river/create_table_inline_comments.expected
  • tests/fixtures/river/create_table_inline_comments.sql
  • tests/fixtures_test.rs

Comment thread src/formatter/stmt.rs Outdated
The comment scan in format_create_table_stmt appended any CreateStmt-level
comment after the element list to the last column, so a comment attached to
a following clause (WITH, INHERITS, a partition spec) was folded into the
column list. It now stops at the element list's closing paren — a direct
child of CreateStmt — and leaves later-clause comments out of the columns.

Leading comments are also emitted in source order: comments that precede the
element list are kept ahead of comments inside it, rather than after them.

Addresses CodeRabbit review feedback on #42.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@gmr

gmr commented Jul 8, 2026

Copy link
Copy Markdown
Owner Author

🤖 This comment was posted by Claude on behalf of @gmr

Addressed the CodeRabbit review on this cycle (commit 4477ae9):

  • Bound comment routing to the element list. Comments after the closing paren (belonging to WITH/INHERITS/partition clauses) are no longer folded into the last column; the scan stops at the element list's closing paren.
  • Leading comments now emit in source order — comments before the list precede in-list leading comments.
  • Added create_table_comment_boundaries regression fixtures for river and mozilla.

CI: all checks were green on the prior commit; verified locally with cargo test, cargo clippy -- -D warnings, and cargo fmt --check. Resolved the review thread.

@gmr

gmr commented Jul 8, 2026

Copy link
Copy Markdown
Owner Author

pr-agent: PR is ready to merge ✅

Automated monitoring complete. Summary of this session:

  • CI/checks: All passing — test (stable) and test (nightly) green; cargo build, cargo test, cargo clippy -- -D warnings, and cargo fmt --check all verified locally. CodeRabbit status check resolved to success.
  • Review feedback: Addressed CodeRabbit's Major finding by bounding inline-comment routing at the closing paren and preserving source-order leading comments (pushed as 4477ae9). Thread resolved after verification.
  • Re-review: CodeRabbit re-reviewed HEAD 4477ae9 with no new comments; all review threads resolved.
  • Out of scope: The sibling CREATE FOREIGN TABLE bug remains tracked separately in CREATE FOREIGN TABLE mangles inline column comments #41 and was intentionally not touched here.

No outstanding blockers — ready for human merge.

@gmr

gmr commented Jul 8, 2026

Copy link
Copy Markdown
Owner Author

This addresses gmr/pgfmt#11 (comment)

@gmr gmr merged commit 278e428 into main Jul 8, 2026
3 checks passed
@gmr gmr deleted the fix/create-table-inline-comments branch July 8, 2026 14:50
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