JavaScript Python PHP
import { format } from "sql-formatter";
import { parse } from "pgsql-ast-parser";
import { locationOf, toSql } from "pgsql-ast-parser";
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
function executar(values) {
function buildDatabaseTable(values) {
const name = dbString(values.table, 'Tabela'), schema = values.schema || 'public';
dbQuote(name);
dbQuote(schema);
const config = dbObject(dbJson(values.definition));
dbKeys(config, ['columns', 'constraints', 'indexes']);
if (!Array.isArray(config.columns) || !config.columns.length || config.columns.length > 100)
throw new Error('Defina de 1 a 100 colunas.');
const columns = config.columns.map(item => {
const column = dbObject(item);
dbKeys(column, ['name', 'type', 'nullable', 'default']);
if (column.nullable !== undefined && typeof column.nullable !== 'boolean')
throw new Error('nullable deve ser booleano.');
const name = dbString(column.name, 'Coluna'), type = dbType(dbString(column.type, 'Tipo'));
// Parse the type in isolation; SQL fragments cannot escape a configured type.
const typeAst = parse('CREATE TABLE "t" ("c" ' + type + ');');
if (typeAst.length !== 1 || typeAst[0].type !== 'create table' || typeAst[0].columns.length !== 1 || typeAst[0].columns[0].kind !== 'column' || typeAst[0].columns[0].constraints?.length)
throw new Error('Tipo deve conter apenas um tipo SQL, sem constraints ou comandos.');
return dbQuote(name) + ' ' + type + (column.nullable === false ? ' NOT NULL' : '') + (Object.hasOwn(column, 'default') ? ' DEFAULT ' + dbLiteral(column.default) : '');
});
const array = (value, label) => { if (value === undefined)
return []; if (!Array.isArray(value) || value.length > 100)
throw new Error(label + ': use uma lista de até 100 itens.'); return value; };
const names = (value) => { if (!Array.isArray(value) || !value.length || value.some(item => typeof item !== 'string'))
throw new Error('columns deve ser lista não vazia de nomes.'); return value.map(dbQuote).join(', '); };
const constraints = array(config.constraints, 'Constraints').map(item => {
const constraint = dbObject(item);
dbKeys(constraint, ['name', 'type', 'columns', 'references', 'expression', 'onDelete', 'onUpdate']);
const type = dbString(constraint.type, 'Tipo de constraint').toUpperCase();
const prefix = constraint.name === undefined ? '' : 'CONSTRAINT ' + dbQuote(dbString(constraint.name, 'Nome da constraint')) + ' ';
if (type === 'CHECK') {
if (constraint.columns !== undefined || constraint.references !== undefined || constraint.onDelete !== undefined || constraint.onUpdate !== undefined)
throw new Error('CHECK aceita somente name, type e expression.');
const expression = dbString(constraint.expression, 'Expressão CHECK');
const probe = readDbSchema('CREATE TABLE ' + dbTarget({ schema, name }) + ' (' + columns.join(', ') + ', CHECK (' + expression + '));');
if (probe.length !== 1 || probe[0].constraints.length !== 1 || probe[0].constraints[0].type !== 'check')
throw new Error('Expressão CHECK inválida.');
return prefix + 'CHECK (' + probe[0].constraints[0].check + ')';
}
if (!['PRIMARY KEY', 'UNIQUE', 'FOREIGN KEY'].includes(type))
throw new Error('Constraint deve ser PRIMARY KEY, UNIQUE, FOREIGN KEY ou CHECK.');
let sql = prefix + type + ' (' + names(constraint.columns) + ')';
if (type === 'FOREIGN KEY') {
if (constraint.expression !== undefined)
throw new Error('FOREIGN KEY não aceita expression.');
const target = dbObject(constraint.references);
dbKeys(target, ['schema', 'table', 'columns']);
sql += ' REFERENCES ' + dbTarget({ schema: target.schema === undefined ? schema : dbString(target.schema, 'Schema da FK'), name: dbString(target.table, 'Tabela da FK') }) + ' (' + names(target.columns) + ')';
for (const [key, label] of [['onDelete', 'ON DELETE'], ['onUpdate', 'ON UPDATE']])
if (constraint[key] !== undefined) {
const action = dbString(constraint[key], key).toUpperCase();
if (!['NO ACTION', 'RESTRICT', 'CASCADE', 'SET NULL', 'SET DEFAULT'].includes(action))
throw new Error('Ação referencial inválida.');
sql += ' ' + label + ' ' + action;
}
}
else if (constraint.references !== undefined || constraint.expression !== undefined || constraint.onDelete !== undefined || constraint.onUpdate !== undefined)
throw new Error('Configuração não aplicável à constraint.');
return sql;
});
const indexes = array(config.indexes, 'Índices').map(item => { const index = dbObject(item); dbKeys(index, ['name', 'columns', 'unique']); if (index.unique !== undefined && typeof index.unique !== 'boolean')
throw new Error('unique deve ser booleano.'); return 'CREATE ' + (index.unique ? 'UNIQUE ' : '') + 'INDEX ' + dbQuote(dbString(index.name, 'Índice')) + ' ON ' + dbTarget({ schema, name }) + ' (' + names(index.columns) + ');'; });
const sql = 'CREATE TABLE ' + dbTarget({ schema, name }) + ' (\n ' + [...columns, ...constraints].join(',\n ') + '\n);' + (indexes.length ? '\n\n' + indexes.join('\n') : '');
// External reference definitions are required for semantic validation, never emitted.
const context = values.context?.trim() || '';
const model = readDbSchema((context ? context + '\n' : '') + sql);
const table = model.find(t => t.schema === schema && t.name === name);
return dbOutput([dbCreateSql(table), ...table.indexes.map(index => dbIndexSql(table, index)), ...table.constraints.filter(c => c.type === 'foreign key').map(c => 'ALTER TABLE ' + dbTarget(table) + ' ADD ' + dbConstraintSql(c) + ';')].join('\n\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 dbTarget(table) { return dbQuote(table.schema) + '.' + dbQuote(table.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 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 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 dbJson(input) { return parseJsonCompatible(dbText(input), 'JSON'); }
function dbObject(value) {
if (!value || typeof value !== 'object' || Array.isArray(value))
throw new Error('Informe um objeto JSON.');
return value;
}
function dbKeys(value, keys) { for (const key of Object.keys(value))
if (!keys.includes(key))
throw new Error('Propriedade não suportada: ' + key); }
function dbString(value, label) { if (typeof value !== 'string' || !value)
throw new Error(label + ': informe texto não vazio.'); return dbText(value, label); }
function dbOutput(output) { if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.'); return output; }
function dbLiteral(value) {
if (value === null)
return 'NULL';
if (typeof value === 'boolean')
return value ? 'TRUE' : 'FALSE';
if (typeof value === 'number') {
if (!Number.isFinite(value) || Math.abs(value) > Number.MAX_SAFE_INTEGER)
throw new Error('Número fora do intervalo seguro.');
return String(value);
}
const text = dbText(typeof value === 'string' ? value : JSON.stringify(value));
return "'" + text.replace(/'/g, "''") + "'";
}
function dbText(input, label = 'Entrada') {
if (typeof input !== 'string' || input.length > 100_000)
throw new Error(label + ': limite de 100 mil caracteres.');
if (/[\0]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(input))
throw new Error(label + ': NUL e Unicode inválido não são aceitos.');
return input;
}
function dbKey(table) { return JSON.stringify([table.schema, table.name]); }
function dbName(name) { return name.name.replace(/""/g, '"'); }
function dbReference(name) { return dbKey({ schema: name.schema?.replace(/""/g, '"') ?? 'public', name: dbName(name) }); }
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);
}
function dbColumnSql(column) { return dbQuote(column.name) + ' ' + column.type + (column.nullable ? '' : ' NOT NULL') + (column.default === undefined ? '' : ' DEFAULT ' + column.default); }
function parseJsonCompatible(input, format, onObjectKeys) {
if (!input.trim())
throw new Error(`Informe um documento ${format}.`);
if (input.length > 1_000_000)
throw new Error('A entrada excede o limite de 1 milhão de caracteres.');
if (format === 'JSON') {
// Syntax check only: do not use the rounded numeric values from JSON.parse.
try {
JSON.parse(input);
}
catch (cause) {
throw new Error(`JSON inválido: ${cause instanceof Error ? cause.message : 'erro de sintaxe'}`);
}
}
const lines = new LineCounter();
const doc = parseDocument(input, { version: '1.2', schema: format === 'JSON' ? 'json' : 'core', intAsBigInt: true, uniqueKeys: true, lineCounter: lines, prettyErrors: true, resolveKnownTags: false });
const issue = doc.errors[0] ?? doc.warnings[0];
if (issue)
throw new Error(`${format} inválido (${issue.code}): ${issue.message}`);
if (doc.directives?.yaml.version !== '1.2')
throw new Error('Somente YAML 1.2 é aceito para preservar os tipos de JSON.');
let count = 0;
function fail(message, node) {
const offset = node?.range?.[0];
const position = offset === undefined ? '' : (() => { const { line, col } = lines.linePos(offset); return ` (linha ${line}, coluna ${col})`; })();
throw new Error(message + position);
}
function convert(node, depth = 0) {
if (++count > 100_000 || depth > 100)
fail('Documento muito complexo: limite de 100 níveis ou 100 mil nós.', node);
if (!node)
return null;
if (isAlias(node))
fail('Aliases YAML não são aceitos: JSON não preserva referências ou ciclos.', node);
if (node.tag && !SAFE_TAGS.has(node.tag))
fail(`Tag não permitida: ${node.tag}.`, node);
if (isScalar(node)) {
const value = node.value;
if (typeof value === 'bigint') {
if (value === BigInt(0) && node.source?.startsWith('-'))
fail('JSON de saída não preserva o sinal de zero negativo. Use 0 ou uma string.', node);
if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER))
fail('Inteiro fora do intervalo seguro de JSON/JavaScript. Use uma string entre aspas para preservar todos os dígitos.', node);
return Number(value);
}
if (typeof value === 'number') {
if (!Number.isFinite(value))
fail('JSON não representa NaN ou infinito.', node);
if (Number.isInteger(value) && !Number.isSafeInteger(value))
fail('Número inteiro fora do intervalo seguro. Use uma string entre aspas para preservar a precisão.', node);
if (value === 0 && /[1-9]/.test((node.source ?? '').split(/[eE]/)[0]))
fail('Número pequeno demais para a precisão de JavaScript. Use uma string entre aspas.', node);
if (Object.is(value, -0))
fail('JSON de saída não preserva o sinal de zero negativo. Use 0 ou uma string.', node);
return value;
}
if (value === null || typeof value === 'string' || typeof value === 'boolean')
return value;
fail('Valor não representável em JSON.', node);
}
if (isSeq(node))
return node.items.map(item => convert(item, depth + 1));
if (isMap(node)) {
const result = Object.create(null);
const keys = [];
for (const pair of node.items) {
if (!isScalar(pair.key) || typeof pair.key.value !== 'string')
fail('Chaves de objetos devem ser strings; chaves numéricas, booleanas ou complexas não são preservadas em JSON.', pair.key);
const key = pair.key.value;
if (format === 'YAML' && key === '<<' && pair.key.type === 'PLAIN')
fail('Chaves de merge YAML (<<) não são aceitas.', pair.key);
if (Object.hasOwn(result, key))
fail(`Chave duplicada: ${key}.`, pair.key);
keys.push(key);
result[key] = convert(pair.value, depth + 1);
}
onObjectKeys?.(result, keys);
return result;
}
fail('Estrutura não representável em JSON.', node);
}
if (!doc.contents)
throw new Error('Informe um documento com um valor; use null para um valor nulo.');
return convert(doc.contents);
}
const SAFE_TAGS = new Set(['str', 'bool', 'null', 'int', 'float', 'map', 'seq'].map(tag => `tag:yaml.org,2002:${tag}`));
for (const value of Object.values(values)) dbText(value);
return buildDatabaseTable(values);
}
import json
import subprocess
def executar(values):
# Requer Node.js 22+ e os pacotes npm indicados no código abaixo.
source = r'''
import { format } from "sql-formatter";
import { parse } from "pgsql-ast-parser";
import { locationOf, toSql } from "pgsql-ast-parser";
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
function executar(values) {
function buildDatabaseTable(values) {
const name = dbString(values.table, 'Tabela'), schema = values.schema || 'public';
dbQuote(name);
dbQuote(schema);
const config = dbObject(dbJson(values.definition));
dbKeys(config, ['columns', 'constraints', 'indexes']);
if (!Array.isArray(config.columns) || !config.columns.length || config.columns.length > 100)
throw new Error('Defina de 1 a 100 colunas.');
const columns = config.columns.map(item => {
const column = dbObject(item);
dbKeys(column, ['name', 'type', 'nullable', 'default']);
if (column.nullable !== undefined && typeof column.nullable !== 'boolean')
throw new Error('nullable deve ser booleano.');
const name = dbString(column.name, 'Coluna'), type = dbType(dbString(column.type, 'Tipo'));
// Parse the type in isolation; SQL fragments cannot escape a configured type.
const typeAst = parse('CREATE TABLE "t" ("c" ' + type + ');');
if (typeAst.length !== 1 || typeAst[0].type !== 'create table' || typeAst[0].columns.length !== 1 || typeAst[0].columns[0].kind !== 'column' || typeAst[0].columns[0].constraints?.length)
throw new Error('Tipo deve conter apenas um tipo SQL, sem constraints ou comandos.');
return dbQuote(name) + ' ' + type + (column.nullable === false ? ' NOT NULL' : '') + (Object.hasOwn(column, 'default') ? ' DEFAULT ' + dbLiteral(column.default) : '');
});
const array = (value, label) => { if (value === undefined)
return []; if (!Array.isArray(value) || value.length > 100)
throw new Error(label + ': use uma lista de até 100 itens.'); return value; };
const names = (value) => { if (!Array.isArray(value) || !value.length || value.some(item => typeof item !== 'string'))
throw new Error('columns deve ser lista não vazia de nomes.'); return value.map(dbQuote).join(', '); };
const constraints = array(config.constraints, 'Constraints').map(item => {
const constraint = dbObject(item);
dbKeys(constraint, ['name', 'type', 'columns', 'references', 'expression', 'onDelete', 'onUpdate']);
const type = dbString(constraint.type, 'Tipo de constraint').toUpperCase();
const prefix = constraint.name === undefined ? '' : 'CONSTRAINT ' + dbQuote(dbString(constraint.name, 'Nome da constraint')) + ' ';
if (type === 'CHECK') {
if (constraint.columns !== undefined || constraint.references !== undefined || constraint.onDelete !== undefined || constraint.onUpdate !== undefined)
throw new Error('CHECK aceita somente name, type e expression.');
const expression = dbString(constraint.expression, 'Expressão CHECK');
const probe = readDbSchema('CREATE TABLE ' + dbTarget({ schema, name }) + ' (' + columns.join(', ') + ', CHECK (' + expression + '));');
if (probe.length !== 1 || probe[0].constraints.length !== 1 || probe[0].constraints[0].type !== 'check')
throw new Error('Expressão CHECK inválida.');
return prefix + 'CHECK (' + probe[0].constraints[0].check + ')';
}
if (!['PRIMARY KEY', 'UNIQUE', 'FOREIGN KEY'].includes(type))
throw new Error('Constraint deve ser PRIMARY KEY, UNIQUE, FOREIGN KEY ou CHECK.');
let sql = prefix + type + ' (' + names(constraint.columns) + ')';
if (type === 'FOREIGN KEY') {
if (constraint.expression !== undefined)
throw new Error('FOREIGN KEY não aceita expression.');
const target = dbObject(constraint.references);
dbKeys(target, ['schema', 'table', 'columns']);
sql += ' REFERENCES ' + dbTarget({ schema: target.schema === undefined ? schema : dbString(target.schema, 'Schema da FK'), name: dbString(target.table, 'Tabela da FK') }) + ' (' + names(target.columns) + ')';
for (const [key, label] of [['onDelete', 'ON DELETE'], ['onUpdate', 'ON UPDATE']])
if (constraint[key] !== undefined) {
const action = dbString(constraint[key], key).toUpperCase();
if (!['NO ACTION', 'RESTRICT', 'CASCADE', 'SET NULL', 'SET DEFAULT'].includes(action))
throw new Error('Ação referencial inválida.');
sql += ' ' + label + ' ' + action;
}
}
else if (constraint.references !== undefined || constraint.expression !== undefined || constraint.onDelete !== undefined || constraint.onUpdate !== undefined)
throw new Error('Configuração não aplicável à constraint.');
return sql;
});
const indexes = array(config.indexes, 'Índices').map(item => { const index = dbObject(item); dbKeys(index, ['name', 'columns', 'unique']); if (index.unique !== undefined && typeof index.unique !== 'boolean')
throw new Error('unique deve ser booleano.'); return 'CREATE ' + (index.unique ? 'UNIQUE ' : '') + 'INDEX ' + dbQuote(dbString(index.name, 'Índice')) + ' ON ' + dbTarget({ schema, name }) + ' (' + names(index.columns) + ');'; });
const sql = 'CREATE TABLE ' + dbTarget({ schema, name }) + ' (\n ' + [...columns, ...constraints].join(',\n ') + '\n);' + (indexes.length ? '\n\n' + indexes.join('\n') : '');
// External reference definitions are required for semantic validation, never emitted.
const context = values.context?.trim() || '';
const model = readDbSchema((context ? context + '\n' : '') + sql);
const table = model.find(t => t.schema === schema && t.name === name);
return dbOutput([dbCreateSql(table), ...table.indexes.map(index => dbIndexSql(table, index)), ...table.constraints.filter(c => c.type === 'foreign key').map(c => 'ALTER TABLE ' + dbTarget(table) + ' ADD ' + dbConstraintSql(c) + ';')].join('\n\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 dbTarget(table) { return dbQuote(table.schema) + '.' + dbQuote(table.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 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 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 dbJson(input) { return parseJsonCompatible(dbText(input), 'JSON'); }
function dbObject(value) {
if (!value || typeof value !== 'object' || Array.isArray(value))
throw new Error('Informe um objeto JSON.');
return value;
}
function dbKeys(value, keys) { for (const key of Object.keys(value))
if (!keys.includes(key))
throw new Error('Propriedade não suportada: ' + key); }
function dbString(value, label) { if (typeof value !== 'string' || !value)
throw new Error(label + ': informe texto não vazio.'); return dbText(value, label); }
function dbOutput(output) { if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.'); return output; }
function dbLiteral(value) {
if (value === null)
return 'NULL';
if (typeof value === 'boolean')
return value ? 'TRUE' : 'FALSE';
if (typeof value === 'number') {
if (!Number.isFinite(value) || Math.abs(value) > Number.MAX_SAFE_INTEGER)
throw new Error('Número fora do intervalo seguro.');
return String(value);
}
const text = dbText(typeof value === 'string' ? value : JSON.stringify(value));
return "'" + text.replace(/'/g, "''") + "'";
}
function dbText(input, label = 'Entrada') {
if (typeof input !== 'string' || input.length > 100_000)
throw new Error(label + ': limite de 100 mil caracteres.');
if (/[\0]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(input))
throw new Error(label + ': NUL e Unicode inválido não são aceitos.');
return input;
}
function dbKey(table) { return JSON.stringify([table.schema, table.name]); }
function dbName(name) { return name.name.replace(/""/g, '"'); }
function dbReference(name) { return dbKey({ schema: name.schema?.replace(/""/g, '"') ?? 'public', name: dbName(name) }); }
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);
}
function dbColumnSql(column) { return dbQuote(column.name) + ' ' + column.type + (column.nullable ? '' : ' NOT NULL') + (column.default === undefined ? '' : ' DEFAULT ' + column.default); }
function parseJsonCompatible(input, format, onObjectKeys) {
if (!input.trim())
throw new Error(`Informe um documento ${format}.`);
if (input.length > 1_000_000)
throw new Error('A entrada excede o limite de 1 milhão de caracteres.');
if (format === 'JSON') {
// Syntax check only: do not use the rounded numeric values from JSON.parse.
try {
JSON.parse(input);
}
catch (cause) {
throw new Error(`JSON inválido: ${cause instanceof Error ? cause.message : 'erro de sintaxe'}`);
}
}
const lines = new LineCounter();
const doc = parseDocument(input, { version: '1.2', schema: format === 'JSON' ? 'json' : 'core', intAsBigInt: true, uniqueKeys: true, lineCounter: lines, prettyErrors: true, resolveKnownTags: false });
const issue = doc.errors[0] ?? doc.warnings[0];
if (issue)
throw new Error(`${format} inválido (${issue.code}): ${issue.message}`);
if (doc.directives?.yaml.version !== '1.2')
throw new Error('Somente YAML 1.2 é aceito para preservar os tipos de JSON.');
let count = 0;
function fail(message, node) {
const offset = node?.range?.[0];
const position = offset === undefined ? '' : (() => { const { line, col } = lines.linePos(offset); return ` (linha ${line}, coluna ${col})`; })();
throw new Error(message + position);
}
function convert(node, depth = 0) {
if (++count > 100_000 || depth > 100)
fail('Documento muito complexo: limite de 100 níveis ou 100 mil nós.', node);
if (!node)
return null;
if (isAlias(node))
fail('Aliases YAML não são aceitos: JSON não preserva referências ou ciclos.', node);
if (node.tag && !SAFE_TAGS.has(node.tag))
fail(`Tag não permitida: ${node.tag}.`, node);
if (isScalar(node)) {
const value = node.value;
if (typeof value === 'bigint') {
if (value === BigInt(0) && node.source?.startsWith('-'))
fail('JSON de saída não preserva o sinal de zero negativo. Use 0 ou uma string.', node);
if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER))
fail('Inteiro fora do intervalo seguro de JSON/JavaScript. Use uma string entre aspas para preservar todos os dígitos.', node);
return Number(value);
}
if (typeof value === 'number') {
if (!Number.isFinite(value))
fail('JSON não representa NaN ou infinito.', node);
if (Number.isInteger(value) && !Number.isSafeInteger(value))
fail('Número inteiro fora do intervalo seguro. Use uma string entre aspas para preservar a precisão.', node);
if (value === 0 && /[1-9]/.test((node.source ?? '').split(/[eE]/)[0]))
fail('Número pequeno demais para a precisão de JavaScript. Use uma string entre aspas.', node);
if (Object.is(value, -0))
fail('JSON de saída não preserva o sinal de zero negativo. Use 0 ou uma string.', node);
return value;
}
if (value === null || typeof value === 'string' || typeof value === 'boolean')
return value;
fail('Valor não representável em JSON.', node);
}
if (isSeq(node))
return node.items.map(item => convert(item, depth + 1));
if (isMap(node)) {
const result = Object.create(null);
const keys = [];
for (const pair of node.items) {
if (!isScalar(pair.key) || typeof pair.key.value !== 'string')
fail('Chaves de objetos devem ser strings; chaves numéricas, booleanas ou complexas não são preservadas em JSON.', pair.key);
const key = pair.key.value;
if (format === 'YAML' && key === '<<' && pair.key.type === 'PLAIN')
fail('Chaves de merge YAML (<<) não são aceitas.', pair.key);
if (Object.hasOwn(result, key))
fail(`Chave duplicada: ${key}.`, pair.key);
keys.push(key);
result[key] = convert(pair.value, depth + 1);
}
onObjectKeys?.(result, keys);
return result;
}
fail('Estrutura não representável em JSON.', node);
}
if (!doc.contents)
throw new Error('Informe um documento com um valor; use null para um valor nulo.');
return convert(doc.contents);
}
const SAFE_TAGS = new Set(['str', 'bool', 'null', 'int', 'float', 'map', 'seq'].map(tag => `tag:yaml.org,2002:${tag}`));
for (const value of Object.values(values)) dbText(value);
return buildDatabaseTable(values);
}
let input = "";
for await (const chunk of process.stdin) input += chunk;
try { process.stdout.write(JSON.stringify({ok: true, result: executar(JSON.parse(input))})); }
catch (error) { process.stdout.write(JSON.stringify({ok: false, error: error.message})); }
'''
payload = json.dumps(values, ensure_ascii=True)
process = subprocess.run(["node", "--input-type=module", "-e", source], input=payload, capture_output=True, text=True, timeout=10, check=True)
response = json.loads(process.stdout)
if not response["ok"]:
raise ValueError(response["error"])
return response["result"]
<?php
function executar(array $values): string {
// Requer Node.js 22+ e os pacotes npm indicados no código abaixo.
$source = <<<'JAVASCRIPT'
import { format } from "sql-formatter";
import { parse } from "pgsql-ast-parser";
import { locationOf, toSql } from "pgsql-ast-parser";
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
function executar(values) {
function buildDatabaseTable(values) {
const name = dbString(values.table, 'Tabela'), schema = values.schema || 'public';
dbQuote(name);
dbQuote(schema);
const config = dbObject(dbJson(values.definition));
dbKeys(config, ['columns', 'constraints', 'indexes']);
if (!Array.isArray(config.columns) || !config.columns.length || config.columns.length > 100)
throw new Error('Defina de 1 a 100 colunas.');
const columns = config.columns.map(item => {
const column = dbObject(item);
dbKeys(column, ['name', 'type', 'nullable', 'default']);
if (column.nullable !== undefined && typeof column.nullable !== 'boolean')
throw new Error('nullable deve ser booleano.');
const name = dbString(column.name, 'Coluna'), type = dbType(dbString(column.type, 'Tipo'));
// Parse the type in isolation; SQL fragments cannot escape a configured type.
const typeAst = parse('CREATE TABLE "t" ("c" ' + type + ');');
if (typeAst.length !== 1 || typeAst[0].type !== 'create table' || typeAst[0].columns.length !== 1 || typeAst[0].columns[0].kind !== 'column' || typeAst[0].columns[0].constraints?.length)
throw new Error('Tipo deve conter apenas um tipo SQL, sem constraints ou comandos.');
return dbQuote(name) + ' ' + type + (column.nullable === false ? ' NOT NULL' : '') + (Object.hasOwn(column, 'default') ? ' DEFAULT ' + dbLiteral(column.default) : '');
});
const array = (value, label) => { if (value === undefined)
return []; if (!Array.isArray(value) || value.length > 100)
throw new Error(label + ': use uma lista de até 100 itens.'); return value; };
const names = (value) => { if (!Array.isArray(value) || !value.length || value.some(item => typeof item !== 'string'))
throw new Error('columns deve ser lista não vazia de nomes.'); return value.map(dbQuote).join(', '); };
const constraints = array(config.constraints, 'Constraints').map(item => {
const constraint = dbObject(item);
dbKeys(constraint, ['name', 'type', 'columns', 'references', 'expression', 'onDelete', 'onUpdate']);
const type = dbString(constraint.type, 'Tipo de constraint').toUpperCase();
const prefix = constraint.name === undefined ? '' : 'CONSTRAINT ' + dbQuote(dbString(constraint.name, 'Nome da constraint')) + ' ';
if (type === 'CHECK') {
if (constraint.columns !== undefined || constraint.references !== undefined || constraint.onDelete !== undefined || constraint.onUpdate !== undefined)
throw new Error('CHECK aceita somente name, type e expression.');
const expression = dbString(constraint.expression, 'Expressão CHECK');
const probe = readDbSchema('CREATE TABLE ' + dbTarget({ schema, name }) + ' (' + columns.join(', ') + ', CHECK (' + expression + '));');
if (probe.length !== 1 || probe[0].constraints.length !== 1 || probe[0].constraints[0].type !== 'check')
throw new Error('Expressão CHECK inválida.');
return prefix + 'CHECK (' + probe[0].constraints[0].check + ')';
}
if (!['PRIMARY KEY', 'UNIQUE', 'FOREIGN KEY'].includes(type))
throw new Error('Constraint deve ser PRIMARY KEY, UNIQUE, FOREIGN KEY ou CHECK.');
let sql = prefix + type + ' (' + names(constraint.columns) + ')';
if (type === 'FOREIGN KEY') {
if (constraint.expression !== undefined)
throw new Error('FOREIGN KEY não aceita expression.');
const target = dbObject(constraint.references);
dbKeys(target, ['schema', 'table', 'columns']);
sql += ' REFERENCES ' + dbTarget({ schema: target.schema === undefined ? schema : dbString(target.schema, 'Schema da FK'), name: dbString(target.table, 'Tabela da FK') }) + ' (' + names(target.columns) + ')';
for (const [key, label] of [['onDelete', 'ON DELETE'], ['onUpdate', 'ON UPDATE']])
if (constraint[key] !== undefined) {
const action = dbString(constraint[key], key).toUpperCase();
if (!['NO ACTION', 'RESTRICT', 'CASCADE', 'SET NULL', 'SET DEFAULT'].includes(action))
throw new Error('Ação referencial inválida.');
sql += ' ' + label + ' ' + action;
}
}
else if (constraint.references !== undefined || constraint.expression !== undefined || constraint.onDelete !== undefined || constraint.onUpdate !== undefined)
throw new Error('Configuração não aplicável à constraint.');
return sql;
});
const indexes = array(config.indexes, 'Índices').map(item => { const index = dbObject(item); dbKeys(index, ['name', 'columns', 'unique']); if (index.unique !== undefined && typeof index.unique !== 'boolean')
throw new Error('unique deve ser booleano.'); return 'CREATE ' + (index.unique ? 'UNIQUE ' : '') + 'INDEX ' + dbQuote(dbString(index.name, 'Índice')) + ' ON ' + dbTarget({ schema, name }) + ' (' + names(index.columns) + ');'; });
const sql = 'CREATE TABLE ' + dbTarget({ schema, name }) + ' (\n ' + [...columns, ...constraints].join(',\n ') + '\n);' + (indexes.length ? '\n\n' + indexes.join('\n') : '');
// External reference definitions are required for semantic validation, never emitted.
const context = values.context?.trim() || '';
const model = readDbSchema((context ? context + '\n' : '') + sql);
const table = model.find(t => t.schema === schema && t.name === name);
return dbOutput([dbCreateSql(table), ...table.indexes.map(index => dbIndexSql(table, index)), ...table.constraints.filter(c => c.type === 'foreign key').map(c => 'ALTER TABLE ' + dbTarget(table) + ' ADD ' + dbConstraintSql(c) + ';')].join('\n\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 dbTarget(table) { return dbQuote(table.schema) + '.' + dbQuote(table.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 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 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 dbJson(input) { return parseJsonCompatible(dbText(input), 'JSON'); }
function dbObject(value) {
if (!value || typeof value !== 'object' || Array.isArray(value))
throw new Error('Informe um objeto JSON.');
return value;
}
function dbKeys(value, keys) { for (const key of Object.keys(value))
if (!keys.includes(key))
throw new Error('Propriedade não suportada: ' + key); }
function dbString(value, label) { if (typeof value !== 'string' || !value)
throw new Error(label + ': informe texto não vazio.'); return dbText(value, label); }
function dbOutput(output) { if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.'); return output; }
function dbLiteral(value) {
if (value === null)
return 'NULL';
if (typeof value === 'boolean')
return value ? 'TRUE' : 'FALSE';
if (typeof value === 'number') {
if (!Number.isFinite(value) || Math.abs(value) > Number.MAX_SAFE_INTEGER)
throw new Error('Número fora do intervalo seguro.');
return String(value);
}
const text = dbText(typeof value === 'string' ? value : JSON.stringify(value));
return "'" + text.replace(/'/g, "''") + "'";
}
function dbText(input, label = 'Entrada') {
if (typeof input !== 'string' || input.length > 100_000)
throw new Error(label + ': limite de 100 mil caracteres.');
if (/[\0]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(input))
throw new Error(label + ': NUL e Unicode inválido não são aceitos.');
return input;
}
function dbKey(table) { return JSON.stringify([table.schema, table.name]); }
function dbName(name) { return name.name.replace(/""/g, '"'); }
function dbReference(name) { return dbKey({ schema: name.schema?.replace(/""/g, '"') ?? 'public', name: dbName(name) }); }
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);
}
function dbColumnSql(column) { return dbQuote(column.name) + ' ' + column.type + (column.nullable ? '' : ' NOT NULL') + (column.default === undefined ? '' : ' DEFAULT ' + column.default); }
function parseJsonCompatible(input, format, onObjectKeys) {
if (!input.trim())
throw new Error(`Informe um documento ${format}.`);
if (input.length > 1_000_000)
throw new Error('A entrada excede o limite de 1 milhão de caracteres.');
if (format === 'JSON') {
// Syntax check only: do not use the rounded numeric values from JSON.parse.
try {
JSON.parse(input);
}
catch (cause) {
throw new Error(`JSON inválido: ${cause instanceof Error ? cause.message : 'erro de sintaxe'}`);
}
}
const lines = new LineCounter();
const doc = parseDocument(input, { version: '1.2', schema: format === 'JSON' ? 'json' : 'core', intAsBigInt: true, uniqueKeys: true, lineCounter: lines, prettyErrors: true, resolveKnownTags: false });
const issue = doc.errors[0] ?? doc.warnings[0];
if (issue)
throw new Error(`${format} inválido (${issue.code}): ${issue.message}`);
if (doc.directives?.yaml.version !== '1.2')
throw new Error('Somente YAML 1.2 é aceito para preservar os tipos de JSON.');
let count = 0;
function fail(message, node) {
const offset = node?.range?.[0];
const position = offset === undefined ? '' : (() => { const { line, col } = lines.linePos(offset); return ` (linha ${line}, coluna ${col})`; })();
throw new Error(message + position);
}
function convert(node, depth = 0) {
if (++count > 100_000 || depth > 100)
fail('Documento muito complexo: limite de 100 níveis ou 100 mil nós.', node);
if (!node)
return null;
if (isAlias(node))
fail('Aliases YAML não são aceitos: JSON não preserva referências ou ciclos.', node);
if (node.tag && !SAFE_TAGS.has(node.tag))
fail(`Tag não permitida: ${node.tag}.`, node);
if (isScalar(node)) {
const value = node.value;
if (typeof value === 'bigint') {
if (value === BigInt(0) && node.source?.startsWith('-'))
fail('JSON de saída não preserva o sinal de zero negativo. Use 0 ou uma string.', node);
if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER))
fail('Inteiro fora do intervalo seguro de JSON/JavaScript. Use uma string entre aspas para preservar todos os dígitos.', node);
return Number(value);
}
if (typeof value === 'number') {
if (!Number.isFinite(value))
fail('JSON não representa NaN ou infinito.', node);
if (Number.isInteger(value) && !Number.isSafeInteger(value))
fail('Número inteiro fora do intervalo seguro. Use uma string entre aspas para preservar a precisão.', node);
if (value === 0 && /[1-9]/.test((node.source ?? '').split(/[eE]/)[0]))
fail('Número pequeno demais para a precisão de JavaScript. Use uma string entre aspas.', node);
if (Object.is(value, -0))
fail('JSON de saída não preserva o sinal de zero negativo. Use 0 ou uma string.', node);
return value;
}
if (value === null || typeof value === 'string' || typeof value === 'boolean')
return value;
fail('Valor não representável em JSON.', node);
}
if (isSeq(node))
return node.items.map(item => convert(item, depth + 1));
if (isMap(node)) {
const result = Object.create(null);
const keys = [];
for (const pair of node.items) {
if (!isScalar(pair.key) || typeof pair.key.value !== 'string')
fail('Chaves de objetos devem ser strings; chaves numéricas, booleanas ou complexas não são preservadas em JSON.', pair.key);
const key = pair.key.value;
if (format === 'YAML' && key === '<<' && pair.key.type === 'PLAIN')
fail('Chaves de merge YAML (<<) não são aceitas.', pair.key);
if (Object.hasOwn(result, key))
fail(`Chave duplicada: ${key}.`, pair.key);
keys.push(key);
result[key] = convert(pair.value, depth + 1);
}
onObjectKeys?.(result, keys);
return result;
}
fail('Estrutura não representável em JSON.', node);
}
if (!doc.contents)
throw new Error('Informe um documento com um valor; use null para um valor nulo.');
return convert(doc.contents);
}
const SAFE_TAGS = new Set(['str', 'bool', 'null', 'int', 'float', 'map', 'seq'].map(tag => `tag:yaml.org,2002:${tag}`));
for (const value of Object.values(values)) dbText(value);
return buildDatabaseTable(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"];
}