Skip to content

Fix inline comments mangling CREATE FOREIGN TABLE formatting#43

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

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

Conversation

@gmr

@gmr gmr commented Jul 8, 2026

Copy link
Copy Markdown
Owner

Closes #41.

Problem

CREATE FOREIGN TABLE mishandled inline -- ... comments the same way CREATE TABLE did before #40. For:

CREATE FOREIGN TABLE films (
    code CHAR(5) NOT NULL, -- primary identifier
    title VARCHAR(40) NOT NULL, -- film title
    did INTEGER NOT NULL --director id
) SERVER film_server OPTIONS (schema_name 'public', table_name 'films');

it produced (aweber/river):

CREATE FOREIGN TABLE films (
    code                  CHAR(5)     NOT NULL,
    -- primary identifier ,
    title                 VARCHAR(40) NOT NULL,
    -- film title         ,
    did                   INTEGER     NOT NULL
)
...

Comments got alignment padding and a trailing comma (mangling the comment text, breaking idempotency), and the final comment (--director id, before the closing paren) was dropped.

Fix

The comment-association logic added for CREATE TABLE in #40 is factored into a shared collect_table_elements helper, now used by both format_create_table_stmt and format_create_foreign_table_stmt. The foreign-table formatter renders trailing comments at the end of the element they follow — aligned to a common column in river style, single-space in left-aligned styles — while keeping the original element order.

Result:

CREATE FOREIGN TABLE films (
    code  CHAR(5)     NOT NULL, -- primary identifier
    title VARCHAR(40) NOT NULL, -- film title
    did   INTEGER     NOT NULL  --director id
)
SERVER film_server
OPTIONS (
    schema_name 'public',
    table_name 'films'
);

Tests

  • New create_foreign_table_inline_comments fixtures (river + mozilla).
  • Wired up the two pre-existing but unregistered create_foreign_table river fixtures for regression coverage of the rewritten path.
  • Full suite passes (65 fixtures); cargo fmt --check and cargo clippy -D warnings clean; verified idempotent.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of inline -- ... comments in CREATE TABLE and CREATE FOREIGN TABLE, ensuring comments remain associated with the correct table elements.
    • Improved comment placement and river-style alignment for foreign table formatting to keep output more consistent.
  • Tests
    • Added new fixture coverage for foreign table formatting with inline comments under both supported styles.

CREATE FOREIGN TABLE mishandled inline `-- ...` comments the same way
CREATE TABLE did before #40: comments between columns were treated as
bogus columns (alignment padding plus a trailing comma that mangled the
comment text), and a comment after the last element was dropped.

Factor the comment-association logic added for CREATE TABLE into a shared
`collect_table_elements` helper and use it from both statement formatters.
`format_create_foreign_table_stmt` now renders trailing comments at the
end of the element they follow (aligned to a common column in river
style, single-space in left-aligned styles), keeping the original element
order.

Also registers the previously unwired CREATE FOREIGN TABLE fixtures in the
test harness alongside the new inline-comment fixtures.

Closes #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: 6784b72c-2495-4ec1-b952-a14c0eacacb7

📥 Commits

Reviewing files that changed from the base of the PR and between 3ad2331 and f7fbbc3.

📒 Files selected for processing (1)
  • src/formatter/stmt.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/formatter/stmt.rs

📝 Walkthrough

Walkthrough

This change fixes inline -- ... comment handling in CREATE FOREIGN TABLE formatting by reusing shared table-element comment grouping, updating foreign-table rendering to keep comments attached to their preceding elements, and adding fixtures and tests for the new output.

Changes

Inline comment association for table elements

Layer / File(s) Summary
collect_table_elements helper and CREATE TABLE integration
src/formatter/stmt.rs
Adds collect_table_elements(node, elem_list) to flatten table elements, group trailing comments, and split leading vs trailing comments; format_create_table_stmt uses the helper and the left-aligned renderer.
CREATE FOREIGN TABLE rendering using collect_table_elements
src/formatter/stmt.rs
format_create_foreign_table_stmt switches to collect_table_elements, emits leading comments before elements, and renders grouped elements with aligned trailing comments in river and non-river modes.
Fixtures and tests for foreign table inline comments
tests/fixtures/mozilla/create_foreign_table_inline_comments.*, tests/fixtures/river/create_foreign_table_inline_comments.*, tests/fixtures_test.rs
Adds SQL/expected fixtures for a films foreign table with inline column comments and new fixture tests for both River and Mozilla styles.

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

Possibly related PRs

  • gmr/libpgfmt#1: Modifies the same src/formatter/stmt.rs statement-formatting path that this PR refactors for inline comment handling.
  • gmr/libpgfmt#4: Also changes CREATE FOREIGN TABLE formatting logic in src/formatter/stmt.rs.
  • gmr/libpgfmt#39: Also touches format_create_table_stmt behavior in the same formatter module.

