JavaScript Python PHP
import { parse } from "pgsql-ast-parser";
import { locationOf, toSql } from "pgsql-ast-parser";
function executar(values) {
function generateDatabaseMigration(values) {
const before = readDbSchema(values.input), after = readDbSchema(values.target), changes = compareDbSchemas(before, after);
if (!changes.length)
return '-- Nenhuma alteração estrutural.';
if (changes.some(c => c.kind === 'ordem das colunas alterada'))
throw new Error('Reordenar colunas exigiria reconstruir a tabela; migration automática não suportada.');
const old = new Map(before.map(t => [dbKey(t), t])), next = new Map(after.map(t => [dbKey(t), t]));
const sql = ['-- Revisão manual obrigatória: não executado. Faça backup e teste com dados reais em ambiente isolado.', '-- Remoção de tabela/coluna perde dados; rollback estrutural não restaura dados.', '-- Renomeações não são inferidas. Tipos usam cast explícito; conversões e constraints podem falhar com os dados existentes.', 'BEGIN;'];
for (const table of before)
for (const fk of table.constraints.filter(c => c.type === 'foreign key'))
sql.push('ALTER TABLE ' + dbTarget(table) + ' DROP CONSTRAINT ' + dbQuote(fk.name) + ';');
// Drop old names before creating replacements in any table, including cross-table moves.
for (const table of before)
if (next.has(dbKey(table)) && changes.some(c => c.table === dbTarget(table))) {
for (const index of table.indexes)
sql.push('DROP INDEX ' + dbQuote(table.schema) + '.' + dbQuote(index.name) + ';');
for (const c of table.constraints.filter(c => c.type !== 'foreign key'))
sql.push('ALTER TABLE ' + dbTarget(table) + ' DROP CONSTRAINT ' + dbQuote(c.name) + ';');
}
for (const table of before)
if (!next.has(dbKey(table)))
sql.push('-- DESTRUTIVO: remove tabela e seus dados.', 'DROP TABLE ' + dbTarget(table) + ';');
for (const table of before) {
const target = next.get(dbKey(table));
if (!target)
continue;
if (!changes.some(c => c.table === dbTarget(table)))
continue;
for (const column of table.columns)
if (!target.columns.some(c => c.name === column.name))
sql.push('-- DESTRUTIVO: remove coluna e seus dados.', 'ALTER TABLE ' + dbTarget(table) + ' DROP COLUMN ' + dbQuote(column.name) + ';');
for (const column of target.columns) {
const previous = table.columns.find(c => c.name === column.name), prefix = 'ALTER TABLE ' + dbTarget(table) + ' ';
if (!previous) {
sql.push('-- Nova coluna NOT NULL sem DEFAULT pode falhar em tabela preenchida.', prefix + 'ADD COLUMN ' + dbColumnSql(column) + ';');
continue;
}
if (previous.type !== column.type) {
if ([previous.type, column.type].some(t => ['serial', 'bigserial'].includes(t)))
throw new Error('Alterar serial/bigserial exige tratar sequences manualmente.');
sql.push('-- POTENCIALMENTE DESTRUTIVO: conversão de tipo.', prefix + 'ALTER COLUMN ' + dbQuote(column.name) + ' DROP DEFAULT;', prefix + 'ALTER COLUMN ' + dbQuote(column.name) + ' TYPE ' + column.type + ' USING ' + dbQuote(column.name) + '::' + column.type + ';');
}
if (previous.nullable !== column.nullable)
sql.push(prefix + 'ALTER COLUMN ' + dbQuote(column.name) + (column.nullable ? ' DROP NOT NULL;' : ' SET NOT NULL;'));
if (previous.default !== column.default || previous.type !== column.type)
sql.push(prefix + 'ALTER COLUMN ' + dbQuote(column.name) + (column.default === undefined ? ' DROP DEFAULT;' : ' SET DEFAULT ' + column.default + ';'));
}
}
for (const table of after)
if (old.has(dbKey(table)) && changes.some(c => c.table === dbTarget(table)))
for (const c of table.constraints.filter(c => c.type !== 'foreign key'))
sql.push('ALTER TABLE ' + dbTarget(table) + ' ADD ' + dbConstraintSql(c) + ';');
for (const table of after)
if (!old.has(dbKey(table)))
sql.push(dbCreateSql(table), ...table.indexes.map(i => dbIndexSql(table, i)));
for (const table of after)
if (old.has(dbKey(table)) && changes.some(c => c.table === dbTarget(table)))
for (const index of table.indexes)
sql.push(dbIndexSql(table, index));
for (const table of after)
for (const fk of table.constraints.filter(c => c.type === 'foreign key'))
sql.push('ALTER TABLE ' + dbTarget(table) + ' ADD ' + dbConstraintSql(fk) + ';');
sql.push('COMMIT;', '-- Não há down automático: inverter schemas gera apenas outra proposta estrutural e não recupera dados.');
return dbOutput(sql.join('\n'));
}
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 dbKey(table) { return JSON.stringify([table.schema, table.name]); }
function dbTarget(table) { return dbQuote(table.schema) + '.' + dbQuote(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 dbColumnSql(column) { return dbQuote(column.name) + ' ' + column.type + (column.nullable ? '' : ' NOT NULL') + (column.default === undefined ? '' : ' DEFAULT ' + column.default); }
function dbConstraintSql(constraint) {
let body;
if (constraint.type === 'check')
body = 'CHECK (' + constraint.check + ')';
else {
body = constraint.type.toUpperCase() + ' (' + constraint.columns.map(dbQuote).join(', ') + ')';
if (constraint.type === 'foreign key') {
const [schema, name] = JSON.parse(constraint.target);
body += ' REFERENCES ' + dbTarget({ schema, name }) + ' (' + constraint.references.map(dbQuote).join(', ') + ') ON DELETE ' + constraint.onDelete.toUpperCase() + ' ON UPDATE ' + constraint.onUpdate.toUpperCase();
}
}
return 'CONSTRAINT ' + dbQuote(constraint.name) + ' ' + body;
}
function dbCreateSql(table) { return 'CREATE TABLE ' + dbTarget(table) + ' (\n ' + [...table.columns.map(dbColumnSql), ...table.constraints.filter(item => item.type !== 'foreign key').map(dbConstraintSql)].join(',\n ') + '\n);'; }
function dbIndexSql(table, index) { return 'CREATE ' + (index.unique ? 'UNIQUE ' : '') + 'INDEX ' + dbQuote(index.name) + ' ON ' + dbTarget(table) + ' (' + index.columns.map(dbQuote).join(', ') + ');'; }
function dbOutput(output) { if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.'); return output; }
function compareDbSchemas(before, after) {
const changes = [];
const old = new Map(before.map(t => [dbKey(t), t])), next = new Map(after.map(t => [dbKey(t), t]));
for (const table of before)
if (!next.has(dbKey(table)))
changes.push({ table: dbTarget(table), kind: 'tabela removida', name: table.name, before: table, destructive: true });
for (const table of after) {
const previous = old.get(dbKey(table));
if (!previous) {
changes.push({ table: dbTarget(table), kind: 'tabela adicionada', name: table.name, after: table, destructive: false });
continue;
}
for (const [key, label] of [['columns', 'coluna'], ['constraints', 'constraint'], ['indexes', 'índice']]) {
const left = new Map(previous[key].map(item => [item.name, item])), right = new Map(table[key].map(item => [item.name, item]));
for (const [name, item] of left)
if (!right.has(name))
changes.push({ table: dbTarget(table), kind: label + ' removido(a)', name, before: item, destructive: label === 'coluna' });
for (const [name, item] of right)
if (!left.has(name))
changes.push({ table: dbTarget(table), kind: label + ' adicionado(a)', name, after: item, destructive: false });
else if (JSON.stringify(left.get(name)) !== JSON.stringify(item))
changes.push({ table: dbTarget(table), kind: label + ' alterado(a)', name, before: left.get(name), after: item, destructive: label === 'coluna' });
}
if (JSON.stringify(previous.columns.map(c => c.name).filter(n => table.columns.some(c => c.name === n))) !== JSON.stringify(table.columns.map(c => c.name).filter(n => previous.columns.some(c => c.name === n))))
changes.push({ table: dbTarget(table), kind: 'ordem das colunas alterada', name: table.name, destructive: false });
}
return changes;
}
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 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 generateDatabaseMigration(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 generateDatabaseMigration(values) {
const before = readDbSchema(values.input), after = readDbSchema(values.target), changes = compareDbSchemas(before, after);
if (!changes.length)
return '-- Nenhuma alteração estrutural.';
if (changes.some(c => c.kind === 'ordem das colunas alterada'))
throw new Error('Reordenar colunas exigiria reconstruir a tabela; migration automática não suportada.');
const old = new Map(before.map(t => [dbKey(t), t])), next = new Map(after.map(t => [dbKey(t), t]));
const sql = ['-- Revisão manual obrigatória: não executado. Faça backup e teste com dados reais em ambiente isolado.', '-- Remoção de tabela/coluna perde dados; rollback estrutural não restaura dados.', '-- Renomeações não são inferidas. Tipos usam cast explícito; conversões e constraints podem falhar com os dados existentes.', 'BEGIN;'];
for (const table of before)
for (const fk of table.constraints.filter(c => c.type === 'foreign key'))
sql.push('ALTER TABLE ' + dbTarget(table) + ' DROP CONSTRAINT ' + dbQuote(fk.name) + ';');
// Drop old names before creating replacements in any table, including cross-table moves.
for (const table of before)
if (next.has(dbKey(table)) && changes.some(c => c.table === dbTarget(table))) {
for (const index of table.indexes)
sql.push('DROP INDEX ' + dbQuote(table.schema) + '.' + dbQuote(index.name) + ';');
for (const c of table.constraints.filter(c => c.type !== 'foreign key'))
sql.push('ALTER TABLE ' + dbTarget(table) + ' DROP CONSTRAINT ' + dbQuote(c.name) + ';');
}
for (const table of before)
if (!next.has(dbKey(table)))
sql.push('-- DESTRUTIVO: remove tabela e seus dados.', 'DROP TABLE ' + dbTarget(table) + ';');
for (const table of before) {
const target = next.get(dbKey(table));
if (!target)
continue;
if (!changes.some(c => c.table === dbTarget(table)))
continue;
for (const column of table.columns)
if (!target.columns.some(c => c.name === column.name))
sql.push('-- DESTRUTIVO: remove coluna e seus dados.', 'ALTER TABLE ' + dbTarget(table) + ' DROP COLUMN ' + dbQuote(column.name) + ';');
for (const column of target.columns) {
const previous = table.columns.find(c => c.name === column.name), prefix = 'ALTER TABLE ' + dbTarget(table) + ' ';
if (!previous) {
sql.push('-- Nova coluna NOT NULL sem DEFAULT pode falhar em tabela preenchida.', prefix + 'ADD COLUMN ' + dbColumnSql(column) + ';');
continue;
}
if (previous.type !== column.type) {
if ([previous.type, column.type].some(t => ['serial', 'bigserial'].includes(t)))
throw new Error('Alterar serial/bigserial exige tratar sequences manualmente.');
sql.push('-- POTENCIALMENTE DESTRUTIVO: conversão de tipo.', prefix + 'ALTER COLUMN ' + dbQuote(column.name) + ' DROP DEFAULT;', prefix + 'ALTER COLUMN ' + dbQuote(column.name) + ' TYPE ' + column.type + ' USING ' + dbQuote(column.name) + '::' + column.type + ';');
}
if (previous.nullable !== column.nullable)
sql.push(prefix + 'ALTER COLUMN ' + dbQuote(column.name) + (column.nullable ? ' DROP NOT NULL;' : ' SET NOT NULL;'));
if (previous.default !== column.default || previous.type !== column.type)
sql.push(prefix + 'ALTER COLUMN ' + dbQuote(column.name) + (column.default === undefined ? ' DROP DEFAULT;' : ' SET DEFAULT ' + column.default + ';'));
}
}
for (const table of after)
if (old.has(dbKey(table)) && changes.some(c => c.table === dbTarget(table)))
for (const c of table.constraints.filter(c => c.type !== 'foreign key'))
sql.push('ALTER TABLE ' + dbTarget(table) + ' ADD ' + dbConstraintSql(c) + ';');
for (const table of after)
if (!old.has(dbKey(table)))
sql.push(dbCreateSql(table), ...table.indexes.map(i => dbIndexSql(table, i)));
for (const table of after)
if (old.has(dbKey(table)) && changes.some(c => c.table === dbTarget(table)))
for (const index of table.indexes)
sql.push(dbIndexSql(table, index));
for (const table of after)
for (const fk of table.constraints.filter(c => c.type === 'foreign key'))
sql.push('ALTER TABLE ' + dbTarget(table) + ' ADD ' + dbConstraintSql(fk) + ';');
sql.push('COMMIT;', '-- Não há down automático: inverter schemas gera apenas outra proposta estrutural e não recupera dados.');
return dbOutput(sql.join('\n'));
}
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 dbKey(table) { return JSON.stringify([table.schema, table.name]); }
function dbTarget(table) { return dbQuote(table.schema) + '.' + dbQuote(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 dbColumnSql(column) { return dbQuote(column.name) + ' ' + column.type + (column.nullable ? '' : ' NOT NULL') + (column.default === undefined ? '' : ' DEFAULT ' + column.default); }
function dbConstraintSql(constraint) {
let body;
if (constraint.type === 'check')
body = 'CHECK (' + constraint.check + ')';
else {
body = constraint.type.toUpperCase() + ' (' + constraint.columns.map(dbQuote).join(', ') + ')';
if (constraint.type === 'foreign key') {
const [schema, name] = JSON.parse(constraint.target);
body += ' REFERENCES ' + dbTarget({ schema, name }) + ' (' + constraint.references.map(dbQuote).join(', ') + ') ON DELETE ' + constraint.onDelete.toUpperCase() + ' ON UPDATE ' + constraint.onUpdate.toUpperCase();
}
}
return 'CONSTRAINT ' + dbQuote(constraint.name) + ' ' + body;
}
function dbCreateSql(table) { return 'CREATE TABLE ' + dbTarget(table) + ' (\n ' + [...table.columns.map(dbColumnSql), ...table.constraints.filter(item => item.type !== 'foreign key').map(dbConstraintSql)].join(',\n ') + '\n);'; }
function dbIndexSql(table, index) { return 'CREATE ' + (index.unique ? 'UNIQUE ' : '') + 'INDEX ' + dbQuote(index.name) + ' ON ' + dbTarget(table) + ' (' + index.columns.map(dbQuote).join(', ') + ');'; }
function dbOutput(output) { if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.'); return output; }
function compareDbSchemas(before, after) {
const changes = [];
const old = new Map(before.map(t => [dbKey(t), t])), next = new Map(after.map(t => [dbKey(t), t]));
for (const table of before)
if (!next.has(dbKey(table)))
changes.push({ table: dbTarget(table), kind: 'tabela removida', name: table.name, before: table, destructive: true });
for (const table of after) {
const previous = old.get(dbKey(table));
if (!previous) {
changes.push({ table: dbTarget(table), kind: 'tabela adicionada', name: table.name, after: table, destructive: false });
continue;
}
for (const [key, label] of [['columns', 'coluna'], ['constraints', 'constraint'], ['indexes', 'índice']]) {
const left = new Map(previous[key].map(item => [item.name, item])), right = new Map(table[key].map(item => [item.name, item]));
for (const [name, item] of left)
if (!right.has(name))
changes.push({ table: dbTarget(table), kind: label + ' removido(a)', name, before: item, destructive: label === 'coluna' });
for (const [name, item] of right)
if (!left.has(name))
changes.push({ table: dbTarget(table), kind: label + ' adicionado(a)', name, after: item, destructive: false });
else if (JSON.stringify(left.get(name)) !== JSON.stringify(item))
changes.push({ table: dbTarget(table), kind: label + ' alterado(a)', name, before: left.get(name), after: item, destructive: label === 'coluna' });
}
if (JSON.stringify(previous.columns.map(c => c.name).filter(n => table.columns.some(c => c.name === n))) !== JSON.stringify(table.columns.map(c => c.name).filter(n => previous.columns.some(c => c.name === n))))
changes.push({ table: dbTarget(table), kind: 'ordem das colunas alterada', name: table.name, destructive: false });
}
return changes;
}
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 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 generateDatabaseMigration(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 generateDatabaseMigration(values) {
const before = readDbSchema(values.input), after = readDbSchema(values.target), changes = compareDbSchemas(before, after);
if (!changes.length)
return '-- Nenhuma alteração estrutural.';
if (changes.some(c => c.kind === 'ordem das colunas alterada'))
throw new Error('Reordenar colunas exigiria reconstruir a tabela; migration automática não suportada.');
const old = new Map(before.map(t => [dbKey(t), t])), next = new Map(after.map(t => [dbKey(t), t]));
const sql = ['-- Revisão manual obrigatória: não executado. Faça backup e teste com dados reais em ambiente isolado.', '-- Remoção de tabela/coluna perde dados; rollback estrutural não restaura dados.', '-- Renomeações não são inferidas. Tipos usam cast explícito; conversões e constraints podem falhar com os dados existentes.', 'BEGIN;'];
for (const table of before)
for (const fk of table.constraints.filter(c => c.type === 'foreign key'))
sql.push('ALTER TABLE ' + dbTarget(table) + ' DROP CONSTRAINT ' + dbQuote(fk.name) + ';');
// Drop old names before creating replacements in any table, including cross-table moves.
for (const table of before)
if (next.has(dbKey(table)) && changes.some(c => c.table === dbTarget(table))) {
for (const index of table.indexes)
sql.push('DROP INDEX ' + dbQuote(table.schema) + '.' + dbQuote(index.name) + ';');
for (const c of table.constraints.filter(c => c.type !== 'foreign key'))
sql.push('ALTER TABLE ' + dbTarget(table) + ' DROP CONSTRAINT ' + dbQuote(c.name) + ';');
}
for (const table of before)
if (!next.has(dbKey(table)))
sql.push('-- DESTRUTIVO: remove tabela e seus dados.', 'DROP TABLE ' + dbTarget(table) + ';');
for (const table of before) {
const target = next.get(dbKey(table));
if (!target)
continue;
if (!changes.some(c => c.table === dbTarget(table)))
continue;
for (const column of table.columns)
if (!target.columns.some(c => c.name === column.name))
sql.push('-- DESTRUTIVO: remove coluna e seus dados.', 'ALTER TABLE ' + dbTarget(table) + ' DROP COLUMN ' + dbQuote(column.name) + ';');
for (const column of target.columns) {
const previous = table.columns.find(c => c.name === column.name), prefix = 'ALTER TABLE ' + dbTarget(table) + ' ';
if (!previous) {
sql.push('-- Nova coluna NOT NULL sem DEFAULT pode falhar em tabela preenchida.', prefix + 'ADD COLUMN ' + dbColumnSql(column) + ';');
continue;
}
if (previous.type !== column.type) {
if ([previous.type, column.type].some(t => ['serial', 'bigserial'].includes(t)))
throw new Error('Alterar serial/bigserial exige tratar sequences manualmente.');
sql.push('-- POTENCIALMENTE DESTRUTIVO: conversão de tipo.', prefix + 'ALTER COLUMN ' + dbQuote(column.name) + ' DROP DEFAULT;', prefix + 'ALTER COLUMN ' + dbQuote(column.name) + ' TYPE ' + column.type + ' USING ' + dbQuote(column.name) + '::' + column.type + ';');
}
if (previous.nullable !== column.nullable)
sql.push(prefix + 'ALTER COLUMN ' + dbQuote(column.name) + (column.nullable ? ' DROP NOT NULL;' : ' SET NOT NULL;'));
if (previous.default !== column.default || previous.type !== column.type)
sql.push(prefix + 'ALTER COLUMN ' + dbQuote(column.name) + (column.default === undefined ? ' DROP DEFAULT;' : ' SET DEFAULT ' + column.default + ';'));
}
}
for (const table of after)
if (old.has(dbKey(table)) && changes.some(c => c.table === dbTarget(table)))
for (const c of table.constraints.filter(c => c.type !== 'foreign key'))
sql.push('ALTER TABLE ' + dbTarget(table) + ' ADD ' + dbConstraintSql(c) + ';');
for (const table of after)
if (!old.has(dbKey(table)))
sql.push(dbCreateSql(table), ...table.indexes.map(i => dbIndexSql(table, i)));
for (const table of after)
if (old.has(dbKey(table)) && changes.some(c => c.table === dbTarget(table)))
for (const index of table.indexes)
sql.push(dbIndexSql(table, index));
for (const table of after)
for (const fk of table.constraints.filter(c => c.type === 'foreign key'))
sql.push('ALTER TABLE ' + dbTarget(table) + ' ADD ' + dbConstraintSql(fk) + ';');
sql.push('COMMIT;', '-- Não há down automático: inverter schemas gera apenas outra proposta estrutural e não recupera dados.');
return dbOutput(sql.join('\n'));
}
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 dbKey(table) { return JSON.stringify([table.schema, table.name]); }
function dbTarget(table) { return dbQuote(table.schema) + '.' + dbQuote(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 dbColumnSql(column) { return dbQuote(column.name) + ' ' + column.type + (column.nullable ? '' : ' NOT NULL') + (column.default === undefined ? '' : ' DEFAULT ' + column.default); }
function dbConstraintSql(constraint) {
let body;
if (constraint.type === 'check')
body = 'CHECK (' + constraint.check + ')';
else {
body = constraint.type.toUpperCase() + ' (' + constraint.columns.map(dbQuote).join(', ') + ')';
if (constraint.type === 'foreign key') {
const [schema, name] = JSON.parse(constraint.target);
body += ' REFERENCES ' + dbTarget({ schema, name }) + ' (' + constraint.references.map(dbQuote).join(', ') + ') ON DELETE ' + constraint.onDelete.toUpperCase() + ' ON UPDATE ' + constraint.onUpdate.toUpperCase();
}
}
return 'CONSTRAINT ' + dbQuote(constraint.name) + ' ' + body;
}
function dbCreateSql(table) { return 'CREATE TABLE ' + dbTarget(table) + ' (\n ' + [...table.columns.map(dbColumnSql), ...table.constraints.filter(item => item.type !== 'foreign key').map(dbConstraintSql)].join(',\n ') + '\n);'; }
function dbIndexSql(table, index) { return 'CREATE ' + (index.unique ? 'UNIQUE ' : '') + 'INDEX ' + dbQuote(index.name) + ' ON ' + dbTarget(table) + ' (' + index.columns.map(dbQuote).join(', ') + ');'; }
function dbOutput(output) { if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.'); return output; }
function compareDbSchemas(before, after) {
const changes = [];
const old = new Map(before.map(t => [dbKey(t), t])), next = new Map(after.map(t => [dbKey(t), t]));
for (const table of before)
if (!next.has(dbKey(table)))
changes.push({ table: dbTarget(table), kind: 'tabela removida', name: table.name, before: table, destructive: true });
for (const table of after) {
const previous = old.get(dbKey(table));
if (!previous) {
changes.push({ table: dbTarget(table), kind: 'tabela adicionada', name: table.name, after: table, destructive: false });
continue;
}
for (const [key, label] of [['columns', 'coluna'], ['constraints', 'constraint'], ['indexes', 'índice']]) {
const left = new Map(previous[key].map(item => [item.name, item])), right = new Map(table[key].map(item => [item.name, item]));
for (const [name, item] of left)
if (!right.has(name))
changes.push({ table: dbTarget(table), kind: label + ' removido(a)', name, before: item, destructive: label === 'coluna' });
for (const [name, item] of right)
if (!left.has(name))
changes.push({ table: dbTarget(table), kind: label + ' adicionado(a)', name, after: item, destructive: false });
else if (JSON.stringify(left.get(name)) !== JSON.stringify(item))
changes.push({ table: dbTarget(table), kind: label + ' alterado(a)', name, before: left.get(name), after: item, destructive: label === 'coluna' });
}
if (JSON.stringify(previous.columns.map(c => c.name).filter(n => table.columns.some(c => c.name === n))) !== JSON.stringify(table.columns.map(c => c.name).filter(n => previous.columns.some(c => c.name === n))))
changes.push({ table: dbTarget(table), kind: 'ordem das colunas alterada', name: table.name, destructive: false });
}
return changes;
}
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 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 generateDatabaseMigration(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"];
}