@stacksjs/database 0.75.515 → 0.75.518
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.
- package/dist/affected-rows.js +1 -1
- package/dist/auth-tables.js +16 -16
- package/dist/column.js +1 -1
- package/dist/connection-lifecycle.js +1 -1
- package/dist/custom/audits.js +2 -2
- package/dist/custom/errors.js +2 -2
- package/dist/custom/jobs.js +9 -9
- package/dist/database.js +1 -1
- package/dist/datetime-columns.js +4 -4
- package/dist/ddl-constraints.js +4 -4
- package/dist/declared-unique-indexes.js +1 -1
- package/dist/defaults.js +1 -1
- package/dist/dialect.js +1 -1
- package/dist/driver-config.js +1 -1
- package/dist/drivers/defaults/traits.js +1 -1
- package/dist/drivers/dynamodb.js +1 -1
- package/dist/drivers/helpers.js +1 -1
- package/dist/drivers/mysql.js +11 -11
- package/dist/drivers/postgres.js +12 -12
- package/dist/drivers/sqlite.js +18 -17
- package/dist/ensure-database.js +1 -1
- package/dist/erd.js +1 -1
- package/dist/error-reporter.js +2 -2
- package/dist/fk-audit.js +1 -1
- package/dist/framework-renames.js +1 -1
- package/dist/framework-route-admission.js +1 -1
- package/dist/generated-migration-marker.js +1 -1
- package/dist/hand-written-migrations.js +1 -1
- package/dist/ignored-migrations.js +1 -1
- package/dist/index-shape.js +1 -1
- package/dist/managed-columns.js +1 -1
- package/dist/migration-dialect.js +3 -3
- package/dist/migration-ledger.js +1 -1
- package/dist/migration-lock.js +1 -1
- package/dist/migration-names.js +1 -1
- package/dist/migration-path.js +1 -1
- package/dist/migrations.js +18 -18
- package/dist/model-sources.js +7 -7
- package/dist/notification-tables.js +1 -1
- package/dist/package-migrations.js +1 -1
- package/dist/query-log-bindings.js +2 -2
- package/dist/query-logger.js +2 -2
- package/dist/query-parser.js +1 -1
- package/dist/rbac-tables.js +1 -1
- package/dist/relation-columns.js +1 -1
- package/dist/replicas.js +1 -1
- package/dist/row-lease.js +1 -1
- package/dist/row-lock.js +1 -1
- package/dist/safe-migrations.js +2 -2
- package/dist/schema-align.js +5 -5
- package/dist/schema-drift.js +1 -1
- package/dist/seeder.js +1 -1
- package/dist/shadowed-models.js +1 -1
- package/dist/sql-helpers.js +1 -1
- package/dist/sql-statements.js +2 -2
- package/dist/table.js +1 -1
- package/dist/trait-tables.js +2 -2
- package/dist/transaction-context.js +1 -1
- package/dist/transaction-options.js +1 -1
- package/dist/types.js +1 -1
- package/dist/unique-audit.js +2 -2
- package/dist/utc-defaults.js +2 -2
- package/dist/utils.js +1 -1
- package/dist/uuid-columns.js +1 -1
- package/dist/validators.js +1 -1
- package/dist/vschema.js +1 -1
- package/package.json +16 -16
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readdirSync,readFileSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{isPackageMigration}from"./package-migrations";export const QB_GENERATED_MARKER="-- qb:generated";export function carriesGeneratedMarker(sql){const head=sql.slice(0,400);return head.includes(QB_GENERATED_MARKER)||head.includes("@generated by `buddy migrate:regenerate`")}export function handWrittenMigrationPolicy(configured,envValue=process.env.DB_ALLOW_HAND_WRITTEN_MIGRATIONS){const env=envValue?.trim();if(env){if(/^(?:1|true|yes|on)$/i.test(env))return{allowAll
|
|
1
|
+
import{readdirSync,readFileSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{isPackageMigration}from"./package-migrations";export const QB_GENERATED_MARKER="-- qb:generated";export function carriesGeneratedMarker(sql){const head=sql.slice(0,400);return head.includes(QB_GENERATED_MARKER)||head.includes("@generated by `buddy migrate:regenerate`")}export function handWrittenMigrationPolicy(configured,envValue=process.env.DB_ALLOW_HAND_WRITTEN_MIGRATIONS){const env=envValue?.trim();if(env){if(/^(?:1|true|yes|on)$/i.test(env))return{allowAll:true,allowed:new Set};if(!/^(?:0|false|no|off)$/i.test(env))return{allowAll:false,allowed:new Set(env.split(",").map((name)=>name.trim()).filter(Boolean))}}if(configured===true)return{allowAll:true,allowed:new Set};return{allowAll:false,allowed:new Set(Array.isArray(configured)?configured:[])}}const logicalName=(file)=>file.replace(/^\d+[-_]/,"").replace(/\.sql$/i,"");export function findHandWrittenMigrations(dir,policy={allowAll:false,allowed:new Set}){if(policy.allowAll)return[];let files;try{files=readdirSync(dir).filter((file)=>file.toLowerCase().endsWith(".sql")).sort()}catch{return[]}return files.filter((file)=>{if(isPackageMigration(file))return false;if(policy.allowed.has(file)||policy.allowed.has(logicalName(file)))return false;try{return!carriesGeneratedMarker(readFileSync(join(dir,file),"utf8"))}catch{return false}})}export async function handWrittenMigrations(){try{const{activeMigrationDirectory}=await import("./migrations");const dir=await activeMigrationDirectory();let configured;try{const{config,overridesReady}=await import("@stacksjs/config");await overridesReady;configured=config?.database?.safety?.allowHandWrittenMigrations}catch{}return{dir,files:findHandWrittenMigrations(dir,handWrittenMigrationPolicy(configured))}}catch{return{dir:"",files:[]}}}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{spawnSync}from"node:child_process";import fs from"node:fs";import{basename}from"node:path";import{path}from"@stacksjs/path";import{isGeneratedMigration}from"./generated-migration-marker";export function findIgnoredMigrations(migrationsDir=path.userMigrationsPath()){let files;try{files=fs.readdirSync(migrationsDir).filter((file)=>file.endsWith(".sql"))}catch{return[]}if(!files.length)return[];try{const result=spawnSync("git",["check-ignore","--stdin","-z"],{cwd:migrationsDir,input:`${files.join("\x00")}\x00`,encoding:"utf8",timeout:5000});if(result.status!==0||typeof result.stdout!=="string")return[];return result.stdout.split("\x00").filter(Boolean).map((file)=>basename(file)).sort()}catch{return[]}}export function trackIgnoredGeneratedMigrations(migrationsDir=path.userMigrationsPath()){const files=findIgnoredMigrations(migrationsDir).filter((file)=>isGeneratedMigration(migrationsDir,file));if(!files.length)return[];const result=spawnSync("git",["add","--intent-to-add","--force","--",...files],{cwd:migrationsDir,encoding:"utf8",timeout:5000});if(result.status!==0){const reason=result.error?.message||result.stderr.trim()||"git add failed";throw Error(`Could not make generated migrations visible to Git: ${reason}. Resolve the Git error and rerun buddy generate:migrations.`)}return files}export function describeIgnoreRule(migrationsDir,file){try{const result=spawnSync("git",["check-ignore","-v",file],{cwd:migrationsDir,encoding:"utf8",timeout:5000});
|
|
1
|
+
import{spawnSync}from"node:child_process";import fs from"node:fs";import{basename}from"node:path";import{path}from"@stacksjs/path";import{isGeneratedMigration}from"./generated-migration-marker";export function findIgnoredMigrations(migrationsDir=path.userMigrationsPath()){let files;try{files=fs.readdirSync(migrationsDir).filter((file)=>file.endsWith(".sql"))}catch{return[]}if(!files.length)return[];try{const result=spawnSync("git",["check-ignore","--stdin","-z"],{cwd:migrationsDir,input:`${files.join("\x00")}\x00`,encoding:"utf8",timeout:5000});if(result.status!==0||typeof result.stdout!=="string")return[];return result.stdout.split("\x00").filter(Boolean).map((file)=>basename(file)).sort()}catch{return[]}}export function trackIgnoredGeneratedMigrations(migrationsDir=path.userMigrationsPath()){const files=findIgnoredMigrations(migrationsDir).filter((file)=>isGeneratedMigration(migrationsDir,file));if(!files.length)return[];const result=spawnSync("git",["add","--intent-to-add","--force","--",...files],{cwd:migrationsDir,encoding:"utf8",timeout:5000});if(result.status!==0){const reason=result.error?.message||result.stderr.trim()||"git add failed";throw new Error(`Could not make generated migrations visible to Git: ${reason}. Resolve the Git error and rerun buddy generate:migrations.`)}return files}export function describeIgnoreRule(migrationsDir,file){try{const result=spawnSync("git",["check-ignore","-v",file],{cwd:migrationsDir,encoding:"utf8",timeout:5000});const line=result.status===0?result.stdout.trim():"";const rule=line.split("\t")[0];return rule||null}catch{return null}}export function formatIgnoredMigrations(files,migrationsDir=path.userMigrationsPath()){const shown=files.slice(0,5).map((file)=>` - database/migrations/${file}`);if(files.length>5)shown.push(` - …and ${files.length-5} more`);const rule=files[0]?describeIgnoreRule(migrationsDir,files[0]):null;return[`${files.length===1?"A migration is":`${files.length} migrations are`} ignored by git and will never be committed:`,...shown,rule?`The rule matching them: ${rule}`:"A gitignore rule (often a global `*.sql`) matches them.","They run here, but CI and the deploy will build a database without them.","Run `buddy generate:migrations` to register ignored generated migrations for normal Git staging.","For an existing unmarked migration, use `git add --force -- <migration-path>` after reviewing it."].join(`
|
|
2
2
|
`)}
|
package/dist/index-shape.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const unquoteIdentifiers=(sql)=>sql.replace(/["'`[\]]/g,"")
|
|
1
|
+
const unquoteIdentifiers=(sql)=>sql.replace(/["'`[\]]/g,"");const collapseWhitespace=(sql)=>sql.replace(/\s+/g," ").trim();export function indexShape(statement){const head=/^\s*CREATE\s+(UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?["'`[]?([\w$]+)["'`\]]?\s+ON\s+["'`[]?([\w$]+)["'`\]]?\s*\(/i.exec(statement);if(!head?.[2]||!head[3])return;let depth=1;let end=head[0].length;for(;end<statement.length&&depth>0;end++){if(statement[end]==="(")depth++;else if(statement[end]===")")depth--}if(depth>0)return;const columns=statement.slice(head[0].length,end-1).split(",").map((column)=>collapseWhitespace(unquoteIdentifiers(column)).toLowerCase().replace(/\s+asc$/,""));const where=collapseWhitespace(unquoteIdentifiers(statement.slice(end)).replace(/;\s*$/,"")).toLowerCase();const table=head[3].toLowerCase();return{name:head[2].toLowerCase(),table,key:`${head[1]?"unique":"index"} ${table} (${columns.join(", ")})${where?` ${where}`:""}`}}export function postgresIndexStatement(definition){return definition.replace(/\bON\s+ONLY\s+/i,"ON ").replace(/\bON\s+(?:"[^"]+"|\w+)\.("?[\w$]+"?)/i,"ON $1").replace(/\s+USING\s+btree\s*\(/i," (")}export function comparableIndexKey(statement){const shape=indexShape(statement);if(!shape)return;return collapseWhitespace(shape.key.replace(/::\s*(?:"[^"]+"|[a-z_]\w*)(?:\s+varying|\s+precision|\s+with(?:out)?\s+time\s+zone)?(?:\[\])?/gi,"").replace(/[()]/g," ").replace(/\s*,\s*/g,", "))}
|
package/dist/managed-columns.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const USERS_GUARANTEED_COLUMNS=["email_verified_at","password_changed_at","two_factor_secret","two_factor_enabled","two_factor_last_used_step","stripe_id"];export async function frameworkManagedColumns(){const managed=new Map;managed.set("users",new Set(USERS_GUARANTEED_COLUMNS));const add=(table,column)=>{const columns=managed.get(table)??new Set;columns.add(column);managed.set(table,columns)};try{const{findUuidTables}=await import("./uuid-columns");for(const table of await findUuidTables())add(table,"uuid")}catch{}try{const{findRelationForeignKeys}=await import("./relation-columns");for(const[table,columns]of await findRelationForeignKeys())for(const column of columns)add(table,column)}catch{}return managed}export function isManagedColumnDrop(op,managed){return op.kind==="drop_column"&&op.column!=null&&(managed.get(op.table)?.has(op.column)
|
|
1
|
+
export const USERS_GUARANTEED_COLUMNS=["email_verified_at","password_changed_at","two_factor_secret","two_factor_enabled","two_factor_last_used_step","stripe_id"];export async function frameworkManagedColumns(){const managed=new Map;managed.set("users",new Set(USERS_GUARANTEED_COLUMNS));const add=(table,column)=>{const columns=managed.get(table)??new Set;columns.add(column);managed.set(table,columns)};try{const{findUuidTables}=await import("./uuid-columns");for(const table of await findUuidTables())add(table,"uuid")}catch{}try{const{findRelationForeignKeys}=await import("./relation-columns");for(const[table,columns]of await findRelationForeignKeys()){for(const column of columns)add(table,column)}}catch{}return managed}export function isManagedColumnDrop(op,managed){return op.kind==="drop_column"&&op.column!=null&&(managed.get(op.table)?.has(op.column)??false)}export function withoutManagedColumnDrops(operations,managed){const suppressed=new Set(operations.filter((op)=>isManagedColumnDrop(op,managed)).map((op)=>op.sql?normalizeSql(op.sql):"").filter((sql)=>sql.length>0));return operations.filter((op)=>{if(isManagedColumnDrop(op,managed))return false;return!(op.sql&&suppressed.has(normalizeSql(op.sql)))})}function normalizeSql(sql){return sql.trim().replace(/\s+/g," ").replace(/;+\s*$/,"")}const DROP_COLUMN_RE=/ALTER\s+TABLE\s+["'`]?(\w+)["'`]?\s+DROP\s+COLUMN\s+(?:IF\s+EXISTS\s+)?["'`]?(\w+)["'`]?/i;export function withoutManagedColumnDropSql(statements,managed,operations=[]){const protectedSql=new Set(operations.filter((op)=>isManagedColumnDrop(op,managed)).map((op)=>normalizeSql(op.sql)));const removed=[];const kept=statements.filter((statement)=>{if(protectedSql.has(normalizeSql(statement))){removed.push(statement);return false}const match=statement.match(DROP_COLUMN_RE);if(match?.[1]&&match[2]&&(managed.get(match[1])?.has(match[2])??false)){removed.push(statement);return false}return true});return{statements:kept,removed}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync,readdirSync,readFileSync}from"node:fs";import{join}from"node:path";const MARKERS=[{dialect:"sqlite",pattern:/\bAUTOINCREMENT\b/i,label:"AUTOINCREMENT"},{dialect:"sqlite",pattern:/\bWITHOUT\s+ROWID\b/i,label:"WITHOUT ROWID"},{dialect:"sqlite",pattern:/\bPRAGMA\b/i,label:"PRAGMA"},{dialect:"mysql",pattern:/\bAUTO_INCREMENT\b/i,label:"AUTO_INCREMENT"},{dialect:"mysql",pattern:/\bENGINE\s*=/i,label:"ENGINE="},{dialect:"postgres",pattern:/\bBIGSERIAL\b/i,label:"BIGSERIAL"},{dialect:"postgres",pattern:/\bSERIAL\b/i,label:"SERIAL"},{dialect:"postgres",pattern:/\bCREATE\s+TYPE\b/i,label:"CREATE TYPE"},{dialect:"postgres",pattern:/\bGENERATED\s+(?:ALWAYS|BY\s+DEFAULT)\s+AS\s+IDENTITY\b/i,label:"GENERATED AS IDENTITY"}];export function stripSqlNoise(sql){let out=""
|
|
2
|
-
`)
|
|
3
|
-
`)
|
|
1
|
+
import{existsSync,readdirSync,readFileSync}from"node:fs";import{join}from"node:path";const MARKERS=[{dialect:"sqlite",pattern:/\bAUTOINCREMENT\b/i,label:"AUTOINCREMENT"},{dialect:"sqlite",pattern:/\bWITHOUT\s+ROWID\b/i,label:"WITHOUT ROWID"},{dialect:"sqlite",pattern:/\bPRAGMA\b/i,label:"PRAGMA"},{dialect:"mysql",pattern:/\bAUTO_INCREMENT\b/i,label:"AUTO_INCREMENT"},{dialect:"mysql",pattern:/\bENGINE\s*=/i,label:"ENGINE="},{dialect:"postgres",pattern:/\bBIGSERIAL\b/i,label:"BIGSERIAL"},{dialect:"postgres",pattern:/\bSERIAL\b/i,label:"SERIAL"},{dialect:"postgres",pattern:/\bCREATE\s+TYPE\b/i,label:"CREATE TYPE"},{dialect:"postgres",pattern:/\bGENERATED\s+(?:ALWAYS|BY\s+DEFAULT)\s+AS\s+IDENTITY\b/i,label:"GENERATED AS IDENTITY"}];export function stripSqlNoise(sql){let out="";let i=0;const blank=(text)=>text.replace(/[^\n]/g," ");while(i<sql.length){const rest=sql.slice(i);const line=rest.match(/^--[^\n]*/);if(line){out+=blank(line[0]);i+=line[0].length;continue}if(rest.startsWith("/*")){const end=rest.indexOf("*/");const chunk=end===-1?rest:rest.slice(0,end+2);out+=blank(chunk);i+=chunk.length;continue}const quote=rest[0];if(quote==='"'||quote==="'"||quote==="`"){let j=1;while(j<rest.length&&rest[j]!==quote)j++;const chunk=rest.slice(0,Math.min(j+1,rest.length));out+=blank(chunk);i+=chunk.length;continue}out+=sql[i];i+=1}return out}export function classifyMigrationSql(sql,file){const cleaned=stripSqlNoise(sql);const lines=cleaned.split(`
|
|
2
|
+
`);const rawLines=sql.split(`
|
|
3
|
+
`);const found=[];for(let index=0;index<lines.length;index++){for(const{dialect,pattern,label}of MARKERS){if(pattern.test(lines[index]??"")){found.push({dialect,marker:label,file,line:index+1,snippet:(rawLines[index]??"").trim().slice(0,120)})}}}return found}export function auditMigrationCorpus(options){const{dir,target}=options;if(!existsSync(dir))return{total:0,inferred:null,incompatible:[],empty:true};let files;try{files=readdirSync(dir).filter((f)=>f.endsWith(".sql")).sort()}catch{return{total:0,inferred:null,incompatible:[],empty:true}}if(options.only){const judged=new Set(options.only);files=files.filter((file)=>judged.has(file))}const all=[];for(const file of files){let sql;try{sql=readFileSync(join(dir,file),"utf8")}catch{continue}all.push(...classifyMigrationSql(sql,file))}const dialects=new Set(all.map((m)=>m.dialect));return{total:files.length,inferred:dialects.size===1?[...dialects][0]??null:null,incompatible:all.filter((m)=>m.dialect!==target),empty:files.length===0}}export const DIALECT_OVERRIDE_ENV="STACKS_ALLOW_DIALECT_MISMATCH";export function formatMigrationDialectError(audit,target,dir){const affected=new Set(audit.incompatible.map((m)=>m.file));const sample=audit.incompatible.slice(0,3);const inferred=audit.inferred?`${audit.inferred}-flavoured`:"written for a different database";const lines=[`The migration files in ${dir} are ${inferred} and cannot run on ${target}.`,`${affected.size} of ${audit.total} files use SQL that ${target} does not accept. For example:`,...sample.map((m)=>` ${m.file}:${m.line} ${m.marker}`),"",`Nothing was migrated, so the database is unchanged.`,"",`Stacks ships one set of migration files, and they are emitted for a single database.`,`Regenerate them from your models:`,` ./buddy migrate:regenerate ${target}`,`or point DB_CONNECTION back at the database they were written for.`,"",`If you know this corpus is correct, re-run with ${DIALECT_OVERRIDE_ENV}=1 to proceed anyway.`];return lines.join(`
|
|
4
4
|
`)}
|
package/dist/migration-ledger.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,readdirSync,readFileSync}from"node:fs";import{join}from"node:path";import{resolvedDatabaseDriver}from"./dialect";import{comparableIndexKey,postgresIndexStatement}from"./index-shape";import{resolveMigrationDirectory}from"./migration-path";import{guardedBlockStatements,sqlStatementsOf}from"./sql-statements";const SAFE_MIGRATION_FILE=/^[\w.-]+\.sql$/,IDENT=String.raw`["\`\[]?([A-Za-z_]\w*)["\`\]]?`;export function stripForEffects(sql){let out="",i=0;const blank=(text)=>text.replace(/[^\n]/g," ");while(i<sql.length){const rest=sql.slice(i),line=rest.match(/^--[^\n]*/);if(line){out+=blank(line[0]);i+=line[0].length;continue}if(rest.startsWith("/*")){const end=rest.indexOf("*/"),chunk=end===-1?rest:rest.slice(0,end+2);out+=blank(chunk);i+=chunk.length;continue}if(rest[0]==="'"){let j=1;while(j<rest.length&&rest[j]!=="'")j++;const chunk=rest.slice(0,Math.min(j+1,rest.length));out+=blank(chunk);i+=chunk.length;continue}out+=sql[i];i+=1}return out}function withoutGuard(statement){const inner=guardedBlockStatements(statement);return inner?inner.flatMap(withoutGuard):[statement]}function rawStatementsOf(sql){return sqlStatementsOf(sql).flatMap(withoutGuard)}function statementsOf(sql){return rawStatementsOf(stripForEffects(sql)).map((s)=>s.trim()).filter((s)=>s.length>0)}export function logicalName(file){return file.replace(/^\d+[-_]/,"").replace(/\.sql$/i,"")}export function migrationRemovals(sql){const removals=[],seen=new Set,push=(effect)=>{const key=effectKey(effect);if(seen.has(key))return;seen.add(key);removals.push(effect)};for(const statement of statementsOf(sql)){const index=new RegExp(String.raw`^DROP\s+INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+EXISTS\s+)?${IDENT}`,"i").exec(statement);if(index?.[1]){push({kind:"index",name:index[1]});continue}const table=new RegExp(String.raw`^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?${IDENT}`,"i").exec(statement);if(table?.[1]){push({kind:"table",name:table[1]});continue}const enumType=new RegExp(String.raw`^DROP\s+TYPE\s+(?:IF\s+EXISTS\s+)?${IDENT}`,"i").exec(statement);if(enumType?.[1]){push({kind:"enum",name:enumType[1]});continue}const alter=new RegExp(String.raw`^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?${IDENT}\s+(.*)$`,"is").exec(statement);if(!alter?.[1])continue;const owner=alter[1];for(const clause of(alter[2]??"").split(",")){const constraint=new RegExp(String.raw`^\s*DROP\s+CONSTRAINT\s+(?:IF\s+EXISTS\s+)?${IDENT}`,"i").exec(clause);if(constraint?.[1]){push({kind:"constraint",table:owner,name:constraint[1]});continue}const column=new RegExp(String.raw`^\s*DROP\s+(?:COLUMN\s+)?(?:IF\s+EXISTS\s+)?${IDENT}`,"i").exec(clause);if(column?.[1]&&!/^(?:constraint|index|key|primary|foreign|unique|check|default|partition)$/i.test(column[1]))push({kind:"column",table:owner,name:column[1]})}}return removals}export function migrationEffects(sql){const effects=[],seen=new Set,renamedAway=new Set,push=(effect)=>{const key=effectKey(effect);if(seen.has(key))return;seen.add(key);effects.push(effect)},shapes=new Map;for(const statement of rawStatementsOf(sql)){const match=/^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?["`[]?([\w$]+)/i.exec(statement),key=match?.[1]?comparableIndexKey(statement):void 0;if(match?.[1]&&key)shapes.set(match[1].toLowerCase(),key)}for(const statement of statementsOf(sql)){const create=new RegExp(String.raw`^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?${IDENT}`,"i").exec(statement);if(create?.[1]){push({kind:"table",name:create[1]});continue}const rename=new RegExp(String.raw`^ALTER\s+TABLE\s+${IDENT}\s+RENAME\s+TO\s+${IDENT}`,"i").exec(statement);if(rename?.[2]){if(rename[1])renamedAway.add(rename[1].toLowerCase());push({kind:"table",name:rename[2]});continue}const index=new RegExp(String.raw`^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?${IDENT}(?:\s+ON\s+${IDENT})?`,"i").exec(statement);if(index?.[1]){const shape=shapes.get(index[1].toLowerCase());push({kind:"index",name:index[1],...index[2]?{table:index[2]}:{},...shape?{shape}:{}});continue}const enumType=new RegExp(String.raw`^CREATE\s+TYPE\s+${IDENT}\s+AS\s+ENUM`,"i").exec(statement);if(enumType?.[1]){push({kind:"enum",name:enumType[1]});continue}const alter=new RegExp(String.raw`^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?${IDENT}\s+(.*)$`,"is").exec(statement);if(!alter?.[1]||!alter[2])continue;const table=alter[1],addColumn=new RegExp(String.raw`\bADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?${IDENT}`,"gi");for(const m of alter[2].matchAll(addColumn))if(m[1])push({kind:"column",table,name:m[1]});const addConstraint=new RegExp(String.raw`\bADD\s+CONSTRAINT\s+(?:IF\s+NOT\s+EXISTS\s+)?${IDENT}`,"gi");for(const m of alter[2].matchAll(addConstraint))if(m[1])push({kind:"constraint",table,name:m[1]});const addBare=new RegExp(String.raw`\bADD\s+(?!COLUMN\b|CONSTRAINT\b|INDEX\b|KEY\b|PRIMARY\b|UNIQUE\b|FOREIGN\b|FULLTEXT\b|SPATIAL\b|CHECK\b)${IDENT}\s+\w`,"gi");for(const m of alter[2].matchAll(addBare))if(m[1])push({kind:"column",table,name:m[1]})}if(renamedAway.size===0)return effects;return effects.filter((effect)=>{const owner=(effect.kind==="table"?effect.name:effect.table??"").toLowerCase();return!renamedAway.has(owner)})}function effectKey(effect){return`${effect.kind}:${(effect.table??"").toLowerCase()}.${effect.name.toLowerCase()}`}function removalKey(effect){if(effect.kind==="column"||effect.kind==="constraint")return effectKey(effect);return`${effect.kind}:${effect.name.toLowerCase()}`}export function verifiableEffects(effects,dialect){if(dialect==="postgres")return effects;if(dialect==="mysql")return effects.filter((e)=>e.kind!=="enum");return effects.filter((e)=>e.kind!=="constraint"&&e.kind!=="enum")}function emptySchema(){return{tables:new Set,columns:new Map,indexes:new Set,indexShapes:new Set,constraints:new Set,enums:new Set}}function rowsOf(result){return Array.isArray(result)?result:[]}async function defaultRunner(){const{db}=await import("./utils");return async(sql)=>rowsOf(await db.unsafe(sql).execute())}function pick(row,...keys){for(const key of keys){const value=row?.[key]??row?.[key.toLowerCase()]??row?.[key.toUpperCase()];if(typeof value==="string"&&value.length>0)return value}return""}export async function readLiveSchema(dialect,runner){const schema=emptySchema(),run=runner??await defaultRunner();if(dialect==="sqlite"){for(const row of await run("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")){const name=pick(row,"name");if(name)schema.tables.add(name.toLowerCase())}for(const row of await run("SELECT name, sql FROM sqlite_master WHERE type='index' AND name NOT LIKE 'sqlite_%'")){const name=pick(row,"name");if(name)schema.indexes.add(name.toLowerCase());const key=comparableIndexKey(pick(row,"sql"));if(key)schema.indexShapes.add(key)}for(const table of schema.tables){if(!/^[a-z_]\w*$/i.test(table))continue;const cols=new Set;for(const row of await run(`PRAGMA table_info("${table}")`)){const name=pick(row,"name");if(name)cols.add(name.toLowerCase())}schema.columns.set(table,cols)}return schema}if(dialect==="mysql"){for(const row of await run("SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE()")){const name=pick(row,"name","TABLE_NAME");if(name)schema.tables.add(name.toLowerCase())}for(const row of await run("SELECT TABLE_NAME, COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE()")){const table=pick(row,"TABLE_NAME").toLowerCase(),column=pick(row,"COLUMN_NAME").toLowerCase();if(!table||!column)continue;if(!schema.columns.has(table))schema.columns.set(table,new Set);schema.columns.get(table).add(column)}for(const row of await run("SELECT DISTINCT INDEX_NAME AS name FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE()")){const name=pick(row,"name","INDEX_NAME");if(name)schema.indexes.add(name.toLowerCase())}for(const row of await run("SELECT CONSTRAINT_NAME AS name FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE()")){const name=pick(row,"name","CONSTRAINT_NAME");if(name)schema.constraints.add(name.toLowerCase())}return schema}for(const row of await run("SELECT tablename AS name FROM pg_tables WHERE schemaname = 'public'")){const name=pick(row,"name","tablename");if(name)schema.tables.add(name.toLowerCase())}for(const row of await run("SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = 'public'")){const table=pick(row,"table_name").toLowerCase(),column=pick(row,"column_name").toLowerCase();if(!table||!column)continue;if(!schema.columns.has(table))schema.columns.set(table,new Set);schema.columns.get(table).add(column)}for(const row of await run("SELECT indexname AS name, indexdef AS definition FROM pg_indexes WHERE schemaname = 'public'")){const name=pick(row,"name","indexname");if(name)schema.indexes.add(name.toLowerCase());const key=comparableIndexKey(postgresIndexStatement(pick(row,"definition","indexdef")));if(key)schema.indexShapes.add(key)}for(const row of await run("SELECT c.conname AS name FROM pg_constraint c JOIN pg_namespace n ON n.oid = c.connamespace WHERE n.nspname = 'public'")){const name=pick(row,"name","conname");if(name)schema.constraints.add(name.toLowerCase())}for(const row of await run("SELECT t.typname AS name FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace WHERE t.typtype = 'e' AND n.nspname = 'public'")){const name=pick(row,"name","typname");if(name)schema.enums.add(name.toLowerCase())}return schema}export function effectPresent(effect,schema){const name=effect.name.toLowerCase();switch(effect.kind){case"table":return schema.tables.has(name);case"column":return schema.columns.get((effect.table??"").toLowerCase())?.has(name)??!1;case"index":{if(schema.indexes.has(name))return!0;if(effect.shape&&schema.indexShapes.has(effect.shape))return!0;const table=(effect.table??"").toLowerCase();if(!table)return!1;return schema.indexes.has(`${table}_${name}`)}case"constraint":return schema.constraints.has(name);case"enum":return schema.enums.has(name)}}export function classifyMigration(recorded,present,absent){const verifiable=present.length+absent.length;if(recorded){if(verifiable===0||absent.length===0)return"applied";return"reverted"}if(verifiable===0)return"unverifiable";if(absent.length===0)return"stranded";if(present.length===0)return"pending";return"partial"}function migrationsDir(dir){if(dir)return dir;const driver=resolvedDatabaseDriver().toLowerCase();return resolveMigrationDirectory(driver==="singlestore"?"singlestore":driver)}function listMigrationFiles(dir){if(!existsSync(dir))return[];try{return readdirSync(dir).filter((f)=>f.toLowerCase().endsWith(".sql")).sort()}catch{return[]}}function currentDialect(){const driver=resolvedDatabaseDriver().toLowerCase();if(driver==="sqlite"||driver==="mysql"||driver==="postgres")return driver;if(driver==="vitess"||driver==="singlestore")return"mysql";if(driver==="turso"||driver==="libsql")return"sqlite";return"other"}export async function readLedger(runner){try{return(await(runner??await defaultRunner())("SELECT migration FROM migrations")).map((row)=>pick(row,"migration")).filter((name)=>name.length>0).sort()}catch{return[]}}export function planLedgerRemap(ledger,diskFiles){const onDisk=new Set(diskFiles),byLogical=new Map;for(const file of diskFiles){const key=logicalName(file);if(!byLogical.has(key))byLogical.set(key,[]);byLogical.get(key).push(file)}const claimed=new Set(ledger.filter((row)=>onDisk.has(row))),remap=[],ambiguous=[],dropped=[],superseded=[],targets=new Map;for(const row of ledger){if(onDisk.has(row))continue;const sameLogical=byLogical.get(logicalName(row))??[],candidates=sameLogical.filter((f)=>!claimed.has(f));if(candidates.length===0){if(sameLogical.length>0)superseded.push(row);else dropped.push(row);continue}if(candidates.length>1){ambiguous.push(row);continue}const to=candidates[0];if(!targets.has(to))targets.set(to,[]);targets.get(to).push(row);remap.push({from:row,to})}const contested=new Set([...targets.entries()].filter(([,rows])=>rows.length>1).flatMap(([,rows])=>rows));if(contested.size===0)return{remap,ambiguous,dropped,superseded};return{remap:remap.filter((r)=>!contested.has(r.from)),ambiguous:[...ambiguous,...contested].sort(),dropped,superseded}}export async function auditMigrationLedger(options={}){const dir=migrationsDir(options.dir),dialect=options.dialect??currentDialect(),files=listMigrationFiles(dir),counts={applied:0,stranded:0,pending:0,partial:0,unverifiable:0,reverted:0},emptyPlan={remap:[],ambiguous:[],dropped:[],superseded:[]};if(dialect==="other")return{supported:!1,dialect,dir,entries:[],orphans:[],gated:[],counts,recordedCount:0,remapPlan:emptyPlan,drift:!1};const run=options.run??await defaultRunner(),ledger=await readLedger(run),recorded=new Set(ledger),schema=await readLiveSchema(dialect,run),gate=await resolveGate(options,dir),sources=new Map,gated=files.filter((file)=>gate?.exclude.has(file));for(const file of files){if(gate?.exclude.has(file))continue;try{const sql=readFileSync(join(dir,file),"utf8");sources.set(file,gate?gate.rewrite(sql):sql)}catch{continue}}const readFiles=[...sources.keys()],removedLater=new Map,tablesDroppedLater=new Map;for(let i=0;i<readFiles.length;i++){const laterKeys=new Set,laterTables=new Set;for(let j=i+1;j<readFiles.length;j++)for(const removal of migrationRemovals(sources.get(readFiles[j]))){laterKeys.add(removalKey(removal));if(removal.kind==="table")laterTables.add(removal.name.toLowerCase())}removedLater.set(readFiles[i],laterKeys);tablesDroppedLater.set(readFiles[i],laterTables)}const entries=[];for(const file of readFiles){const sql=sources.get(file),effects=verifiableEffects(migrationEffects(sql),dialect),dropped=removedLater.get(file)??new Set,droppedTables=tablesDroppedLater.get(file)??new Set,survives=(effect)=>effectPresent(effect,schema)||dropped.has(removalKey(effect))||effect.table!==void 0&&droppedTables.has(effect.table.toLowerCase()),present=effects.filter(survives),absent=effects.filter((effect)=>!survives(effect)),isRecorded=recorded.has(file),status=classifyMigration(isRecorded,present,absent);counts[status]+=1;entries.push({file,logical:logicalName(file),recorded:isRecorded,status,effects,present,absent})}const readable=[...entries.map((entry)=>entry.file),...gated].sort(),remapPlan=planLedgerRemap(ledger,readable),renamedTo=new Map(remapPlan.remap.map((r)=>[r.from,r.to])),orphans=ledger.filter((row)=>!readable.includes(row)).map((row)=>({migration:row,renamedTo:renamedTo.get(row)})),drift=counts.stranded>0||counts.partial>0||counts.reverted>0||orphans.length>0;return{supported:!0,dialect,dir,entries,orphans,gated,counts,recordedCount:ledger.length,remapPlan,drift}}async function ensureLedgerTable(dialect,run){const id=dialect==="postgres"?"id SERIAL PRIMARY KEY":dialect==="mysql"?"id INT AUTO_INCREMENT PRIMARY KEY":"id INTEGER PRIMARY KEY AUTOINCREMENT",timestamp=dialect==="postgres"?"TIMESTAMP":"DATETIME",utcNow=dialect==="postgres"?"(now() AT TIME ZONE 'utc')":dialect==="mysql"?"(UTC_TIMESTAMP)":"CURRENT_TIMESTAMP";await run(`CREATE TABLE IF NOT EXISTS migrations (${id}, migration VARCHAR(255) NOT NULL UNIQUE, executed_at ${timestamp} DEFAULT ${utcNow})`);if(dialect!=="sqlite")try{await run(`ALTER TABLE migrations ALTER COLUMN executed_at SET DEFAULT ${utcNow}`)}catch{}}const Q=(pattern)=>new RegExp(pattern.replaceAll("{id}",IDENT),"i"),CREATE_TABLE=Q(String.raw`^CREATE\s+(?:TEMP(?:ORARY)?\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?{id}`),DROP_TABLE=Q(String.raw`^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?{id}`),RENAME_TABLE=Q(String.raw`^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?{id}\s+RENAME\s+TO\s+{id}`),ALTER_TABLE=Q(String.raw`^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?{id}`),CREATE_INDEX=Q(String.raw`^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?{id}\s+ON\s+(?:ONLY\s+)?{id}`),DROP_INDEX=Q(String.raw`^DROP\s+INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+EXISTS\s+)?{id}(?:\s+ON\s+{id})?`),DML=Q(String.raw`^(?:INSERT\s+(?:OR\s+\w+\s+)?INTO|REPLACE\s+INTO|UPDATE|DELETE\s+FROM)\s+{id}`),NEUTRAL=/^(?:BEGIN|COMMIT|END|PRAGMA|SET|SELECT\s+1|COMMENT\s+ON|CREATE\s+TYPE\s+\S+\s+AS\s+ENUM|ALTER\s+TYPE\s+\S+\s+ADD\s+VALUE|STACKS_ENUM_GUARD)\b/i;function statementShape(statement,indexTables){const lower=(name)=>(name??"").toLowerCase();if(NEUTRAL.test(statement))return{modifies:[]};let m=RENAME_TABLE.exec(statement);if(m)return{modifies:[lower(m[1]),lower(m[2])],rename:{from:lower(m[1]),to:lower(m[2])}};m=CREATE_TABLE.exec(statement);if(m)return{modifies:[lower(m[1])],creates:lower(m[1])};m=DROP_TABLE.exec(statement);if(m)return{modifies:[lower(m[1])],drops:lower(m[1])};m=ALTER_TABLE.exec(statement);if(m)return{modifies:[lower(m[1])]};m=CREATE_INDEX.exec(statement);if(m)return{modifies:[lower(m[2])],index:{name:lower(m[1]),table:lower(m[2])}};m=DROP_INDEX.exec(statement);if(m){const table=m[2]?lower(m[2]):indexTables.get(lower(m[1]));return table?{modifies:[table]}:{modifies:[],unknown:!0}}m=DML.exec(statement);if(m)return{modifies:[lower(m[1])]};return{modifies:[],unknown:!0}}function requeueStatements(sql){return stripForEffects(sql).replace(/\bDO\s+\$(\w*)\$([\s\S]*?)\$\1\$/gi,(block,_tag,body)=>/^\s*BEGIN\s+CREATE\s+TYPE\b[\s\S]*\bEXCEPTION\s+WHEN\s+duplicate_object\s+THEN\s+null\s*;\s*END\s*$/i.test(body)?"STACKS_ENUM_GUARD":block).split(";").map((statement)=>statement.trim()).filter(Boolean)}async function resolveGate(options,dir){if(options.gate||options.dir)return options.gate;try{const{featureGateForLedger}=await import("./migrations");return await featureGateForLedger(dir)}catch{return}}export function planRequeue(files,liveTables){const ordered=[...files].sort((a,b)=>a.file.localeCompare(b.file)),indexTables=new Map,expected=new Set,lineageOf=new Map,lineage=(table)=>{let group=lineageOf.get(table);if(!group){group=new Set([table]);lineageOf.set(table,group)}return group},link=(a,b)=>{const merged=new Set([...lineage(a),...lineage(b)]);for(const name of merged)lineageOf.set(name,merged)},shapes=ordered.map(({file,sql,recorded})=>{const statements=requeueStatements(sql).map((statement)=>statementShape(statement,indexTables));for(const shape of statements){if(shape.index)indexTables.set(shape.index.name,shape.index.table);if(shape.creates)expected.add(shape.creates);if(shape.drops)expected.delete(shape.drops);if(shape.rename){expected.delete(shape.rename.from);expected.add(shape.rename.to);link(shape.rename.from,shape.rename.to)}}const created=new Set(statements.flatMap((shape)=>shape.creates?[shape.creates]:[])),removed=new Set(statements.flatMap((shape)=>[shape.drops,shape.rename?.from].filter((t)=>Boolean(t)))),scaffold=new Set([...created].filter((table)=>removed.has(table)||statements.some((shape)=>shape.rename?.from===table)));return{file,recorded,unknown:statements.some((shape)=>shape.unknown),modifies:new Set(statements.flatMap((shape)=>shape.modifies)),scaffold}}),missing=[...expected].filter((table)=>!liveTables.has(table)).sort(),rebuildable=new Set(missing.flatMap((table)=>[...lineage(table)]).filter((table)=>!liveTables.has(table))),chains=new Map(missing.map((table)=>{const names=lineage(table);return[table,shapes.filter((shape)=>[...shape.modifies].some((name)=>names.has(name)))]})),why=new Map;for(const[table,chain]of chains)for(const shape of chain){if(shape.unknown){why.set(table,`${shape.file} contains a statement the planner cannot classify`);break}const elsewhere=[...shape.modifies].filter((t)=>!rebuildable.has(t)&&!shape.scaffold.has(t));if(elsewhere.length>0){why.set(table,`${shape.file} also changes ${elsewhere.join(", ")}, which ${elsewhere.length===1?"is":"are"} not missing`);break}}let changed=!0;while(changed){changed=!1;for(const[table,chain]of chains){if(why.has(table))continue;const blocker=chain.flatMap((shape)=>[...shape.modifies]).find((other)=>other!==table&&missing.some((t)=>why.has(t)&&lineage(t).has(other)));if(blocker){why.set(table,`shares a migration with ${blocker}, which cannot be rebuilt`);changed=!0}}}const requeue=new Set;for(const[table,chain]of chains){if(why.has(table))continue;for(const shape of chain)if(shape.recorded)requeue.add(shape.file)}return{missing,requeue:ordered.map(({file})=>file).filter((file)=>requeue.has(file)),refused:[...why].map(([table,reason])=>({table,reason}))}}export async function auditMissingTables(options={}){const dialect=options.dialect??currentDialect();if(dialect==="other")return{supported:!1,missing:[],live:new Set};const dir=migrationsDir(options.dir),run=options.run??await defaultRunner(),recorded=new Set(await readLedger(run)),gate=await resolveGate(options,dir),files=listMigrationFiles(dir).filter((file)=>recorded.has(file)&&!gate?.exclude.has(file)).flatMap((file)=>{try{const sql=readFileSync(join(dir,file),"utf8");return[{file,sql:gate?gate.rewrite(sql):sql,recorded:!0}]}catch{return[]}}),live=await readLiveSchema(dialect,run);return{supported:!0,missing:planRequeue(files,live.tables).missing,live:live.tables}}function byLogicalOnDisk(row,diskFiles){const key=logicalName(row),matches=diskFiles.filter((f)=>logicalName(f)===key);return matches.length===1?matches[0]:void 0}export async function reconcileMigrationLedger(options={}){const run=options.run??await defaultRunner(),gate=await resolveGate(options,migrationsDir(options.dir)),audit=await auditMigrationLedger({dir:options.dir,dialect:options.dialect,run,gate}),result={remapped:[],recorded:[],pruned:[],requeued:[],retired:[],skipped:[]};if(!audit.supported){result.skipped.push({file:"*",reason:`dialect "${audit.dialect}" is not audited`});return result}const written=new Set(options.regenerated?.written??[]),removedByRegeneration=new Set(options.regenerated?.removed??[]),onDisk=new Set([...audit.entries.map((entry)=>entry.file),...audit.gated]),plan={...audit.remapPlan,remap:audit.remapPlan.remap.filter((r)=>!written.has(r.to))},retirable=[...audit.remapPlan.remap.filter((r)=>written.has(r.to)).map((r)=>r.from),...audit.remapPlan.dropped,...audit.remapPlan.superseded,...audit.remapPlan.ambiguous].filter((row)=>removedByRegeneration.has(row)&&!onDisk.has(row)&&SAFE_MIGRATION_FILE.test(row)),retiring=new Set(retirable);for(const row of plan.ambiguous.filter((row)=>!retiring.has(row)))result.skipped.push({file:row,reason:"ledger row matches more than one file by logical name"});for(const row of plan.dropped.filter((row)=>!retiring.has(row)))result.skipped.push({file:row,reason:"recorded migration no longer exists on disk"});for(const{from}of audit.remapPlan.remap.filter((r)=>written.has(r.to)&&!retiring.has(r.from)))result.skipped.push({file:from,reason:"its file was replaced by a regenerated one; not repointed, because the contents differ"});const prunable=plan.superseded.filter((row)=>SAFE_MIGRATION_FILE.test(row)&&!retiring.has(row));for(const row of plan.superseded.filter((row)=>!SAFE_MIGRATION_FILE.test(row)))result.skipped.push({file:row,reason:"ledger row is not safe to write to the ledger"});const toRecord=[],revertedEntries=[];for(const entry of audit.entries){if(entry.status==="stranded"){toRecord.push(entry.file);continue}if(entry.status==="partial"){if(options.includePartial){toRecord.push(entry.file);continue}result.skipped.push({file:entry.file,reason:written.has(entry.file)?`${entry.present.length}/${entry.effects.length} effects present - left pending; run \`buddy migrate:align\` first so the next migrate does not duplicate what exists under another name`:`${entry.present.length}/${entry.effects.length} effects present - resolve by hand, or pass --include-partial`});continue}if(entry.status==="reverted")revertedEntries.push(entry)}const toRequeue=[];if(options.requeueReverted){const live=await readLiveSchema(audit.dialect,run),recordedFiles=new Set(audit.entries.filter((entry)=>entry.recorded).map((entry)=>entry.file)),corpus=audit.entries.flatMap((entry)=>{try{const sql=readFileSync(join(audit.dir,entry.file),"utf8");return[{file:entry.file,sql:gate?gate.rewrite(sql):sql,recorded:recordedFiles.has(entry.file)}]}catch{return[]}}),plan=planRequeue(corpus,live.tables);toRequeue.push(...plan.requeue);for(const{table,reason}of plan.refused)result.skipped.push({file:table,reason:`missing table not rebuilt: ${reason}`})}for(const entry of revertedEntries.filter((entry)=>!toRequeue.includes(entry.file))){if(written.has(entry.file)){result.skipped.push({file:entry.file,reason:`recorded under the same name as the file it replaced, but ${entry.absent.length} effect(s) of the regenerated file are missing - \`buddy migrate:align\` creates them`});continue}result.skipped.push({file:entry.file,reason:options.requeueReverted?`recorded, but ${entry.absent.length} effect(s) are missing from the schema`:`recorded, but ${entry.absent.length} effect(s) are missing from the schema - --requeue-reverted rebuilds a table that is gone entirely`})}const unsafe=(file)=>!SAFE_MIGRATION_FILE.test(file);for(const{from,to}of plan.remap.filter((r)=>unsafe(r.from)||unsafe(r.to)))result.skipped.push({file:unsafe(from)?from:to,reason:"migration filename is not safe to write to the ledger"});for(const file of toRecord.filter(unsafe))result.skipped.push({file,reason:"migration filename is not safe to write to the ledger"});const remapped=plan.remap.filter((r)=>!unsafe(r.from)&&!unsafe(r.to)),recordable=toRecord.filter((file)=>!unsafe(file)&&!remapped.some((r)=>r.to===file)),requeueable=toRequeue.filter((file)=>!unsafe(file));for(const file of toRequeue.filter(unsafe))result.skipped.push({file,reason:"migration filename is not safe to write to the ledger"});if(options.dryRun){result.remapped=remapped;result.recorded=recordable;result.pruned=prunable;result.requeued=requeueable;result.retired=retirable;return result}await ensureLedgerTable(audit.dialect,run);for(const{from,to}of remapped){await run(`UPDATE migrations SET migration = '${to}' WHERE migration = '${from}'`);result.remapped.push({from,to})}for(const file of recordable){if((await run(`SELECT migration FROM migrations WHERE migration = '${file}'`)).length>0)continue;await run(`INSERT INTO migrations (migration) VALUES ('${file}')`);result.recorded.push(file)}for(const row of prunable){const survivor=byLogicalOnDisk(row,audit.entries.map((e)=>e.file));if(!survivor)continue;if((await run(`SELECT migration FROM migrations WHERE migration = '${survivor}'`)).length===0){result.skipped.push({file:row,reason:`would leave ${survivor} unrecorded`});continue}await run(`DELETE FROM migrations WHERE migration = '${row}'`);result.pruned.push(row)}for(const row of retirable){await run(`DELETE FROM migrations WHERE migration = '${row}'`);result.retired.push(row)}for(const file of requeueable){await run(`DELETE FROM migrations WHERE migration = '${file}'`);result.requeued.push(file)}return result}
|
|
1
|
+
import{existsSync,readdirSync,readFileSync}from"node:fs";import{join}from"node:path";import{resolvedDatabaseDriver}from"./dialect";import{comparableIndexKey,postgresIndexStatement}from"./index-shape";import{resolveMigrationDirectory}from"./migration-path";import{guardedBlockStatements,sqlStatementsOf}from"./sql-statements";const SAFE_MIGRATION_FILE=/^[\w.-]+\.sql$/;const IDENT=String.raw`["\`\[]?([A-Za-z_]\w*)["\`\]]?`;export function stripForEffects(sql){let out="";let i=0;const blank=(text)=>text.replace(/[^\n]/g," ");while(i<sql.length){const rest=sql.slice(i);const line=rest.match(/^--[^\n]*/);if(line){out+=blank(line[0]);i+=line[0].length;continue}if(rest.startsWith("/*")){const end=rest.indexOf("*/");const chunk=end===-1?rest:rest.slice(0,end+2);out+=blank(chunk);i+=chunk.length;continue}if(rest[0]==="'"){let j=1;while(j<rest.length&&rest[j]!=="'")j++;const chunk=rest.slice(0,Math.min(j+1,rest.length));out+=blank(chunk);i+=chunk.length;continue}out+=sql[i];i+=1}return out}function withoutGuard(statement){const inner=guardedBlockStatements(statement);return inner?inner.flatMap(withoutGuard):[statement]}function rawStatementsOf(sql){return sqlStatementsOf(sql).flatMap(withoutGuard)}function statementsOf(sql){return rawStatementsOf(stripForEffects(sql)).map((s)=>s.trim()).filter((s)=>s.length>0)}export function logicalName(file){return file.replace(/^\d+[-_]/,"").replace(/\.sql$/i,"")}export function migrationRemovals(sql){const removals=[];const seen=new Set;const push=(effect)=>{const key=effectKey(effect);if(seen.has(key))return;seen.add(key);removals.push(effect)};for(const statement of statementsOf(sql)){const index=new RegExp(String.raw`^DROP\s+INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+EXISTS\s+)?${IDENT}`,"i").exec(statement);if(index?.[1]){push({kind:"index",name:index[1]});continue}const table=new RegExp(String.raw`^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?${IDENT}`,"i").exec(statement);if(table?.[1]){push({kind:"table",name:table[1]});continue}const enumType=new RegExp(String.raw`^DROP\s+TYPE\s+(?:IF\s+EXISTS\s+)?${IDENT}`,"i").exec(statement);if(enumType?.[1]){push({kind:"enum",name:enumType[1]});continue}const alter=new RegExp(String.raw`^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?${IDENT}\s+(.*)$`,"is").exec(statement);if(!alter?.[1])continue;const owner=alter[1];for(const clause of(alter[2]??"").split(",")){const constraint=new RegExp(String.raw`^\s*DROP\s+CONSTRAINT\s+(?:IF\s+EXISTS\s+)?${IDENT}`,"i").exec(clause);if(constraint?.[1]){push({kind:"constraint",table:owner,name:constraint[1]});continue}const column=new RegExp(String.raw`^\s*DROP\s+(?:COLUMN\s+)?(?:IF\s+EXISTS\s+)?${IDENT}`,"i").exec(clause);if(column?.[1]&&!/^(?:constraint|index|key|primary|foreign|unique|check|default|partition)$/i.test(column[1]))push({kind:"column",table:owner,name:column[1]})}}return removals}export function migrationEffects(sql){const effects=[];const seen=new Set;const renamedAway=new Set;const push=(effect)=>{const key=effectKey(effect);if(seen.has(key))return;seen.add(key);effects.push(effect)};const shapes=new Map;for(const statement of rawStatementsOf(sql)){const match=/^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?["`[]?([\w$]+)/i.exec(statement);const key=match?.[1]?comparableIndexKey(statement):undefined;if(match?.[1]&&key)shapes.set(match[1].toLowerCase(),key)}for(const statement of statementsOf(sql)){const create=new RegExp(String.raw`^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?${IDENT}`,"i").exec(statement);if(create?.[1]){push({kind:"table",name:create[1]});continue}const rename=new RegExp(String.raw`^ALTER\s+TABLE\s+${IDENT}\s+RENAME\s+TO\s+${IDENT}`,"i").exec(statement);if(rename?.[2]){if(rename[1])renamedAway.add(rename[1].toLowerCase());push({kind:"table",name:rename[2]});continue}const index=new RegExp(String.raw`^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?${IDENT}(?:\s+ON\s+${IDENT})?`,"i").exec(statement);if(index?.[1]){const shape=shapes.get(index[1].toLowerCase());push({kind:"index",name:index[1],...index[2]?{table:index[2]}:{},...shape?{shape}:{}});continue}const enumType=new RegExp(String.raw`^CREATE\s+TYPE\s+${IDENT}\s+AS\s+ENUM`,"i").exec(statement);if(enumType?.[1]){push({kind:"enum",name:enumType[1]});continue}const alter=new RegExp(String.raw`^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?${IDENT}\s+(.*)$`,"is").exec(statement);if(!alter?.[1]||!alter[2])continue;const table=alter[1];const addColumn=new RegExp(String.raw`\bADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?${IDENT}`,"gi");for(const m of alter[2].matchAll(addColumn)){if(m[1])push({kind:"column",table,name:m[1]})}const addConstraint=new RegExp(String.raw`\bADD\s+CONSTRAINT\s+(?:IF\s+NOT\s+EXISTS\s+)?${IDENT}`,"gi");for(const m of alter[2].matchAll(addConstraint)){if(m[1])push({kind:"constraint",table,name:m[1]})}const addBare=new RegExp(String.raw`\bADD\s+(?!COLUMN\b|CONSTRAINT\b|INDEX\b|KEY\b|PRIMARY\b|UNIQUE\b|FOREIGN\b|FULLTEXT\b|SPATIAL\b|CHECK\b)${IDENT}\s+\w`,"gi");for(const m of alter[2].matchAll(addBare)){if(m[1])push({kind:"column",table,name:m[1]})}}if(renamedAway.size===0)return effects;return effects.filter((effect)=>{const owner=(effect.kind==="table"?effect.name:effect.table??"").toLowerCase();return!renamedAway.has(owner)})}function effectKey(effect){return`${effect.kind}:${(effect.table??"").toLowerCase()}.${effect.name.toLowerCase()}`}function removalKey(effect){if(effect.kind==="column"||effect.kind==="constraint")return effectKey(effect);return`${effect.kind}:${effect.name.toLowerCase()}`}export function verifiableEffects(effects,dialect){if(dialect==="postgres")return effects;if(dialect==="mysql")return effects.filter((e)=>e.kind!=="enum");return effects.filter((e)=>e.kind!=="constraint"&&e.kind!=="enum")}function emptySchema(){return{tables:new Set,columns:new Map,indexes:new Set,indexShapes:new Set,constraints:new Set,enums:new Set}}function rowsOf(result){return Array.isArray(result)?result:[]}async function defaultRunner(){const{db}=await import("./utils");return async(sql)=>rowsOf(await db.unsafe(sql).execute())}function pick(row,...keys){for(const key of keys){const value=row?.[key]??row?.[key.toLowerCase()]??row?.[key.toUpperCase()];if(typeof value==="string"&&value.length>0)return value}return""}export async function readLiveSchema(dialect,runner){const schema=emptySchema();const run=runner??await defaultRunner();if(dialect==="sqlite"){for(const row of await run(`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'`)){const name=pick(row,"name");if(name)schema.tables.add(name.toLowerCase())}for(const row of await run(`SELECT name, sql FROM sqlite_master WHERE type='index' AND name NOT LIKE 'sqlite_%'`)){const name=pick(row,"name");if(name)schema.indexes.add(name.toLowerCase());const key=comparableIndexKey(pick(row,"sql"));if(key)schema.indexShapes.add(key)}for(const table of schema.tables){if(!/^[a-z_]\w*$/i.test(table))continue;const cols=new Set;for(const row of await run(`PRAGMA table_info("${table}")`)){const name=pick(row,"name");if(name)cols.add(name.toLowerCase())}schema.columns.set(table,cols)}return schema}if(dialect==="mysql"){for(const row of await run(`SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE()`)){const name=pick(row,"name","TABLE_NAME");if(name)schema.tables.add(name.toLowerCase())}for(const row of await run(`SELECT TABLE_NAME, COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE()`)){const table=pick(row,"TABLE_NAME").toLowerCase();const column=pick(row,"COLUMN_NAME").toLowerCase();if(!table||!column)continue;if(!schema.columns.has(table))schema.columns.set(table,new Set);schema.columns.get(table).add(column)}for(const row of await run(`SELECT DISTINCT INDEX_NAME AS name FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE()`)){const name=pick(row,"name","INDEX_NAME");if(name)schema.indexes.add(name.toLowerCase())}for(const row of await run(`SELECT CONSTRAINT_NAME AS name FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE()`)){const name=pick(row,"name","CONSTRAINT_NAME");if(name)schema.constraints.add(name.toLowerCase())}return schema}for(const row of await run(`SELECT tablename AS name FROM pg_tables WHERE schemaname = 'public'`)){const name=pick(row,"name","tablename");if(name)schema.tables.add(name.toLowerCase())}for(const row of await run(`SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = 'public'`)){const table=pick(row,"table_name").toLowerCase();const column=pick(row,"column_name").toLowerCase();if(!table||!column)continue;if(!schema.columns.has(table))schema.columns.set(table,new Set);schema.columns.get(table).add(column)}for(const row of await run(`SELECT indexname AS name, indexdef AS definition FROM pg_indexes WHERE schemaname = 'public'`)){const name=pick(row,"name","indexname");if(name)schema.indexes.add(name.toLowerCase());const key=comparableIndexKey(postgresIndexStatement(pick(row,"definition","indexdef")));if(key)schema.indexShapes.add(key)}for(const row of await run(`SELECT c.conname AS name FROM pg_constraint c JOIN pg_namespace n ON n.oid = c.connamespace WHERE n.nspname = 'public'`)){const name=pick(row,"name","conname");if(name)schema.constraints.add(name.toLowerCase())}for(const row of await run(`SELECT t.typname AS name FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace WHERE t.typtype = 'e' AND n.nspname = 'public'`)){const name=pick(row,"name","typname");if(name)schema.enums.add(name.toLowerCase())}return schema}export function effectPresent(effect,schema){const name=effect.name.toLowerCase();switch(effect.kind){case"table":return schema.tables.has(name);case"column":return schema.columns.get((effect.table??"").toLowerCase())?.has(name)??false;case"index":{if(schema.indexes.has(name))return true;if(effect.shape&&schema.indexShapes.has(effect.shape))return true;const table=(effect.table??"").toLowerCase();if(!table)return false;return schema.indexes.has(`${table}_${name}`)}case"constraint":return schema.constraints.has(name);case"enum":return schema.enums.has(name)}}export function classifyMigration(recorded,present,absent){const verifiable=present.length+absent.length;if(recorded){if(verifiable===0||absent.length===0)return"applied";return"reverted"}if(verifiable===0)return"unverifiable";if(absent.length===0)return"stranded";if(present.length===0)return"pending";return"partial"}function migrationsDir(dir){if(dir)return dir;const driver=resolvedDatabaseDriver().toLowerCase();return resolveMigrationDirectory(driver==="singlestore"?"singlestore":driver)}function listMigrationFiles(dir){if(!existsSync(dir))return[];try{return readdirSync(dir).filter((f)=>f.toLowerCase().endsWith(".sql")).sort()}catch{return[]}}function currentDialect(){const driver=resolvedDatabaseDriver().toLowerCase();if(driver==="sqlite"||driver==="mysql"||driver==="postgres")return driver;if(driver==="vitess"||driver==="singlestore")return"mysql";if(driver==="turso"||driver==="libsql")return"sqlite";return"other"}export async function readLedger(runner){try{const run=runner??await defaultRunner();const rows=await run("SELECT migration FROM migrations");return rows.map((row)=>pick(row,"migration")).filter((name)=>name.length>0).sort()}catch{return[]}}export function planLedgerRemap(ledger,diskFiles){const onDisk=new Set(diskFiles);const byLogical=new Map;for(const file of diskFiles){const key=logicalName(file);if(!byLogical.has(key))byLogical.set(key,[]);byLogical.get(key).push(file)}const claimed=new Set(ledger.filter((row)=>onDisk.has(row)));const remap=[];const ambiguous=[];const dropped=[];const superseded=[];const targets=new Map;for(const row of ledger){if(onDisk.has(row))continue;const sameLogical=byLogical.get(logicalName(row))??[];const candidates=sameLogical.filter((f)=>!claimed.has(f));if(candidates.length===0){if(sameLogical.length>0)superseded.push(row);else dropped.push(row);continue}if(candidates.length>1){ambiguous.push(row);continue}const to=candidates[0];if(!targets.has(to))targets.set(to,[]);targets.get(to).push(row);remap.push({from:row,to})}const contested=new Set([...targets.entries()].filter(([,rows])=>rows.length>1).flatMap(([,rows])=>rows));if(contested.size===0)return{remap,ambiguous,dropped,superseded};return{remap:remap.filter((r)=>!contested.has(r.from)),ambiguous:[...ambiguous,...contested].sort(),dropped,superseded}}export async function auditMigrationLedger(options={}){const dir=migrationsDir(options.dir);const dialect=options.dialect??currentDialect();const files=listMigrationFiles(dir);const counts={applied:0,stranded:0,pending:0,partial:0,unverifiable:0,reverted:0};const emptyPlan={remap:[],ambiguous:[],dropped:[],superseded:[]};if(dialect==="other"){return{supported:false,dialect,dir,entries:[],orphans:[],gated:[],counts,recordedCount:0,remapPlan:emptyPlan,drift:false}}const run=options.run??await defaultRunner();const ledger=await readLedger(run);const recorded=new Set(ledger);const schema=await readLiveSchema(dialect,run);const gate=await resolveGate(options,dir);const sources=new Map;const gated=files.filter((file)=>gate?.exclude.has(file));for(const file of files){if(gate?.exclude.has(file))continue;try{const sql=readFileSync(join(dir,file),"utf8");sources.set(file,gate?gate.rewrite(sql):sql)}catch{continue}}const readFiles=[...sources.keys()];const removedLater=new Map;const tablesDroppedLater=new Map;for(let i=0;i<readFiles.length;i++){const laterKeys=new Set;const laterTables=new Set;for(let j=i+1;j<readFiles.length;j++){for(const removal of migrationRemovals(sources.get(readFiles[j]))){laterKeys.add(removalKey(removal));if(removal.kind==="table")laterTables.add(removal.name.toLowerCase())}}removedLater.set(readFiles[i],laterKeys);tablesDroppedLater.set(readFiles[i],laterTables)}const entries=[];for(const file of readFiles){const sql=sources.get(file);const effects=verifiableEffects(migrationEffects(sql),dialect);const dropped=removedLater.get(file)??new Set;const droppedTables=tablesDroppedLater.get(file)??new Set;const survives=(effect)=>effectPresent(effect,schema)||dropped.has(removalKey(effect))||effect.table!==undefined&&droppedTables.has(effect.table.toLowerCase());const present=effects.filter(survives);const absent=effects.filter((effect)=>!survives(effect));const isRecorded=recorded.has(file);const status=classifyMigration(isRecorded,present,absent);counts[status]+=1;entries.push({file,logical:logicalName(file),recorded:isRecorded,status,effects,present,absent})}const readable=[...entries.map((entry)=>entry.file),...gated].sort();const remapPlan=planLedgerRemap(ledger,readable);const renamedTo=new Map(remapPlan.remap.map((r)=>[r.from,r.to]));const orphans=ledger.filter((row)=>!readable.includes(row)).map((row)=>({migration:row,renamedTo:renamedTo.get(row)}));const drift=counts.stranded>0||counts.partial>0||counts.reverted>0||orphans.length>0;return{supported:true,dialect,dir,entries,orphans,gated,counts,recordedCount:ledger.length,remapPlan,drift}}async function ensureLedgerTable(dialect,run){const id=dialect==="postgres"?"id SERIAL PRIMARY KEY":dialect==="mysql"?"id INT AUTO_INCREMENT PRIMARY KEY":"id INTEGER PRIMARY KEY AUTOINCREMENT";const timestamp=dialect==="postgres"?"TIMESTAMP":"DATETIME";const utcNow=dialect==="postgres"?`(now() AT TIME ZONE 'utc')`:dialect==="mysql"?"(UTC_TIMESTAMP)":"CURRENT_TIMESTAMP";await run(`CREATE TABLE IF NOT EXISTS migrations (${id}, migration VARCHAR(255) NOT NULL UNIQUE, executed_at ${timestamp} DEFAULT ${utcNow})`);if(dialect!=="sqlite"){try{await run(`ALTER TABLE migrations ALTER COLUMN executed_at SET DEFAULT ${utcNow}`)}catch{}}}const Q=(pattern)=>new RegExp(pattern.replaceAll("{id}",IDENT),"i");const CREATE_TABLE=Q(String.raw`^CREATE\s+(?:TEMP(?:ORARY)?\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?{id}`);const DROP_TABLE=Q(String.raw`^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?{id}`);const RENAME_TABLE=Q(String.raw`^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?{id}\s+RENAME\s+TO\s+{id}`);const ALTER_TABLE=Q(String.raw`^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?{id}`);const CREATE_INDEX=Q(String.raw`^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?{id}\s+ON\s+(?:ONLY\s+)?{id}`);const DROP_INDEX=Q(String.raw`^DROP\s+INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+EXISTS\s+)?{id}(?:\s+ON\s+{id})?`);const DML=Q(String.raw`^(?:INSERT\s+(?:OR\s+\w+\s+)?INTO|REPLACE\s+INTO|UPDATE|DELETE\s+FROM)\s+{id}`);const NEUTRAL=/^(?:BEGIN|COMMIT|END|PRAGMA|SET|SELECT\s+1|COMMENT\s+ON|CREATE\s+TYPE\s+\S+\s+AS\s+ENUM|ALTER\s+TYPE\s+\S+\s+ADD\s+VALUE|STACKS_ENUM_GUARD)\b/i;function statementShape(statement,indexTables){const lower=(name)=>(name??"").toLowerCase();if(NEUTRAL.test(statement))return{modifies:[]};let m=RENAME_TABLE.exec(statement);if(m)return{modifies:[lower(m[1]),lower(m[2])],rename:{from:lower(m[1]),to:lower(m[2])}};m=CREATE_TABLE.exec(statement);if(m)return{modifies:[lower(m[1])],creates:lower(m[1])};m=DROP_TABLE.exec(statement);if(m)return{modifies:[lower(m[1])],drops:lower(m[1])};m=ALTER_TABLE.exec(statement);if(m)return{modifies:[lower(m[1])]};m=CREATE_INDEX.exec(statement);if(m)return{modifies:[lower(m[2])],index:{name:lower(m[1]),table:lower(m[2])}};m=DROP_INDEX.exec(statement);if(m){const table=m[2]?lower(m[2]):indexTables.get(lower(m[1]));return table?{modifies:[table]}:{modifies:[],unknown:true}}m=DML.exec(statement);if(m)return{modifies:[lower(m[1])]};return{modifies:[],unknown:true}}function requeueStatements(sql){const folded=stripForEffects(sql).replace(/\bDO\s+\$(\w*)\$([\s\S]*?)\$\1\$/gi,(block,_tag,body)=>/^\s*BEGIN\s+CREATE\s+TYPE\b[\s\S]*\bEXCEPTION\s+WHEN\s+duplicate_object\s+THEN\s+null\s*;\s*END\s*$/i.test(body)?"STACKS_ENUM_GUARD":block);return folded.split(";").map((statement)=>statement.trim()).filter(Boolean)}async function resolveGate(options,dir){if(options.gate||options.dir)return options.gate;try{const{featureGateForLedger}=await import("./migrations");return await featureGateForLedger(dir)}catch{return}}export function planRequeue(files,liveTables){const ordered=[...files].sort((a,b)=>a.file.localeCompare(b.file));const indexTables=new Map;const expected=new Set;const lineageOf=new Map;const lineage=(table)=>{let group=lineageOf.get(table);if(!group){group=new Set([table]);lineageOf.set(table,group)}return group};const link=(a,b)=>{const merged=new Set([...lineage(a),...lineage(b)]);for(const name of merged)lineageOf.set(name,merged)};const shapes=ordered.map(({file,sql,recorded})=>{const statements=requeueStatements(sql).map((statement)=>statementShape(statement,indexTables));for(const shape of statements){if(shape.index)indexTables.set(shape.index.name,shape.index.table);if(shape.creates)expected.add(shape.creates);if(shape.drops)expected.delete(shape.drops);if(shape.rename){expected.delete(shape.rename.from);expected.add(shape.rename.to);link(shape.rename.from,shape.rename.to)}}const created=new Set(statements.flatMap((shape)=>shape.creates?[shape.creates]:[]));const removed=new Set(statements.flatMap((shape)=>[shape.drops,shape.rename?.from].filter((t)=>Boolean(t))));const scaffold=new Set([...created].filter((table)=>removed.has(table)||statements.some((shape)=>shape.rename?.from===table)));return{file,recorded,unknown:statements.some((shape)=>shape.unknown),modifies:new Set(statements.flatMap((shape)=>shape.modifies)),scaffold}});const missing=[...expected].filter((table)=>!liveTables.has(table)).sort();const rebuildable=new Set(missing.flatMap((table)=>[...lineage(table)]).filter((table)=>!liveTables.has(table)));const chains=new Map(missing.map((table)=>{const names=lineage(table);return[table,shapes.filter((shape)=>[...shape.modifies].some((name)=>names.has(name)))]}));const why=new Map;for(const[table,chain]of chains){for(const shape of chain){if(shape.unknown){why.set(table,`${shape.file} contains a statement the planner cannot classify`);break}const elsewhere=[...shape.modifies].filter((t)=>!rebuildable.has(t)&&!shape.scaffold.has(t));if(elsewhere.length>0){why.set(table,`${shape.file} also changes ${elsewhere.join(", ")}, which ${elsewhere.length===1?"is":"are"} not missing`);break}}}let changed=true;while(changed){changed=false;for(const[table,chain]of chains){if(why.has(table))continue;const blocker=chain.flatMap((shape)=>[...shape.modifies]).find((other)=>other!==table&&missing.some((t)=>why.has(t)&&lineage(t).has(other)));if(blocker){why.set(table,`shares a migration with ${blocker}, which cannot be rebuilt`);changed=true}}}const requeue=new Set;for(const[table,chain]of chains){if(why.has(table))continue;for(const shape of chain){if(shape.recorded)requeue.add(shape.file)}}return{missing,requeue:ordered.map(({file})=>file).filter((file)=>requeue.has(file)),refused:[...why].map(([table,reason])=>({table,reason}))}}export async function auditMissingTables(options={}){const dialect=options.dialect??currentDialect();if(dialect==="other")return{supported:false,missing:[],live:new Set};const dir=migrationsDir(options.dir);const run=options.run??await defaultRunner();const recorded=new Set(await readLedger(run));const gate=await resolveGate(options,dir);const files=listMigrationFiles(dir).filter((file)=>recorded.has(file)&&!gate?.exclude.has(file)).flatMap((file)=>{try{const sql=readFileSync(join(dir,file),"utf8");return[{file,sql:gate?gate.rewrite(sql):sql,recorded:true}]}catch{return[]}});const live=await readLiveSchema(dialect,run);return{supported:true,missing:planRequeue(files,live.tables).missing,live:live.tables}}function byLogicalOnDisk(row,diskFiles){const key=logicalName(row);const matches=diskFiles.filter((f)=>logicalName(f)===key);return matches.length===1?matches[0]:undefined}export async function reconcileMigrationLedger(options={}){const run=options.run??await defaultRunner();const gate=await resolveGate(options,migrationsDir(options.dir));const audit=await auditMigrationLedger({dir:options.dir,dialect:options.dialect,run,gate});const result={remapped:[],recorded:[],pruned:[],requeued:[],retired:[],skipped:[]};if(!audit.supported){result.skipped.push({file:"*",reason:`dialect "${audit.dialect}" is not audited`});return result}const written=new Set(options.regenerated?.written??[]);const removedByRegeneration=new Set(options.regenerated?.removed??[]);const onDisk=new Set([...audit.entries.map((entry)=>entry.file),...audit.gated]);const plan={...audit.remapPlan,remap:audit.remapPlan.remap.filter((r)=>!written.has(r.to))};const retirable=[...audit.remapPlan.remap.filter((r)=>written.has(r.to)).map((r)=>r.from),...audit.remapPlan.dropped,...audit.remapPlan.superseded,...audit.remapPlan.ambiguous].filter((row)=>removedByRegeneration.has(row)&&!onDisk.has(row)&&SAFE_MIGRATION_FILE.test(row));const retiring=new Set(retirable);for(const row of plan.ambiguous.filter((row)=>!retiring.has(row)))result.skipped.push({file:row,reason:"ledger row matches more than one file by logical name"});for(const row of plan.dropped.filter((row)=>!retiring.has(row)))result.skipped.push({file:row,reason:"recorded migration no longer exists on disk"});for(const{from}of audit.remapPlan.remap.filter((r)=>written.has(r.to)&&!retiring.has(r.from)))result.skipped.push({file:from,reason:"its file was replaced by a regenerated one; not repointed, because the contents differ"});const prunable=plan.superseded.filter((row)=>SAFE_MIGRATION_FILE.test(row)&&!retiring.has(row));for(const row of plan.superseded.filter((row)=>!SAFE_MIGRATION_FILE.test(row)))result.skipped.push({file:row,reason:"ledger row is not safe to write to the ledger"});const toRecord=[];const revertedEntries=[];for(const entry of audit.entries){if(entry.status==="stranded"){toRecord.push(entry.file);continue}if(entry.status==="partial"){if(options.includePartial){toRecord.push(entry.file);continue}result.skipped.push({file:entry.file,reason:written.has(entry.file)?`${entry.present.length}/${entry.effects.length} effects present - left pending; run \`buddy migrate:align\` first so the next migrate does not duplicate what exists under another name`:`${entry.present.length}/${entry.effects.length} effects present - resolve by hand, or pass --include-partial`});continue}if(entry.status==="reverted")revertedEntries.push(entry)}const toRequeue=[];if(options.requeueReverted){const live=await readLiveSchema(audit.dialect,run);const recordedFiles=new Set(audit.entries.filter((entry)=>entry.recorded).map((entry)=>entry.file));const corpus=audit.entries.flatMap((entry)=>{try{const sql=readFileSync(join(audit.dir,entry.file),"utf8");return[{file:entry.file,sql:gate?gate.rewrite(sql):sql,recorded:recordedFiles.has(entry.file)}]}catch{return[]}});const plan=planRequeue(corpus,live.tables);toRequeue.push(...plan.requeue);for(const{table,reason}of plan.refused)result.skipped.push({file:table,reason:`missing table not rebuilt: ${reason}`})}for(const entry of revertedEntries.filter((entry)=>!toRequeue.includes(entry.file))){if(written.has(entry.file)){result.skipped.push({file:entry.file,reason:`recorded under the same name as the file it replaced, but ${entry.absent.length} effect(s) of the regenerated file are missing - \`buddy migrate:align\` creates them`});continue}result.skipped.push({file:entry.file,reason:options.requeueReverted?`recorded, but ${entry.absent.length} effect(s) are missing from the schema`:`recorded, but ${entry.absent.length} effect(s) are missing from the schema - --requeue-reverted rebuilds a table that is gone entirely`})}const unsafe=(file)=>!SAFE_MIGRATION_FILE.test(file);for(const{from,to}of plan.remap.filter((r)=>unsafe(r.from)||unsafe(r.to)))result.skipped.push({file:unsafe(from)?from:to,reason:"migration filename is not safe to write to the ledger"});for(const file of toRecord.filter(unsafe))result.skipped.push({file,reason:"migration filename is not safe to write to the ledger"});const remapped=plan.remap.filter((r)=>!unsafe(r.from)&&!unsafe(r.to));const recordable=toRecord.filter((file)=>!unsafe(file)&&!remapped.some((r)=>r.to===file));const requeueable=toRequeue.filter((file)=>!unsafe(file));for(const file of toRequeue.filter(unsafe))result.skipped.push({file,reason:"migration filename is not safe to write to the ledger"});if(options.dryRun){result.remapped=remapped;result.recorded=recordable;result.pruned=prunable;result.requeued=requeueable;result.retired=retirable;return result}await ensureLedgerTable(audit.dialect,run);for(const{from,to}of remapped){await run(`UPDATE migrations SET migration = '${to}' WHERE migration = '${from}'`);result.remapped.push({from,to})}for(const file of recordable){const existing=await run(`SELECT migration FROM migrations WHERE migration = '${file}'`);if(existing.length>0)continue;await run(`INSERT INTO migrations (migration) VALUES ('${file}')`);result.recorded.push(file)}for(const row of prunable){const survivor=byLogicalOnDisk(row,audit.entries.map((e)=>e.file));if(!survivor)continue;const kept=await run(`SELECT migration FROM migrations WHERE migration = '${survivor}'`);if(kept.length===0){result.skipped.push({file:row,reason:`would leave ${survivor} unrecorded`});continue}await run(`DELETE FROM migrations WHERE migration = '${row}'`);result.pruned.push(row)}for(const row of retirable){await run(`DELETE FROM migrations WHERE migration = '${row}'`);result.retired.push(row)}for(const file of requeueable){await run(`DELETE FROM migrations WHERE migration = '${file}'`);result.requeued.push(file)}return result}
|
package/dist/migration-lock.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Buffer}from"node:buffer";import{createHash,randomUUID}from"node:crypto";import{closeSync,openSync,readFileSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{hostname}from"node:os";import process from"node:process";import{userDatabasePath}from"@stacksjs/path";const DEFAULT_TIMEOUT_MS=30000
|
|
1
|
+
import{Buffer}from"node:buffer";import{createHash,randomUUID}from"node:crypto";import{closeSync,openSync,readFileSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{hostname}from"node:os";import process from"node:process";import{userDatabasePath}from"@stacksjs/path";const DEFAULT_TIMEOUT_MS=30000;const INITIAL_BACKOFF_MS=100;const MAX_BACKOFF_MS=2000;const STALE_LOCK_MS=60000;const LOCK_NAME="stacks_migrations";export async function acquireMigrationLock(dialect,adminDb,opts={}){const timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT_MS;if(dialect!=="sqlite"&&dialect!=="postgres"&&dialect!=="mysql"&&dialect!=="vitess")throw new Error(`[migration-lock] unknown dialect: ${String(dialect)}`);if(dialect==="sqlite")return acquireSqliteLock(opts.sqliteLockPath,timeoutMs);if(!adminDb)throw new Error(`[migration-lock] ${dialect} requires a database connection to acquire the lock`);if(dialect==="postgres")return acquirePostgresLock(adminDb,timeoutMs);return acquireMySqlLock(adminDb,timeoutMs)}function lockKeysForPostgres(){const hash=createHash("sha256").update(LOCK_NAME).digest();const key1=hash.readInt32BE(0);const key2=hash.readInt32BE(4);return{key1,key2}}async function acquirePostgresLock(adminDb,timeoutMs){const{key1,key2}=lockKeysForPostgres();const start=Date.now();let backoff=INITIAL_BACKOFF_MS;while(true){const result=await adminDb.unsafe(`SELECT pg_try_advisory_lock(${key1}, ${key2}) AS acquired`);const acquired=extractFirstBool(result,"acquired");if(acquired){return{release:async()=>{try{await adminDb.unsafe(`SELECT pg_advisory_unlock(${key1}, ${key2})`)}catch{}}}}if(Date.now()-start>=timeoutMs)throw new Error("[migration-lock] another migration is in progress - could not acquire postgres advisory lock within timeout");await sleepWithJitter(backoff);backoff=Math.min(backoff*2,MAX_BACKOFF_MS)}}async function acquireMySqlLock(adminDb,timeoutMs){const start=Date.now();let backoff=INITIAL_BACKOFF_MS;while(true){const result=await adminDb.unsafe(`SELECT GET_LOCK('${LOCK_NAME}', 0) AS acquired`);const acquired=extractFirstInt(result,"acquired")===1;if(acquired){return{release:async()=>{try{await adminDb.unsafe(`SELECT RELEASE_LOCK('${LOCK_NAME}')`)}catch{}}}}if(Date.now()-start>=timeoutMs)throw new Error("[migration-lock] another migration is in progress - could not acquire MySQL named lock within timeout");await sleepWithJitter(backoff);backoff=Math.min(backoff*2,MAX_BACKOFF_MS)}}function defaultSqliteLockPath(){return userDatabasePath(".migration.lock")}async function acquireSqliteLock(lockPath,timeoutMs){const path=lockPath??defaultSqliteLockPath();const start=Date.now();let backoff=INITIAL_BACKOFF_MS;while(true){if(tryCreateLockFile(path)){let released=false;return{release:async()=>{if(released)return;released=true;try{unlinkSync(path)}catch{}}}}reclaimIfStale(path);if(Date.now()-start>=timeoutMs)throw new Error(`[migration-lock] another migration is in progress - lock file ${path} held within timeout`);await sleepWithJitter(backoff);backoff=Math.min(backoff*2,MAX_BACKOFF_MS)}}function tryCreateLockFile(path){try{const fd=openSync(path,"wx");try{const payload=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});writeFileSync(fd,Buffer.from(payload,"utf8"))}finally{closeSync(fd)}return true}catch(e){if(e.code==="EEXIST")return false;throw e}}function reclaimIfStale(path){try{const st=statSync(path);const age=Date.now()-st.mtimeMs;if(age<=STALE_LOCK_MS||lockOwnerIsAlive(path))return;try{unlinkSync(path)}catch{}}catch{}}function lockOwnerIsAlive(path){try{const payload=JSON.parse(readFileSync(path,"utf8"));const pid=payload.pid;if(typeof pid!=="number"||!Number.isInteger(pid)||pid<=0)return false;try{process.kill(pid,0);return true}catch(error){return error.code==="EPERM"}}catch{return false}}function sleepWithJitter(ms){const jittered=ms*(1+Math.random()*0.25);return new Promise((resolve)=>setTimeout(resolve,jittered))}function extractFirstBool(result,column){const row=pluckFirstRow(result);if(!row)return false;const value=firstColumnValue(row,column);return value===true||value===1||value==="1"||value==="t"}function extractFirstInt(result,column){const row=pluckFirstRow(result);if(!row)return null;const value=firstColumnValue(row,column);if(typeof value==="number")return value;if(typeof value==="string"&&/^-?\d+$/.test(value))return Number.parseInt(value,10);return null}function firstColumnValue(row,column){if(!row||typeof row!=="object")return;const record=row;if(column in record)return record[column];const values=Object.values(record);return values.length===1?values[0]:undefined}function pluckFirstRow(result){if(!result)return null;if(Array.isArray(result))return result[0];if(typeof result==="object"&&"rows"in result&&Array.isArray(result.rows))return result.rows[0];return null}export const LIBSQL_LOCK_TABLE="stacks_migration_lock";const LIBSQL_HEARTBEAT_MS=15000;export async function acquireLibsqlMigrationLock(adminDb,opts={}){const timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT_MS;const staleMs=opts.staleMs??STALE_LOCK_MS;const heartbeatMs=opts.heartbeatMs??LIBSQL_HEARTBEAT_MS;const holder=`${hostname()}:${process.pid}:${randomUUID()}`;const run=async(sql,params=[])=>await adminDb.unsafe(sql,params);await run(`CREATE TABLE IF NOT EXISTS "${LIBSQL_LOCK_TABLE}" (name TEXT PRIMARY KEY, holder TEXT NOT NULL, heartbeat_at INTEGER NOT NULL)`);const start=Date.now();let backoff=INITIAL_BACKOFF_MS;while(true){await run(`DELETE FROM "${LIBSQL_LOCK_TABLE}" WHERE name = ? AND heartbeat_at < ?`,[LOCK_NAME,Date.now()-staleMs]);await run(`INSERT INTO "${LIBSQL_LOCK_TABLE}" (name, holder, heartbeat_at) VALUES (?, ?, ?) ON CONFLICT (name) DO NOTHING`,[LOCK_NAME,holder,Date.now()]);const rows=await run(`SELECT holder FROM "${LIBSQL_LOCK_TABLE}" WHERE name = ?`,[LOCK_NAME]);const current=Array.isArray(rows)?rows[0]?.holder:undefined;if(current===holder){const heartbeat=setInterval(()=>{Promise.resolve(run(`UPDATE "${LIBSQL_LOCK_TABLE}" SET heartbeat_at = ? WHERE name = ? AND holder = ?`,[Date.now(),LOCK_NAME,holder])).catch(()=>{})},heartbeatMs);heartbeat.unref?.();let released=false;return{release:async()=>{if(released)return;released=true;clearInterval(heartbeat);try{await run(`DELETE FROM "${LIBSQL_LOCK_TABLE}" WHERE name = ? AND holder = ?`,[LOCK_NAME,holder])}catch{}}}}if(Date.now()-start>=timeoutMs)throw new Error(`[migration-lock] another migration is in progress - the libSQL lock row in "${LIBSQL_LOCK_TABLE}" was held within timeout`);await sleepWithJitter(backoff);backoff=Math.min(backoff*2,MAX_BACKOFF_MS)}}
|
package/dist/migration-names.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync}from"node:child_process";import{createHash}from"node:crypto";import{readdirSync,readFileSync}from"node:fs";import{basename,join}from"node:path";import{carriesGeneratedMarker}from"./hand-written-migrations";import{isPackageMigration}from"./package-migrations";export function migrationNameOrdinal(file){const match=/^(\d+)[-_]/.exec(file);return match?Number.parseInt(match[1],10):
|
|
1
|
+
import{spawnSync}from"node:child_process";import{createHash}from"node:crypto";import{readdirSync,readFileSync}from"node:fs";import{basename,join}from"node:path";import{carriesGeneratedMarker}from"./hand-written-migrations";import{isPackageMigration}from"./package-migrations";export function migrationNameOrdinal(file){const match=/^(\d+)[-_]/.exec(file);return match?Number.parseInt(match[1],10):undefined}export function retiredMigrationNames(dir,options={}){const git=(args)=>spawnSync("git",args,{cwd:dir,encoding:"utf8",timeout:options.timeoutMs??1e4,maxBuffer:64*1024*1024});try{const result=git(["log","--no-renames","--diff-filter=D","--raw","--no-abbrev","-z","--pretty=format:","--","."]);if(result.status!==0||typeof result.stdout!=="string")return[];const deletedObjects=new Map;const records=result.stdout.split("\x00");for(let index=0;index<records.length;index++){const deletion=/^:[0-7]{6} [0-7]{6} ([a-f0-9]{40}|[a-f0-9]{64}) 0+ D$/.exec(records[index].trim());if(!deletion)continue;const path=records[++index];if(!path)continue;const name=basename(path);if(!name.toLowerCase().endsWith(".sql"))continue;const objects=deletedObjects.get(name)??new Set;objects.add(deletion[1]);deletedObjects.set(name,objects)}const names=[];for(const[name,objects]of deletedObjects){if(objects.size===1){try{const current=readFileSync(join(dir,name));const previous=objects.values().next().value;const currentObject=createHash(previous.length===64?"sha256":"sha1").update(`blob ${current.byteLength}\x00`).update(current).digest("hex");if(currentObject===previous)continue}catch{}}names.push(name)}return names.sort()}catch{return[]}}export const TIMESTAMP_MIGRATION_ORDINAL=1e9;export function nextMigrationOrdinal(diskFiles,claimed=[]){let max=0;for(const file of diskFiles){if(isPackageMigration(file))continue;const ordinal=migrationNameOrdinal(file);if(ordinal!==undefined)max=Math.max(max,ordinal)}const reserved=reservedMigrationOrdinals(claimed);for(const ordinal of reserved){if(ordinal<TIMESTAMP_MIGRATION_ORDINAL)max=Math.max(max,ordinal)}return nextFreeMigrationOrdinal(max+1,reserved)}export function reservedMigrationOrdinals(claimed){const reserved=new Set;for(const name of claimed){if(isPackageMigration(name))continue;const ordinal=migrationNameOrdinal(name);if(ordinal!==undefined)reserved.add(ordinal)}return reserved}export function nextFreeMigrationOrdinal(from,reserved){let cursor=from;while(reserved.has(cursor))cursor+=1;return cursor}export function duplicateMigrationOrdinals(files){const byOrdinal=new Map;for(const file of files){if(!file.toLowerCase().endsWith(".sql"))continue;const ordinal=/^(\d+)[-_]/.exec(file)?.[1];if(ordinal===undefined)continue;const key=String(Number.parseInt(ordinal,10));if(!byOrdinal.has(key))byOrdinal.set(key,[]);byOrdinal.get(key).push(file)}return[...byOrdinal.values()].filter((group)=>group.length>1).map((group)=>{const sorted=[...group].sort();return{ordinal:/^(\d+)/.exec(sorted[0])[1],files:sorted}}).sort((a,b)=>a.files[0].localeCompare(b.files[0]))}export function duplicateMigrationOrdinalsIn(dir){let files;try{files=readdirSync(dir)}catch{return[]}return duplicateMigrationOrdinals(files).map((group)=>({...group,generated:group.files.some((file)=>{try{return carriesGeneratedMarker(readFileSync(join(dir,file),"utf8"))}catch{return false}})}))}
|
package/dist/migration-path.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,readdirSync,readFileSync}from"node:fs";import{isAbsolute,join,relative}from"node:path";import process from"node:process";const DEFAULT_MIGRATION_DIR="database/migrations"
|
|
1
|
+
import{existsSync,readdirSync,readFileSync}from"node:fs";import{isAbsolute,join,relative}from"node:path";import process from"node:process";const DEFAULT_MIGRATION_DIR="database/migrations";const DEFAULT_SNAPSHOT_DIR="storage/framework/database";export function resolveMigrationDirectory(dialect,options={}){if(dialect==="turso"||dialect==="libsql")dialect="sqlite";const cwd=options.cwd??process.cwd();const configured=process.env.DB_MIGRATIONS_PATH||options.configured||DEFAULT_MIGRATION_DIR;const absoluteConfigured=isAbsolute(configured)?configured:join(cwd,configured);if(configured!==DEFAULT_MIGRATION_DIR||isAbsolute(configured))return absoluteConfigured;const dialectDir=join(absoluteConfigured,dialect);if(existsSync(dialectDir))return dialectDir;if(dialect==="sqlite")return absoluteConfigured;const snapshotDir=isAbsolute(options.snapshotDir||"")?options.snapshotDir:join(cwd,options.snapshotDir||DEFAULT_SNAPSHOT_DIR);let snapshots=[];try{snapshots=readdirSync(snapshotDir)}catch{}const wanted=`model-snapshot.${dialect}.json`;const hasOtherDialect=snapshots.some((file)=>/^model-snapshot\.\w+\.json$/.test(file)&&file!==wanted);if(hasOtherDialect&&ownerOfFlatCorpus(absoluteConfigured)===wireOf(dialect))return absoluteConfigured;return hasOtherDialect?dialectDir:absoluteConfigured}function ownerOfFlatCorpus(directory){let files=[];try{files=readdirSync(directory).filter((file)=>file.endsWith(".sql")).sort()}catch{return null}for(const file of files){let sql;try{sql=readFileSync(join(directory,file),"utf8")}catch{continue}const create=/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(["`])/i.exec(sql);if(create)return create[1]==="`"?"mysql":"postgres"}return null}function wireOf(dialect){return dialect==="mysql"||dialect==="mariadb"||dialect==="singlestore"||dialect==="vitess"||dialect==="planetscale"?"mysql":"postgres"}export function relativeMigrationDirectory(directory,cwd=process.cwd()){const prefix=`${cwd}/`;return directory.startsWith(prefix)?directory.slice(prefix.length):directory}export function resolveSnapshotDirectory(cwd=process.cwd()){const configured=process.env.DB_SNAPSHOT_PATH||DEFAULT_SNAPSHOT_DIR;return isAbsolute(configured)?configured:join(cwd,configured)}export function snapshotDirForQueryBuilder(cwd=process.cwd()){return relative(cwd,resolveSnapshotDirectory(cwd))||"."}export function snapshotDirectoryIsShared(){return Boolean(process.env.DB_SNAPSHOT_PATH)}
|