# SQL Formatter Studio — Format, Lint, Analyze (`perryay/sql-formatter-studio`) Actor

Enterprise-grade SQL formatter, linter, and analyzer across 10 dialects. Auto-dialect detection, anti-pattern lint rules, heuristic query analysis, batch processing. Per-statement error isolation — errors never charged. Ideal for SQL code reviews and CI pipeline gating.

- **URL**: https://apify.com/perryay/sql-formatter-studio.md
- **Developed by:** [Perry AY](https://apify.com/perryay) (community)
- **Categories:** Developer tools
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.012 / actor start

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## SQL Formatter Studio 🗄️ — Format, Lint, Analyze SQL

**All-in-one SQL toolkit: beautify, lint anti-patterns, and heuristic-analyze queries across 10 dialects — format, batch, lint, and analyze modes in one fully offline actor.**

SQL Formatter Studio takes raw, messy SQL — from application logs, ORMs, legacy codebases, or copy-pasted queries — and returns clean, consistently styled statements, static anti-pattern findings, and structural query analysis. It supports ten dialects with automatic detection, so you never have to tell it whether a statement is MySQL, PostgreSQL, Snowflake, or anything else. The actor is pure Python (sqlparse + sqlglot), makes zero network calls, and isolates errors per statement so one bad query never sinks the batch.

***

### ✨ Features

- **4 modes in one actor** — `format` (beautify), `batch` (many statements at once), `lint` (9 static anti-pattern rules + parse-error capture), and `analyze` (heuristic query analysis).
- **10 dialects with auto-detection** — MySQL, PostgreSQL, T-SQL, Snowflake, BigQuery, SQLite, Oracle, Hive, DuckDB, plus a default fallback. Auto-detect tries parsers in order; the first clean parse wins.
- **Configurable formatting** — UPPER/lower/preserved keyword casing, 2- or 4-space indentation, optional comment stripping.
- **Lint rules that catch real mistakes** — `SELECT *`, WHERE-less DELETE/UPDATE, implicit comma joins, OR in JOIN ON, non-SARGable predicates, NOT IN subquery NULL traps, DISTINCT \*, and (strict mode) missing LIMIT and ORDER BY ordinals.
- **Honest heuristic analysis** — table-scan estimates, subquery nesting depth, join/union/CTE counts, and DISTINCT cost notes. Clearly labeled: this is static inspection, **not an execution plan**.
- **Batch isolation** — a syntax error in statement 4 of 500 does not abort the run; it produces one error row and the rest process normally.
- **Fully offline** — no HTTP calls, no upstream APIs, no rate limits. Runs start in milliseconds.

### 🚀 Quick Start

**Input** — format a messy query:

```json
{
  "mode": "format",
  "sql": "select id,name from users where active=1",
  "dialect": "auto",
  "keyword_case": "upper",
  "indent_width": 2,
  "strip_comments": false
}
```

**Output** — one result row per statement, then a summary row:

```json
{
  "type": "result",
  "statement_id": 1,
  "mode": "format",
  "dialect_detected": "mysql",
  "formatted_sql": "SELECT id,\n       name\nFROM users\nWHERE active=1",
  "lint_findings": [],
  "analysis": {},
  "error": null
}
```

```json
{
  "type": "summary",
  "statements": 1,
  "errors": 0,
  "lint_errors": 0,
  "lint_warnings": 0
}
```

**Lint example** — `{"mode": "lint", "sql": "select * from users, orders where users.id = orders.uid"}` returns findings for `SELECT_STAR` and `IMPLICIT_JOIN`, each with `rule`, `severity`, `message`, and an approximate `line_hint`.

**Analyze example** — `{"mode": "analyze", "sql": "select * from a join b on a.id=b.id"}` returns `join_count: 1`, `estimated_table_scans: 2` (no WHERE), `subquery_depth: 0`, and more.

### Input Parameters

| Field | Type | Required | Default | Description |
|---|---|---|---|---|
| `mode` | select | no | `format` | `format`, `batch`, `lint`, or `analyze`. |
| `sql` | string | no | — | Single SQL statement (format/lint/analyze). In batch mode a multi-statement string is split automatically. |
| `statements` | array of strings | no | — | Batch mode: statements processed independently with per-statement error isolation. |
| `dialect` | select | no | `auto` | `auto`, `mysql`, `postgres`, `tsql`, `snowflake`, `bigquery`, `sqlite`, `oracle`, `hive`, `duckdb`, or `default`. |
| `keyword_case` | select | no | `upper` | `upper`, `lower`, or `preserve` — casing applied to SQL keywords. |
| `indent_width` | select | no | `2` | Indentation width: `2` or `4` spaces. |
| `strip_comments` | boolean | no | `false` | Remove `--` and `/* */` comments from formatted output. |
| `lint_level` | select | no | `basic` | `basic` runs 7 rules; `strict` adds `MISSING_LIMIT` and `ORDER_BY_ORDINAL`. |

All fields are optional; missing input is handled gracefully (an empty run produces one explanatory error row and a zeroed summary).

### Output Format

Every dataset item is one row. Two shapes are emitted:

**Result row (one per statement):**

| Field | Type | Description |
|---|---|---|
| `type` | string | Always `"result"`. |
| `statement_id` | integer | 1-based position of the statement in the input. |
| `mode` | string | Mode that produced the row: `format`, `batch`, `lint`, or `analyze`. |
| `dialect_detected` | string | Detected or explicitly requested dialect (e.g. `mysql`, `postgres`, `default`). |
| `formatted_sql` | string | null | Beautified statement (format/batch modes); `null` otherwise. |
| `lint_findings` | array | Lint findings, each `{rule, severity, message, line_hint}`; empty in other modes. |
| `analysis` | object | Heuristic analysis metrics (analyze mode); empty otherwise. |
| `error` | string | null | `null` on success; otherwise the failure description (e.g. `Parse error at position 27: ...`). |

**Summary row (always last):**

| Field | Type | Description |
|---|---|---|
| `type` | string | Always `"summary"`. |
| `statements` | integer | Total statements processed (including errored ones). |
| `errors` | integer | Statements that failed to parse or process. |
| `lint_errors` | integer | Lint findings with severity `error` across all statements. |
| `lint_warnings` | integer | Lint findings with severity `warning` across all statements. |

**Lint finding fields:** `rule` (e.g. `SELECT_STAR`), `severity` (`error`, `warning`, or `info`), `message` (what and why), `line_hint` (approximate source line).

**Analysis fields:** `estimated_table_scans`, `subquery_depth`, `distinct_cost_note`, `join_count`, `union_count`, `limit_present`, `cte_count`, `dialect_detected`, plus a `note` stating the methodology.

### API Usage

> Replace `example.com` with your Apify API host.

#### cURL

```bash
## Format a single statement
curl -X POST "https://example.com/v2/acts/sql-formatter-studio/runs" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ***" \
  -d '{"mode":"format","sql":"select id,name from users where active=1"}'

## Lint with strict rules
curl -X POST "https://example.com/v2/acts/sql-formatter-studio/runs" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ***" \
  -d '{"mode":"lint","lint_level":"strict","sql":"select * from logs order by 1"}'

## Batch format several statements
curl -X POST "https://example.com/v2/acts/sql-formatter-studio/runs" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ***" \
  -d '{"mode":"batch","statements":["select 1","select   a,b  from t"]}'
```

#### Python

```python
import requests

API_TOKEN = "<APIFY_TOKEN>"
ACTOR_URL = "https://example.com/v2/acts/sql-formatter-studio/runs"

headers = {"Content-Type": "application/json", "Authorization": f"Bearer {API_TOKEN}"}

## Format
response = requests.post(ACTOR_URL, headers=headers, json={
    "mode": "format",
    "sql": "select id,name from users where active=1",
})
print(response.json()["formatted_sql"])

## Analyze
response = requests.post(ACTOR_URL, headers=headers, json={
    "mode": "analyze",
    "sql": "select * from orders join users on orders.uid = users.id",
})
print(response.json()["analysis"])
```

### Use Cases

1. **CI SQL review gates** — run `lint` mode in your pipeline on every migration or query PR; fail the build on `error`-severity findings like WHERE-less DELETE/UPDATE before they reach production.
2. **Legacy query cleanup** — feed hundreds of hand-written queries from old codebases through `batch` mode to normalize style (keyword casing, indentation) before refactoring or extraction.
3. **Onboarding SQL style guides** — new team members paste their queries and get instantly formatted, rule-checked output that matches the team's style guide without installing anything locally.
4. **Query troubleshooting** — when a query behaves strangely, `lint` surfaces traps like `NOT IN (SELECT ...)` NULL semantics and non-SARGable predicates that explain weird results or slow plans.
5. **Documentation generation** — `format` mode produces clean, readable SQL blocks ready to paste into wikis, runbooks, and data dictionaries.

### MCP Integration

SQL Formatter Studio is available as a remote MCP server. Connect with OAuth using a URL-only configuration — no client ID or secret needed in the client config:

```json
{
  "mcpServers": {
    "apify": {
      "url": "https://mcp.apify.com"
    }
  }
}
```

Alternatively, authenticate with a Bearer token:

```json
{
  "mcpServers": {
    "apify": {
      "url": "https://mcp.apify.com",
      "headers": {
        "Authorization": "Bearer YOUR_APIFY_TOKEN"
      }
    }
  }
}
```

Example prompts:

1. "Format this SQL statement with uppercase keywords and 4-space indent: `select id from users where active=1`"
2. "Lint my SQL batch and tell me if there are any WHERE-less DELETE or UPDATE statements"

On first connection, your browser opens to sign in to Apify and authorize access.

Learn more: https://mcp.apify.com and https://docs.apify.com/integrations/mcp

### FAQ

**Q: Which SQL dialects are supported?**
A: Ten: MySQL, PostgreSQL, T-SQL, Snowflake, BigQuery, SQLite, Oracle, Hive, and DuckDB for auto-detection, plus a `default` parser fallback. Set `dialect` explicitly to skip detection, or leave it on `auto` (the default).

**Q: How does auto-detection work?**
A: The statement is parsed with each candidate dialect in a fixed order (mysql, postgres, tsql, snowflake, bigquery, sqlite, oracle, hive, duckdb); the first parser that accepts it wins. If all reject it, the default parser is tried as a final fallback.

**Q: Does formatting change my query's meaning?**
A: No. Formatting only rewrites whitespace, line breaks, and keyword casing. It never renames identifiers, reorders logic, or drops clauses. As with any formatter, review output before deploying to production.

**Q: What are the nine lint rules?**
A: `SELECT_STAR`, `DELETE_UPDATE_NO_WHERE`, `IMPLICIT_JOIN`, `OR_IN_JOIN`, `MISSING_LIMIT` (strict), `NON_SARGABLE`, `NOT_IN_NULL_TRAP`, `SELECT_DISTINCT_STAR`, and `ORDER_BY_ORDINAL` (strict). Parse failures are reported as per-statement error rows, giving ten distinct diagnostics in total.

**Q: What is the difference between basic and strict lint levels?**
A: Strict mode adds two rules on top of the basic seven: `MISSING_LIMIT` (SELECT without LIMIT) and `ORDER_BY_ORDINAL` (ORDER BY column position). Basic mode stays quiet on those so it suits CI gates; strict suits interactive review.

**Q: Why did I get a "Parse error" row instead of formatted SQL?**
A: The statement could not be parsed by any of the ten dialect parsers — usually a typo, truncated query, or non-SQL text. The error row names the position. Errored statements are never charged, and the rest of the batch continues.

**Q: Is analyze mode an execution plan?**
A: No — and it does not pretend to be. It is heuristic static analysis of the query's structure (table count, nesting depth, join count, and similar). It performs no optimization, uses no statistics, and makes no cardinality estimates. Always rely on your engine's EXPLAIN/EXPLAIN ANALYZE for real plans.

**Q: Can I format many statements in one run?**
A: Yes. Use `batch` mode with a `statements` array, or pass a single string containing multiple semicolon-separated statements — it is split automatically. Each statement gets its own result row and its own error isolation.

**Q: How is billing counted?**
A: Per successfully processed statement: `sql-format` (format mode), `batch-format` (batch mode), `lint-analysis` (lint mode), or `query-plan` (analyze mode), plus one `apify-actor-start` event per run. Statements that error are never charged.

**Q: Does the actor make any network calls?**
A: None. It is pure Python (sqlparse + sqlglot) with zero outbound HTTP, which is why runs start in milliseconds and there are no upstream dependencies to fail.

**Q: Can I keep the original keyword casing?**
A: Yes — set `keyword_case` to `preserve`. Use `upper` or `lower` to normalize casing across a codebase.

**Q: How do I remove comments from the output?**
A: Set `strip_comments` to `true`; both `--` line comments and `/* */` block comments are removed during formatting.

**Q: What happens with empty or missing input?**
A: The actor degrades gracefully: an empty run emits one explanatory error row and a zeroed summary instead of crashing, and no charge events are emitted for it.

**Q: What are the resource limits?**
A: Default run options are 256 MB memory and a 300-second timeout. For very large batches, split the statements array across multiple runs.

# Changelog

This Actor's version history is a separate document: https://apify.com/perryay/sql-formatter-studio/changelog.md

# Actor input Schema

## `mode` (type: `string`):

Operation mode: format (beautify one statement or array), batch (format many statements), lint (anti-pattern rules), analyze (heuristic query analysis).

## `sql` (type: `string`):

Single SQL statement to process (format, lint, analyze modes). In batch mode a multi-statement string is split automatically.

## `statements` (type: `array`):

Array of SQL statements for batch mode. Each statement is formatted independently; per-statement errors are isolated.

## `dialect` (type: `string`):

Target dialect. 'auto' detects the dialect by trying parsers in order (mysql, postgres, tsql, snowflake, bigquery, sqlite, oracle, hive, duckdb) and falls back to 'default'.

## `keyword_case` (type: `string`):

Casing applied to SQL keywords (SELECT, FROM, WHERE, ...) in format/batch modes.

## `indent_width` (type: `integer`):

Spaces used per indentation level in formatted output.

## `strip_comments` (type: `boolean`):

Remove SQL comments (-- and /\* \*/) from formatted output.

## `lint_level` (type: `string`):

Lint strictness. 'strict' adds MISSING_LIMIT and ORDER_BY_ORDINAL rules on top of the basic set.

## Actor input object example

```json
{
  "mode": "format",
  "sql": "select id,name from users where active=1",
  "statements": [
    "select id,name from users where active=1",
    "select * from orders o, customers c where o.cid=c.id"
  ],
  "dialect": "auto",
  "keyword_case": "upper",
  "indent_width": 2,
  "strip_comments": false,
  "lint_level": "basic"
}
```

# Actor output Schema

## `results` (type: `string`):

Per-statement result rows and the run summary row in the default dataset

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "sql": "select id,name from users where active=1",
    "statements": [
        "select id,name from users where active=1",
        "select * from orders o, customers c where o.cid=c.id"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("perryay/sql-formatter-studio").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "sql": "select id,name from users where active=1",
    "statements": [
        "select id,name from users where active=1",
        "select * from orders o, customers c where o.cid=c.id",
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("perryay/sql-formatter-studio").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "sql": "select id,name from users where active=1",
  "statements": [
    "select id,name from users where active=1",
    "select * from orders o, customers c where o.cid=c.id"
  ]
}' |
apify call perryay/sql-formatter-studio --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,perryay/sql-formatter-studio"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/qBtGVJpl0N7e7SrdB/builds/bnaoCsLSe4yq9Beye/openapi.json
