JavaScript Python PHP
import { parse } from "pgsql-ast-parser";
import { locationOf, toSql } from "pgsql-ast-parser";
function executar(values) {
function generateDatabaseModels(values) {
const schema = readDbSchema(values.input);
if (schema.some(t => t.schema !== 'public'))
throw new Error('Models Prisma nesta versão aceitam somente schema public; multiSchema exige configuração específica.');
const valid = (name) => /^[A-Za-z][A-Za-z0-9_]*$/.test(name) && !['model', 'enum', 'type', 'String', 'Int', 'Boolean', 'Float', 'Decimal', 'DateTime', 'BigInt', 'Json', 'Bytes'].includes(name);
const used = new Set();
for (const table of schema) {
if (!valid(table.name) || table.columns.some(c => !valid(c.name)))
throw new Error('Prisma exige nomes de models/campos válidos e sem palavras reservadas. Nenhum nome é renomeado silenciosamente.');
if (!table.constraints.some(c => ['primary key', 'unique'].includes(c.type) && c.columns.every(name => !table.columns.find(col => col.name === name).nullable)) && !table.indexes.some(i => i.unique && i.columns.every(name => !table.columns.find(col => col.name === name).nullable)))
throw new Error('Prisma exige PK ou UNIQUE com campos não nulos: ' + table.name);
used.add(table.name);
}
const relationFields = new Map(schema.map(t => [dbKey(t), new Set(t.columns.map(c => c.name))]));
const additions = new Map(schema.map(t => [dbKey(t), []]));
let index = 0;
for (const table of schema)
for (const fk of table.constraints.filter(c => c.type === 'foreign key')) {
const parent = schema.find(t => dbKey(t) === fk.target), id = 'Rel' + index++, out = 'relation_' + id, back = 'related_' + id;
if (relationFields.get(dbKey(table)).has(out) || relationFields.get(dbKey(parent)).has(back))
throw new Error('Conflito com nome de relação gerada: ' + out);
const unique = [...table.constraints.filter(c => ['primary key', 'unique'].includes(c.type)), ...table.indexes.filter(i => i.unique)].some(c => JSON.stringify(c.columns) === JSON.stringify(fk.columns));
const nullable = fk.columns.some(name => table.columns.find(c => c.name === name).nullable);
const action = (name) => ({ 'no action': 'NoAction', restrict: 'Restrict', cascade: 'Cascade', 'set null': 'SetNull', 'set default': 'SetDefault' }[name]);
if (fk.onDelete === 'set default' || fk.onUpdate === 'set default')
throw new Error('SET DEFAULT não é representado automaticamente nos models Prisma.');
additions.get(dbKey(table)).push(' ' + out + ' ' + parent.name + (nullable ? '?' : '') + ' @relation(' + JSON.stringify(id) + ', fields: [' + fk.columns.join(', ') + '], references: [' + fk.references.join(', ') + '], onDelete: ' + action(fk.onDelete) + ', onUpdate: ' + action(fk.onUpdate) + ', map: ' + JSON.stringify(fk.name) + ')');
additions.get(dbKey(parent)).push(' ' + back + ' ' + table.name + (unique ? '?' : '[]') + ' @relation(' + JSON.stringify(id) + ')');
}
const models = schema.map(table => {
const lines = ['model ' + table.name + ' {'];
for (const column of table.columns) {
const type = dbBase(column.type);
let prisma, native = '';
if (type === 'integer')
prisma = 'Int';
else if (type === 'smallint') {
prisma = 'Int';
native = ' @db.SmallInt';
}
else if (type === 'bigint')
prisma = 'BigInt';
else if (type === 'boolean')
prisma = 'Boolean';
else if (type === 'text') {
prisma = 'String';
native = ' @db.Text';
}
else if (type.startsWith('varchar(')) {
prisma = 'String';
native = ' @db.VarChar(' + type.slice(8, -1) + ')';
}
else if (type.startsWith('numeric(')) {
prisma = 'Decimal';
native = ' @db.Decimal(' + type.slice(8, -1) + ')';
}
else if (type === 'uuid') {
prisma = 'String';
native = ' @db.Uuid';
}
else if (['json', 'jsonb'].includes(type)) {
prisma = 'Json';
native = type === 'json' ? ' @db.Json' : '';
}
else {
prisma = 'DateTime';
native = ' @db.' + (type === 'date' ? 'Date' : type === 'timestamp' ? 'Timestamp(6)' : 'Timestamptz(6)');
}
let line = ' ' + column.name + ' ' + prisma + (column.nullable ? '?' : '') + native;
if (['serial', 'bigserial'].includes(column.type))
line += ' @default(autoincrement())';
else if (column.default !== undefined)
line += ' @default(dbgenerated(' + JSON.stringify(column.default) + '))';
lines.push(line);
}
lines.push(...additions.get(dbKey(table)));
for (const constraint of table.constraints) {
if (constraint.type === 'check')
lines.push(' // CHECK não suportado por Prisma Schema: ' + JSON.stringify(constraint.name + ' ' + constraint.check));
if (constraint.type === 'primary key' || constraint.type === 'unique')
lines.push(' @@' + (constraint.type === 'primary key' ? 'id' : 'unique') + '([' + constraint.columns.join(', ') + '], map: ' + JSON.stringify(constraint.name) + ')');
}
for (const item of table.indexes)
lines.push(' @@' + (item.unique ? 'unique' : 'index') + '([' + item.columns.join(', ') + '], map: ' + JSON.stringify(item.name) + ')');
lines.push('}');
return lines.join('\n');
});
return dbOutput('// Prisma ORM 6/7, PostgreSQL. Acrescente datasource/generator ao projeto.\n// CHECK aparece apenas em comentários: mantenha essas constraints nas migrations SQL.\n\n' + models.join('\n\n'));
}
function dbKey(table) { return JSON.stringify([table.schema, table.name]); }
function dbBase(type) { return type === 'serial' ? 'integer' : type === 'bigserial' ? 'bigint' : type; }
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 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 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 generateDatabaseModels(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 generateDatabaseModels(values) {
const schema = readDbSchema(values.input);
if (schema.some(t => t.schema !== 'public'))
throw new Error('Models Prisma nesta versão aceitam somente schema public; multiSchema exige configuração específica.');
const valid = (name) => /^[A-Za-z][A-Za-z0-9_]*$/.test(name) && !['model', 'enum', 'type', 'String', 'Int', 'Boolean', 'Float', 'Decimal', 'DateTime', 'BigInt', 'Json', 'Bytes'].includes(name);
const used = new Set();
for (const table of schema) {
if (!valid(table.name) || table.columns.some(c => !valid(c.name)))
throw new Error('Prisma exige nomes de models/campos válidos e sem palavras reservadas. Nenhum nome é renomeado silenciosamente.');
if (!table.constraints.some(c => ['primary key', 'unique'].includes(c.type) && c.columns.every(name => !table.columns.find(col => col.name === name).nullable)) && !table.indexes.some(i => i.unique && i.columns.every(name => !table.columns.find(col => col.name === name).nullable)))
throw new Error('Prisma exige PK ou UNIQUE com campos não nulos: ' + table.name);
used.add(table.name);
}
const relationFields = new Map(schema.map(t => [dbKey(t), new Set(t.columns.map(c => c.name))]));
const additions = new Map(schema.map(t => [dbKey(t), []]));
let index = 0;
for (const table of schema)
for (const fk of table.constraints.filter(c => c.type === 'foreign key')) {
const parent = schema.find(t => dbKey(t) === fk.target), id = 'Rel' + index++, out = 'relation_' + id, back = 'related_' + id;
if (relationFields.get(dbKey(table)).has(out) || relationFields.get(dbKey(parent)).has(back))
throw new Error('Conflito com nome de relação gerada: ' + out);
const unique = [...table.constraints.filter(c => ['primary key', 'unique'].includes(c.type)), ...table.indexes.filter(i => i.unique)].some(c => JSON.stringify(c.columns) === JSON.stringify(fk.columns));
const nullable = fk.columns.some(name => table.columns.find(c => c.name === name).nullable);
const action = (name) => ({ 'no action': 'NoAction', restrict: 'Restrict', cascade: 'Cascade', 'set null': 'SetNull', 'set default': 'SetDefault' }[name]);
if (fk.onDelete === 'set default' || fk.onUpdate === 'set default')
throw new Error('SET DEFAULT não é representado automaticamente nos models Prisma.');
additions.get(dbKey(table)).push(' ' + out + ' ' + parent.name + (nullable ? '?' : '') + ' @relation(' + JSON.stringify(id) + ', fields: [' + fk.columns.join(', ') + '], references: [' + fk.references.join(', ') + '], onDelete: ' + action(fk.onDelete) + ', onUpdate: ' + action(fk.onUpdate) + ', map: ' + JSON.stringify(fk.name) + ')');
additions.get(dbKey(parent)).push(' ' + back + ' ' + table.name + (unique ? '?' : '[]') + ' @relation(' + JSON.stringify(id) + ')');
}
const models = schema.map(table => {
const lines = ['model ' + table.name + ' {'];
for (const column of table.columns) {
const type = dbBase(column.type);
let prisma, native = '';
if (type === 'integer')
prisma = 'Int';
else if (type === 'smallint') {
prisma = 'Int';
native = ' @db.SmallInt';
}
else if (type === 'bigint')
prisma = 'BigInt';
else if (type === 'boolean')
prisma = 'Boolean';
else if (type === 'text') {
prisma = 'String';
native = ' @db.Text';
}
else if (type.startsWith('varchar(')) {
prisma = 'String';
native = ' @db.VarChar(' + type.slice(8, -1) + ')';
}
else if (type.startsWith('numeric(')) {
prisma = 'Decimal';
native = ' @db.Decimal(' + type.slice(8, -1) + ')';
}
else if (type === 'uuid') {
prisma = 'String';
native = ' @db.Uuid';
}
else if (['json', 'jsonb'].includes(type)) {
prisma = 'Json';
native = type === 'json' ? ' @db.Json' : '';
}
else {
prisma = 'DateTime';
native = ' @db.' + (type === 'date' ? 'Date' : type === 'timestamp' ? 'Timestamp(6)' : 'Timestamptz(6)');
}
let line = ' ' + column.name + ' ' + prisma + (column.nullable ? '?' : '') + native;
if (['serial', 'bigserial'].includes(column.type))
line += ' @default(autoincrement())';
else if (column.default !== undefined)
line += ' @default(dbgenerated(' + JSON.stringify(column.default) + '))';
lines.push(line);
}
lines.push(...additions.get(dbKey(table)));
for (const constraint of table.constraints) {
if (constraint.type === 'check')
lines.push(' // CHECK não suportado por Prisma Schema: ' + JSON.stringify(constraint.name + ' ' + constraint.check));
if (constraint.type === 'primary key' || constraint.type === 'unique')
lines.push(' @@' + (constraint.type === 'primary key' ? 'id' : 'unique') + '([' + constraint.columns.join(', ') + '], map: ' + JSON.stringify(constraint.name) + ')');
}
for (const item of table.indexes)
lines.push(' @@' + (item.unique ? 'unique' : 'index') + '([' + item.columns.join(', ') + '], map: ' + JSON.stringify(item.name) + ')');
lines.push('}');
return lines.join('\n');
});
return dbOutput('// Prisma ORM 6/7, PostgreSQL. Acrescente datasource/generator ao projeto.\n// CHECK aparece apenas em comentários: mantenha essas constraints nas migrations SQL.\n\n' + models.join('\n\n'));
}
function dbKey(table) { return JSON.stringify([table.schema, table.name]); }
function dbBase(type) { return type === 'serial' ? 'integer' : type === 'bigserial' ? 'bigint' : type; }
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 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 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 generateDatabaseModels(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 generateDatabaseModels(values) {
const schema = readDbSchema(values.input);
if (schema.some(t => t.schema !== 'public'))
throw new Error('Models Prisma nesta versão aceitam somente schema public; multiSchema exige configuração específica.');
const valid = (name) => /^[A-Za-z][A-Za-z0-9_]*$/.test(name) && !['model', 'enum', 'type', 'String', 'Int', 'Boolean', 'Float', 'Decimal', 'DateTime', 'BigInt', 'Json', 'Bytes'].includes(name);
const used = new Set();
for (const table of schema) {
if (!valid(table.name) || table.columns.some(c => !valid(c.name)))
throw new Error('Prisma exige nomes de models/campos válidos e sem palavras reservadas. Nenhum nome é renomeado silenciosamente.');
if (!table.constraints.some(c => ['primary key', 'unique'].includes(c.type) && c.columns.every(name => !table.columns.find(col => col.name === name).nullable)) && !table.indexes.some(i => i.unique && i.columns.every(name => !table.columns.find(col => col.name === name).nullable)))
throw new Error('Prisma exige PK ou UNIQUE com campos não nulos: ' + table.name);
used.add(table.name);
}
const relationFields = new Map(schema.map(t => [dbKey(t), new Set(t.columns.map(c => c.name))]));
const additions = new Map(schema.map(t => [dbKey(t), []]));
let index = 0;
for (const table of schema)
for (const fk of table.constraints.filter(c => c.type === 'foreign key')) {
const parent = schema.find(t => dbKey(t) === fk.target), id = 'Rel' + index++, out = 'relation_' + id, back = 'related_' + id;
if (relationFields.get(dbKey(table)).has(out) || relationFields.get(dbKey(parent)).has(back))
throw new Error('Conflito com nome de relação gerada: ' + out);
const unique = [...table.constraints.filter(c => ['primary key', 'unique'].includes(c.type)), ...table.indexes.filter(i => i.unique)].some(c => JSON.stringify(c.columns) === JSON.stringify(fk.columns));
const nullable = fk.columns.some(name => table.columns.find(c => c.name === name).nullable);
const action = (name) => ({ 'no action': 'NoAction', restrict: 'Restrict', cascade: 'Cascade', 'set null': 'SetNull', 'set default': 'SetDefault' }[name]);
if (fk.onDelete === 'set default' || fk.onUpdate === 'set default')
throw new Error('SET DEFAULT não é representado automaticamente nos models Prisma.');
additions.get(dbKey(table)).push(' ' + out + ' ' + parent.name + (nullable ? '?' : '') + ' @relation(' + JSON.stringify(id) + ', fields: [' + fk.columns.join(', ') + '], references: [' + fk.references.join(', ') + '], onDelete: ' + action(fk.onDelete) + ', onUpdate: ' + action(fk.onUpdate) + ', map: ' + JSON.stringify(fk.name) + ')');
additions.get(dbKey(parent)).push(' ' + back + ' ' + table.name + (unique ? '?' : '[]') + ' @relation(' + JSON.stringify(id) + ')');
}
const models = schema.map(table => {
const lines = ['model ' + table.name + ' {'];
for (const column of table.columns) {
const type = dbBase(column.type);
let prisma, native = '';
if (type === 'integer')
prisma = 'Int';
else if (type === 'smallint') {
prisma = 'Int';
native = ' @db.SmallInt';
}
else if (type === 'bigint')
prisma = 'BigInt';
else if (type === 'boolean')
prisma = 'Boolean';
else if (type === 'text') {
prisma = 'String';
native = ' @db.Text';
}
else if (type.startsWith('varchar(')) {
prisma = 'String';
native = ' @db.VarChar(' + type.slice(8, -1) + ')';
}
else if (type.startsWith('numeric(')) {
prisma = 'Decimal';
native = ' @db.Decimal(' + type.slice(8, -1) + ')';
}
else if (type === 'uuid') {
prisma = 'String';
native = ' @db.Uuid';
}
else if (['json', 'jsonb'].includes(type)) {
prisma = 'Json';
native = type === 'json' ? ' @db.Json' : '';
}
else {
prisma = 'DateTime';
native = ' @db.' + (type === 'date' ? 'Date' : type === 'timestamp' ? 'Timestamp(6)' : 'Timestamptz(6)');
}
let line = ' ' + column.name + ' ' + prisma + (column.nullable ? '?' : '') + native;
if (['serial', 'bigserial'].includes(column.type))
line += ' @default(autoincrement())';
else if (column.default !== undefined)
line += ' @default(dbgenerated(' + JSON.stringify(column.default) + '))';
lines.push(line);
}
lines.push(...additions.get(dbKey(table)));
for (const constraint of table.constraints) {
if (constraint.type === 'check')
lines.push(' // CHECK não suportado por Prisma Schema: ' + JSON.stringify(constraint.name + ' ' + constraint.check));
if (constraint.type === 'primary key' || constraint.type === 'unique')
lines.push(' @@' + (constraint.type === 'primary key' ? 'id' : 'unique') + '([' + constraint.columns.join(', ') + '], map: ' + JSON.stringify(constraint.name) + ')');
}
for (const item of table.indexes)
lines.push(' @@' + (item.unique ? 'unique' : 'index') + '([' + item.columns.join(', ') + '], map: ' + JSON.stringify(item.name) + ')');
lines.push('}');
return lines.join('\n');
});
return dbOutput('// Prisma ORM 6/7, PostgreSQL. Acrescente datasource/generator ao projeto.\n// CHECK aparece apenas em comentários: mantenha essas constraints nas migrations SQL.\n\n' + models.join('\n\n'));
}
function dbKey(table) { return JSON.stringify([table.schema, table.name]); }
function dbBase(type) { return type === 'serial' ? 'integer' : type === 'bigserial' ? 'bigint' : type; }
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 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 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 generateDatabaseModels(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"];
}