@stacksjs/buddy 0.75.657 → 0.75.659

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,11 +12,11 @@ The model-backed create migrations may be stale for this database - run \`./budd
12
12
  `);const more=result.orphans.length>5?`
13
13
  + ${result.orphans.length-5} more - run \`./buddy doctor\` for the full list.`:"";const first=result.orphans[0];log.warn(`${result.total} row${result.total===1?"":"s"} violate foreign keys (orphaned parents), now that SQLite enforces \`foreign_keys = ON\`:
14
14
  ${sample}${more}
15
- These were written under the old \`foreign_keys = OFF\` default (#1951). Review and clean up manually - e.g. DELETE FROM ${first.table} WHERE ${first.column} IS NOT NULL AND ${first.column} NOT IN (SELECT id FROM ${first.parent}). migrate never deletes data.`)}catch(err){log.debug(`[migrate] FK orphan scan skipped: ${err instanceof Error?err.message:String(err)}`)}}function describeOp(op){switch(op.kind){case"drop_table":return`drop table "${op.table}" (all rows lost)`;case"drop_column":return`drop column "${op.table}"."${op.column}" (column data lost)`;case"modify_column":return`change type of "${op.table}"."${op.column}" (possible data loss)`;case"rebuild_table":return`rebuild table "${op.table}" (SQLite rebuilds in place; compare the SQL below against the live schema)`;case"rename_column":return`rename "${op.table}"."${op.from}" → "${op.to}"`;case"rename_table":return`rename table "${op.from}" → "${op.to}"`;case"add_enum_value":return`add value(s) to the enum type of "${op.table}"."${op.column}"`;case"create_enum":return`create the enum type for "${op.table}"${op.column?`."${op.column}"`:""}`;default:return`${op.kind} on "${op.table}"${op.column?`."${op.column}"`:""}`}}async function missingBaselineNote(){try{const{resolveSnapshotDirectory,snapshotDirectoryIsShared}=await import("@stacksjs/database");const dir=resolveSnapshotDirectory();if(existsSync(dir)&&readdirSync(dir).some((f)=>/^model-snapshot\.\w+\.json$/.test(f)))return;return`No model snapshot in ${dir}, so this change was derived without a baseline and will be proposed again on the next run.${snapshotDirectoryIsShared()?" DB_SNAPSHOT_PATH points there; check the directory exists and is writable.":" If each deploy runs from a new directory, point DB_SNAPSHOT_PATH at a shared one that survives the release."}`}catch(error){log.debug(`[migrate] baseline check skipped: ${error instanceof Error?error.message:String(error)}`);return}}async function confirmDestructiveMigrations(opts){let operations=[];try{const{previewPendingMigrations}=await import("@stacksjs/database");operations=await previewPendingMigrations({fromDb:opts.fromDb,applyRenames:opts.applyRenames})}catch(error){log.debug(`Migration preview unavailable: ${error instanceof Error?error.message:String(error)}`);return true}const renames=operations.filter((o)=>o.kind==="rename_column"||o.kind==="rename_table");for(const r of renames)log.info(`Detected ${describeOp(r)} - applying as a rename (data preserved). Use --no-rename to drop + add instead.`);for(const op of operations.filter((o)=>o.warning))log.warn(`${describeOp(op)}: ${op.warning}`);const destructive=operations.filter((o)=>o.destructive);if(destructive.length===0)return true;log.warn(`This migration includes ${destructive.length} potentially destructive change${destructive.length===1?"":"s"}:`);for(const op of destructive)log.warn(` • ${describeOp(op)}`);const baseline=await missingBaselineNote();if(baseline)log.warn(baseline);if(opts.force)return true;if(isCI||!hasTTY){log.error("Refusing to apply destructive changes in a non-interactive environment. Re-run with --force to proceed.");return false}return confirm({message:"Apply these destructive changes?",initial:false})}export function isMigratePreview(options,argv=process.argv){return options.diff===true||options.dryRun===true||options.pretend===true||argv.includes("--dry-run")||argv.includes("--pretend")}function parseGuardBool(raw){if(raw==null||raw==="")return;const v=raw.toLowerCase().trim();if(v==="1"||v==="true"||v==="yes"||v==="on")return true;if(v==="0"||v==="false"||v==="no"||v==="off")return false;return}function parseFreshGuard(raw){const v=raw?.toLowerCase().trim();return v==="allow"||v==="confirm"||v==="disabled"?v:undefined}async function resolveMigrationGuards(){const isProd=/^prod/i.test(process.env.APP_ENV||"local");let cfg={};try{const{awaitConfig}=await import("@stacksjs/config");const resolved=await awaitConfig();cfg=resolved.database?.safety??{}}catch(error){log.debug(`[migrate] safety config unavailable, using defaults: ${error instanceof Error?error.message:String(error)}`)}const confirmMigrate=parseGuardBool(process.env.DB_MIGRATE_CONFIRM)??cfg.confirmMigrate??true;const migrateFresh=parseFreshGuard(process.env.DB_MIGRATE_FRESH)??cfg.migrateFresh??(isProd?"disabled":"allow");return{confirmMigrate,migrateFresh}}function currentDatabaseLabel(){const driver=(process.env.DB_CONNECTION||"sqlite").toLowerCase();if(driver==="sqlite")return process.env.DB_DATABASE_PATH||"database/stacks.sqlite";if(isLibsqlDriver(driver))return process.env.TURSO_DATABASE_URL||"the Turso database";return process.env.DB_DATABASE||"stacks"}export function migrate(buddy){const descriptions={migrate:"Migrates your database",fresh:"Drop all tables and re-run every migration (destroys all data)",project:"Target a specific project",verbose:"Enable verbose output",auth:"Also migrate auth tables (oauth_clients, oauth_access_tokens, oauth_refresh_tokens, password_resets)",force:"Apply destructive changes (drop column/table, lossy type change) without confirmation",fromDb:"Diff against the live database schema instead of the snapshot (self-heal drift)",noRename:"Treat renamed columns as drop + add instead of a data-preserving rename",generate:"Generate migrations from your models before applying them. The default in an interactive terminal; a non-interactive run (CI, a deploy) applies committed files only unless this is passed. --no-generate never generates"};buddy.command("migrate",descriptions.migrate).alias("db:migrate").option("-d, --diff","Show the SQL that would be run",{default:false}).option("--pretend","Same as --diff (and --dry-run): preview, change nothing",{default:false}).option("--dry-run","Same as --diff: preview, change nothing",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("-a, --auth",descriptions.auth,{default:true}).option("--no-auth","Skip auth/oauth table migrations").option("-f, --force",descriptions.force,{default:false}).option("--create-database","Create the database if it does not exist, without asking",{default:false}).option("--from-db",descriptions.fromDb,{default:false}).option("--no-rename",descriptions.noRename).option("--generate",descriptions.generate).option("--strict","Fail when the schema has drifted from the models, a migration is git-ignored or hand-written, or two migrations share a number (for CI)",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy migrate` ...",options);const perf=await intro("buddy migrate");const validation=validateModelsExist();if(!validation.valid){console.error(`
15
+ These were written under the old \`foreign_keys = OFF\` default (#1951). Review and clean up manually - e.g. DELETE FROM ${first.table} WHERE ${first.column} IS NOT NULL AND ${first.column} NOT IN (SELECT id FROM ${first.parent}). migrate never deletes data.`)}catch(err){log.debug(`[migrate] FK orphan scan skipped: ${err instanceof Error?err.message:String(err)}`)}}function describeOp(op){switch(op.kind){case"drop_table":return`drop table "${op.table}" (all rows lost)`;case"drop_column":return`drop column "${op.table}"."${op.column}" (column data lost)`;case"modify_column":return`change type of "${op.table}"."${op.column}" (possible data loss)`;case"rebuild_table":return`rebuild table "${op.table}" (SQLite rebuilds in place; compare the SQL below against the live schema)`;case"rename_column":return`rename "${op.table}"."${op.from}" → "${op.to}"`;case"rename_table":return`rename table "${op.from}" → "${op.to}"`;case"add_enum_value":return`add value(s) to the enum type of "${op.table}"."${op.column}"`;case"create_enum":return`create the enum type for "${op.table}"${op.column?`."${op.column}"`:""}`;default:return`${op.kind} on "${op.table}"${op.column?`."${op.column}"`:""}`}}async function missingBaselineNote(){try{const{resolveSnapshotDirectory,snapshotDirectoryIsShared}=await import("@stacksjs/database");const dir=resolveSnapshotDirectory();if(existsSync(dir)&&readdirSync(dir).some((f)=>/^model-snapshot\.\w+\.json$/.test(f)))return;return`No model snapshot in ${dir}, so this change was derived without a baseline and will be proposed again on the next run.${snapshotDirectoryIsShared()?" DB_SNAPSHOT_PATH points there; check the directory exists and is writable.":" If each deploy runs from a new directory, point DB_SNAPSHOT_PATH at a shared one that survives the release."}`}catch(error){log.debug(`[migrate] baseline check skipped: ${error instanceof Error?error.message:String(error)}`);return}}async function confirmDestructiveMigrations(opts){let operations=[];try{const{previewPendingMigrations}=await import("@stacksjs/database");operations=await previewPendingMigrations({fromDb:opts.fromDb,applyRenames:opts.applyRenames})}catch(error){log.debug(`Migration preview unavailable: ${error instanceof Error?error.message:String(error)}`);return"apply"}const renames=operations.filter((o)=>o.kind==="rename_column"||o.kind==="rename_table");for(const r of renames)log.info(`Detected ${describeOp(r)} - applying as a rename (data preserved). Use --no-rename to drop + add instead.`);for(const op of operations.filter((o)=>o.warning))log.warn(`${describeOp(op)}: ${op.warning}`);const destructive=operations.filter((o)=>o.destructive);if(destructive.length===0)return"apply";log.warn(`This migration includes ${destructive.length} potentially destructive change${destructive.length===1?"":"s"}:`);for(const op of destructive)log.warn(` • ${describeOp(op)}`);const baseline=await missingBaselineNote();if(baseline)log.warn(baseline);if(opts.force)return"apply";if(isCI||!hasTTY){log.warn("Nobody to ask in a non-interactive environment, so these are held back and the rest of the migration goes ahead. Re-run with --force to apply them.");return"hold"}const approved=await confirm({message:"Apply these destructive changes? (No applies everything else and keeps these pending)",initial:false});if(!approved)log.info("Held back. The rest of the migration goes ahead; these will be proposed again next time.");return approved?"apply":"hold"}export function isMigratePreview(options,argv=process.argv){return options.diff===true||options.dryRun===true||options.pretend===true||argv.includes("--dry-run")||argv.includes("--pretend")}function parseGuardBool(raw){if(raw==null||raw==="")return;const v=raw.toLowerCase().trim();if(v==="1"||v==="true"||v==="yes"||v==="on")return true;if(v==="0"||v==="false"||v==="no"||v==="off")return false;return}function parseFreshGuard(raw){const v=raw?.toLowerCase().trim();return v==="allow"||v==="confirm"||v==="disabled"?v:undefined}async function resolveMigrationGuards(){const isProd=/^prod/i.test(process.env.APP_ENV||"local");let cfg={};try{const{awaitConfig}=await import("@stacksjs/config");const resolved=await awaitConfig();cfg=resolved.database?.safety??{}}catch(error){log.debug(`[migrate] safety config unavailable, using defaults: ${error instanceof Error?error.message:String(error)}`)}const confirmMigrate=parseGuardBool(process.env.DB_MIGRATE_CONFIRM)??cfg.confirmMigrate??true;const migrateFresh=parseFreshGuard(process.env.DB_MIGRATE_FRESH)??cfg.migrateFresh??(isProd?"disabled":"allow");return{confirmMigrate,migrateFresh}}function currentDatabaseLabel(){const driver=(process.env.DB_CONNECTION||"sqlite").toLowerCase();if(driver==="sqlite")return process.env.DB_DATABASE_PATH||"database/stacks.sqlite";if(isLibsqlDriver(driver))return process.env.TURSO_DATABASE_URL||"the Turso database";return process.env.DB_DATABASE||"stacks"}export function migrate(buddy){const descriptions={migrate:"Migrates your database",fresh:"Drop all tables and re-run every migration (destroys all data)",project:"Target a specific project",verbose:"Enable verbose output",auth:"Also migrate auth tables (oauth_clients, oauth_access_tokens, oauth_refresh_tokens, password_resets)",force:"Apply destructive changes (drop column/table, lossy type change) without confirmation. Without it they are held back and everything else is applied",fromDb:"Diff against the live database schema instead of the snapshot (self-heal drift)",noRename:"Treat renamed columns as drop + add instead of a data-preserving rename",generate:"Generate migrations from your models before applying them. The default in an interactive terminal; a non-interactive run (CI, a deploy) applies committed files only unless this is passed. --no-generate never generates"};buddy.command("migrate",descriptions.migrate).alias("db:migrate").option("-d, --diff","Show the SQL that would be run",{default:false}).option("--pretend","Same as --diff (and --dry-run): preview, change nothing",{default:false}).option("--dry-run","Same as --diff: preview, change nothing",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("-a, --auth",descriptions.auth,{default:true}).option("--no-auth","Skip auth/oauth table migrations").option("-f, --force",descriptions.force,{default:false}).option("--create-database","Create the database if it does not exist, without asking",{default:false}).option("--from-db",descriptions.fromDb,{default:false}).option("--no-rename",descriptions.noRename).option("--generate",descriptions.generate).option("--strict","Fail when the schema has drifted from the models, a migration is git-ignored or hand-written, or two migrations share a number (for CI)",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy migrate` ...",options);const perf=await intro("buddy migrate");const validation=validateModelsExist();if(!validation.valid){console.error(`
16
16
  ❌ Error: ${validation.error}
17
17
  `);process.exit(ExitCode.FatalError)}const{pendingMigrationFiles:pendingForDialect}=await import("@stacksjs/database");let willRun;try{willRun=await pendingForDialect()}catch{willRun=undefined}const dialectCheck=validateMigrationDialect(process.cwd(),{only:willRun});if(!dialectCheck.valid){console.error(`
18
18
  ❌ Error: ${dialectCheck.error}
19
- `);process.exit(ExitCode.FatalError)}if(!await reportDuplicateMigrationNumbers({strict:strictMode(options)}))process.exit(ExitCode.FatalError);const applyRenames=options.rename===false?false:undefined;if(options.fromDb)process.env.STACKS_MIGRATE_FROM_DB="1";if(applyRenames===false)process.env.STACKS_MIGRATE_NO_RENAME="1";const generate=generatesMigrations(options.generate,hasTTY&&!isCI);if(!generate)process.env.STACKS_MIGRATE_NO_GENERATE="1";if(options.generate===undefined&&!generate)log.info("Applying committed migrations only: this run is not interactive, so nothing is generated from your models. Run `./buddy generate:migrations` and commit the result, or pass --generate.");if(options.strict)process.env.STACKS_MIGRATE_STRICT="1";if(isMigratePreview(options)){const{auditSchemaDrift,formatSchemaDrift,pendingMigrationFiles,pendingMigrationOperations}=await import("@stacksjs/database");let failed=false;let files=[];try{files=await pendingMigrationFiles()}catch(error){failed=true;await log.error("Could not read the migrations table:",error)}if(files.length>0){log.info(`${files.length} committed migration file${files.length===1?"":"s"} not applied yet - \`buddy migrate\` will run ${files.length===1?"it":"them"}:`);for(const file of files.slice(0,10))log.info(` • ${file}`);if(files.length>10)log.info(` • … +${files.length-10} more`)}let ops=[];try{ops=await pendingMigrationOperations({fromDb:options.fromDb,applyRenames})}catch(error){failed=true;await log.error("Failed to diff the models against the migration snapshot:",error)}if(ops.length>0){log.info(`${ops.length} model change${ops.length===1?"":"s"} not in a migration file yet:`);for(const op of ops){log.info(` • ${describeOp(op)}${op.destructive?" [destructive]":""}`);if(op.warning)log.warn(` ${op.warning}`)}}const drift=await auditSchemaDrift();const modelsDrifted=!drift.skipped&&!drift.clean;if(modelsDrifted)log.warn(await formatSchemaDrift(drift));const drifted=modelsDrifted||!await reportMissingRecordedTables();if(failed){await outro("Diff incomplete - see the errors above. No changes applied.",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}if(files.length===0&&ops.length===0&&!drifted){log.info("No pending schema changes - your models match the database.");await outro("Diff complete - no changes applied.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}if(drifted&&files.length===0&&ops.length===0)logDriftRemedy();await outro("Diff complete - no changes applied.",{startTime:perf,useSeconds:true,type:drifted?"warning":"success"});process.exit(drifted&&strictMode(options)?ExitCode.FatalError:ExitCode.Success)}await preflightDatabase({createDatabase:options.createDatabase,command:"migrate"});const guards=await resolveMigrationGuards();if(guards.confirmMigrate&&!options.force){if(isCI||!hasTTY){log.debug("[migrate] confirmMigrate guard skipped - non-interactive environment.")}else{const APP_ENV=process.env.APP_ENV||"local";await log.flush();const proceed=await confirm({message:`Run migrations against the ${APP_ENV} database "${currentDatabaseLabel()}"?`,initial:true});if(!proceed){await outro("Migration cancelled - no changes applied.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}}}await ensureDatabaseOrExit();const lock=acquireMigrationLock();if(!lock.acquired){log.syncError("Another migration is already running (storage/framework/runtime/migrations.lock exists). Wait for it to finish, or remove the lockfile if it is stale.");process.exit(ExitCode.FatalError)}try{const{catchUpFrameworkRenames}=await import("@stacksjs/database");await catchUpFrameworkRenames()}catch(error){lock.release();log.syncError(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}if(generate){const proceed=await confirmDestructiveMigrations({force:options.force,fromDb:options.fromDb,applyRenames});if(!proceed){lock.release();await outro("Migration cancelled - no changes applied.",{startTime:perf,useSeconds:true});process.exit(isCI||!hasTTY?ExitCode.FatalError:ExitCode.Success)}}if(options.auth!==false){log.debug("Migrating auth tables...");try{const{migrateAuthTables}=await import("@stacksjs/database");const authResult=await migrateAuthTables({verbose:options.verbose});if(!authResult.success){log.error(`Failed to migrate auth tables: ${authResult.error}`)}}catch(error){log.error("Failed to migrate auth tables:",error)}}const result=await runAction(Action.Migrate,options).finally(()=>lock.release());if(resultFailed(result)){log.error("Model migrations failed - applying notification/RBAC table guarantees before exiting.")}let traitMigrationError;if(options.auth!==false){try{const{ensureUtcDatetimeColumns,ensureUtcTimestampDefaults,migrateNotificationTables,migrateRbacTables,migrateTraitTables}=await import("@stacksjs/database");const notifResult=await migrateNotificationTables({verbose:options.verbose});if(!notifResult.success){log.error(`Failed to migrate notification tables: ${notifResult.error}`)}const rbacResult=await migrateRbacTables({verbose:options.verbose});if(!rbacResult.success){log.error(`Failed to migrate RBAC tables: ${rbacResult.error}`)}const{migrateEnabledImpersonationTables}=await import("@stacksjs/auth/impersonation-store");await migrateEnabledImpersonationTables();const traitResult=await migrateTraitTables({verbose:options.verbose});if(!traitResult.success){traitMigrationError=traitResult.error||"Polymorphic trait table migration failed";log.error(`Failed to migrate polymorphic trait tables: ${traitMigrationError}`)}const datetimeResult=await ensureUtcDatetimeColumns({verbose:options.verbose});if(!datetimeResult.success){log.error(`Failed to convert TIMESTAMP columns to DATETIME: ${datetimeResult.error}`)}const defaultsResult=await ensureUtcTimestampDefaults({verbose:options.verbose});if(!defaultsResult.success){log.error(`Failed to pin timestamp defaults to UTC: ${defaultsResult.error}`)}}catch(error){traitMigrationError=error instanceof Error?error.message:String(error);log.error("Failed to migrate notification/RBAC/trait tables:",error)}}if(resultFailed(result)||traitMigrationError){await outro("While running the migrate command, there was an issue",{startTime:perf,useSeconds:true},resultFailed(result)?result.error:traitMigrationError);await log.flush();process.exit(ExitCode.FatalError)}if(options.auth!==false){try{const{ensureUsersAuthColumns,sqlHelpers}=await import("@stacksjs/database");const driver=process.env.DB_CONNECTION||"sqlite";await ensureUsersAuthColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure users auth columns post-migration:",error)}}try{const{ensureUuidColumns,sqlHelpers}=await import("@stacksjs/database");const driver=process.env.DB_CONNECTION||"sqlite";await ensureUuidColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure uuid columns post-migration:",error)}await addMissingEnumLabels();await reportMissingForeignKeys();const modelsMatch=await reportSchemaDrift();const tablesPresent=await reportMissingRecordedTables();const schemaMatches=modelsMatch&&tablesPresent;const allCommittable=await reportIgnoredMigrations();const allGenerated=await reportHandWrittenMigrations({list:strictMode(options)});if(strictMode(options)&&(!schemaMatches||!allCommittable||!allGenerated)){const why=!allCommittable?"a migration is git-ignored":!allGenerated?"a migration was written by hand rather than generated from the models":"the live schema does not match the models";console.error(`
19
+ `);process.exit(ExitCode.FatalError)}if(!await reportDuplicateMigrationNumbers({strict:strictMode(options)}))process.exit(ExitCode.FatalError);const applyRenames=options.rename===false?false:undefined;if(options.fromDb)process.env.STACKS_MIGRATE_FROM_DB="1";if(applyRenames===false)process.env.STACKS_MIGRATE_NO_RENAME="1";const generate=generatesMigrations(options.generate,hasTTY&&!isCI);if(!generate)process.env.STACKS_MIGRATE_NO_GENERATE="1";if(options.generate===undefined&&!generate)log.info("Applying committed migrations only: this run is not interactive, so nothing is generated from your models. Run `./buddy generate:migrations` and commit the result, or pass --generate.");if(options.strict)process.env.STACKS_MIGRATE_STRICT="1";if(isMigratePreview(options)){const{auditSchemaDrift,formatSchemaDrift,pendingMigrationFiles,pendingMigrationOperations}=await import("@stacksjs/database");let failed=false;let files=[];try{files=await pendingMigrationFiles()}catch(error){failed=true;await log.error("Could not read the migrations table:",error)}if(files.length>0){log.info(`${files.length} committed migration file${files.length===1?"":"s"} not applied yet - \`buddy migrate\` will run ${files.length===1?"it":"them"}:`);for(const file of files.slice(0,10))log.info(` • ${file}`);if(files.length>10)log.info(` • … +${files.length-10} more`)}let ops=[];try{ops=await pendingMigrationOperations({fromDb:options.fromDb,applyRenames})}catch(error){failed=true;await log.error("Failed to diff the models against the migration snapshot:",error)}if(ops.length>0){log.info(`${ops.length} model change${ops.length===1?"":"s"} not in a migration file yet:`);for(const op of ops){log.info(` • ${describeOp(op)}${op.destructive?" [destructive]":""}`);if(op.warning)log.warn(` ${op.warning}`)}}const drift=await auditSchemaDrift();const modelsDrifted=!drift.skipped&&!drift.clean;if(modelsDrifted)log.warn(await formatSchemaDrift(drift));const drifted=modelsDrifted||!await reportMissingRecordedTables();if(failed){await outro("Diff incomplete - see the errors above. No changes applied.",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}if(files.length===0&&ops.length===0&&!drifted){log.info("No pending schema changes - your models match the database.");await outro("Diff complete - no changes applied.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}if(drifted&&files.length===0&&ops.length===0)logDriftRemedy();await outro("Diff complete - no changes applied.",{startTime:perf,useSeconds:true,type:drifted?"warning":"success"});process.exit(drifted&&strictMode(options)?ExitCode.FatalError:ExitCode.Success)}await preflightDatabase({createDatabase:options.createDatabase,command:"migrate"});const guards=await resolveMigrationGuards();if(guards.confirmMigrate&&!options.force){if(isCI||!hasTTY){log.debug("[migrate] confirmMigrate guard skipped - non-interactive environment.")}else{const APP_ENV=process.env.APP_ENV||"local";await log.flush();const proceed=await confirm({message:`Run migrations against the ${APP_ENV} database "${currentDatabaseLabel()}"?`,initial:true});if(!proceed){await outro("Migration cancelled - no changes applied.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}}}await ensureDatabaseOrExit();const lock=acquireMigrationLock();if(!lock.acquired){log.syncError("Another migration is already running (storage/framework/runtime/migrations.lock exists). Wait for it to finish, or remove the lockfile if it is stale.");process.exit(ExitCode.FatalError)}try{const{catchUpFrameworkRenames}=await import("@stacksjs/database");await catchUpFrameworkRenames()}catch(error){lock.release();log.syncError(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}if(generate){const decision=await confirmDestructiveMigrations({force:options.force,fromDb:options.fromDb,applyRenames});if(decision==="hold")process.env.STACKS_MIGRATE_HOLD_DESTRUCTIVE="1";else delete process.env.STACKS_MIGRATE_HOLD_DESTRUCTIVE}if(options.auth!==false){log.debug("Migrating auth tables...");try{const{migrateAuthTables}=await import("@stacksjs/database");const authResult=await migrateAuthTables({verbose:options.verbose});if(!authResult.success){log.error(`Failed to migrate auth tables: ${authResult.error}`)}}catch(error){log.error("Failed to migrate auth tables:",error)}}const result=await runAction(Action.Migrate,options).finally(()=>lock.release());if(resultFailed(result)){log.error("Model migrations failed - applying notification/RBAC table guarantees before exiting.")}let traitMigrationError;if(options.auth!==false){try{const{ensureUtcDatetimeColumns,ensureUtcTimestampDefaults,migrateNotificationTables,migrateRbacTables,migrateTraitTables}=await import("@stacksjs/database");const notifResult=await migrateNotificationTables({verbose:options.verbose});if(!notifResult.success){log.error(`Failed to migrate notification tables: ${notifResult.error}`)}const rbacResult=await migrateRbacTables({verbose:options.verbose});if(!rbacResult.success){log.error(`Failed to migrate RBAC tables: ${rbacResult.error}`)}const{migrateEnabledImpersonationTables}=await import("@stacksjs/auth/impersonation-store");await migrateEnabledImpersonationTables();const traitResult=await migrateTraitTables({verbose:options.verbose});if(!traitResult.success){traitMigrationError=traitResult.error||"Polymorphic trait table migration failed";log.error(`Failed to migrate polymorphic trait tables: ${traitMigrationError}`)}const datetimeResult=await ensureUtcDatetimeColumns({verbose:options.verbose});if(!datetimeResult.success){log.error(`Failed to convert TIMESTAMP columns to DATETIME: ${datetimeResult.error}`)}const defaultsResult=await ensureUtcTimestampDefaults({verbose:options.verbose});if(!defaultsResult.success){log.error(`Failed to pin timestamp defaults to UTC: ${defaultsResult.error}`)}}catch(error){traitMigrationError=error instanceof Error?error.message:String(error);log.error("Failed to migrate notification/RBAC/trait tables:",error)}}if(resultFailed(result)||traitMigrationError){await outro("While running the migrate command, there was an issue",{startTime:perf,useSeconds:true},resultFailed(result)?result.error:traitMigrationError);await log.flush();process.exit(ExitCode.FatalError)}if(options.auth!==false){try{const{ensureUsersAuthColumns,sqlHelpers}=await import("@stacksjs/database");const driver=process.env.DB_CONNECTION||"sqlite";await ensureUsersAuthColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure users auth columns post-migration:",error)}}try{const{ensureUuidColumns,sqlHelpers}=await import("@stacksjs/database");const driver=process.env.DB_CONNECTION||"sqlite";await ensureUuidColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure uuid columns post-migration:",error)}await addMissingEnumLabels();await reportMissingForeignKeys();const modelsMatch=await reportSchemaDrift();const tablesPresent=await reportMissingRecordedTables();const schemaMatches=modelsMatch&&tablesPresent;const allCommittable=await reportIgnoredMigrations();const allGenerated=await reportHandWrittenMigrations({list:strictMode(options)});if(strictMode(options)&&(!schemaMatches||!allCommittable||!allGenerated)){const why=!allCommittable?"a migration is git-ignored":!allGenerated?"a migration was written by hand rather than generated from the models":"the live schema does not match the models";console.error(`
20
20
  ❌ --strict: ${why} (see above).
21
21
  `);process.exit(ExitCode.FatalError)}await reportFkOrphans();const APP_ENV=process.env.APP_ENV||"local";const marker=readMigrateMarker();const authSuffix=options.auth!==false?" (including auth tables)":"";const applied=marker==null?`Migrated your ${APP_ENV} database.${authSuffix}`:marker.appliedCount===0?schemaMatches?`Nothing to migrate - your ${APP_ENV} database is already up to date.${authSuffix}`:`Nothing to migrate${authSuffix}.`:`Applied ${marker.appliedCount} migration${marker.appliedCount===1?"":"s"} to your ${APP_ENV} database.${authSuffix}`;const outroMessage=schemaMatches?applied:`${applied} The database is still not in the state its migrations and models describe - see above.`;if(!schemaMatches)logDriftRemedy();await outro(outroMessage,{startTime:perf,useSeconds:true,type:schemaMatches?"success":"warning"});process.exit(ExitCode.Success)});buddy.command("migrate:fresh",descriptions.fresh).alias("db:fresh").option("-d, --diff","Show what would be dropped and replayed, and change nothing",{default:false}).option("--pretend","Same as --diff (and --dry-run): preview, change nothing",{default:false}).option("--dry-run","Same as --diff: preview, change nothing",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("-s, --seed","Run database seeders after migration",{default:false}).option("-a, --auth",descriptions.auth,{default:true}).option("--no-auth","Skip auth/oauth table migrations").option("--create-database","Create the database if it does not exist, without asking",{default:false}).option("-f, --force",'Skip the drop-database confirmation (only honored when the migrateFresh guard is "allow")',{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy migrate:fresh` ...",options);const perf=await intro("buddy migrate:fresh");const validation=validateModelsExist();if(!validation.valid){console.error(`
22
22
  ❌ Error: ${validation.error}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/buddy",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.657",
5
+ "version": "0.75.659",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -95,71 +95,71 @@
95
95
  "prepublishOnly": "bun run build"
96
96
  },
97
97
  "dependencies": {
98
- "@stacksjs/actions": "0.75.657",
99
- "@stacksjs/docs": "0.75.657",
100
- "@stacksjs/ai": "0.75.657",
101
- "@stacksjs/alias": "0.75.657",
102
- "@stacksjs/analytics": "0.75.657",
103
- "@stacksjs/api": "0.75.657",
104
- "@stacksjs/arrays": "0.75.657",
105
- "@stacksjs/auth": "0.75.657",
106
- "@stacksjs/browser-extension": "0.75.657",
107
- "@stacksjs/build": "0.75.657",
98
+ "@stacksjs/actions": "0.75.659",
99
+ "@stacksjs/docs": "0.75.659",
100
+ "@stacksjs/ai": "0.75.659",
101
+ "@stacksjs/alias": "0.75.659",
102
+ "@stacksjs/analytics": "0.75.659",
103
+ "@stacksjs/api": "0.75.659",
104
+ "@stacksjs/arrays": "0.75.659",
105
+ "@stacksjs/auth": "0.75.659",
106
+ "@stacksjs/browser-extension": "0.75.659",
107
+ "@stacksjs/build": "0.75.659",
108
108
  "@stacksjs/bumpx": "^0.2.32",
109
- "@stacksjs/cache": "0.75.657",
110
- "@stacksjs/chat": "0.75.657",
109
+ "@stacksjs/cache": "0.75.659",
110
+ "@stacksjs/chat": "0.75.659",
111
111
  "@stacksjs/clapp": "^0.2.17",
112
- "@stacksjs/cli": "0.75.657",
113
- "@stacksjs/cloud": "0.75.657",
114
- "@stacksjs/cms": "0.75.657",
115
- "@stacksjs/collections": "0.75.657",
116
- "@stacksjs/commerce": "0.75.657",
117
- "@stacksjs/config": "0.75.657",
118
- "@stacksjs/database": "0.75.657",
119
- "@stacksjs/desktop-build": "0.75.657",
120
- "@stacksjs/dns": "0.75.657",
112
+ "@stacksjs/cli": "0.75.659",
113
+ "@stacksjs/cloud": "0.75.659",
114
+ "@stacksjs/cms": "0.75.659",
115
+ "@stacksjs/collections": "0.75.659",
116
+ "@stacksjs/commerce": "0.75.659",
117
+ "@stacksjs/config": "0.75.659",
118
+ "@stacksjs/database": "0.75.659",
119
+ "@stacksjs/desktop-build": "0.75.659",
120
+ "@stacksjs/dns": "0.75.659",
121
121
  "@stacksjs/dnsx": "^0.2.3",
122
- "@stacksjs/email": "0.75.657",
123
- "@stacksjs/enums": "0.75.657",
124
- "@stacksjs/env": "0.75.657",
125
- "@stacksjs/error-handling": "0.75.657",
126
- "@stacksjs/events": "0.75.657",
127
- "@stacksjs/features": "0.75.657",
128
- "@stacksjs/git": "0.75.657",
122
+ "@stacksjs/email": "0.75.659",
123
+ "@stacksjs/enums": "0.75.659",
124
+ "@stacksjs/env": "0.75.659",
125
+ "@stacksjs/error-handling": "0.75.659",
126
+ "@stacksjs/events": "0.75.659",
127
+ "@stacksjs/features": "0.75.659",
128
+ "@stacksjs/git": "0.75.659",
129
129
  "@stacksjs/gitit": "^0.2.5",
130
- "@stacksjs/health": "0.75.657",
131
- "@stacksjs/hq": "0.75.657",
130
+ "@stacksjs/health": "0.75.659",
131
+ "@stacksjs/hq": "0.75.659",
132
132
  "@stacksjs/httx": "^0.1.10",
133
- "@stacksjs/image": "0.75.657",
134
- "@stacksjs/lint": "0.75.657",
135
- "@stacksjs/logging": "0.75.657",
136
- "@stacksjs/notifications": "0.75.657",
137
- "@stacksjs/objects": "0.75.657",
138
- "@stacksjs/orm": "0.75.657",
139
- "@stacksjs/path": "0.75.657",
140
- "@stacksjs/payments": "0.75.657",
141
- "@stacksjs/realtime": "0.75.657",
142
- "@stacksjs/router": "0.75.657",
133
+ "@stacksjs/image": "0.75.659",
134
+ "@stacksjs/lint": "0.75.659",
135
+ "@stacksjs/logging": "0.75.659",
136
+ "@stacksjs/notifications": "0.75.659",
137
+ "@stacksjs/objects": "0.75.659",
138
+ "@stacksjs/orm": "0.75.659",
139
+ "@stacksjs/path": "0.75.659",
140
+ "@stacksjs/payments": "0.75.659",
141
+ "@stacksjs/realtime": "0.75.659",
142
+ "@stacksjs/router": "0.75.659",
143
143
  "@stacksjs/rpx": "^0.11.54",
144
- "@stacksjs/scheduler": "0.75.657",
145
- "@stacksjs/search-engine": "0.75.657",
146
- "@stacksjs/security": "0.75.657",
147
- "@stacksjs/server": "0.75.657",
148
- "@stacksjs/sites": "0.75.657",
149
- "@stacksjs/skills": "0.75.657",
150
- "@stacksjs/socials": "0.75.657",
151
- "@stacksjs/storage": "0.75.657",
152
- "@stacksjs/strings": "0.75.657",
144
+ "@stacksjs/scheduler": "0.75.659",
145
+ "@stacksjs/search-engine": "0.75.659",
146
+ "@stacksjs/security": "0.75.659",
147
+ "@stacksjs/server": "0.75.659",
148
+ "@stacksjs/sites": "0.75.659",
149
+ "@stacksjs/skills": "0.75.659",
150
+ "@stacksjs/socials": "0.75.659",
151
+ "@stacksjs/storage": "0.75.659",
152
+ "@stacksjs/strings": "0.75.659",
153
153
  "@stacksjs/stx": "^0.2.908",
154
- "@stacksjs/testing": "0.75.657",
155
- "@stacksjs/tinker": "0.75.657",
154
+ "@stacksjs/testing": "0.75.659",
155
+ "@stacksjs/tinker": "0.75.659",
156
156
  "@stacksjs/tlsx": "^0.13.19",
157
157
  "@stacksjs/ts-cloud": "^0.16.144",
158
- "@stacksjs/tunnel": "0.75.657",
159
- "@stacksjs/types": "0.75.657",
160
- "@stacksjs/ui": "0.75.657",
161
- "@stacksjs/utils": "0.75.657",
162
- "@stacksjs/validation": "0.75.657",
158
+ "@stacksjs/tunnel": "0.75.659",
159
+ "@stacksjs/types": "0.75.659",
160
+ "@stacksjs/ui": "0.75.659",
161
+ "@stacksjs/utils": "0.75.659",
162
+ "@stacksjs/validation": "0.75.659",
163
163
  "ajv": "^8.20.0",
164
164
  "ajv-formats": "^3.0.1",
165
165
  "bun-plugin-stx": "^0.2.908",