rawsql-ts
Version:
[beta]High-performance SQL parser and AST analyzer written in TypeScript. Provides fast parsing and advanced transformation capabilities.
42 lines • 2.09 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.SqlSchemaValidator = void 0;
const SchemaCollector_1 = require("../transformers/SchemaCollector");
const SelectQueryParser_1 = require("../parsers/SelectQueryParser");
class SqlSchemaValidator {
/**
* Validates a SQL query structure against a provided TableColumnResolver or TableSchema array.
* @param sql The SQL query structure to validate, can be a SQL string or a SqlComponent.
* @param tableResolver The TableColumnResolver or TableSchema array to validate against.
* @throws Error if the query contains undefined tables or columns.
*/
static validate(sql, tableResolver) {
const sqlComponent = typeof sql === 'string' ? SelectQueryParser_1.SelectQueryParser.parse(sql) : sql;
// Convert TableSchema[] to a resolver function if necessary
const resolver = Array.isArray(tableResolver)
? (tableName) => {
const schema = tableResolver.find((t) => t.name === tableName);
return schema ? schema.columns : [];
}
: tableResolver;
const schemaCollector = new SchemaCollector_1.SchemaCollector(resolver);
const tableSchemas = schemaCollector.collect(sqlComponent);
const errors = [];
for (const tableSchema of tableSchemas) {
const resolvedColumns = resolver(tableSchema.name);
if (resolvedColumns.length === 0) {
errors.push(`Table '${tableSchema.name}' is not defined.`);
continue;
}
const undefinedColumns = tableSchema.columns.filter(column => !resolvedColumns.includes(column));
if (undefinedColumns.length > 0) {
errors.push(`Table '${tableSchema.name}' contains undefined columns: ${undefinedColumns.join(', ')}.`);
}
}
if (errors.length > 0) {
throw new Error(errors.join('\n'));
}
}
}
exports.SqlSchemaValidator = SqlSchemaValidator;
//# sourceMappingURL=SqlSchemaValidator.js.map
;