UNPKG

rawsql-ts

Version:

High-performance SQL parser and AST analyzer written in TypeScript. Provides fast parsing and advanced transformation capabilities.

75 lines 3.21 kB
import { SqlTokenizer } from "./SqlTokenizer"; import { DropSchemaStatement } from "../models/DDLStatements"; import { TokenType } from "../models/Lexeme"; import { FullNameParser } from "./FullNameParser"; import { QualifiedName } from "../models/ValueComponent"; /** * Parses DROP SCHEMA statements. */ export class DropSchemaParser { /** * Parses a DROP SCHEMA statement from raw SQL and validates that the entire string is consumed. * @param sql - The SQL string to parse * @returns The parsed DropSchemaStatement * @throws Error if the SQL string contains unexpected trailing tokens or is malformed */ static parse(sql) { const tokenizer = new SqlTokenizer(sql); const lexemes = tokenizer.readLexemes(); const result = this.parseFromLexeme(lexemes, 0); if (result.newIndex < lexemes.length) { throw new Error(`[DropSchemaParser] Unexpected token "${lexemes[result.newIndex].value}" after DROP SCHEMA statement.`); } return result.value; } /** * Parses a DROP SCHEMA statement from lexemes starting at the provided index. * @param lexemes - The lexeme stream that contains the statement * @param index - The position within the lexeme stream where DROP SCHEMA should begin * @returns An object containing the parsed DropSchemaStatement and the new lexeme index */ static parseFromLexeme(lexemes, index) { var _a, _b, _c, _d; let idx = index; if (((_a = lexemes[idx]) === null || _a === void 0 ? void 0 : _a.value.toLowerCase()) !== "drop schema") { throw new Error(`[DropSchemaParser] Expected DROP SCHEMA at index ${idx}.`); } idx++; // Handle optional IF EXISTS modifier. let ifExists = false; if (((_b = lexemes[idx]) === null || _b === void 0 ? void 0 : _b.value.toLowerCase()) === "if exists") { ifExists = true; idx++; } const schemaNames = []; // Parse comma-separated schema identifiers. while (idx < lexemes.length) { if (!lexemes[idx]) { break; } const { namespaces, name, newIndex } = FullNameParser.parseFromLexeme(lexemes, idx); schemaNames.push(new QualifiedName(namespaces, name)); idx = newIndex; if (((_c = lexemes[idx]) === null || _c === void 0 ? void 0 : _c.type) === TokenType.Comma) { idx++; continue; } break; } if (schemaNames.length === 0) { throw new Error("[DropSchemaParser] DROP SCHEMA must specify at least one schema name."); } // Handle optional CASCADE/RESTRICT behavior. let behavior = null; const nextValue = (_d = lexemes[idx]) === null || _d === void 0 ? void 0 : _d.value.toLowerCase(); if (nextValue === "cascade" || nextValue === "restrict") { behavior = nextValue; idx++; } return { value: new DropSchemaStatement({ schemaNames, ifExists, behavior }), newIndex: idx }; } } //# sourceMappingURL=DropSchemaParser.js.map