Poem

I’m a rabbit with a formatter nose,
I hop where the inline comment goes.
No more comma-munching in the night,
Just tidy films and comments right.
Hop, hop—these tables now look grand! 🐇

🚥 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 and concisely describes the main change: fixing inline comment handling in CREATE FOREIGN TABLE formatting.
Linked Issues check ✅ Passed The formatter now reuses the comment-grouping fix for CREATE FOREIGN TABLE, preserving order and rendering inline comments correctly in both styles for [#41].
Out of Scope Changes check ✅ Passed The added helper extraction and fixtures are directly tied to the foreign-table comment fix and regression coverage, with no unrelated changes evident.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


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.

🧹 Nitpick comments (1)
src/formatter/stmt.rs (1)

642-657: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated non-river rendering loop.

The non-river branch of format_create_foreign_table_stmt (Line 1362-1378) is identical to the corresponding branch in format_create_table_stmt (Line 642-657). Consider extracting a shared helper (e.g. render_grouped_elements_left_aligned(&self, grouped: &[(Node<'a>, Vec<String>)], indent: &str) -> Vec<String>) that both callers can use, mirroring how collect_table_elements was already extracted for comment association.

♻️ Proposed extraction
+    fn render_grouped_elements_left_aligned(
+        &self,
+        grouped: &[(Node<'a>, Vec<String>)],
+        indent: &str,
+    ) -> Vec<String> {
+        let mut lines = Vec::new();
+        let total = grouped.len();
+        for (i, (elem_node, comments)) in grouped.iter().enumerate() {
+            let elem = self.format_table_element(*elem_node);
+            let comma = if i < total - 1 { "," } else { "" };
+            let line = format!("{indent}{elem}{comma}");
+            if let Some((first, rest)) = comments.split_first() {
+                lines.push(format!("{line} {first}"));
+                for extra in rest {
+                    lines.push(format!("{indent}{extra}"));
+                }
+            } else {
+                lines.push(line);
+            }
+        }
+        lines
+    }

Also applies to: 1362-1378

🤖 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 `@src/formatter/stmt.rs` around lines 642 - 657, The non-river rendering loop
is duplicated between format_create_table_stmt and
format_create_foreign_table_stmt, so extract the shared left-aligned
grouped-element rendering into a helper such as
render_grouped_elements_left_aligned on the formatter and have both branches
call it. Keep the existing behavior for commas, indentation, and attached
comments intact, and reuse the same grouped input shape used by
collect_table_elements to avoid the repeated logic.
🤖 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.

Nitpick comments:
In `@src/formatter/stmt.rs`:
- Around line 642-657: The non-river rendering loop is duplicated between
format_create_table_stmt and format_create_foreign_table_stmt, so extract the
shared left-aligned grouped-element rendering into a helper such as
render_grouped_elements_left_aligned on the formatter and have both branches
call it. Keep the existing behavior for commas, indentation, and attached
comments intact, and reuse the same grouped input shape used by
collect_table_elements to avoid the repeated logic.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0df342c9-6ba5-4280-8761-555e9cd38470

📥 Commits

Reviewing files that changed from the base of the PR and between 278e428 and 3ad2331.

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

The non-river rendering loop in format_create_foreign_table_stmt was
byte-identical to the one in format_create_table_stmt. Extract it into a
render_grouped_elements_left_aligned helper that both callers use,
mirroring the earlier collect_table_elements extraction.

Addresses CodeRabbit nitpick on PR #43. Behavior is unchanged; all
fixtures and unit tests pass.

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 nitpick on src/formatter/stmt.rs: the non-river rendering loop in format_create_foreign_table_stmt was byte-identical to the one in format_create_table_stmt. Extracted it into a shared render_grouped_elements_left_aligned helper that both callers now use, mirroring the earlier collect_table_elements extraction.

Behavior is unchanged; cargo fmt --check, cargo clippy -- -D warnings, and the full test suite all pass locally. Pushed as f7fbbc3.

@gmr

gmr commented Jul 8, 2026

Copy link
Copy Markdown
Owner Author

Automated PR monitoring complete — this PR is ready to merge.

  • CI / GitHub Actions: all checks green
  • Review threads: 0 unresolved
  • CodeRabbit: re-reviewed the latest commit (f7fbbc3) with no actionable comments
  • One CodeRabbit nitpick was addressed during monitoring (extracted render_grouped_elements_left_aligned)

All checks passing and review feedback addressed.

@gmr gmr merged commit d056365 into main Jul 8, 2026
3 checks passed
@gmr gmr deleted the fix/create-foreign-table-inline-comments branch July 8, 2026 16:33
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.

CREATE FOREIGN TABLE mangles inline column comments

1 participant