Skip to content

feat(wren-ui): Support SQL formatting in FixSQL modal#1900

Merged
fredalai merged 3 commits intomainfrom
feature/sql-formatting-for-fixsql
Aug 21, 2025
Merged

feat(wren-ui): Support SQL formatting in FixSQL modal#1900
fredalai merged 3 commits intomainfrom
feature/sql-formatting-for-fixsql

Conversation

@fredalai
Copy link
Copy Markdown
Contributor

@fredalai fredalai commented Aug 20, 2025

Description

Support SQL formatting in FixSQL modal

Solution

  • Handle invalid SQL formatting on the backend
    • Adjustment Task
    • Asking Task
  • Other, replace with safe format SQL for preventing parsed error

Summary by CodeRabbit

  • Bug Fixes

    • Reduced errors when displaying SQL previews and breakdowns; invalid or partial SQL is now shown safely without crashing.
    • Improved reliability of SQL formatting across ask flows, models, and SQL pairs.
  • Refactor

    • Consolidated SQL formatting behind a single, resilient formatter for consistent results throughout the app.
    • Standardized SQL output for better readability, with smarter fallback behavior to handle edge cases.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Aug 20, 2025

Walkthrough

Centralized SQL formatting via a new safeFormatSQL utility. Replaced direct sql-formatter usage across resolvers and a service. Added fallback formatting behavior and logging in the utility. Adjusted handling of invalidSql to format when present or return null. No exported API signatures changed.

Changes

Cohort / File(s) Summary
Resolvers: centralized SQL formatting
wren-ui/src/apollo/server/resolvers/askingResolver.ts, wren-ui/src/apollo/server/resolvers/modelResolver.ts, wren-ui/src/apollo/server/resolvers/sqlPairResolver.ts
Switched imports from sql-formatter’s format to internal safeFormatSQL; replaced all format(...) calls; askingResolver now formats invalidSql via safeFormatSQL or returns null.
Service: formatting swap
wren-ui/src/apollo/server/services/askingService.ts
Replaced format(constructCteSql(...)) with safeFormatSQL(...); updated import.
Utility: new safe formatter
wren-ui/src/apollo/server/utils/sqlFormat.ts
Added safeFormatSQL(sql, options?) wrapping sql-formatter with fallback to Trino dialect; logs debug/error and returns original SQL on repeated failure. Exported function.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor R as Resolver/Service
  participant U as safeFormatSQL
  participant F as sql-formatter
  Note over R,U: Centralized SQL formatting
  R->>U: safeFormatSQL(sql, options?)
  U->>F: format(sql, options)
  alt Format succeeds
    F-->>U: formattedSQL
    U-->>R: formattedSQL
  else Format throws
    Note over U: Fallback to Trino dialect
    U->>F: format(sql, { language: "trino" })
    alt Fallback succeeds
      F-->>U: formattedSQL
      U-->>R: formattedSQL
    else Fallback throws
      U-->>R: original sql (unformatted)
      Note over U: Logs error with original message
    end
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested labels

wren-ui

Suggested reviewers

  • andreashimin
  • wwwy3y3

Poem

A bunny hops through queries’ maze,
Tucks SQL strings in tidy arrays.
If formats fail, no need to fear—
A Trino trail appears quite clear.
With gentle logs and whisker’d grace,
Our hops leave tidy tracks in place. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/sql-formatting-for-fixsql

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@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: 0

🧹 Nitpick comments (4)
wren-ui/src/apollo/server/resolvers/sqlPairResolver.ts (1)

114-114: PostgreSQL dialect hint looks correct; consider a typed helper to avoid repeated casting.

You always cast back to WrenSQL after formatting. Consider introducing a small wrapper that returns WrenSQL to reduce casts and standardize dialect options.

Example helper (outside this file, e.g., in @server/utils/sqlFormat.ts):

export function formatWrenSQL(sql: WrenSQL): WrenSQL {
  return safeFormatSQL(sql as string, { language: 'postgresql' }) as WrenSQL;
}

Then here:

-    return safeFormatSQL(wrenSQL, { language: 'postgresql' }) as WrenSQL;
+    return formatWrenSQL(wrenSQL);
wren-ui/src/apollo/server/services/askingService.ts (1)

978-978: Consider passing dialect based on project type for better formatting fidelity.

You have project in scope here. Aligning the dialect with the data source (e.g., tsql for MSSQL, bigquery for BigQuery, etc.) will improve formatting consistency across engines. Today, this call uses the default dialect and only falls back to trino.

Apply this diff locally within the selected line to pass a dialect:

-    const sql = safeFormatSQL(constructCteSql(steps, stepIndex));
+    const sql = safeFormatSQL(constructCteSql(steps, stepIndex), {
+      language: project.type === DataSourceName.MSSQL ? 'tsql' : undefined,
+    });

And add the missing import (outside this hunk):

import { DataSourceName } from '@server/models/adaptor';

If you’d like, I can propose a small mapping helper to cover more engines (bigquery, mysql, trino, etc.) and reuse it in resolvers/services.

wren-ui/src/apollo/server/utils/sqlFormat.ts (1)

1-22: Harden catch-typing, unify logger import, and consolidate SQL formatting

