JavaScript Python PHP
import { parse } from "pgsql-ast-parser";
import { locationOf, toSql } from "pgsql-ast-parser";
function executar(values) {
function databaseDiagram(values) {
const schema = readDbSchema(values.input), width = 1000, boxWidth = 430;
const positions = new Map();
let y = 30;
for (let i = 0; i < schema.length; i += 2) {
let height = 0;
for (let j = i; j < Math.min(i + 2, schema.length); j++) {
const table = schema[j], h = 72 + table.columns.length * 24;
positions.set(dbKey(table), { x: 30 + (j % 2) * 500, y, h });
height = Math.max(height, h);
}
y += height + 70;
}
const svg = ['<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + y + '" viewBox="0 0 ' + width + ' ' + y + '" role="img" aria-label="Diagrama de tabelas e relacionamentos">', '<rect width="100%" height="100%" fill="#ffffff"/>', '<defs><marker id="arrow" markerWidth="8" markerHeight="8" refX="8" refY="4" orient="auto"><path d="M0,0 L8,4 L0,8 Z" fill="#6d28d9"/></marker></defs>'];
for (const table of schema) {
const from = positions.get(dbKey(table));
for (const fk of table.constraints.filter(c => c.type === 'foreign key')) {
const to = positions.get(fk.target);
const label = dbXml(fk.columns.join(', ') + ' → ' + fk.references.join(', '));
svg.push('<path d="M' + (from.x + boxWidth) + ' ' + (from.y + 35) + ' C' + (from.x + boxWidth + 35) + ' ' + (from.y + 35) + ',' + (to.x - 25) + ' ' + (to.y + 35) + ',' + to.x + ' ' + (to.y + 35) + '" fill="none" stroke="#6d28d9" stroke-width="2" marker-end="url(#arrow)"><title>' + label + '</title></path>');
}
}
for (const table of schema) {
const pos = positions.get(dbKey(table));
svg.push('<g font-family="monospace" font-size="12" fill="#172033"><rect x="' + pos.x + '" y="' + pos.y + '" width="' + boxWidth + '" height="' + pos.h + '" rx="8" fill="#f8fafc" stroke="#64748b"/><text x="' + (pos.x + 12) + '" y="' + (pos.y + 25) + '" font-weight="bold">' + dbXml(table.schema + '.' + table.name) + '</text>');
table.columns.forEach((column, i) => { const tags = table.constraints.filter(c => c.columns.includes(column.name)).map(c => c.type === 'primary key' ? 'PK' : c.type === 'foreign key' ? 'FK' : c.type === 'unique' ? 'UQ' : 'CHECK'); svg.push('<text x="' + (pos.x + 12) + '" y="' + (pos.y + 55 + i * 24) + '"><title>' + dbXml(column.name + ' ' + column.type) + '</title>' + dbXml((column.name + ' : ' + column.type + ' ' + tags.join('/') + (column.nullable ? '' : ' NOT NULL')).slice(0, 53)) + '</text>'); });
svg.push('</g>');
}
svg.push('</svg>');
return dbOutput(svg.join('\n'));
}
function dbKey(table) { return JSON.stringify([table.schema, table.name]); }
function readDbSchema(input) {
dbText(input, 'DDL PostgreSQL');
if (!input.trim())
throw new Error('Informe pelo menos um CREATE TABLE.');
let statements;
try {
statements = parse(input, { locationTracking: true });
}
catch (cause) {
throw new Error('DDL inválido ou não suportado: ' + (cause instanceof Error ? cause.message : 'erro de parsing'));
}
if (statements.length > 300)
throw new Error('Limite de 300 instruções e 30 tabelas.');
const tables = new Map();
const addConstraints = new Map();
for (const statement of statements) {
if (statement.type === 'create index' || statement.type === 'alter table')
continue;
if (statement.type !== 'create table')
dbFail('Somente CREATE TABLE, CREATE INDEX e ALTER TABLE ADD CONSTRAINT são aceitos; recebido ' + statement.type + '.', input, statement);
dbNoExtra(statement, ['type', 'name', 'columns', 'constraints'], input);
const table = { schema: statement.name.schema?.replace(/""/g, '"') ?? 'public', name: dbName(statement.name), columns: [], constraints: [], indexes: [] };
dbQuote(table.schema);
dbQuote(table.name);
const key = dbKey(table);
if (tables.has(key) || tables.size >= 30)
dbFail('Tabela duplicada ou limite de 30 tabelas.', input, statement);
const addConstraint = (constraint, columns) => {
let type = constraint.type;
if (type === 'reference')
type = 'foreign key';
if (!['primary key', 'unique', 'foreign key', 'check'].includes(type))
dbFail('Constraint não suportada: ' + type, input, constraint);
const suffix = type === 'primary key' ? 'pkey' : type === 'unique' ? 'key' : type === 'foreign key' ? 'fkey' : 'check';
const name = constraint.constraintName ? dbName(constraint.constraintName) : [table.name, ...(type === 'primary key' ? [] : columns), suffix].join('_');
dbQuote(name);
const value = { name, type: type, columns };
if (constraint.type === 'reference' || constraint.type === 'foreign key') {
dbNoExtra(constraint, ['type', 'constraintName', 'foreignTable', 'foreignColumns', 'localColumns', 'onDelete', 'onUpdate'], input);
value.target = dbReference(constraint.foreignTable);
value.references = constraint.foreignColumns.map(dbName);
value.onDelete = constraint.onDelete ?? 'no action';
value.onUpdate = constraint.onUpdate ?? 'no action';
}
else if (constraint.type === 'check') {
dbNoExtra(constraint, ['type', 'constraintName', 'expr'], input);
value.check = dbExpression(constraint.expr, input, true);
const refs = new Set();
const visit = (node) => { if (node.type === 'ref')
refs.add(node.name); if (node.type === 'binary') {
visit(node.left);
visit(node.right);
} };
visit(constraint.expr);
value.columns = [...refs];
}
else
dbNoExtra(constraint, ['type', 'constraintName', 'columns'], input);
if (table.constraints.some(item => item.name === name))
dbFail('Nome de constraint duplicado: ' + name, input, constraint);
table.constraints.push(value);
};
for (const column of statement.columns) {
if (column.kind !== 'column')
dbFail('LIKE e herança não são suportados.', input, column);
dbNoExtra(column, ['kind', 'name', 'dataType', 'constraints'], input);
if (column.dataType.kind === 'array' || column.dataType.schema || column.dataType.doubleQuoted)
dbFail('Arrays e tipos personalizados não são suportados.', input, column);
const name = dbName(column.name);
dbQuote(name);
if (table.columns.some(item => item.name === name))
dbFail('Coluna duplicada: ' + name, input, column);
const config = column.dataType.config;
const base = dbType((column.dataType.name === 'varchar' || column.dataType.name === 'character varying' ? 'varchar' : column.dataType.name === 'decimal' ? 'numeric' : column.dataType.name) + (config?.length ? '(' + config.join(',') + ')' : ''));
const item = { name, type: base, nullable: !['serial', 'bigserial'].includes(base) };
const types = new Set();
for (const constraint of column.constraints ?? []) {
if (types.has(constraint.type))
dbFail('Constraint de coluna repetida: ' + constraint.type, input, constraint);
types.add(constraint.type);
if (constraint.type === 'not null')
item.nullable = false;
else if (constraint.type === 'null') {
if (['serial', 'bigserial'].includes(base) || types.has('not null'))
dbFail('NULL contradiz NOT NULL/serial.', input, constraint);
item.nullable = true;
}
else if (constraint.type === 'default') {
if (['serial', 'bigserial'].includes(base))
dbFail('Serial com DEFAULT explícito não é suportado.', input, constraint);
item.default = dbExpression(constraint.default, input);
}
else
addConstraint(constraint, [name]);
}
if (types.has('null') && types.has('not null'))
dbFail('NULL e NOT NULL são contraditórios.', input, column);
table.columns.push(item);
}
if (!table.columns.length || table.columns.length > 100)
dbFail('Use de 1 a 100 colunas por tabela.', input, statement);
for (const constraint of statement.constraints ?? [])
addConstraint(constraint, constraint.type === 'foreign key' ? constraint.localColumns.map(dbName) : constraint.type === 'check' ? [] : constraint.columns.map(dbName));
const primary = table.constraints.filter(item => item.type === 'primary key');
if (primary.length > 1)
dbFail('A tabela só pode ter uma chave primária.', input, statement);
for (const column of table.columns)
if (primary.some(item => item.columns.includes(column.name)))
column.nullable = false;
tables.set(key, table);
addConstraints.set(key, addConstraint);
}
if (!tables.size)
throw new Error('Informe pelo menos um CREATE TABLE.');
for (const statement of statements)
if (statement.type === 'alter table') {
dbNoExtra(statement, ['type', 'table', 'changes'], input);
const add = addConstraints.get(dbReference(statement.table));
if (!add)
dbFail('ALTER exige tabela declarada na entrada.', input, statement);
for (const change of statement.changes) {
if (change.type !== 'add constraint')
dbFail('Somente ALTER TABLE ADD CONSTRAINT é aceito no leitor de schema.', input, change);
dbNoExtra(change, ['type', 'constraint'], input);
const c = change.constraint;
add(c, c.type === 'foreign key' ? c.localColumns.map(dbName) : c.type === 'check' ? [] : c.columns.map(dbName));
}
}
const relationNames = new Set([...tables.values()].map(table => dbKey(table)));
for (const table of tables.values())
for (const constraint of table.constraints.filter(c => c.type === 'primary key' || c.type === 'unique')) {
const key = dbKey({ schema: table.schema, name: constraint.name });
if (relationNames.has(key))
throw new Error('Nome de índice implícito duplicado no schema: ' + constraint.name);
relationNames.add(key);
}
for (const statement of statements) {
if (statement.type !== 'create index')
continue;
dbNoExtra(statement, ['type', 'table', 'indexName', 'expressions', 'unique', 'using'], input);
if (statement.using && dbName(statement.using).toLowerCase() !== 'btree')
dbFail('Somente índices btree simples são suportados.', input, statement);
const table = tables.get(dbReference(statement.table));
if (!table || !statement.indexName)
dbFail('Índice exige tabela declarada e nome explícito.', input, statement);
const name = dbName(statement.indexName);
dbQuote(name);
const indexKey = dbKey({ schema: table.schema, name });
if (relationNames.has(indexKey))
dbFail('Nome de índice/tabela duplicado no schema: ' + name, input, statement);
relationNames.add(indexKey);
const columns = statement.expressions.map(item => {
dbNoExtra(item, ['expression'], input);
if (item.expression.type !== 'ref' || item.expression.table || item.expression.name === '*')
dbFail('Índices aceitam somente colunas, sem expressões, ordem ou filtros.', input, item);
return item.expression.name.replace(/""/g, '"');
});
table.indexes.push({ name, columns, unique: !!statement.unique });
}
for (const table of tables.values()) {
const primary = table.constraints.filter(c => c.type === 'primary key');
if (primary.length > 1)
throw new Error('A tabela só pode ter uma chave primária: ' + table.name);
for (const column of table.columns)
if (primary.some(c => c.columns.includes(column.name)))
column.nullable = false;
const names = new Set(table.columns.map(item => item.name));
for (const item of [...table.constraints, ...table.indexes]) {
if (new Set(item.columns).size !== item.columns.length || item.columns.some(name => !names.has(name)) || !item.columns.length && !('type' in item && item.type === 'check'))
throw new Error('Colunas inválidas em ' + table.name + '.' + item.name);
}
for (const fk of table.constraints.filter(item => item.type === 'foreign key')) {
const target = tables.get(fk.target);
if (!target || !fk.references?.length || fk.references.length !== fk.columns.length)
throw new Error('FK ' + fk.name + ': declare a tabela e as colunas de destino explicitamente.');
if (new Set(fk.references).size !== fk.references.length || fk.references.some(name => !target.columns.some(c => c.name === name)))
throw new Error('Colunas de destino inválidas na FK ' + fk.name);
const unique = [...target.constraints.filter(item => ['primary key', 'unique'].includes(item.type)), ...target.indexes.filter(item => item.unique)];
if (!unique.some(item => JSON.stringify(item.columns) === JSON.stringify(fk.references)))
throw new Error('FK ' + fk.name + ': destino precisa de PK ou UNIQUE na mesma ordem.');
fk.columns.forEach((name, i) => { if (dbBase(table.columns.find(c => c.name === name).type) !== dbBase(target.columns.find(c => c.name === fk.references[i]).type))
throw new Error('Tipos incompatíveis na FK ' + fk.name); });
if (fk.onDelete === 'set null' || fk.onUpdate === 'set null')
if (fk.columns.some(name => !table.columns.find(c => c.name === name).nullable))
throw new Error('SET NULL exige colunas anuláveis: ' + fk.name);
}
}
return [...tables.values()];
}
function dbOutput(output) { if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.'); return output; }
function dbXml(text) { return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/[\x01-\x08\x0b\x0c\x0e-\x1f]/g, '�'); }
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 dbQuote(name) {
dbText(name, 'Nome');
if (!name || new TextEncoder().encode(name).length > 63)
throw new Error('Nomes devem ter de 1 a 63 bytes UTF-8, sem truncamento.');
return '"' + name.replace(/"/g, '""') + '"';
}
function dbName(name) { return name.name.replace(/""/g, '"'); }
function dbReference(name) { return dbKey({ schema: name.schema?.replace(/""/g, '"') ?? 'public', name: dbName(name) }); }
function dbType(input) {
const raw = input.toLowerCase().replace(/\s+/g, ' ').trim();
const aliases = { int: 'integer', int4: 'integer', int2: 'smallint', int8: 'bigint', bool: 'boolean', 'character varying': 'varchar', 'timestamp without time zone': 'timestamp', 'timestamp with time zone': 'timestamptz', decimal: 'numeric' };
const type = aliases[raw] ?? raw;
if (!/^(?:smallint|integer|bigint|serial|bigserial|text|boolean|date|timestamp|timestamptz|uuid|json|jsonb)$/.test(type) && !/^varchar\([1-9]\d{0,3}\)$/.test(type) && !/^numeric\((?:[1-9]|1[0-5]),(?:[0-9]|1[0-5])\)$/.test(type))
throw new Error('Tipo não suportado: ' + input + '. Use os tipos documentados; varchar(n) até 9999 ou numeric(p,s) com p até 15.');
if (type.startsWith('numeric(')) {
const [p, s] = type.slice(8, -1).split(',').map(Number);
if (s > p)
throw new Error('A escala numeric não pode exceder a precisão.');
}
return type;
}
function dbBase(type) { return type === 'serial' ? 'integer' : type === 'bigserial' ? 'bigint' : type; }
function dbFail(message, input, node) {
const offset = locationOf(node)?.start;
const prefix = offset === undefined ? '' : input.slice(0, offset);
throw new Error(message + (offset === undefined ? '' : ` (linha ${prefix.split('\n').length}, coluna ${offset - prefix.lastIndexOf('\n')})`));
}
function dbExpression(expr, input, check = false) {
function inspect(node, depth = 0) {
if (depth > 20)
throw new Error('Expressão excede 20 níveis.');
if (node.type === 'integer' || node.type === 'numeric') {
if (!Number.isFinite(node.value) || Number.isInteger(node.value) && !Number.isSafeInteger(node.value))
throw new Error('Literal numérico fora da precisão segura; use uma string.');
const location = locationOf(node), raw = location ? input.slice(location.start, location.end) : '';
const normalize = (text) => text.replace(/^\+/, '').replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '').replace(/^(-?)0+(?=\d)/, '$1');
if (!/^[+-]?\d+(?:\.\d+)?$/.test(raw) || normalize(raw) !== normalize(String(node.value)))
throw new Error('Literal numérico não preservável pelo parser. Use número sem expoente, dentro da precisão segura, ou uma string.');
return;
}
if (['string', 'boolean', 'null'].includes(node.type))
return;
if (check && node.type === 'ref' && !node.table && node.name !== '*')
return;
if (check && node.type === 'binary' && ['=', '!=', '<>', '>', '>=', '<', '<=', 'AND', 'OR'].includes(node.op)) {
inspect(node.left, depth + 1);
inspect(node.right, depth + 1);
return;
}
throw new Error('Expressão não suportada: ' + node.type + '. DEFAULT aceita literais; CHECK aceita comparações entre colunas/literais e AND/OR.');
}
inspect(expr);
return toSql.expr(expr);
}
function dbNoExtra(node, keys, input) {
for (const key of Object.keys(node))
if (key !== '_location' && !keys.includes(key))
dbFail('Construção não suportada: ' + key + '.', input, node);
}
for (const value of Object.values(values)) dbText(value);
return databaseDiagram(values);
}
import json
import subprocess
def executar(values):
# Requer Node.js 22+ e os pacotes npm indicados no código abaixo.
source = r'''
import { parse } from "pgsql-ast-parser";
import { locationOf, toSql } from "pgsql-ast-parser";
function executar(values) {
function databaseDiagram(values) {
const schema = readDbSchema(values.input), width = 1000, boxWidth = 430;
const positions = new Map();
let y = 30;
for (let i = 0; i < schema.length; i += 2) {
let height = 0;
for (let j = i; j < Math.min(i + 2, schema.length); j++) {
const table = schema[j], h = 72 + table.columns.length * 24;
positions.set(dbKey(table), { x: 30 + (j % 2) * 500, y, h });
height = Math.max(height, h);
}
y += height + 70;
}
const svg = ['<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + y + '" viewBox="0 0 ' + width + ' ' + y + '" role="img" aria-label="Diagrama de tabelas e relacionamentos">', '<rect width="100%" height="100%" fill="#ffffff"/>', '<defs><marker id="arrow" markerWidth="8" markerHeight="8" refX="8" refY="4" orient="auto"><path d="M0,0 L8,4 L0,8 Z" fill="#6d28d9"/></marker></defs>'];
for (const table of schema) {
const from = positions.get(dbKey(table));
for (const fk of table.constraints.filter(c => c.type === 'foreign key')) {
const to = positions.get(fk.target);
const label = dbXml(fk.columns.join(', ') + ' → ' + fk.references.join(', '));
svg.push('<path d="M' + (from.x + boxWidth) + ' ' + (from.y + 35) + ' C' + (from.x + boxWidth + 35) + ' ' + (from.y + 35) + ',' + (to.x - 25) + ' ' + (to.y + 35) + ',' + to.x + ' ' + (to.y + 35) + '" fill="none" stroke="#6d28d9" stroke-width="2" marker-end="url(#arrow)"><title>' + label + '</title></path>');
}
}
for (const table of schema) {
const pos = positions.get(dbKey(table));
svg.push('<g font-family="monospace" font-size="12" fill="#172033"><rect x="' + pos.x + '" y="' + pos.y + '" width="' + boxWidth + '" height="' + pos.h + '" rx="8" fill="#f8fafc" stroke="#64748b"/><text x="' + (pos.x + 12) + '" y="' + (pos.y + 25) + '" font-weight="bold">' + dbXml(table.schema + '.' + table.name) + '</text>');
table.columns.forEach((column, i) => { const tags = table.constraints.filter(c => c.columns.includes(column.name)).map(c => c.type === 'primary key' ? 'PK' : c.type === 'foreign key' ? 'FK' : c.type === 'unique' ? 'UQ' : 'CHECK'); svg.push('<text x="' + (pos.x + 12) + '" y="' + (pos.y + 55 + i * 24) + '"><title>' + dbXml(column.name + ' ' + column.type) + '</title>' + dbXml((column.name + ' : ' + column.type + ' ' + tags.join('/') + (column.nullable ? '' : ' NOT NULL')).slice(0, 53)) + '</text>'); });
svg.push('</g>');
}
svg.push('</svg>');
return dbOutput(svg.join('\n'));
}
function dbKey(table) { return JSON.stringify([table.schema, table.name]); }
function readDbSchema(input) {
dbText(input, 'DDL PostgreSQL');
if (!input.trim())
throw new Error('Informe pelo menos um CREATE TABLE.');
let statements;
try {
statements = parse(input, { locationTracking: true });
}
catch (cause) {
throw new Error('DDL inválido ou não suportado: ' + (cause instanceof Error ? cause.message : 'erro de parsing'));
}
if (statements.length > 300)
throw new Error('Limite de 300 instruções e 30 tabelas.');
const tables = new Map();
const addConstraints = new Map();
for (const statement of statements) {
if (statement.type === 'create index' || statement.type === 'alter table')
continue;
if (statement.type !== 'create table')
dbFail('Somente CREATE TABLE, CREATE INDEX e ALTER TABLE ADD CONSTRAINT são aceitos; recebido ' + statement.type + '.', input, statement);
dbNoExtra(statement, ['type', 'name', 'columns', 'constraints'], input);
const table = { schema: statement.name.schema?.replace(/""/g, '"') ?? 'public', name: dbName(statement.name), columns: [], constraints: [], indexes: [] };
dbQuote(table.schema);
dbQuote(table.name);
const key = dbKey(table);
if (tables.has(key) || tables.size >= 30)
dbFail('Tabela duplicada ou limite de 30 tabelas.', input, statement);
const addConstraint = (constraint, columns) => {
let type = constraint.type;
if (type === 'reference')
type = 'foreign key';
if (!['primary key', 'unique', 'foreign key', 'check'].includes(type))
dbFail('Constraint não suportada: ' + type, input, constraint);
const suffix = type === 'primary key' ? 'pkey' : type === 'unique' ? 'key' : type === 'foreign key' ? 'fkey' : 'check';
const name = constraint.constraintName ? dbName(constraint.constraintName) : [table.name, ...(type === 'primary key' ? [] : columns), suffix].join('_');
dbQuote(name);
const value = { name, type: type, columns };
if (constraint.type === 'reference' || constraint.type === 'foreign key') {
dbNoExtra(constraint, ['type', 'constraintName', 'foreignTable', 'foreignColumns', 'localColumns', 'onDelete', 'onUpdate'], input);
value.target = dbReference(constraint.foreignTable);
value.references = constraint.foreignColumns.map(dbName);
value.onDelete = constraint.onDelete ?? 'no action';
value.onUpdate = constraint.onUpdate ?? 'no action';
}
else if (constraint.type === 'check') {
dbNoExtra(constraint, ['type', 'constraintName', 'expr'], input);
value.check = dbExpression(constraint.expr, input, true);
const refs = new Set();
const visit = (node) => { if (node.type === 'ref')
refs.add(node.name); if (node.type === 'binary') {
visit(node.left);
visit(node.right);
} };
visit(constraint.expr);
value.columns = [...refs];
}
else
dbNoExtra(constraint, ['type', 'constraintName', 'columns'], input);
if (table.constraints.some(item => item.name === name))
dbFail('Nome de constraint duplicado: ' + name, input, constraint);
table.constraints.push(value);
};
for (const column of statement.columns) {
if (column.kind !== 'column')
dbFail('LIKE e herança não são suportados.', input, column);
dbNoExtra(column, ['kind', 'name', 'dataType', 'constraints'], input);
if (column.dataType.kind === 'array' || column.dataType.schema || column.dataType.doubleQuoted)
dbFail('Arrays e tipos personalizados não são suportados.', input, column);
const name = dbName(column.name);
dbQuote(name);
if (table.columns.some(item => item.name === name))
dbFail('Coluna duplicada: ' + name, input, column);
const config = column.dataType.config;
const base = dbType((column.dataType.name === 'varchar' || column.dataType.name === 'character varying' ? 'varchar' : column.dataType.name === 'decimal' ? 'numeric' : column.dataType.name) + (config?.length ? '(' + config.join(',') + ')' : ''));
const item = { name, type: base, nullable: !['serial', 'bigserial'].includes(base) };
const types = new Set();
for (const constraint of column.constraints ?? []) {
if (types.has(constraint.type))
dbFail('Constraint de coluna repetida: ' + constraint.type, input, constraint);
types.add(constraint.type);
if (constraint.type === 'not null')
item.nullable = false;
else if (constraint.type === 'null') {
if (['serial', 'bigserial'].includes(base) || types.has('not null'))
dbFail('NULL contradiz NOT NULL/serial.', input, constraint);
item.nullable = true;
}
else if (constraint.type === 'default') {
if (['serial', 'bigserial'].includes(base))
dbFail('Serial com DEFAULT explícito não é suportado.', input, constraint);
item.default = dbExpression(constraint.default, input);
}
else
addConstraint(constraint, [name]);
}
if (types.has('null') && types.has('not null'))
dbFail('NULL e NOT NULL são contraditórios.', input, column);
table.columns.push(item);
}
if (!table.columns.length || table.columns.length > 100)
dbFail('Use de 1 a 100 colunas por tabela.', input, statement);
for (const constraint of statement.constraints ?? [])
addConstraint(constraint, constraint.type === 'foreign key' ? constraint.localColumns.map(dbName) : constraint.type === 'check' ? [] : constraint.columns.map(dbName));
const primary = table.constraints.filter(item => item.type === 'primary key');
if (primary.length > 1)
dbFail('A tabela só pode ter uma chave primária.', input, statement);
for (const column of table.columns)
if (primary.some(item => item.columns.includes(column.name)))
column.nullable = false;
tables.set(key, table);
addConstraints.set(key, addConstraint);
}
if (!tables.size)
throw new Error('Informe pelo menos um CREATE TABLE.');
for (const statement of statements)
if (statement.type === 'alter table') {
dbNoExtra(statement, ['type', 'table', 'changes'], input);
const add = addConstraints.get(dbReference(statement.table));
if (!add)
dbFail('ALTER exige tabela declarada na entrada.', input, statement);
for (const change of statement.changes) {
if (change.type !== 'add constraint')
dbFail('Somente ALTER TABLE ADD CONSTRAINT é aceito no leitor de schema.', input, change);
dbNoExtra(change, ['type', 'constraint'], input);
const c = change.constraint;
add(c, c.type === 'foreign key' ? c.localColumns.map(dbName) : c.type === 'check' ? [] : c.columns.map(dbName));
}
}
const relationNames = new Set([...tables.values()].map(table => dbKey(table)));
for (const table of tables.values())
for (const constraint of table.constraints.filter(c => c.type === 'primary key' || c.type === 'unique')) {
const key = dbKey({ schema: table.schema, name: constraint.name });
if (relationNames.has(key))
throw new Error('Nome de índice implícito duplicado no schema: ' + constraint.name);
relationNames.add(key);
}
for (const statement of statements) {
if (statement.type !== 'create index')
continue;
dbNoExtra(statement, ['type', 'table', 'indexName', 'expressions', 'unique', 'using'], input);
if (statement.using && dbName(statement.using).toLowerCase() !== 'btree')
dbFail('Somente índices btree simples são suportados.', input, statement);
const table = tables.get(dbReference(statement.table));
if (!table || !statement.indexName)
dbFail('Índice exige tabela declarada e nome explícito.', input, statement);
const name = dbName(statement.indexName);
dbQuote(name);
const indexKey = dbKey({ schema: table.schema, name });
if (relationNames.has(indexKey))
dbFail('Nome de índice/tabela duplicado no schema: ' + name, input, statement);
relationNames.add(indexKey);
const columns = statement.expressions.map(item => {
dbNoExtra(item, ['expression'], input);
if (item.expression.type !== 'ref' || item.expression.table || item.expression.name === '*')
dbFail('Índices aceitam somente colunas, sem expressões, ordem ou filtros.', input, item);
return item.expression.name.replace(/""/g, '"');
});
table.indexes.push({ name, columns, unique: !!statement.unique });
}
for (const table of tables.values()) {
const primary = table.constraints.filter(c => c.type === 'primary key');
if (primary.length > 1)
throw new Error('A tabela só pode ter uma chave primária: ' + table.name);
for (const column of table.columns)
if (primary.some(c => c.columns.includes(column.name)))
column.nullable = false;
const names = new Set(table.columns.map(item => item.name));
for (const item of [...table.constraints, ...table.indexes]) {
if (new Set(item.columns).size !== item.columns.length || item.columns.some(name => !names.has(name)) || !item.columns.length && !('type' in item && item.type === 'check'))
throw new Error('Colunas inválidas em ' + table.name + '.' + item.name);
}
for (const fk of table.constraints.filter(item => item.type === 'foreign key')) {
const target = tables.get(fk.target);
if (!target || !fk.references?.length || fk.references.length !== fk.columns.length)
throw new Error('FK ' + fk.name + ': declare a tabela e as colunas de destino explicitamente.');
if (new Set(fk.references).size !== fk.references.length || fk.references.some(name => !target.columns.some(c => c.name === name)))
throw new Error('Colunas de destino inválidas na FK ' + fk.name);
const unique = [...target.constraints.filter(item => ['primary key', 'unique'].includes(item.type)), ...target.indexes.filter(item => item.unique)];
if (!unique.some(item => JSON.stringify(item.columns) === JSON.stringify(fk.references)))
throw new Error('FK ' + fk.name + ': destino precisa de PK ou UNIQUE na mesma ordem.');
fk.columns.forEach((name, i) => { if (dbBase(table.columns.find(c => c.name === name).type) !== dbBase(target.columns.find(c => c.name === fk.references[i]).type))
throw new Error('Tipos incompatíveis na FK ' + fk.name); });
if (fk.onDelete === 'set null' || fk.onUpdate === 'set null')
if (fk.columns.some(name => !table.columns.find(c => c.name === name).nullable))
throw new Error('SET NULL exige colunas anuláveis: ' + fk.name);
}
}
return [...tables.values()];
}
function dbOutput(output) { if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.'); return output; }
function dbXml(text) { return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/[\x01-\x08\x0b\x0c\x0e-\x1f]/g, '�'); }
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 dbQuote(name) {
dbText(name, 'Nome');
if (!name || new TextEncoder().encode(name).length > 63)
throw new Error('Nomes devem ter de 1 a 63 bytes UTF-8, sem truncamento.');
return '"' + name.replace(/"/g, '""') + '"';
}
function dbName(name) { return name.name.replace(/""/g, '"'); }
function dbReference(name) { return dbKey({ schema: name.schema?.replace(/""/g, '"') ?? 'public', name: dbName(name) }); }
function dbType(input) {
const raw = input.toLowerCase().replace(/\s+/g, ' ').trim();
const aliases = { int: 'integer', int4: 'integer', int2: 'smallint', int8: 'bigint', bool: 'boolean', 'character varying': 'varchar', 'timestamp without time zone': 'timestamp', 'timestamp with time zone': 'timestamptz', decimal: 'numeric' };
const type = aliases[raw] ?? raw;
if (!/^(?:smallint|integer|bigint|serial|bigserial|text|boolean|date|timestamp|timestamptz|uuid|json|jsonb)$/.test(type) && !/^varchar\([1-9]\d{0,3}\)$/.test(type) && !/^numeric\((?:[1-9]|1[0-5]),(?:[0-9]|1[0-5])\)$/.test(type))
throw new Error('Tipo não suportado: ' + input + '. Use os tipos documentados; varchar(n) até 9999 ou numeric(p,s) com p até 15.');
if (type.startsWith('numeric(')) {
const [p, s] = type.slice(8, -1).split(',').map(Number);
if (s > p)
throw new Error('A escala numeric não pode exceder a precisão.');
}
return type;
}
function dbBase(type) { return type === 'serial' ? 'integer' : type === 'bigserial' ? 'bigint' : type; }
function dbFail(message, input, node) {
const offset = locationOf(node)?.start;
const prefix = offset === undefined ? '' : input.slice(0, offset);
throw new Error(message + (offset === undefined ? '' : ` (linha ${prefix.split('\n').length}, coluna ${offset - prefix.lastIndexOf('\n')})`));
}
function dbExpression(expr, input, check = false) {
function inspect(node, depth = 0) {
if (depth > 20)
throw new Error('Expressão excede 20 níveis.');
if (node.type === 'integer' || node.type === 'numeric') {
if (!Number.isFinite(node.value) || Number.isInteger(node.value) && !Number.isSafeInteger(node.value))
throw new Error('Literal numérico fora da precisão segura; use uma string.');
const location = locationOf(node), raw = location ? input.slice(location.start, location.end) : '';
const normalize = (text) => text.replace(/^\+/, '').replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '').replace(/^(-?)0+(?=\d)/, '$1');
if (!/^[+-]?\d+(?:\.\d+)?$/.test(raw) || normalize(raw) !== normalize(String(node.value)))
throw new Error('Literal numérico não preservável pelo parser. Use número sem expoente, dentro da precisão segura, ou uma string.');
return;
}
if (['string', 'boolean', 'null'].includes(node.type))
return;
if (check && node.type === 'ref' && !node.table && node.name !== '*')
return;
if (check && node.type === 'binary' && ['=', '!=', '<>', '>', '>=', '<', '<=', 'AND', 'OR'].includes(node.op)) {
inspect(node.left, depth + 1);
inspect(node.right, depth + 1);
return;
}
throw new Error('Expressão não suportada: ' + node.type + '. DEFAULT aceita literais; CHECK aceita comparações entre colunas/literais e AND/OR.');
}
inspect(expr);
return toSql.expr(expr);
}
function dbNoExtra(node, keys, input) {
for (const key of Object.keys(node))
if (key !== '_location' && !keys.includes(key))
dbFail('Construção não suportada: ' + key + '.', input, node);
}
for (const value of Object.values(values)) dbText(value);
return databaseDiagram(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 { parse } from "pgsql-ast-parser";
import { locationOf, toSql } from "pgsql-ast-parser";
function executar(values) {
function databaseDiagram(values) {
const schema = readDbSchema(values.input), width = 1000, boxWidth = 430;
const positions = new Map();
let y = 30;
for (let i = 0; i < schema.length; i += 2) {
let height = 0;
for (let j = i; j < Math.min(i + 2, schema.length); j++) {
const table = schema[j], h = 72 + table.columns.length * 24;
positions.set(dbKey(table), { x: 30 + (j % 2) * 500, y, h });
height = Math.max(height, h);
}
y += height + 70;
}
const svg = ['<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + y + '" viewBox="0 0 ' + width + ' ' + y + '" role="img" aria-label="Diagrama de tabelas e relacionamentos">', '<rect width="100%" height="100%" fill="#ffffff"/>', '<defs><marker id="arrow" markerWidth="8" markerHeight="8" refX="8" refY="4" orient="auto"><path d="M0,0 L8,4 L0,8 Z" fill="#6d28d9"/></marker></defs>'];
for (const table of schema) {
const from = positions.get(dbKey(table));
for (const fk of table.constraints.filter(c => c.type === 'foreign key')) {
const to = positions.get(fk.target);
const label = dbXml(fk.columns.join(', ') + ' → ' + fk.references.join(', '));
svg.push('<path d="M' + (from.x + boxWidth) + ' ' + (from.y + 35) + ' C' + (from.x + boxWidth + 35) + ' ' + (from.y + 35) + ',' + (to.x - 25) + ' ' + (to.y + 35) + ',' + to.x + ' ' + (to.y + 35) + '" fill="none" stroke="#6d28d9" stroke-width="2" marker-end="url(#arrow)"><title>' + label + '</title></path>');
}
}
for (const table of schema) {
const pos = positions.get(dbKey(table));
svg.push('<g font-family="monospace" font-size="12" fill="#172033"><rect x="' + pos.x + '" y="' + pos.y + '" width="' + boxWidth + '" height="' + pos.h + '" rx="8" fill="#f8fafc" stroke="#64748b"/><text x="' + (pos.x + 12) + '" y="' + (pos.y + 25) + '" font-weight="bold">' + dbXml(table.schema + '.' + table.name) + '</text>');
table.columns.forEach((column, i) => { const tags = table.constraints.filter(c => c.columns.includes(column.name)).map(c => c.type === 'primary key' ? 'PK' : c.type === 'foreign key' ? 'FK' : c.type === 'unique' ? 'UQ' : 'CHECK'); svg.push('<text x="' + (pos.x + 12) + '" y="' + (pos.y + 55 + i * 24) + '"><title>' + dbXml(column.name + ' ' + column.type) + '</title>' + dbXml((column.name + ' : ' + column.type + ' ' + tags.join('/') + (column.nullable ? '' : ' NOT NULL')).slice(0, 53)) + '</text>'); });
svg.push('</g>');
}
svg.push('</svg>');
return dbOutput(svg.join('\n'));
}
function dbKey(table) { return JSON.stringify([table.schema, table.name]); }
function readDbSchema(input) {
dbText(input, 'DDL PostgreSQL');
if (!input.trim())
throw new Error('Informe pelo menos um CREATE TABLE.');
let statements;
try {
statements = parse(input, { locationTracking: true });
}
catch (cause) {
throw new Error('DDL inválido ou não suportado: ' + (cause instanceof Error ? cause.message : 'erro de parsing'));
}
if (statements.length > 300)
throw new Error('Limite de 300 instruções e 30 tabelas.');
const tables = new Map();
const addConstraints = new Map();
for (const statement of statements) {
if (statement.type === 'create index' || statement.type === 'alter table')
continue;
if (statement.type !== 'create table')
dbFail('Somente CREATE TABLE, CREATE INDEX e ALTER TABLE ADD CONSTRAINT são aceitos; recebido ' + statement.type + '.', input, statement);
dbNoExtra(statement, ['type', 'name', 'columns', 'constraints'], input);
const table = { schema: statement.name.schema?.replace(/""/g, '"') ?? 'public', name: dbName(statement.name), columns: [], constraints: [], indexes: [] };
dbQuote(table.schema);
dbQuote(table.name);
const key = dbKey(table);
if (tables.has(key) || tables.size >= 30)
dbFail('Tabela duplicada ou limite de 30 tabelas.', input, statement);
const addConstraint = (constraint, columns) => {
let type = constraint.type;
if (type === 'reference')
type = 'foreign key';
if (!['primary key', 'unique', 'foreign key', 'check'].includes(type))
dbFail('Constraint não suportada: ' + type, input, constraint);
const suffix = type === 'primary key' ? 'pkey' : type === 'unique' ? 'key' : type === 'foreign key' ? 'fkey' : 'check';
const name = constraint.constraintName ? dbName(constraint.constraintName) : [table.name, ...(type === 'primary key' ? [] : columns), suffix].join('_');
dbQuote(name);
const value = { name, type: type, columns };
if (constraint.type === 'reference' || constraint.type === 'foreign key') {
dbNoExtra(constraint, ['type', 'constraintName', 'foreignTable', 'foreignColumns', 'localColumns', 'onDelete', 'onUpdate'], input);
value.target = dbReference(constraint.foreignTable);
value.references = constraint.foreignColumns.map(dbName);
value.onDelete = constraint.onDelete ?? 'no action';
value.onUpdate = constraint.onUpdate ?? 'no action';
}
else if (constraint.type === 'check') {
dbNoExtra(constraint, ['type', 'constraintName', 'expr'], input);
value.check = dbExpression(constraint.expr, input, true);
const refs = new Set();
const visit = (node) => { if (node.type === 'ref')
refs.add(node.name); if (node.type === 'binary') {
visit(node.left);
visit(node.right);
} };
visit(constraint.expr);
value.columns = [...refs];
}
else
dbNoExtra(constraint, ['type', 'constraintName', 'columns'], input);
if (table.constraints.some(item => item.name === name))
dbFail('Nome de constraint duplicado: ' + name, input, constraint);
table.constraints.push(value);
};
for (const column of statement.columns) {
if (column.kind !== 'column')
dbFail('LIKE e herança não são suportados.', input, column);
dbNoExtra(column, ['kind', 'name', 'dataType', 'constraints'], input);
if (column.dataType.kind === 'array' || column.dataType.schema || column.dataType.doubleQuoted)
dbFail('Arrays e tipos personalizados não são suportados.', input, column);
const name = dbName(column.name);
dbQuote(name);
if (table.columns.some(item => item.name === name))
dbFail('Coluna duplicada: ' + name, input, column);
const config = column.dataType.config;
const base = dbType((column.dataType.name === 'varchar' || column.dataType.name === 'character varying' ? 'varchar' : column.dataType.name === 'decimal' ? 'numeric' : column.dataType.name) + (config?.length ? '(' + config.join(',') + ')' : ''));
const item = { name, type: base, nullable: !['serial', 'bigserial'].includes(base) };
const types = new Set();
for (const constraint of column.constraints ?? []) {
if (types.has(constraint.type))
dbFail('Constraint de coluna repetida: ' + constraint.type, input, constraint);
types.add(constraint.type);
if (constraint.type === 'not null')
item.nullable = false;
else if (constraint.type === 'null') {
if (['serial', 'bigserial'].includes(base) || types.has('not null'))
dbFail('NULL contradiz NOT NULL/serial.', input, constraint);
item.nullable = true;
}
else if (constraint.type === 'default') {
if (['serial', 'bigserial'].includes(base))
dbFail('Serial com DEFAULT explícito não é suportado.', input, constraint);
item.default = dbExpression(constraint.default, input);
}
else
addConstraint(constraint, [name]);
}
if (types.has('null') && types.has('not null'))
dbFail('NULL e NOT NULL são contraditórios.', input, column);
table.columns.push(item);
}
if (!table.columns.length || table.columns.length > 100)
dbFail('Use de 1 a 100 colunas por tabela.', input, statement);
for (const constraint of statement.constraints ?? [])
addConstraint(constraint, constraint.type === 'foreign key' ? constraint.localColumns.map(dbName) : constraint.type === 'check' ? [] : constraint.columns.map(dbName));
const primary = table.constraints.filter(item => item.type === 'primary key');
if (primary.length > 1)
dbFail('A tabela só pode ter uma chave primária.', input, statement);
for (const column of table.columns)
if (primary.some(item => item.columns.includes(column.name)))
column.nullable = false;
tables.set(key, table);
addConstraints.set(key, addConstraint);
}
if (!tables.size)
throw new Error('Informe pelo menos um CREATE TABLE.');
for (const statement of statements)
if (statement.type === 'alter table') {
dbNoExtra(statement, ['type', 'table', 'changes'], input);
const add = addConstraints.get(dbReference(statement.table));
if (!add)
dbFail('ALTER exige tabela declarada na entrada.', input, statement);
for (const change of statement.changes) {
if (change.type !== 'add constraint')
dbFail('Somente ALTER TABLE ADD CONSTRAINT é aceito no leitor de schema.', input, change);
dbNoExtra(change, ['type', 'constraint'], input);
const c = change.constraint;
add(c, c.type === 'foreign key' ? c.localColumns.map(dbName) : c.type === 'check' ? [] : c.columns.map(dbName));
}
}
const relationNames = new Set([...tables.values()].map(table => dbKey(table)));
for (const table of tables.values())
for (const constraint of table.constraints.filter(c => c.type === 'primary key' || c.type === 'unique')) {
const key = dbKey({ schema: table.schema, name: constraint.name });
if (relationNames.has(key))
throw new Error('Nome de índice implícito duplicado no schema: ' + constraint.name);
relationNames.add(key);
}
for (const statement of statements) {
if (statement.type !== 'create index')
continue;
dbNoExtra(statement, ['type', 'table', 'indexName', 'expressions', 'unique', 'using'], input);
if (statement.using && dbName(statement.using).toLowerCase() !== 'btree')
dbFail('Somente índices btree simples são suportados.', input, statement);
const table = tables.get(dbReference(statement.table));
if (!table || !statement.indexName)
dbFail('Índice exige tabela declarada e nome explícito.', input, statement);
const name = dbName(statement.indexName);
dbQuote(name);
const indexKey = dbKey({ schema: table.schema, name });
if (relationNames.has(indexKey))
dbFail('Nome de índice/tabela duplicado no schema: ' + name, input, statement);
relationNames.add(indexKey);
const columns = statement.expressions.map(item => {
dbNoExtra(item, ['expression'], input);
if (item.expression.type !== 'ref' || item.expression.table || item.expression.name === '*')
dbFail('Índices aceitam somente colunas, sem expressões, ordem ou filtros.', input, item);
return item.expression.name.replace(/""/g, '"');
});
table.indexes.push({ name, columns, unique: !!statement.unique });
}
for (const table of tables.values()) {
const primary = table.constraints.filter(c => c.type === 'primary key');
if (primary.length > 1)
throw new Error('A tabela só pode ter uma chave primária: ' + table.name);
for (const column of table.columns)
if (primary.some(c => c.columns.includes(column.name)))
column.nullable = false;
const names = new Set(table.columns.map(item => item.name));
for (const item of [...table.constraints, ...table.indexes]) {
if (new Set(item.columns).size !== item.columns.length || item.columns.some(name => !names.has(name)) || !item.columns.length && !('type' in item && item.type === 'check'))
throw new Error('Colunas inválidas em ' + table.name + '.' + item.name);
}
for (const fk of table.constraints.filter(item => item.type === 'foreign key')) {
const target = tables.get(fk.target);
if (!target || !fk.references?.length || fk.references.length !== fk.columns.length)
throw new Error('FK ' + fk.name + ': declare a tabela e as colunas de destino explicitamente.');
if (new Set(fk.references).size !== fk.references.length || fk.references.some(name => !target.columns.some(c => c.name === name)))
throw new Error('Colunas de destino inválidas na FK ' + fk.name);
const unique = [...target.constraints.filter(item => ['primary key', 'unique'].includes(item.type)), ...target.indexes.filter(item => item.unique)];
if (!unique.some(item => JSON.stringify(item.columns) === JSON.stringify(fk.references)))
throw new Error('FK ' + fk.name + ': destino precisa de PK ou UNIQUE na mesma ordem.');
fk.columns.forEach((name, i) => { if (dbBase(table.columns.find(c => c.name === name).type) !== dbBase(target.columns.find(c => c.name === fk.references[i]).type))
throw new Error('Tipos incompatíveis na FK ' + fk.name); });
if (fk.onDelete === 'set null' || fk.onUpdate === 'set null')
if (fk.columns.some(name => !table.columns.find(c => c.name === name).nullable))
throw new Error('SET NULL exige colunas anuláveis: ' + fk.name);
}
}
return [...tables.values()];
}
function dbOutput(output) { if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.'); return output; }
function dbXml(text) { return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/[\x01-\x08\x0b\x0c\x0e-\x1f]/g, '�'); }
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 dbQuote(name) {
dbText(name, 'Nome');
if (!name || new TextEncoder().encode(name).length > 63)
throw new Error('Nomes devem ter de 1 a 63 bytes UTF-8, sem truncamento.');
return '"' + name.replace(/"/g, '""') + '"';
}
function dbName(name) { return name.name.replace(/""/g, '"'); }
function dbReference(name) { return dbKey({ schema: name.schema?.replace(/""/g, '"') ?? 'public', name: dbName(name) }); }
function dbType(input) {
const raw = input.toLowerCase().replace(/\s+/g, ' ').trim();
const aliases = { int: 'integer', int4: 'integer', int2: 'smallint', int8: 'bigint', bool: 'boolean', 'character varying': 'varchar', 'timestamp without time zone': 'timestamp', 'timestamp with time zone': 'timestamptz', decimal: 'numeric' };
const type = aliases[raw] ?? raw;
if (!/^(?:smallint|integer|bigint|serial|bigserial|text|boolean|date|timestamp|timestamptz|uuid|json|jsonb)$/.test(type) && !/^varchar\([1-9]\d{0,3}\)$/.test(type) && !/^numeric\((?:[1-9]|1[0-5]),(?:[0-9]|1[0-5])\)$/.test(type))
throw new Error('Tipo não suportado: ' + input + '. Use os tipos documentados; varchar(n) até 9999 ou numeric(p,s) com p até 15.');
if (type.startsWith('numeric(')) {
const [p, s] = type.slice(8, -1).split(',').map(Number);
if (s > p)
throw new Error('A escala numeric não pode exceder a precisão.');
}
return type;
}
function dbBase(type) { return type === 'serial' ? 'integer' : type === 'bigserial' ? 'bigint' : type; }
function dbFail(message, input, node) {
const offset = locationOf(node)?.start;
const prefix = offset === undefined ? '' : input.slice(0, offset);
throw new Error(message + (offset === undefined ? '' : ` (linha ${prefix.split('\n').length}, coluna ${offset - prefix.lastIndexOf('\n')})`));
}
function dbExpression(expr, input, check = false) {
function inspect(node, depth = 0) {
if (depth > 20)
throw new Error('Expressão excede 20 níveis.');
if (node.type === 'integer' || node.type === 'numeric') {
if (!Number.isFinite(node.value) || Number.isInteger(node.value) && !Number.isSafeInteger(node.value))
throw new Error('Literal numérico fora da precisão segura; use uma string.');
const location = locationOf(node), raw = location ? input.slice(location.start, location.end) : '';
const normalize = (text) => text.replace(/^\+/, '').replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '').replace(/^(-?)0+(?=\d)/, '$1');
if (!/^[+-]?\d+(?:\.\d+)?$/.test(raw) || normalize(raw) !== normalize(String(node.value)))
throw new Error('Literal numérico não preservável pelo parser. Use número sem expoente, dentro da precisão segura, ou uma string.');
return;
}
if (['string', 'boolean', 'null'].includes(node.type))
return;
if (check && node.type === 'ref' && !node.table && node.name !== '*')
return;
if (check && node.type === 'binary' && ['=', '!=', '<>', '>', '>=', '<', '<=', 'AND', 'OR'].includes(node.op)) {
inspect(node.left, depth + 1);
inspect(node.right, depth + 1);
return;
}
throw new Error('Expressão não suportada: ' + node.type + '. DEFAULT aceita literais; CHECK aceita comparações entre colunas/literais e AND/OR.');
}
inspect(expr);
return toSql.expr(expr);
}
function dbNoExtra(node, keys, input) {
for (const key of Object.keys(node))
if (key !== '_location' && !keys.includes(key))
dbFail('Construção não suportada: ' + key + '.', input, node);
}
for (const value of Object.values(values)) dbText(value);
return databaseDiagram(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"];
}