{"record":{"id":"b62d51f9be05567c","repo":"slopus/happy","slug":"failed-to-apply-dir-e-message","errorCode":null,"errorMessage":"Failed to apply ${dir}: ${e.message}","messagePattern":"Failed to apply (.+?): (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"critical","filePath":"packages/happy-server/sources/standalone.ts","lineNumber":98,"sourceCode":"        }\n\n        const sqlFile = path.join(migrationsDirResolved, dir, \"migration.sql\");\n        if (!fs.existsSync(sqlFile)) {\n            continue;\n        }\n\n        console.log(`  Applying ${dir}...`);\n        const sql = fs.readFileSync(sqlFile, \"utf-8\");\n\n        try {\n            await pg.exec(sql);\n            await pg.query(\n                `INSERT INTO \"_prisma_migrations\" (\"id\", \"migration_name\", \"finished_at\", \"applied_steps_count\") VALUES ($1, $2, now(), 1)`,\n                [crypto.randomUUID(), dir]\n            );\n            appliedCount++;\n        } catch (e: any) {\n            throw new Error(`Failed to apply ${dir}: ${e.message}`);\n        }\n    }\n\n    if (appliedCount === 0) {\n        console.log(\"No new migrations to apply.\");\n    } else {\n        console.log(`Applied ${appliedCount} migration(s).`);\n    }\n\n    await pg.close();\n}\n\nasync function serve() {\n    // Ensure DB_PROVIDER is set for db.ts\n    process.env.DB_PROVIDER = process.env.DB_PROVIDER || \"pglite\";\n    process.env.PGLITE_DIR = process.env.PGLITE_DIR || pgliteDir;\n\n    const masterSecret = process.env.HANDY_MASTER_SECRET;","sourceCodeStart":80,"sourceCodeEnd":116,"githubUrl":"https://github.com/slopus/happy/blob/b824cd0a4681d41af631a8e422a813873e4455b0/packages/happy-server/sources/standalone.ts#L80-L116","documentation":"During standalone server startup, runMigrations applies SQL migration directories from the migrations folder. For each migration it inserts a row into the _prisma_migrations table; if any statement fails, the error is rethrown with the migration directory name and the underlying database message appended.","triggerScenarios":"A migration SQL file raises a database error (syntax error, conflicting schema, duplicate table/column, constraint violation) when executed against the configured database, and the INSERT INTO _prisma_migrations bookkeeping also fails or the migration body throws inside the try block.","commonSituations":"Applying migrations to a database that was partially migrated by hand; running an older/newer set of migration files against an existing DB; dialect mismatches (Postgres-only SQL against PGlite); corrupted or out-of-order migration directories.","solutions":["Read the wrapped e.message in the thrown error to identify the failing SQL and fix or revert that migration file","Verify the target database state (SELECT * FROM _prisma_migrations) and remove bogus rows or reset the database if safe","Ensure migration files are ordered lexicographically/sequentially and no migration was skipped","Re-run startup with a freshly created database (or dev/test DB) to confirm migrations apply cleanly"],"exampleFix":"// before\nthrow new Error(`Failed to apply ${dir}: ${e.message}`);\n// after\nconsole.error(`Migration ${dir} failed:`, e);\nthrow new Error(`Failed to apply migration ${dir}: ${e.message}`, { cause: e });","handlingStrategy":"try-catch","validationCode":"const applied = await pg.query(`SELECT migration_name FROM \"_prisma_migrations\"`);\nconst pending = dirs.filter(d => !applied.rows.some(r => r.migration_name === d));\nif (pending.length === 0) return;","typeGuard":null,"tryCatchPattern":"try {\n  await runMigrations();\n} catch (e) {\n  if (String(e.message).startsWith('Failed to apply ')) {\n    const dir = e.message.split(' ')[3];\n    console.error(`Fix migration ${dir} before retrying`, { cause: e.cause });\n  }\n  process.exit(1);\n}","preventionTips":["Keep migration files immutable once applied — never edit applied migrations","Test migrations against a fresh database copy in CI before deploying","Check _prisma_migrations table state before manual schema changes","Run a single migration ordering/sequence check before releases"],"tags":["database","migrations","startup"],"backgroundTag":"migration-failed","analyzedSha":"b824cd0a4681d41af631a8e422a813873e4455b0","analyzedAt":"2026-08-31T23:12:36.205Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T05:18:18.240Z"}