JavaScript Python PHP
import { format } from "sql-formatter";
function executar(values) {
function formatDatabaseSql(values) {
const input = dbText(values.input);
if (!input.trim())
return '';
if (!['postgresql', 'mysql', 'sqlite'].includes(values.dialect))
throw new Error('Dialeto não suportado.');
if (!['Formatar', 'Compactar'].includes(values.mode) || !['2', '4'].includes(values.indent))
throw new Error('Modo ou indentação inválidos.');
const formatted = format(input, { language: values.dialect, tabWidth: Number(values.indent), keywordCase: 'preserve' });
if (values.mode === 'Formatar')
return dbOutput(formatted);
// Only collapse whitespace outside literal/comment tokens. Never split SQL on commas.
let output = '', i = 0, space = false;
while (i < formatted.length) {
const char = formatted[i];
if (/\s/.test(char)) {
space = true;
i++;
continue;
}
if (space && output && !output.endsWith('\n'))
output += ' ';
space = false;
const start = i;
if (formatted.startsWith('--', i) || values.dialect === 'mysql' && char === '#') {
while (i < formatted.length && formatted[i] !== '\n')
i++;
output += formatted.slice(start, i) + '\n';
continue;
}
if (formatted.startsWith('/*', i)) {
let depth = 1;
i += 2;
while (i < formatted.length && depth) {
if (formatted.startsWith('/*', i) && values.dialect === 'postgresql') {
depth++;
i += 2;
}
else if (formatted.startsWith('*/', i)) {
depth--;
i += 2;
}
else
i++;
}
if (depth)
throw new Error('Comentário SQL não terminado.');
output += formatted.slice(start, i);
continue;
}
const dollar = values.dialect === 'postgresql' ? formatted.slice(i).match(/^\$(?:[A-Za-z_][A-Za-z_0-9]*)?\$/)?.[0] : undefined;
if (dollar) {
const end = formatted.indexOf(dollar, i + dollar.length);
if (end < 0)
throw new Error('String dollar-quoted não terminada.');
i = end + dollar.length;
output += formatted.slice(start, i);
continue;
}
if (['\'', '"', '`', '['].includes(char) && (char !== '`' || values.dialect === 'mysql') && (char !== '[' || values.dialect === 'sqlite')) {
const closing = char === '[' ? ']' : char;
const slash = values.dialect === 'mysql' || char === "'" && /(?:^|[^A-Za-z0-9_])[eE]$/.test(formatted.slice(0, i));
i++;
let closed = false;
while (i < formatted.length) {
if (slash && formatted[i] === '\\') {
i += 2;
continue;
}
if (formatted[i] === closing) {
if (formatted[i + 1] === closing) {
i += 2;
continue;
}
i++;
closed = true;
break;
}
i++;
}
if (!closed)
throw new Error('String ou identificador não terminado.');
output += formatted.slice(start, i);
continue;
}
output += char;
i++;
}
return dbOutput(output.trim());
}
function dbText(input, label = 'Entrada') {
if (typeof input !== 'string' || input.length > 100_000)
throw new Error(label + ': limite de 100 mil caracteres.');
if (/[\0]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(input))
throw new Error(label + ': NUL e Unicode inválido não são aceitos.');
return input;
}
function dbOutput(output) { if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.'); return output; }
for (const value of Object.values(values)) dbText(value);
return formatDatabaseSql(values);
}
import json
import subprocess
def executar(values):
# Requer Node.js 22+ e os pacotes npm indicados no código abaixo.
source = r'''
import { format } from "sql-formatter";
function executar(values) {
function formatDatabaseSql(values) {
const input = dbText(values.input);
if (!input.trim())
return '';
if (!['postgresql', 'mysql', 'sqlite'].includes(values.dialect))
throw new Error('Dialeto não suportado.');
if (!['Formatar', 'Compactar'].includes(values.mode) || !['2', '4'].includes(values.indent))
throw new Error('Modo ou indentação inválidos.');
const formatted = format(input, { language: values.dialect, tabWidth: Number(values.indent), keywordCase: 'preserve' });
if (values.mode === 'Formatar')
return dbOutput(formatted);
// Only collapse whitespace outside literal/comment tokens. Never split SQL on commas.
let output = '', i = 0, space = false;
while (i < formatted.length) {
const char = formatted[i];
if (/\s/.test(char)) {
space = true;
i++;
continue;
}
if (space && output && !output.endsWith('\n'))
output += ' ';
space = false;
const start = i;
if (formatted.startsWith('--', i) || values.dialect === 'mysql' && char === '#') {
while (i < formatted.length && formatted[i] !== '\n')
i++;
output += formatted.slice(start, i) + '\n';
continue;
}
if (formatted.startsWith('/*', i)) {
let depth = 1;
i += 2;
while (i < formatted.length && depth) {
if (formatted.startsWith('/*', i) && values.dialect === 'postgresql') {
depth++;
i += 2;
}
else if (formatted.startsWith('*/', i)) {
depth--;
i += 2;
}
else
i++;
}
if (depth)
throw new Error('Comentário SQL não terminado.');
output += formatted.slice(start, i);
continue;
}
const dollar = values.dialect === 'postgresql' ? formatted.slice(i).match(/^\$(?:[A-Za-z_][A-Za-z_0-9]*)?\$/)?.[0] : undefined;
if (dollar) {
const end = formatted.indexOf(dollar, i + dollar.length);
if (end < 0)
throw new Error('String dollar-quoted não terminada.');
i = end + dollar.length;
output += formatted.slice(start, i);
continue;
}
if (['\'', '"', '`', '['].includes(char) && (char !== '`' || values.dialect === 'mysql') && (char !== '[' || values.dialect === 'sqlite')) {
const closing = char === '[' ? ']' : char;
const slash = values.dialect === 'mysql' || char === "'" && /(?:^|[^A-Za-z0-9_])[eE]$/.test(formatted.slice(0, i));
i++;
let closed = false;
while (i < formatted.length) {
if (slash && formatted[i] === '\\') {
i += 2;
continue;
}
if (formatted[i] === closing) {
if (formatted[i + 1] === closing) {
i += 2;
continue;
}
i++;
closed = true;
break;
}
i++;
}
if (!closed)
throw new Error('String ou identificador não terminado.');
output += formatted.slice(start, i);
continue;
}
output += char;
i++;
}
return dbOutput(output.trim());
}
function dbText(input, label = 'Entrada') {
if (typeof input !== 'string' || input.length > 100_000)
throw new Error(label + ': limite de 100 mil caracteres.');
if (/[\0]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(input))
throw new Error(label + ': NUL e Unicode inválido não são aceitos.');
return input;
}
function dbOutput(output) { if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.'); return output; }
for (const value of Object.values(values)) dbText(value);
return formatDatabaseSql(values);
}
let input = "";
for await (const chunk of process.stdin) input += chunk;
try { process.stdout.write(JSON.stringify({ok: true, result: executar(JSON.parse(input))})); }
catch (error) { process.stdout.write(JSON.stringify({ok: false, error: error.message})); }
'''
payload = json.dumps(values, ensure_ascii=True)
process = subprocess.run(["node", "--input-type=module", "-e", source], input=payload, capture_output=True, text=True, timeout=10, check=True)
response = json.loads(process.stdout)
if not response["ok"]:
raise ValueError(response["error"])
return response["result"]
<?php
function executar(array $values): string {
// Requer Node.js 22+ e os pacotes npm indicados no código abaixo.
$source = <<<'JAVASCRIPT'
import { format } from "sql-formatter";
function executar(values) {
function formatDatabaseSql(values) {
const input = dbText(values.input);
if (!input.trim())
return '';
if (!['postgresql', 'mysql', 'sqlite'].includes(values.dialect))
throw new Error('Dialeto não suportado.');
if (!['Formatar', 'Compactar'].includes(values.mode) || !['2', '4'].includes(values.indent))
throw new Error('Modo ou indentação inválidos.');
const formatted = format(input, { language: values.dialect, tabWidth: Number(values.indent), keywordCase: 'preserve' });
if (values.mode === 'Formatar')
return dbOutput(formatted);
// Only collapse whitespace outside literal/comment tokens. Never split SQL on commas.
let output = '', i = 0, space = false;
while (i < formatted.length) {
const char = formatted[i];
if (/\s/.test(char)) {
space = true;
i++;
continue;
}
if (space && output && !output.endsWith('\n'))
output += ' ';
space = false;
const start = i;
if (formatted.startsWith('--', i) || values.dialect === 'mysql' && char === '#') {
while (i < formatted.length && formatted[i] !== '\n')
i++;
output += formatted.slice(start, i) + '\n';
continue;
}
if (formatted.startsWith('/*', i)) {
let depth = 1;
i += 2;
while (i < formatted.length && depth) {
if (formatted.startsWith('/*', i) && values.dialect === 'postgresql') {
depth++;
i += 2;
}
else if (formatted.startsWith('*/', i)) {
depth--;
i += 2;
}
else
i++;
}
if (depth)
throw new Error('Comentário SQL não terminado.');
output += formatted.slice(start, i);
continue;
}
const dollar = values.dialect === 'postgresql' ? formatted.slice(i).match(/^\$(?:[A-Za-z_][A-Za-z_0-9]*)?\$/)?.[0] : undefined;
if (dollar) {
const end = formatted.indexOf(dollar, i + dollar.length);
if (end < 0)
throw new Error('String dollar-quoted não terminada.');
i = end + dollar.length;
output += formatted.slice(start, i);
continue;
}
if (['\'', '"', '`', '['].includes(char) && (char !== '`' || values.dialect === 'mysql') && (char !== '[' || values.dialect === 'sqlite')) {
const closing = char === '[' ? ']' : char;
const slash = values.dialect === 'mysql' || char === "'" && /(?:^|[^A-Za-z0-9_])[eE]$/.test(formatted.slice(0, i));
i++;
let closed = false;
while (i < formatted.length) {
if (slash && formatted[i] === '\\') {
i += 2;
continue;
}
if (formatted[i] === closing) {
if (formatted[i + 1] === closing) {
i += 2;
continue;
}
i++;
closed = true;
break;
}
i++;
}
if (!closed)
throw new Error('String ou identificador não terminado.');
output += formatted.slice(start, i);
continue;
}
output += char;
i++;
}
return dbOutput(output.trim());
}
function dbText(input, label = 'Entrada') {
if (typeof input !== 'string' || input.length > 100_000)
throw new Error(label + ': limite de 100 mil caracteres.');
if (/[\0]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(input))
throw new Error(label + ': NUL e Unicode inválido não são aceitos.');
return input;
}
function dbOutput(output) { if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.'); return output; }
for (const value of Object.values(values)) dbText(value);
return formatDatabaseSql(values);
}
let input = "";
for await (const chunk of process.stdin) input += chunk;
try { process.stdout.write(JSON.stringify({ok: true, result: executar(JSON.parse(input))})); }
catch (error) { process.stdout.write(JSON.stringify({ok: false, error: error.message})); }
JAVASCRIPT;
$payload = json_encode($values, JSON_THROW_ON_ERROR);
$process = proc_open(["node", "--input-type=module", "-e", $source], [["pipe", "r"], ["pipe", "w"], ["pipe", "w"]], $pipes);
if (!is_resource($process)) { throw new RuntimeException("Não foi possível iniciar Node.js."); }
$offset = 0;
while ($offset < strlen($payload)) {
$written = fwrite($pipes[0], substr($payload, $offset));
if ($written === false || $written === 0) { fclose($pipes[0]); fclose($pipes[1]); fclose($pipes[2]); proc_terminate($process); proc_close($process); throw new RuntimeException("Falha ao enviar a entrada."); }
$offset += $written;
}
fclose($pipes[0]);
stream_set_timeout($pipes[1], 10);
$output = stream_get_contents($pipes[1]);
$timedOut = stream_get_meta_data($pipes[1])["timed_out"];
fclose($pipes[1]);
if ($timedOut) { proc_terminate($process); }
stream_get_contents($pipes[2]); fclose($pipes[2]);
$status = proc_close($process);
if ($timedOut || $status !== 0) { throw new RuntimeException("Falha técnica ou limite de tempo no Node.js. Confira os pacotes npm necessários."); }
$response = json_decode($output, true, 512, JSON_THROW_ON_ERROR);
if (!$response["ok"]) { throw new InvalidArgumentException($response["error"]); }
return $response["result"];
}