diff --git a/scripts/init-db.ts b/scripts/init-db.ts index a249ac0..bb2cc70 100644 --- a/scripts/init-db.ts +++ b/scripts/init-db.ts @@ -102,11 +102,59 @@ async function initDatabase() { console.log(`Reading schema from ${schemaPath}...`); const schema = readFileSync(schemaPath, "utf-8"); - // Split by semicolons and filter out comments and empty statements - const allStatements = schema - .split(";") - .map((s) => s.trim()) - .filter((s) => s.length > 0 && !s.startsWith("--")); + // Remove comments + const cleanedSchema = schema + .split("\n") + .map((line) => { + const trimmed = line.trim(); + if (trimmed.startsWith("--")) { + return ""; + } + const commentIndex = line.indexOf("--"); + if (commentIndex >= 0) { + return line.substring(0, commentIndex); + } + return line; + }) + .join("\n"); + + // Split by semicolon and reconstruct multi-line statements + const parts = cleanedSchema.split(";"); + const allStatements: string[] = []; + let currentStatement = ""; + + for (let i = 0; i < parts.length; i++) { + const part = parts[i].trim(); + if (part.length === 0) { + // If we have a current statement and hit an empty part, it's the end of a statement + if (currentStatement.trim().length > 0) { + allStatements.push(currentStatement.trim()); + currentStatement = ""; + } + continue; + } + + currentStatement += (currentStatement ? " " : "") + part; + + // Check if parentheses are balanced (for CREATE TABLE) or if it's a simple statement (CREATE INDEX) + const openCount = (currentStatement.match(/\(/g) || []).length; + const closeCount = (currentStatement.match(/\)/g) || []).length; + const isIndex = currentStatement + .toUpperCase() + .trim() + .startsWith("CREATE INDEX"); + + // Statement is complete if: + // 1. It's an INDEX (usually single line) + // 2. Parentheses are balanced + // 3. Or it's the last part + if (isIndex || openCount === closeCount || i === parts.length - 1) { + if (currentStatement.trim().length > 0) { + allStatements.push(currentStatement.trim()); + currentStatement = ""; + } + } + } // Separate CREATE TABLE and CREATE INDEX statements const tableStatements: string[] = [];