From 84c24506332d05d4881a5b65781a34d2b979cc1c Mon Sep 17 00:00:00 2001 From: Ryan Maleki Date: Sun, 15 Nov 2026 20:05:52 -0800 Subject: [PATCH] Add SQL Formatter --- client/src/App.tsx | 2 + client/src/data/defaults.ts | 4 + client/src/data/tools.ts | 76 ++++ client/src/lib/formatters.ts | 73 ++++ client/src/pages/tools/sql-formatter.tsx | 501 +++++++++++++++++++++++ package-lock.json | 82 ++++ package.json | 1 + replit.md | 4 +- tests/e2e/tools/sql-formatter.spec.ts | 39 ++ tests/lib/formatters-async.test.ts | 58 +++ 10 files changed, 838 insertions(+), 2 deletions(-) create mode 100644 client/src/pages/tools/sql-formatter.tsx create mode 100644 tests/e2e/tools/sql-formatter.spec.ts diff --git a/client/src/App.tsx b/client/src/App.tsx index 09b4998a..7f630b60 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -33,6 +33,7 @@ const TypeScriptFormatter = lazy( () => import("@/pages/tools/typescript-formatter") ); const GraphQLFormatter = lazy(() => import("@/pages/tools/graphql-formatter")); +const SqlFormatter = lazy(() => import("@/pages/tools/sql-formatter")); const TimeFormatter = lazy(() => import("@/pages/tools/time-formatter")); const Base64Encoder = lazy(() => import("@/pages/tools/base64-encoder")); const CborEncoder = lazy(() => import("@/pages/tools/cbor-encoder")); @@ -132,6 +133,7 @@ function Router() { component={TypeScriptFormatter} /> + {/* Encoders */} diff --git a/client/src/data/defaults.ts b/client/src/data/defaults.ts index 0145c3c9..50839a87 100644 --- a/client/src/data/defaults.ts +++ b/client/src/data/defaults.ts @@ -526,6 +526,10 @@ export const DEFAULT_GRAPHQL = `type User type Comment{id:ID!content:String!author:User!post:Post!createdAt:String!}type UserProfile{bio:String avatar:String website:String location:String}input CreateUserInput{name:String!email:String!age:Int}input UpdateUserInput{name:String email:String age:Int}type Query{users:[User!]!user(id:ID!):User posts:[Post!]!post(id:ID!):Post searchPosts(query:String!):[Post!]!}type Mutation{createUser(input:CreateUserInput!):User!updateUser(id:ID!,input:UpdateUserInput!):User!deleteUser(id:ID!):Boolean!createPost(title:String!,content:String!,authorId:ID!):Post!}type Subscription{postAdded:Post!commentAdded(postId:ID!):Comment!}schema{query:Query mutation:Mutation subscription:Subscription} `; +export const DEFAULT_SQL = `select u.id, u.name, u.email, count(o.id) as order_count, sum(o.total) as total_spent from users u left join orders o on o.user_id = u.id and o.status = 'completed' where u.created_at >= '2024-01-01' and (u.country = 'US' or u.country = 'CA') and u.id not in (select user_id from banned_users) group by u.id, u.name, u.email having sum(o.total) > 100 order by total_spent desc limit 20; +insert into audit_log (event, created_at) values ('report_generated', current_timestamp); +`; + export const DEFAULT_URL_TO_JSON = `https://api.example.com/users?page=1&limit=10&sort=name&order=asc&filter=active&category=premium#section`; export const DEFAULT_CSV_TO_JSON = `name,email,age,city diff --git a/client/src/data/tools.ts b/client/src/data/tools.ts index 9324e656..1171a559 100644 --- a/client/src/data/tools.ts +++ b/client/src/data/tools.ts @@ -22,6 +22,7 @@ import { FileJson, Braces, DatabaseBackup, + Database, // Encoders / Security KeyRound, @@ -2295,6 +2296,81 @@ export const toolsData: ToolData = { ], }, }, + { + name: "SQL Formatter", + path: "/tools/sql-formatter", + icon: Database, + shortcut: "Ctrl+Shift+Alt+S", + metadata: { + title: "SQL Formatter - Format SQL Queries Online", + description: + "Format and beautify SQL queries for PostgreSQL, MySQL, SQL Server, Oracle, SQLite, BigQuery, Snowflake and more. Configure keyword case, indentation and layout.", + keywords: [ + "SQL formatter", + "SQL beautifier", + "SQL pretty print", + "PostgreSQL formatter", + "MySQL formatter", + "T-SQL formatter", + ], + }, + explanations: { + notice: { + type: "info", + title: "SQL Origins", + items: [ + { + label: "Created:", + text: "IBM, early 1970s, as SEQUEL by Donald Chamberlin and Raymond Boyce", + }, + { + label: "Standardized:", + text: "ANSI in 1986, ISO in 1987, revised many times since (SQL:2023 is the latest)", + }, + { + label: "Dialects:", + text: "Every database extends the standard, so pick your dialect for the best results", + }, + ], + }, + sections: [ + { + title: "Formatting Settings", + items: [ + { + label: "Dialect:", + text: "Teaches the formatter dialect-specific syntax such as ::casts (PostgreSQL), [brackets] (SQL Server) or backticks (MySQL)", + }, + { + label: "Keyword case:", + text: "UPPER keywords (SELECT, FROM) are the most common convention; preserve keeps your input as-is", + }, + { + label: "Indent style:", + text: "Standard indents clauses; tabular styles align keywords in a column", + }, + { + label: "Expression width:", + text: "Parenthesized expressions shorter than this stay on one line", + }, + { + label: "Logical operators:", + text: "Put AND / OR at the start or the end of each line", + }, + ], + }, + { + title: "Pro Tips", + items: [ + "Format generated ORM queries from logs to understand what actually hits the database", + "Leading AND/OR makes it easy to comment out a single condition", + "Format before committing migrations to keep git diffs readable", + "If formatting fails, try a different dialect: vendor syntax may not parse as standard SQL", + ], + }, + ], + }, + }, { name: "Time Formatter", path: "/tools/time-formatter", diff --git a/client/src/lib/formatters.ts b/client/src/lib/formatters.ts index 43824983..c2eb0ca9 100644 --- a/client/src/lib/formatters.ts +++ b/client/src/lib/formatters.ts @@ -1033,3 +1033,76 @@ export async function formatGraphQL(input: string): Promise<{ }; } } + +type SqlDialect = + | "sql" + | "bigquery" + | "clickhouse" + | "db2" + | "db2i" + | "duckdb" + | "hive" + | "mariadb" + | "mysql" + | "n1ql" + | "plsql" + | "postgresql" + | "redshift" + | "singlestoredb" + | "snowflake" + | "spark" + | "sqlite" + | "tidb" + | "transactsql" + | "trino"; + +type SqlCase = "preserve" | "upper" | "lower"; + +export interface SqlFormatOptions { + language: SqlDialect; + tabWidth: number; + useTabs: boolean; + keywordCase: SqlCase; + dataTypeCase: SqlCase; + functionCase: SqlCase; + indentStyle: "standard" | "tabularLeft" | "tabularRight"; + logicalOperatorNewline: "before" | "after"; + expressionWidth: number; + linesBetweenQueries: number; + denseOperators: boolean; + newlineBeforeSemicolon: boolean; +} + +export const DEFAULT_SQL_OPTIONS: SqlFormatOptions = { + language: "sql", + tabWidth: 2, + useTabs: false, + keywordCase: "upper", + dataTypeCase: "upper", + functionCase: "upper", + indentStyle: "standard", + logicalOperatorNewline: "before", + expressionWidth: 50, + linesBetweenQueries: 1, + denseOperators: false, + newlineBeforeSemicolon: false, +}; + +export async function formatSQL( + input: string, + options: Partial = {} +): Promise<{ + formatted: string; + error?: string; +}> { + try { + const { format } = await import("sql-formatter"); + const formatted = format(input, { ...DEFAULT_SQL_OPTIONS, ...options }); + return { formatted }; + } catch (error) { + return { + formatted: input, + error: `SQL formatting error: ${error instanceof Error ? error.message : "Unknown error"}`, + }; + } +} diff --git a/client/src/pages/tools/sql-formatter.tsx b/client/src/pages/tools/sql-formatter.tsx new file mode 100644 index 00000000..c27e43af --- /dev/null +++ b/client/src/pages/tools/sql-formatter.tsx @@ -0,0 +1,501 @@ +import { useShareTool } from "@/hooks/use-share-tool"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { TextArea } from "@/components/ui/textarea"; +import { useTheme } from "@/providers/theme-provider"; +import { + formatSQL, + DEFAULT_SQL_OPTIONS, + type SqlFormatOptions, +} from "@/lib/formatters"; +import { Alert, AlertDescription } from "@/components/ui/alert"; +import { Code } from "lucide-react"; +import { useState, useEffect, useCallback } from "react"; +import { Switch } from "@/components/ui/switch"; +import { Label } from "@/components/ui/label"; +import { Input } from "@/components/ui/input"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip"; +import { + ToolButton, + ResetButton, + ClearButton, + ToolButtonGroup, + ActionButtonGroup, + DataButtonGroup, +} from "@/components/ui/tool-button"; + +import { SecurityBanner } from "@/components/ui/security-banner"; +import { DEFAULT_SQL } from "@/data/defaults"; +import { getToolByPath } from "@/data/tools"; +import { ToolExplanations } from "@/components/tool-explanations"; +import { ShortcutBadge } from "@/components/ui/shortcut-badge"; + +const DIALECTS: Array<{ value: SqlFormatOptions["language"]; label: string }> = + [ + { value: "sql", label: "Standard SQL" }, + { value: "postgresql", label: "PostgreSQL" }, + { value: "mysql", label: "MySQL" }, + { value: "mariadb", label: "MariaDB" }, + { value: "sqlite", label: "SQLite" }, + { value: "transactsql", label: "SQL Server (T-SQL)" }, + { value: "plsql", label: "Oracle PL/SQL" }, + { value: "bigquery", label: "BigQuery" }, + { value: "snowflake", label: "Snowflake" }, + { value: "redshift", label: "Redshift" }, + { value: "duckdb", label: "DuckDB" }, + { value: "clickhouse", label: "ClickHouse" }, + { value: "spark", label: "Spark SQL" }, + { value: "hive", label: "Hive" }, + { value: "trino", label: "Trino / Presto" }, + { value: "db2", label: "DB2" }, + { value: "db2i", label: "DB2 for IBM i" }, + { value: "singlestoredb", label: "SingleStore" }, + { value: "tidb", label: "TiDB" }, + { value: "n1ql", label: "Couchbase N1QL" }, + ]; + +const CASE_OPTIONS = [ + { value: "upper", label: "UPPER" }, + { value: "lower", label: "lower" }, + { value: "preserve", label: "Preserve" }, +]; + +const INDENT_STYLES = [ + { value: "standard", label: "Standard" }, + { value: "tabularLeft", label: "Tabular left" }, + { value: "tabularRight", label: "Tabular right" }, +]; + +const INDENT_OPTIONS = [ + { value: "2", label: "2 spaces" }, + { value: "4", label: "4 spaces" }, + { value: "8", label: "8 spaces" }, + { value: "tab", label: "Tabs" }, +]; + +const OPERATOR_NEWLINE = [ + { value: "before", label: "Before (AND x)" }, + { value: "after", label: "After (x AND)" }, +]; + +function SettingSelect({ + id, + label, + value, + options, + onChange, + width = "w-40", +}: { + id: string; + label: string; + value: string; + options: Array<{ value: string; label: string }>; + onChange: (value: string) => void; + width?: string; +}) { + return ( +
+ + +
+ ); +} + +function SettingNumber({ + id, + label, + value, + min, + max, + onChange, +}: { + id: string; + label: string; + value: number; + min: number; + max: number; + onChange: (value: number) => void; +}) { + return ( +
+ + { + const parsed = parseInt(e.target.value, 10); + if (!Number.isNaN(parsed)) { + onChange(Math.min(max, Math.max(min, parsed))); + } + }} + className="w-24" + data-testid={id} + /> +
+ ); +} + +function SettingSwitch({ + id, + label, + checked, + onChange, +}: { + id: string; + label: string; + checked: boolean; + onChange: (checked: boolean) => void; +}) { + return ( +
+ + +
+ ); +} + +export default function SqlFormatter() { + const { handleShare } = useShareTool(); + const tool = getToolByPath("/tools/sql-formatter"); + const [input, setInput] = useState(DEFAULT_SQL); + const [output, setOutput] = useState(""); + const [error, setError] = useState(null); + const [autoFormat, setAutoFormat] = useState(true); + const [options, setOptions] = useState(DEFAULT_SQL_OPTIONS); + const { theme } = useTheme(); + + const setOption = ( + key: K, + value: SqlFormatOptions[K] + ) => { + setOptions(prev => ({ ...prev, [key]: value })); + }; + + const formatCode = useCallback(async () => { + const { formatted, error: formatError } = await formatSQL(input, options); + setOutput(formatted); + setError(formatError || null); + }, [input, options]); + + const handleInputChange = (value: string) => { + setInput(value); + if (output) { + setOutput(""); + } + }; + + const handleReset = () => { + setInput(DEFAULT_SQL); + setOptions(DEFAULT_SQL_OPTIONS); + setOutput(""); + setError(null); + }; + + const handleClear = () => { + setInput(""); + setOutput(""); + setError(null); + }; + + const optionsModified = + JSON.stringify(options) !== JSON.stringify(DEFAULT_SQL_OPTIONS); + const hasModifiedData = + (input !== DEFAULT_SQL && input.trim() !== "") || optionsModified; + const isAtDefault = input === DEFAULT_SQL && !optionsModified; + + useEffect(() => { + document.title = "SQL Formatter - FreeDevTool.App"; + if (autoFormat) { + formatCode(); + } + }, [autoFormat, formatCode]); + + const indentValue = options.useTabs ? "tab" : String(options.tabWidth); + + return ( +
+
+
+
+

+ SQL Formatter + {tool?.shortcut ? ( + + ) : null} +

+

+ Format and beautify SQL queries for PostgreSQL, MySQL, SQL Server, + Oracle, SQLite, BigQuery and more +

+
+ +
+
+ + {error ? ( + + + {error} + + + ) : null} + + + + } + tooltip="Format and beautify SQL" + className="bg-green-600 hover:bg-green-700 text-white" + > + Format SQL + + + + + +
+ + +
+
+ +

Automatically format the input when it changes

+
+
+
+
+ + + + +
+ + + +
+ + setOption("language", v as SqlFormatOptions["language"]) + } + /> + { + if (v === "tab") { + setOption("useTabs", true); + } else { + setOptions(prev => ({ + ...prev, + useTabs: false, + tabWidth: parseInt(v, 10), + })); + } + }} + /> + + setOption("keywordCase", v as SqlFormatOptions["keywordCase"]) + } + /> + + setOption("functionCase", v as SqlFormatOptions["functionCase"]) + } + /> + + setOption("dataTypeCase", v as SqlFormatOptions["dataTypeCase"]) + } + /> + + setOption("indentStyle", v as SqlFormatOptions["indentStyle"]) + } + /> + + setOption( + "logicalOperatorNewline", + v as SqlFormatOptions["logicalOperatorNewline"] + ) + } + /> + setOption("expressionWidth", v)} + /> + setOption("linesBetweenQueries", v)} + /> + setOption("denseOperators", v)} + /> + setOption("newlineBeforeSemicolon", v)} + /> +
+
+
+ +
+ + + Input SQL + + +