@stacksjs/database 0.75.695 → 0.75.701
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/migration-ledger.d.ts +2 -0
- package/dist/migration-ledger.js +1 -1
- package/dist/migrations.js +1 -1
- package/package.json +16 -16
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { FrameworkRename } from './framework-renames';
|
|
1
2
|
/**
|
|
2
3
|
* Strip a migration's SQL down to something safe to pattern-match.
|
|
3
4
|
*
|
|
@@ -251,6 +252,7 @@ export declare interface ReconcileResult {
|
|
|
251
252
|
export declare interface CorpusGate {
|
|
252
253
|
exclude: ReadonlySet<string>
|
|
253
254
|
rewrite: (sql: string) => string
|
|
255
|
+
frameworkRenames?: readonly FrameworkRename[]
|
|
254
256
|
}
|
|
255
257
|
export declare interface RequeuePlan {
|
|
256
258
|
missing: string[]
|
package/dist/migration-ledger.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,readdirSync,readFileSync}from"node:fs";import{dirname,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[]}}export function siblingMigrationCorpora(dir){const parent=dirname(dir);const flat=listMigrationFiles(parent).length>0?parent:dir;const corpora=[flat];try{for(const entry of readdirSync(flat,{withFileTypes:true})){if(entry.isDirectory()&&listMigrationFiles(join(flat,entry.name)).length>0)corpora.push(join(flat,entry.name))}}catch{}return corpora.filter((corpus)=>corpus!==dir)}function foreignLedgerRows(rows,dir){if(rows.length===0)return[];const corpora=siblingMigrationCorpora(dir).map((corpus)=>({corpus,files:new Set(listMigrationFiles(corpus))}));return rows.flatMap((row)=>{const home=corpora.find((c)=>c.files.has(row));return home?[{migration:row,corpus:home.corpus}]:[]})}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===1)superseded.push(row);else if(sameLogical.length>1)ambiguous.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:[],foreign:[],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 readableSet=new Set(readable);const foreign=foreignLedgerRows(ledger.filter((row)=>!readableSet.has(row)),dir);const foreignSet=new Set(foreign.map((row)=>row.migration));const own=ledger.filter((row)=>!foreignSet.has(row));const remapPlan=planLedgerRemap(own,readable);const renamedTo=new Map(remapPlan.remap.map((r)=>[r.from,r.to]));const orphans=own.filter((row)=>!readableSet.has(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,foreign,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 recordedRows=new Set(await readLedger(run));const survivorOf=new Map;const prunable=[];for(const row of plan.superseded.filter((row)=>!retiring.has(row))){if(!SAFE_MIGRATION_FILE.test(row)){result.skipped.push({file:row,reason:"ledger row is not safe to write to the ledger"});continue}const survivor=byLogicalOnDisk(row,[...onDisk]);if(!survivor||!recordedRows.has(survivor)){result.skipped.push({file:row,reason:survivor?`would leave ${survivor} unrecorded`:"no single file of this corpus carries its name"});continue}survivorOf.set(row,survivor);prunable.push(row)}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=survivorOf.get(row);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}
|
|
1
|
+
import{existsSync,readdirSync,readFileSync}from"node:fs";import{dirname,join}from"node:path";import{resolvedDatabaseDriver}from"./dialect";import{renameIdentifierPart}from"./framework-renames";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)}}function renamedEffectPresent(effect,schema,renames){const{kind}=effect;let name=effect.name.toLowerCase();let table=(kind==="table"?name:effect.table)?.toLowerCase();if(!table)return false;let renamed=false;for(const group of renames){for(const{from,to}of group.tables){if(table!==from||schema.tables.has(from))continue;table=to;if(kind==="table")name=to;if(kind==="index")name=renameIdentifierPart(name,from,to);renamed=true}if(kind==="column"){for(const{table:owner,from,to}of group.columns){if(table!==owner||name!==from||schema.columns.get(owner)?.has(from))continue;name=to;renamed=true}}}return renamed&&schema.tables.has(table)&&effectPresent({kind,name,table},schema)}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[]}}export function siblingMigrationCorpora(dir){const parent=dirname(dir);const flat=listMigrationFiles(parent).length>0?parent:dir;const corpora=[flat];try{for(const entry of readdirSync(flat,{withFileTypes:true})){if(entry.isDirectory()&&listMigrationFiles(join(flat,entry.name)).length>0)corpora.push(join(flat,entry.name))}}catch{}return corpora.filter((corpus)=>corpus!==dir)}function foreignLedgerRows(rows,dir){if(rows.length===0)return[];const corpora=siblingMigrationCorpora(dir).map((corpus)=>({corpus,files:new Set(listMigrationFiles(corpus))}));return rows.flatMap((row)=>{const home=corpora.find((c)=>c.files.has(row));return home?[{migration:row,corpus:home.corpus}]:[]})}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===1)superseded.push(row);else if(sameLogical.length>1)ambiguous.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:[],foreign:[],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 isRecorded=recorded.has(file);const dropped=removedLater.get(file)??new Set;const droppedTables=tablesDroppedLater.get(file)??new Set;const survives=(effect)=>effectPresent(effect,schema)||isRecorded&&renamedEffectPresent(effect,schema,gate?.frameworkRenames??[])||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 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 readableSet=new Set(readable);const foreign=foreignLedgerRows(ledger.filter((row)=>!readableSet.has(row)),dir);const foreignSet=new Set(foreign.map((row)=>row.migration));const own=ledger.filter((row)=>!foreignSet.has(row));const remapPlan=planLedgerRemap(own,readable);const renamedTo=new Map(remapPlan.remap.map((r)=>[r.from,r.to]));const orphans=own.filter((row)=>!readableSet.has(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,foreign,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 recordedRows=new Set(await readLedger(run));const survivorOf=new Map;const prunable=[];for(const row of plan.superseded.filter((row)=>!retiring.has(row))){if(!SAFE_MIGRATION_FILE.test(row)){result.skipped.push({file:row,reason:"ledger row is not safe to write to the ledger"});continue}const survivor=byLogicalOnDisk(row,[...onDisk]);if(!survivor||!recordedRows.has(survivor)){result.skipped.push({file:row,reason:survivor?`would leave ${survivor} unrecorded`:"no single file of this corpus carries its name"});continue}survivorOf.set(row,survivor);prunable.push(row)}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=survivorOf.get(row);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/migrations.js
CHANGED
|
@@ -9,7 +9,7 @@ ${missing.join(`
|
|
|
9
9
|
migration TEXT NOT NULL UNIQUE,
|
|
10
10
|
executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
11
11
|
)`);const insert=writeDb.prepare("INSERT OR IGNORE INTO migrations (migration) VALUES (?)");for(const migration of droppedMigrations)insert.run(migration);const unrecord=writeDb.prepare("DELETE FROM migrations WHERE migration = ?");for(const migration of replayMigrations)unrecord.run(migration)}finally{writeDb.close()}}catch(e){log.debug(`[migration] Could not record dropped migrations as executed: ${e}`)}}return quarantined}function mayCreateMissingDatabase(){const signal=process.env.STACKS_CREATE_DATABASE;if(signal==="1")return true;if(signal==="0")return false;const policy=String(process.env.DB_CREATE_DATABASE||"").toLowerCase();return!(policy==="never"||policy==="false"||policy==="0")}function describeProbeFailure(target,kind,error){const where=describeTarget(target);const detail=error instanceof Error?error.message:String(error??"");switch(kind){case"missing-role":return`The user "${target.username}" does not exist on ${where}. `+`Set DB_USERNAME to a role that exists, or create it with: createuser -s ${target.username}`;case"auth-failed":return`Authentication failed for user "${target.username}" on ${where}. Check DB_USERNAME and DB_PASSWORD.`;case"server-unreachable":return`Could not reach the database server at ${target.host}:${target.port}. `+`Check that it is running and that DB_HOST and DB_PORT are correct.`;case"timeout":return`Timed out connecting to the database server at ${target.host}:${target.port}. ${detail}`;case"permission-denied":return`The user "${target.username}" is not allowed to connect to "${target.database}" on ${where}.`;default:return`Could not connect to the database "${target.database}" on ${where}. ${detail}`}}async function ensureDatabaseExists(){const target=resolveConnectionTarget();if(!target)return;const probe=await probeTargetDatabase(target);if(probe.ok)return;if(probe.kind!=="missing-database")throw new Error(describeProbeFailure(target,probe.kind,probe.error));if(!mayCreateMissingDatabase()){throw new Error(`The database "${target.database}" does not exist on ${describeTarget(target)}. `+`Create it with: ${manualCreateHint(target)}`)}const result=await createDatabase(target);if(!result.created&&result.error){throw new Error(`The database "${target.database}" does not exist on ${describeTarget(target)} `+`and it could not be created automatically. `+`${describeProbeFailure(target,result.kind,result.error)}
|
|
12
|
-
`+`Create it yourself with: ${manualCreateHint(target)}`)}if(result.created){log.success(`Created database "${target.database}" on ${target.host}:${target.port}`)}}let databaseBootstrapped=false;export async function ensureDatabaseReady(){await ensureDatabaseConfigLoaded();if(databaseBootstrapped)return;await ensureDatabaseExists();databaseBootstrapped=true}export function resetDatabaseBootstrapCache(){databaseBootstrapped=false}export async function featureGatedMigrationFiles(dir=migrationDirectory()){const gated=[];try{const{FEATURE_NAMES,migrationFeature,migrationTable}=await import("@stacksjs/features");const{feature:isFeatureEnabled}=await import("@stacksjs/config");if(!existsSync(dir))return gated;const disabledFeatures=new Set(FEATURE_NAMES.filter((f)=>!isFeatureEnabled(f)));if(disabledFeatures.size===0)return gated;const appTables=await appModelTables();for(const file of readdirSync(dir).filter((f)=>f.endsWith(".sql"))){const owner=migrationFeature(file);if(!owner||!disabledFeatures.has(owner))continue;const table=migrationTable(file);if(table&&appTables.has(table.toLowerCase()))continue;gated.push({file,feature:owner,table})}}catch{}return gated}export async function featureGateForLedger(dir=migrationDirectory(getDialect())){const gated=await featureGatedMigrationFiles(dir);const tables=new Set(gated.flatMap((entry)=>entry.table?[entry.table.toLowerCase()]:[]));return{exclude:new Set(gated.map((entry)=>entry.file)),rewrite:(sql)=>tables.size>0?withoutGatedStatements(sql,tables):sql}}async function hideDisabledFeatureMigrations(){const hidden=[];try{const fs=await import("node:fs/promises");const migrationsDir=migrationDirectory();if(!existsSync(migrationsDir))return hidden;const gated=await featureGatedMigrationFiles(migrationsDir);if(gated.length===0)return hidden;const files=readdirSync(migrationsDir).filter((f)=>f.endsWith(".sql"));const gatedTables=new Set;for(const{file,feature,table}of gated){if(table)gatedTables.add(table.toLowerCase());const original=join(migrationsDir,file);const hiddenPath=`${original}.disabled`;await fs.rename(original,hiddenPath);hidden.push({original,hidden:hiddenPath,feature})}for(const file of files){const filePath=join(migrationsDir,file);if(!existsSync(filePath))continue;const sql=readFileSync(filePath,"utf8");const filtered=withoutGatedStatements(sql,gatedTables);if(filtered===sql)continue;const backup=`${filePath}.ungated`;await fs.rename(filePath,backup);writeFileSync(filePath,filtered);hidden.push({original:filePath,hidden:backup,feature:"mixed"})}if(hidden.length>0){const summary=Object.entries(hidden.reduce((acc,h)=>{acc[h.feature]=(acc[h.feature]??0)+1;return acc},{})).map(([f,n])=>`${f}: ${n}`).join(", ");log.info(`[migration] Skipping ${hidden.length} migration(s) for disabled features (${summary}). Run \`./buddy <feature>:install\` to enable.`)}}catch{}return hidden}function afterCommonTableExpressions(statement){if(!/^\s*WITH\b/i.test(statement))return statement;let depth=0;for(let index=0;index<statement.length;index++){const char=statement[index];if(char==="("){depth++;continue}if(char!==")")continue;depth--;if(depth!==0)continue;const rest=statement.slice(index+1);if(/^\s*,/.test(rest))continue;return rest}return statement}export function statementTable(statement){const body=afterCommonTableExpressions(statement);const patterns=[/^\s*ALTER\s+TABLE\s+["`]?([a-z0-9_]+)["`]?/i,/^\s*CREATE\s+(?:(?:TEMP|TEMPORARY)\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]?([a-z0-9_]+)["`]?/i,/^\s*DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?["`]?([a-z0-9_]+)["`]?/i,/^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]?[a-z0-9_]+["`]?\s+ON\s+["`]?([a-z0-9_]+)["`]?/i,/^\s*UPDATE\s+["`]?([a-z0-9_]+)["`]?/i,/^\s*INSERT\s+(?:OR\s+\w+\s+)?INTO\s+["`]?([a-z0-9_]+)["`]?/i,/^\s*DELETE\s+FROM\s+["`]?([a-z0-9_]+)["`]?/i];for(const pattern of patterns){const match=pattern.exec(body);if(match)return match[1].toLowerCase()}return null}export function statementReferencesTable(statement,table){const escaped=table.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b(?:FROM|JOIN|UPDATE|INTO)\\s+["\`\\[]?${escaped}["\`\\]]?\\b`,"i").test(statement)}function rebuiltTable(statement){const rename=/^\s*ALTER\s+TABLE\s+["`]?([a-z0-9_]+)["`]?\s+RENAME\s+TO\s+["`]?([a-z0-9_]+)["`]?/i.exec(statement);if(rename?.[2])return rename[2].toLowerCase();const table=statementTable(statement);if(table?.startsWith("_qb_tmp_"))return table.slice("_qb_tmp_".length);return null}export function withoutGatedStatements(sql,gated){if(gated.size===0)return sql;const statements=sqlStatementsOf(sql);const excluded=new Set(gated);const temporary=new Set(statements.filter((statement)=>/^\s*CREATE\s+(?:TEMP|TEMPORARY)\s+TABLE\b/i.test(statement)).map((statement)=>statementTable(statement)).filter((table)=>table!==null));let changed=true;while(changed){changed=false;for(const statement of statements){const table=statementTable(statement);if(!table||!temporary.has(table)||excluded.has(table))continue;if([...excluded].some((source)=>statementReferencesTable(statement,source))){excluded.add(table);changed=true}}}const kept=statements.filter((statement)=>{const table=rebuiltTable(statement)??statementTable(statement);if(table&&excluded.has(table))return false;for(const candidate of excluded){if(statementReferencesTable(statement,candidate))return false}return true});if(kept.length===statements.length)return sql;return kept.length===0?"":`${kept.join(`;
|
|
12
|
+
`+`Create it yourself with: ${manualCreateHint(target)}`)}if(result.created){log.success(`Created database "${target.database}" on ${target.host}:${target.port}`)}}let databaseBootstrapped=false;export async function ensureDatabaseReady(){await ensureDatabaseConfigLoaded();if(databaseBootstrapped)return;await ensureDatabaseExists();databaseBootstrapped=true}export function resetDatabaseBootstrapCache(){databaseBootstrapped=false}export async function featureGatedMigrationFiles(dir=migrationDirectory()){const gated=[];try{const{FEATURE_NAMES,migrationFeature,migrationTable}=await import("@stacksjs/features");const{feature:isFeatureEnabled}=await import("@stacksjs/config");if(!existsSync(dir))return gated;const disabledFeatures=new Set(FEATURE_NAMES.filter((f)=>!isFeatureEnabled(f)));if(disabledFeatures.size===0)return gated;const appTables=await appModelTables();for(const file of readdirSync(dir).filter((f)=>f.endsWith(".sql"))){const owner=migrationFeature(file);if(!owner||!disabledFeatures.has(owner))continue;const table=migrationTable(file);if(table&&appTables.has(table.toLowerCase()))continue;gated.push({file,feature:owner,table})}}catch{}return gated}export async function featureGateForLedger(dir=migrationDirectory(getDialect())){const gated=await featureGatedMigrationFiles(dir);const tables=new Set(gated.flatMap((entry)=>entry.table?[entry.table.toLowerCase()]:[]));return{exclude:new Set(gated.map((entry)=>entry.file)),rewrite:(sql)=>tables.size>0?withoutGatedStatements(sql,tables):sql,frameworkRenames:frameworkRenamesForThisApp()}}async function hideDisabledFeatureMigrations(){const hidden=[];try{const fs=await import("node:fs/promises");const migrationsDir=migrationDirectory();if(!existsSync(migrationsDir))return hidden;const gated=await featureGatedMigrationFiles(migrationsDir);if(gated.length===0)return hidden;const files=readdirSync(migrationsDir).filter((f)=>f.endsWith(".sql"));const gatedTables=new Set;for(const{file,feature,table}of gated){if(table)gatedTables.add(table.toLowerCase());const original=join(migrationsDir,file);const hiddenPath=`${original}.disabled`;await fs.rename(original,hiddenPath);hidden.push({original,hidden:hiddenPath,feature})}for(const file of files){const filePath=join(migrationsDir,file);if(!existsSync(filePath))continue;const sql=readFileSync(filePath,"utf8");const filtered=withoutGatedStatements(sql,gatedTables);if(filtered===sql)continue;const backup=`${filePath}.ungated`;await fs.rename(filePath,backup);writeFileSync(filePath,filtered);hidden.push({original:filePath,hidden:backup,feature:"mixed"})}if(hidden.length>0){const summary=Object.entries(hidden.reduce((acc,h)=>{acc[h.feature]=(acc[h.feature]??0)+1;return acc},{})).map(([f,n])=>`${f}: ${n}`).join(", ");log.info(`[migration] Skipping ${hidden.length} migration(s) for disabled features (${summary}). Run \`./buddy <feature>:install\` to enable.`)}}catch{}return hidden}function afterCommonTableExpressions(statement){if(!/^\s*WITH\b/i.test(statement))return statement;let depth=0;for(let index=0;index<statement.length;index++){const char=statement[index];if(char==="("){depth++;continue}if(char!==")")continue;depth--;if(depth!==0)continue;const rest=statement.slice(index+1);if(/^\s*,/.test(rest))continue;return rest}return statement}export function statementTable(statement){const body=afterCommonTableExpressions(statement);const patterns=[/^\s*ALTER\s+TABLE\s+["`]?([a-z0-9_]+)["`]?/i,/^\s*CREATE\s+(?:(?:TEMP|TEMPORARY)\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]?([a-z0-9_]+)["`]?/i,/^\s*DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?["`]?([a-z0-9_]+)["`]?/i,/^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]?[a-z0-9_]+["`]?\s+ON\s+["`]?([a-z0-9_]+)["`]?/i,/^\s*UPDATE\s+["`]?([a-z0-9_]+)["`]?/i,/^\s*INSERT\s+(?:OR\s+\w+\s+)?INTO\s+["`]?([a-z0-9_]+)["`]?/i,/^\s*DELETE\s+FROM\s+["`]?([a-z0-9_]+)["`]?/i];for(const pattern of patterns){const match=pattern.exec(body);if(match)return match[1].toLowerCase()}return null}export function statementReferencesTable(statement,table){const escaped=table.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b(?:FROM|JOIN|UPDATE|INTO)\\s+["\`\\[]?${escaped}["\`\\]]?\\b`,"i").test(statement)}function rebuiltTable(statement){const rename=/^\s*ALTER\s+TABLE\s+["`]?([a-z0-9_]+)["`]?\s+RENAME\s+TO\s+["`]?([a-z0-9_]+)["`]?/i.exec(statement);if(rename?.[2])return rename[2].toLowerCase();const table=statementTable(statement);if(table?.startsWith("_qb_tmp_"))return table.slice("_qb_tmp_".length);return null}export function withoutGatedStatements(sql,gated){if(gated.size===0)return sql;const statements=sqlStatementsOf(sql);const excluded=new Set(gated);const temporary=new Set(statements.filter((statement)=>/^\s*CREATE\s+(?:TEMP|TEMPORARY)\s+TABLE\b/i.test(statement)).map((statement)=>statementTable(statement)).filter((table)=>table!==null));let changed=true;while(changed){changed=false;for(const statement of statements){const table=statementTable(statement);if(!table||!temporary.has(table)||excluded.has(table))continue;if([...excluded].some((source)=>statementReferencesTable(statement,source))){excluded.add(table);changed=true}}}const kept=statements.filter((statement)=>{const table=rebuiltTable(statement)??statementTable(statement);if(table&&excluded.has(table))return false;for(const candidate of excluded){if(statementReferencesTable(statement,candidate))return false}return true});if(kept.length===statements.length)return sql;return kept.length===0?"":`${kept.join(`;
|
|
13
13
|
`)};
|
|
14
14
|
`}async function restoreHiddenMigrations(hidden){const fs=await import("node:fs/promises");for(const{original,hidden:h}of hidden){try{if(h.endsWith(".ungated"))await fs.rm(original,{force:true});await fs.rename(h,original)}catch{}}}export async function countAppliedMigrations(){await ensureDatabaseConfigLoaded();try{const rows=await db.unsafe("SELECT COUNT(*) AS n FROM migrations").execute();const row=Array.isArray(rows)?rows[0]:undefined;if(!row)return 0;const n=Number(row.n??row.N??0);return Number.isFinite(n)?n:0}catch{return 0}}async function writeMigrateMarker(appliedCount){try{const fs=await import("node:fs/promises");const dir=path.frameworkRuntimePath();await fs.mkdir(dir,{recursive:true});const file=`${dir}/last-migrate-result.json`;const body=JSON.stringify({appliedCount,completedAt:new Date().toISOString()});await fs.writeFile(file,body,"utf8")}catch{}}export function idempotentSql(sql){const header=/^(?:[^\S\n]*--[^\n]*\n)+/.exec(sql)?.[0]??"";const bodies=[];const masked=sql.slice(header.length).replace(/\$([A-Za-z_]*)\$[\s\S]*?\$\1\$/g,(body)=>`\x00${bodies.push(body)-1}\x00`);const stmts=masked.split(";").map((s)=>s.trim().replace(/\u0000(\d+)\u0000/g,(_m,index)=>bodies[Number(index)])).filter(Boolean);if(stmts.length===0)return sql;const out=[];for(const raw of stmts){const stmt=raw.replace(/\bADD\s+COLUMN\s+(?!IF\s+NOT\s+EXISTS\b)/gi,"ADD COLUMN IF NOT EXISTS ").replace(/\bDROP\s+COLUMN\s+(?!IF\s+EXISTS\b)/gi,"DROP COLUMN IF EXISTS ");const m=/^ALTER\s+TABLE\s+("?\w+"?)\s+ADD\s+CONSTRAINT\s+("?\w+"?)/i.exec(stmt);if(m){const drops=[`ALTER TABLE ${m[1]} DROP CONSTRAINT IF EXISTS ${m[2]}`];const fk=/\bFOREIGN\s+KEY\s*\(\s*"?(\w+)"?\s*\)/i.exec(stmt);if(fk){const table=m[1].replace(/"/g,"");drops.push(`ALTER TABLE ${m[1]} DROP CONSTRAINT IF EXISTS "${table}_${fk[1]}_fkey"`)}const already=new Set;for(let i=out.length-1;i>=0;i--){const previous=out[i];if(!/^ALTER\s+TABLE\s+"?\w+"?\s+DROP\s+CONSTRAINT\b/i.test(previous))break;already.add(previous.toUpperCase())}for(const drop of drops){if(!already.has(drop.toUpperCase()))out.push(drop)}}out.push(stmt)}return`${header}${out.join(`;
|
|
15
15
|
`)};
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/database",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.701",
|
|
6
6
|
"description": "The Stacks database integration.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -66,26 +66,26 @@
|
|
|
66
66
|
"prepublishOnly": "bun run build"
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"@stacksjs/config": "0.75.
|
|
70
|
-
"@stacksjs/env": "0.75.
|
|
71
|
-
"@stacksjs/error-handling": "0.75.
|
|
72
|
-
"@stacksjs/faker": "0.75.
|
|
73
|
-
"@stacksjs/features": "0.75.
|
|
74
|
-
"@stacksjs/logging": "0.75.
|
|
75
|
-
"@stacksjs/model-meta": "0.75.
|
|
76
|
-
"@stacksjs/path": "0.75.
|
|
77
|
-
"@stacksjs/query-builder": "0.75.
|
|
78
|
-
"@stacksjs/security": "0.75.
|
|
79
|
-
"@stacksjs/storage": "0.75.
|
|
80
|
-
"@stacksjs/strings": "0.75.
|
|
69
|
+
"@stacksjs/config": "0.75.701",
|
|
70
|
+
"@stacksjs/env": "0.75.701",
|
|
71
|
+
"@stacksjs/error-handling": "0.75.701",
|
|
72
|
+
"@stacksjs/faker": "0.75.701",
|
|
73
|
+
"@stacksjs/features": "0.75.701",
|
|
74
|
+
"@stacksjs/logging": "0.75.701",
|
|
75
|
+
"@stacksjs/model-meta": "0.75.701",
|
|
76
|
+
"@stacksjs/path": "0.75.701",
|
|
77
|
+
"@stacksjs/query-builder": "0.75.701",
|
|
78
|
+
"@stacksjs/security": "0.75.701",
|
|
79
|
+
"@stacksjs/storage": "0.75.701",
|
|
80
|
+
"@stacksjs/strings": "0.75.701",
|
|
81
81
|
"@stacksjs/ts-validation": "^0.5.7",
|
|
82
82
|
"bun-query-builder": "^0.6.4",
|
|
83
83
|
"dynamodb-tooling": "^0.3.6"
|
|
84
84
|
},
|
|
85
85
|
"devDependencies": {
|
|
86
|
-
"@stacksjs/cli": "0.75.
|
|
87
|
-
"@stacksjs/router": "0.75.
|
|
88
|
-
"@stacksjs/utils": "0.75.
|
|
86
|
+
"@stacksjs/cli": "0.75.701",
|
|
87
|
+
"@stacksjs/router": "0.75.701",
|
|
88
|
+
"@stacksjs/utils": "0.75.701",
|
|
89
89
|
"better-dx": "^0.2.39"
|
|
90
90
|
}
|
|
91
91
|
}
|