Two small tweaks in src/apollo/server/utils/sqlFormat.ts:

  • Annotate catch variables as any and fall back safely:
    } catch (err: any) {
      
    } catch (_fallbackError: any) {
      logger.error(`Failed to format SQL: ${err?.message ?? String(err)}`);
      return sql;
    }
  • Change
    import { getLogger } from './logger';
    to
    import { getLogger } from '@server/utils';

I also found a stray direct import of format from sql-formatter in:

• src/pages/knowledge/question-sql-pairs.tsx:4

Please replace it with our utility:

-import { format } from 'sql-formatter';
+import { safeFormatSQL } from '@server/utils/sqlFormat';  // or from '@server/utils' if re-exported- sqlPairDrawer.openDrawer({ …, sql: format(data.sql) });
+ sqlPairDrawer.openDrawer({ …, sql: safeFormatSQL(data.sql) });
wren-ui/src/apollo/server/resolvers/askingResolver.ts (1)

715-718: Formatting constructed CTE SQL centrally is good; consider dialect in future.

Given project context isn’t passed into nested resolvers, this is fine. If you later decide to tune formatting by datasource, we could fetch the project in this resolver and pass a dialect — but that adds a DB call here. I’d keep it as-is unless you see real formatting issues per engine.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between eabc6e4 and 973d5a6.

📒 Files selected for processing (5)
  • wren-ui/src/apollo/server/resolvers/askingResolver.ts (5 hunks)
  • wren-ui/src/apollo/server/resolvers/modelResolver.ts (3 hunks)
  • wren-ui/src/apollo/server/resolvers/sqlPairResolver.ts (2 hunks)
  • wren-ui/src/apollo/server/services/askingService.ts (2 hunks)
  • wren-ui/src/apollo/server/utils/sqlFormat.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
wren-ui/src/apollo/server/utils/sqlFormat.ts (1)
wren-ui/migrations/20241207000000_update_thread_response_for_answer.js (1)
  • sql (12-12)
wren-ui/src/apollo/server/resolvers/sqlPairResolver.ts (2)
wren-ui/src/apollo/server/utils/sqlFormat.ts (1)
  • safeFormatSQL (6-22)
wren-ui/src/apollo/server/models/adaptor.ts (1)
  • WrenSQL (9-9)
wren-ui/src/apollo/server/resolvers/modelResolver.ts (1)
wren-ui/src/apollo/server/utils/sqlFormat.ts (1)
  • safeFormatSQL (6-22)
wren-ui/src/apollo/server/services/askingService.ts (2)
wren-ui/migrations/20241207000000_update_thread_response_for_answer.js (2)
  • sql (12-12)
  • constructCteSql (1-31)
wren-ui/src/apollo/server/utils/sqlFormat.ts (1)
  • safeFormatSQL (6-22)
wren-ui/src/apollo/server/resolvers/askingResolver.ts (4)
wren-ui/src/apollo/server/utils/sqlFormat.ts (1)
  • safeFormatSQL (6-22)
wren-ui/src/apollo/server/services/askingService.ts (1)
  • constructCteSql (240-278)
wren-ui/src/apollo/client/graphql/__types__.ts (1)
  • DetailStep (346-351)
wren-ui/src/apollo/server/repositories/threadResponseRepository.ts (1)
  • DetailStep (10-14)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (10)
wren-ui/src/apollo/server/resolvers/sqlPairResolver.ts (1)

6-6: Good move to centralized SQL formatting.

Switching to safeFormatSQL consolidates formatting behavior and gives you the fallback path and logging. No concerns here.

wren-ui/src/apollo/server/services/askingService.ts (1)

23-23: LGTM: import aligned with new utility.

Centralizing via safeFormatSQL is consistent with the PR goals.

wren-ui/src/apollo/server/resolvers/modelResolver.ts (3)

18-18: Import swap to safeFormatSQL is consistent with the new approach.

No issues spotted.


824-825: Formatting response SQL via safeFormatSQL is appropriate.

Good to centralize; the utility’s fallback behavior avoids throwing on formatter errors.


990-992: Dialect handling for MSSQL is correct (tsql).

tsql is the right sql-formatter dialect for MSSQL. Using safeFormatSQL preserves behavior with fallbacks and logging.

wren-ui/src/apollo/server/resolvers/askingResolver.ts (5)

19-19: Import aligned with the new safe formatter — good.

This supports the FixSQL modal objective without leaking sql-formatter calls across resolvers.


559-561: Formatting invalidSql before returning is appropriate.

Keeps the FixSQL modal consistent while preserving fallback behavior when formatting fails.


749-752: Consistent invalidSql formatting here as well — looks good.

Matches the pattern above; no concerns.


758-759: DetailStep.sql formatting via safeFormatSQL is correct.

Safe and consistent.


764-765: ResultCandidate.sql formatting via safeFormatSQL is correct.

Maintains consistent formatting in the result candidates.

Copy link
Copy Markdown
Contributor

@andreashimin andreashimin left a comment

Choose a reason for hiding this comment

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

lgtm, thanks for the syncing

@fredalai fredalai merged commit 5590d66 into main Aug 21, 2025
7 checks passed
@fredalai fredalai deleted the feature/sql-formatting-for-fixsql branch August 21, 2025 02:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants