bun-query-builder 0.3.11 → 0.3.13

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.
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{n,e,_,t,I,je,ot,r,w,m}from"./chunk-s9c63x14.js";import{i,Ne,Me}from"./chunk-zrhf7kye.js";import{O,_e,Ie,P}from"./chunk-7wfn6sn7.js";import{u}from"./chunk-6s2dqhn3.js";var Ur=import.meta.require;async function te(s={}){let a=s.iterations||1000,l=s.operations?.split(",")||["select","insert","update","delete","count"];console.log("-- Running Query Builder Benchmarks"),console.log(`-- Iterations: ${a}`),console.log(`-- Operations: ${l.join(", ")}`),console.log();let c=i();console.log("-- Setting up test table...");try{await r.unsafe("DROP TABLE IF EXISTS bench_users").execute(),await r.unsafe(`
2
+ import{n,e,I,t,L,je,ot,r,w,m}from"./chunk-jypmc6m3.js";import{i,Me,Pe}from"./chunk-bhm321nb.js";import{O,Ie,E,B}from"./chunk-ztdtt4hj.js";import{u}from"./chunk-2v1zv4hb.js";var Fr=import.meta.require;async function ne(s={}){let a=s.iterations||1000,l=s.operations?.split(",")||["select","insert","update","delete","count"];console.log("-- Running Query Builder Benchmarks"),console.log(`-- Iterations: ${a}`),console.log(`-- Operations: ${l.join(", ")}`),console.log();let c=i();console.log("-- Setting up test table...");try{await r.unsafe("DROP TABLE IF EXISTS bench_users").execute(),await r.unsafe(`
3
3
  CREATE TABLE bench_users (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  name TEXT NOT NULL,
@@ -10,7 +10,7 @@ import{n,e,_,t,I,je,ot,r,w,m}from"./chunk-s9c63x14.js";import{i,Ne,Me}from"./chu
10
10
  `).execute();for(let p=0;p<100;p++)await r.unsafe(`
11
11
  INSERT INTO bench_users (name, email, created_at)
12
12
  VALUES (?, ?, ?)
13
- `,[`User ${p}`,`user${p}@example.com`,new Date().toISOString()]).execute();console.log("-- \u2713 Test table ready with 100 rows"),console.log()}catch(p){throw console.error("-- Failed to setup test table:",p),p}let f=[];if(l.includes("select")){let p=[];for(let x=0;x<a;x++){let T=performance.now();await c.selectFrom("bench_users").where({active:1}).limit(10).execute(),p.push(performance.now()-T)}f.push({operation:"SELECT with WHERE + LIMIT",avgTime:p.reduce((x,T)=>x+T,0)/p.length,minTime:Math.min(...p),maxTime:Math.max(...p),iterations:a})}if(l.includes("select")){let p=[];for(let x=0;x<a;x++){let T=performance.now();await c.selectFrom("bench_users").where({id:1}).first(),p.push(performance.now()-T)}f.push({operation:"SELECT by ID (first)",avgTime:p.reduce((x,T)=>x+T,0)/p.length,minTime:Math.min(...p),maxTime:Math.max(...p),iterations:a})}if(l.includes("count")){let p=[];for(let x=0;x<a;x++){let T=performance.now();await c.selectFrom("bench_users").count(),p.push(performance.now()-T)}f.push({operation:"COUNT",avgTime:p.reduce((x,T)=>x+T,0)/p.length,minTime:Math.min(...p),maxTime:Math.max(...p),iterations:a})}if(l.includes("insert")){let p=[];for(let x=0;x<a;x++){let T=performance.now();await c.insertInto("bench_users").values({name:`Bench User ${x}`,email:`bench${x}@example.com`,created_at:new Date().toISOString()}).execute(),p.push(performance.now()-T)}f.push({operation:"INSERT",avgTime:p.reduce((x,T)=>x+T,0)/p.length,minTime:Math.min(...p),maxTime:Math.max(...p),iterations:a})}if(l.includes("update")){let p=[];for(let x=0;x<a;x++){let T=performance.now();await c.updateTable("bench_users").set({active:0}).where({id:1}).execute(),p.push(performance.now()-T)}f.push({operation:"UPDATE by ID",avgTime:p.reduce((x,T)=>x+T,0)/p.length,minTime:Math.min(...p),maxTime:Math.max(...p),iterations:a})}if(l.includes("delete")){let p=[],x=[];for(let T=0;T<a;T++){let E=await c.insertInto("bench_users").values({name:"To Delete",email:`delete${T}@example.com`,created_at:new Date().toISOString()}).execute();x.push(E)}for(let T=0;T<a;T++){let E=performance.now();await c.deleteFrom("bench_users").where({id:x[T]}).execute(),p.push(performance.now()-E)}f.push({operation:"DELETE by ID",avgTime:p.reduce((T,E)=>T+E,0)/p.length,minTime:Math.min(...p),maxTime:Math.max(...p),iterations:a})}console.log("-- Benchmark Results"),console.log();let y=Math.max(...f.map((p)=>p.operation.length));console.log("Operation".padEnd(y+2)+"Avg (ms)".padStart(12)+"Min (ms)".padStart(12)+"Max (ms)".padStart(12)+"Ops/sec".padStart(12)),console.log("-".repeat(y+2+12+12+12+12));for(let p of f){let x=p.operation.padEnd(y+2),T=p.avgTime.toFixed(3).padStart(12),E=p.minTime.toFixed(3).padStart(12),C=p.maxTime.toFixed(3).padStart(12),v=(1000/p.avgTime).toFixed(0).padStart(12);console.log(`${x}${T}${E}${C}${v}`)}console.log();try{await r.unsafe("DROP TABLE IF EXISTS bench_users").execute(),console.log("-- \u2713 Cleanup complete")}catch(p){console.error("-- Warning: Failed to cleanup test table:",p)}}async function ne(){console.log("-- Clearing query cache..."),Ne(),console.log("-- \u2713 Query cache cleared")}async function re(){console.log("-- Query Cache Information"),console.log(),console.log("The query cache is an LRU (Least Recently Used) cache with TTL support."),console.log(),console.log("Configuration:"),console.log(" - Default max size: 100 entries"),console.log(" - Default TTL: 60 seconds (60000ms)"),console.log(" - Eviction: LRU when cache is full"),console.log(),console.log("Usage:"),console.log(' qb.selectFrom("users").cache().get() // Cache for 60s'),console.log(' qb.selectFrom("users").cache(5000).get() // Cache for 5s'),console.log(),console.log("Configuration:"),console.log(" clearQueryCache() // Clear all cached queries"),console.log(" setQueryCacheMaxSize(500) // Set max cache size"),console.log(),console.log("Commands:"),console.log(" qb cache:clear // Clear the cache"),console.log(" qb cache:config --size 500 // Configure cache size")}async function ie(s={}){if(console.log("-- Configuring query cache..."),console.log(),s.size!==void 0){let a=Number(s.size);if(Number.isNaN(a)||a<=0)throw console.error("-- Error: Cache size must be a positive number"),Error("Invalid cache size");Me(a),console.log(`-- \u2713 Cache max size set to: ${a}`)}else console.log("-- No configuration changes specified"),console.log("-- Available options:"),console.log("-- --size <n> Set maximum cache size (default: 100)"),console.log(),console.log("-- Example: qb cache:config --size 500")}import ln from"process";import{createInterface as Fr}from"readline";async function K(){console.log("-- Query Builder Interactive Console"),console.log("-- Type .help for available commands"),console.log("-- Type .exit or press Ctrl+C to quit"),console.log();let s=i(),a=Fr({input:ln.stdin,output:ln.stdout,prompt:"qb> "}),l="",c=!1,f=`
13
+ `,[`User ${p}`,`user${p}@example.com`,new Date().toISOString()]).execute();console.log("-- \u2713 Test table ready with 100 rows"),console.log()}catch(p){throw console.error("-- Failed to setup test table:",p),p}let f=[];if(l.includes("select")){let p=[];for(let x=0;x<a;x++){let T=performance.now();await c.selectFrom("bench_users").where({active:1}).limit(10).execute(),p.push(performance.now()-T)}f.push({operation:"SELECT with WHERE + LIMIT",avgTime:p.reduce((x,T)=>x+T,0)/p.length,minTime:Math.min(...p),maxTime:Math.max(...p),iterations:a})}if(l.includes("select")){let p=[];for(let x=0;x<a;x++){let T=performance.now();await c.selectFrom("bench_users").where({id:1}).first(),p.push(performance.now()-T)}f.push({operation:"SELECT by ID (first)",avgTime:p.reduce((x,T)=>x+T,0)/p.length,minTime:Math.min(...p),maxTime:Math.max(...p),iterations:a})}if(l.includes("count")){let p=[];for(let x=0;x<a;x++){let T=performance.now();await c.selectFrom("bench_users").count(),p.push(performance.now()-T)}f.push({operation:"COUNT",avgTime:p.reduce((x,T)=>x+T,0)/p.length,minTime:Math.min(...p),maxTime:Math.max(...p),iterations:a})}if(l.includes("insert")){let p=[];for(let x=0;x<a;x++){let T=performance.now();await c.insertInto("bench_users").values({name:`Bench User ${x}`,email:`bench${x}@example.com`,created_at:new Date().toISOString()}).execute(),p.push(performance.now()-T)}f.push({operation:"INSERT",avgTime:p.reduce((x,T)=>x+T,0)/p.length,minTime:Math.min(...p),maxTime:Math.max(...p),iterations:a})}if(l.includes("update")){let p=[];for(let x=0;x<a;x++){let T=performance.now();await c.updateTable("bench_users").set({active:0}).where({id:1}).execute(),p.push(performance.now()-T)}f.push({operation:"UPDATE by ID",avgTime:p.reduce((x,T)=>x+T,0)/p.length,minTime:Math.min(...p),maxTime:Math.max(...p),iterations:a})}if(l.includes("delete")){let p=[],x=[];for(let T=0;T<a;T++){let R=await c.insertInto("bench_users").values({name:"To Delete",email:`delete${T}@example.com`,created_at:new Date().toISOString()}).execute();x.push(R)}for(let T=0;T<a;T++){let R=performance.now();await c.deleteFrom("bench_users").where({id:x[T]}).execute(),p.push(performance.now()-R)}f.push({operation:"DELETE by ID",avgTime:p.reduce((T,R)=>T+R,0)/p.length,minTime:Math.min(...p),maxTime:Math.max(...p),iterations:a})}console.log("-- Benchmark Results"),console.log();let y=Math.max(...f.map((p)=>p.operation.length));console.log("Operation".padEnd(y+2)+"Avg (ms)".padStart(12)+"Min (ms)".padStart(12)+"Max (ms)".padStart(12)+"Ops/sec".padStart(12)),console.log("-".repeat(y+2+12+12+12+12));for(let p of f){let x=p.operation.padEnd(y+2),T=p.avgTime.toFixed(3).padStart(12),R=p.minTime.toFixed(3).padStart(12),C=p.maxTime.toFixed(3).padStart(12),_=(1000/p.avgTime).toFixed(0).padStart(12);console.log(`${x}${T}${R}${C}${_}`)}console.log();try{await r.unsafe("DROP TABLE IF EXISTS bench_users").execute(),console.log("-- \u2713 Cleanup complete")}catch(p){console.error("-- Warning: Failed to cleanup test table:",p)}}async function re(){console.log("-- Clearing query cache..."),Me(),console.log("-- \u2713 Query cache cleared")}async function ie(){console.log("-- Query Cache Information"),console.log(),console.log("The query cache is an LRU (Least Recently Used) cache with TTL support."),console.log(),console.log("Configuration:"),console.log(" - Default max size: 100 entries"),console.log(" - Default TTL: 60 seconds (60000ms)"),console.log(" - Eviction: LRU when cache is full"),console.log(),console.log("Usage:"),console.log(' qb.selectFrom("users").cache().get() // Cache for 60s'),console.log(' qb.selectFrom("users").cache(5000).get() // Cache for 5s'),console.log(),console.log("Configuration:"),console.log(" clearQueryCache() // Clear all cached queries"),console.log(" setQueryCacheMaxSize(500) // Set max cache size"),console.log(),console.log("Commands:"),console.log(" qb cache:clear // Clear the cache"),console.log(" qb cache:config --size 500 // Configure cache size")}async function se(s={}){if(console.log("-- Configuring query cache..."),console.log(),s.size!==void 0){let a=Number(s.size);if(Number.isNaN(a)||a<=0)throw console.error("-- Error: Cache size must be a positive number"),Error("Invalid cache size");Pe(a),console.log(`-- \u2713 Cache max size set to: ${a}`)}else console.log("-- No configuration changes specified"),console.log("-- Available options:"),console.log("-- --size <n> Set maximum cache size (default: 100)"),console.log(),console.log("-- Example: qb cache:config --size 500")}import ln from"process";import{createInterface as Vr}from"readline";async function F(){console.log("-- Query Builder Interactive Console"),console.log("-- Type .help for available commands"),console.log("-- Type .exit or press Ctrl+C to quit"),console.log();let s=i(),a=Vr({input:ln.stdin,output:ln.stdout,prompt:"qb> "}),l="",c=!1,f=`
14
14
  Available Commands:
15
15
  .help Show this help message
16
16
  .exit Exit the console
@@ -29,21 +29,21 @@ Tips:
29
29
  - Use 'await' for async operations
30
30
  - Multi-line input: end with \\ to continue on next line
31
31
  - Press Enter on an empty line to execute multi-line input
32
- `,y=async(x)=>{try{let C=await new(Object.getPrototypeOf(async()=>{})).constructor("qb",`return (${x})`)(s);if(C!==void 0)if(Array.isArray(C))console.log(`-- ${C.length} row(s) returned`),console.table(C);else if(typeof C==="object"&&C!==null)console.log(C);else console.log(C)}catch(T){console.error("Error:",T.message)}},p=async(x)=>{let T=x.trim();if(T.startsWith(".")){let E=T.toLowerCase();if(E===".exit"||E===".quit")console.log("Goodbye!"),a.close(),ln.exit(0);else if(E===".help")console.log(f);else if(E===".clear")console.clear();else if(E===".tables")try{let C=await s.unsafe(`
32
+ `,y=async(x)=>{try{let C=await new(Object.getPrototypeOf(async()=>{})).constructor("qb",`return (${x})`)(s);if(C!==void 0)if(Array.isArray(C))console.log(`-- ${C.length} row(s) returned`),console.table(C);else if(typeof C==="object"&&C!==null)console.log(C);else console.log(C)}catch(T){console.error("Error:",T.message)}},p=async(x)=>{let T=x.trim();if(T.startsWith(".")){let R=T.toLowerCase();if(R===".exit"||R===".quit")console.log("Goodbye!"),a.close(),ln.exit(0);else if(R===".help")console.log(f);else if(R===".clear")console.clear();else if(R===".tables")try{let C=await s.unsafe(`
33
33
  SELECT name FROM sqlite_master
34
34
  WHERE type = 'table'
35
35
  AND name NOT LIKE 'sqlite_%'
36
36
  ORDER BY name
37
- `);if(C.length>0){console.log("Tables:");for(let v of C)console.log(` - ${v.name}`)}else console.log("No tables found")}catch(C){console.error("Error listing tables:",C.message)}else console.log(`Unknown command: ${T}`),console.log("Type .help for available commands");return}if(T.endsWith("\\")){c=!0,l+=`${T.slice(0,-1)}
37
+ `);if(C.length>0){console.log("Tables:");for(let _ of C)console.log(` - ${_.name}`)}else console.log("No tables found")}catch(C){console.error("Error listing tables:",C.message)}else console.log(`Unknown command: ${T}`),console.log("Type .help for available commands");return}if(T.endsWith("\\")){c=!0,l+=`${T.slice(0,-1)}
38
38
  `;return}if(c){if(T==="")await y(l),l="",c=!1;else l+=`${T}
39
39
  `;return}if(T)await y(T)};a.on("line",async(x)=>{await p(x),a.prompt()}),a.on("SIGINT",()=>{if(c)console.log(`
40
40
  -- Multi-line input cancelled`),l="",c=!1,a.prompt();else console.log(`
41
41
  -- Type .exit to quit`),a.prompt()}),a.on("close",()=>{console.log(`
42
- Goodbye!`),ln.exit(0)}),a.prompt()}async function se(){return K()}import{existsSync as Vr,readFileSync as jr,writeFileSync as Wt}from"fs";async function ae(s,a={}){let l=a.format||"json",c=a.output||`${s}.${l}`,f=a.limit;if(console.log(`-- Exporting data from table: ${s}`),console.log(`-- Format: ${l}`),console.log(`-- Output: ${c}`),f)console.log(`-- Limit: ${f} rows`);console.log();try{let p=i().selectFrom(s);if(f)p=p.limit(f);let x=await p.execute();if(console.log(`-- Retrieved ${x.length} rows`),l==="json")Wt(c,JSON.stringify(x,null,2)),console.log(`-- \u2713 Exported to JSON: ${c}`);else if(l==="csv"){if(x.length===0){Wt(c,""),console.log(`-- \u2713 Exported to CSV: ${c} (empty)`);return}let T=Object.keys(x[0]),E=[T.join(",")];for(let C of x){let v=T.map((k)=>{let L=C[k];if(L===null||L===void 0)return"";let B=String(L);if(B.includes(",")||B.includes('"')||B.includes(`
43
- `))return`"${B.replace(/"/g,'""')}"`;return B});E.push(v.join(","))}Wt(c,E.join(`
44
- `)),console.log(`-- \u2713 Exported to CSV: ${c}`)}else if(l==="sql"){let T=[];for(let E of x){let C=Object.keys(E),v=C.map((k)=>{let L=E[k];if(L===null||L===void 0)return"NULL";if(typeof L==="number")return String(L);return`'${String(L).replace(/'/g,"''")}'`});T.push(`INSERT INTO ${s} (${C.join(", ")}) VALUES (${v.join(", ")});`)}Wt(c,T.join(`
45
- `)),console.log(`-- \u2713 Exported to SQL: ${c}`)}}catch(y){throw console.error(`-- Failed to export data from ${s}:`,y),y}}async function oe(s,a,l={}){if(!Vr(a))throw console.error(`-- File not found: ${a}`),Error(`File not found: ${a}`);let c=l.format||(a.endsWith(".json")?"json":"csv"),f=l.truncate??!1;console.log(`-- Importing data into table: ${s}`),console.log(`-- Format: ${c}`),console.log(`-- File: ${a}`),console.log(`-- Truncate: ${f}`),console.log();try{let y=i();if(f)await y.deleteFrom(s).execute(),console.log("-- Table truncated");let p=jr(a,"utf8"),x=[];if(c==="json"){if(x=JSON.parse(p),!Array.isArray(x))throw TypeError("JSON file must contain an array of objects")}else if(c==="csv"){let C=p.split(`
46
- `).filter((k)=>k.trim());if(C.length<2){console.log("-- No data to import (CSV is empty or has only headers)");return}let v=C[0].split(",").map((k)=>k.trim());for(let k=1;k<C.length;k++){let L=C[k].split(",").map((X)=>X.trim()),B={};for(let X=0;X<v.length;X++){let Pe=L[X];if(Pe.startsWith('"')&&Pe.endsWith('"'))Pe=Pe.slice(1,-1).replace(/""/g,'"');if(Pe==="")Pe=null;else if(!Number.isNaN(Number(Pe)))Pe=Number(Pe);B[v[X]]=Pe}x.push(B)}}if(x.length===0){console.log("-- No data to import");return}let T=100,E=0;for(let C=0;C<x.length;C+=T){let v=x.slice(C,C+T);await y.insertInto(s).values(v).execute(),E+=v.length,console.log(`-- Imported ${E}/${x.length} rows...`)}console.log(`-- \u2713 Successfully imported ${x.length} rows`)}catch(y){throw console.error(`-- Failed to import data into ${s}:`,y),y}}async function le(s={}){let a=e.dialect||"postgres",l=s.output||`dump-${Date.now()}.sql`,c=s.tables?.split(",").map((f)=>f.trim());if(console.log("-- Dumping database"),console.log(`-- Dialect: ${a}`),console.log(`-- Output: ${l}`),c)console.log(`-- Tables: ${c.join(", ")}`);console.log();try{let f=i(),y=[];if(a==="sqlite")y=(await f.unsafe(`
42
+ Goodbye!`),ln.exit(0)}),a.prompt()}async function ae(){return F()}import{existsSync as jr,readFileSync as Yr,writeFileSync as Wt}from"fs";async function oe(s,a={}){let l=a.format||"json",c=a.output||`${s}.${l}`,f=a.limit;if(console.log(`-- Exporting data from table: ${s}`),console.log(`-- Format: ${l}`),console.log(`-- Output: ${c}`),f)console.log(`-- Limit: ${f} rows`);console.log();try{let p=i().selectFrom(s);if(f)p=p.limit(f);let x=await p.execute();if(console.log(`-- Retrieved ${x.length} rows`),l==="json")Wt(c,JSON.stringify(x,null,2)),console.log(`-- \u2713 Exported to JSON: ${c}`);else if(l==="csv"){if(x.length===0){Wt(c,""),console.log(`-- \u2713 Exported to CSV: ${c} (empty)`);return}let T=Object.keys(x[0]),R=[T.join(",")];for(let C of x){let _=T.map((v)=>{let k=C[v];if(k===null||k===void 0)return"";let K=String(k);if(K.includes(",")||K.includes('"')||K.includes(`
43
+ `))return`"${K.replace(/"/g,'""')}"`;return K});R.push(_.join(","))}Wt(c,R.join(`
44
+ `)),console.log(`-- \u2713 Exported to CSV: ${c}`)}else if(l==="sql"){let T=[];for(let R of x){let C=Object.keys(R),_=C.map((v)=>{let k=R[v];if(k===null||k===void 0)return"NULL";if(typeof k==="number")return String(k);return`'${String(k).replace(/'/g,"''")}'`});T.push(`INSERT INTO ${s} (${C.join(", ")}) VALUES (${_.join(", ")});`)}Wt(c,T.join(`
45
+ `)),console.log(`-- \u2713 Exported to SQL: ${c}`)}}catch(y){throw console.error(`-- Failed to export data from ${s}:`,y),y}}async function le(s,a,l={}){if(!jr(a))throw console.error(`-- File not found: ${a}`),Error(`File not found: ${a}`);let c=l.format||(a.endsWith(".json")?"json":"csv"),f=l.truncate??!1;console.log(`-- Importing data into table: ${s}`),console.log(`-- Format: ${c}`),console.log(`-- File: ${a}`),console.log(`-- Truncate: ${f}`),console.log();try{let y=i();if(f)await y.deleteFrom(s).execute(),console.log("-- Table truncated");let p=Yr(a,"utf8"),x=[];if(c==="json"){if(x=JSON.parse(p),!Array.isArray(x))throw TypeError("JSON file must contain an array of objects")}else if(c==="csv"){let C=p.split(`
46
+ `).filter((v)=>v.trim());if(C.length<2){console.log("-- No data to import (CSV is empty or has only headers)");return}let _=C[0].split(",").map((v)=>v.trim());for(let v=1;v<C.length;v++){let k=C[v].split(",").map((Z)=>Z.trim()),K={};for(let Z=0;Z<_.length;Z++){let _e=k[Z];if(_e.startsWith('"')&&_e.endsWith('"'))_e=_e.slice(1,-1).replace(/""/g,'"');if(_e==="")_e=null;else if(!Number.isNaN(Number(_e)))_e=Number(_e);K[_[Z]]=_e}x.push(K)}}if(x.length===0){console.log("-- No data to import");return}let T=100,R=0;for(let C=0;C<x.length;C+=T){let _=x.slice(C,C+T);await y.insertInto(s).values(_).execute(),R+=_.length,console.log(`-- Imported ${R}/${x.length} rows...`)}console.log(`-- \u2713 Successfully imported ${x.length} rows`)}catch(y){throw console.error(`-- Failed to import data into ${s}:`,y),y}}async function ce(s={}){let a=e.dialect||"postgres",l=s.output||`dump-${Date.now()}.sql`,c=s.tables?.split(",").map((f)=>f.trim());if(console.log("-- Dumping database"),console.log(`-- Dialect: ${a}`),console.log(`-- Output: ${l}`),c)console.log(`-- Tables: ${c.join(", ")}`);console.log();try{let f=i(),y=[];if(a==="sqlite")y=(await f.unsafe(`
47
47
  SELECT name FROM sqlite_master
48
48
  WHERE type = 'table'
49
49
  AND name NOT LIKE 'sqlite_%'
@@ -60,8 +60,8 @@ Goodbye!`),ln.exit(0)}),a.prompt()}async function se(){return K()}import{existsS
60
60
  WHERE table_schema = DATABASE()
61
61
  AND table_type = 'BASE TABLE'
62
62
  ORDER BY table_name
63
- `)).map((T)=>T.table_name);if(c)y=y.filter((x)=>c.includes(x));if(y.length===0){console.log("-- No tables to dump");return}console.log(`-- Dumping ${y.length} table(s)`);let p=[];p.push("-- Database dump"),p.push(`-- Generated at: ${new Date().toISOString()}`),p.push(`-- Dialect: ${a}`),p.push("");for(let x of y){console.log(`-- Dumping table: ${x}`);let T=await f.selectFrom(x).execute();p.push(`-- Table: ${x}`),p.push(`-- Rows: ${T.length}`),p.push("");for(let E of T){let C=Object.keys(E),v=C.map((k)=>{let L=E[k];if(L===null||L===void 0)return"NULL";if(typeof L==="number")return String(L);return`'${String(L).replace(/'/g,"''")}'`});p.push(`INSERT INTO ${x} (${C.join(", ")}) VALUES (${v.join(", ")});`)}p.push("")}Wt(l,p.join(`
64
- `)),console.log(),console.log(`-- \u2713 Database dump saved to: ${l}`)}catch(f){throw console.error("-- Failed to dump database:",f),f}}async function F(){let s=e.dialect||"postgres",a=e.database?.database||"unknown";console.log("-- Database Information"),console.log(`-- Dialect: ${s}`),console.log(`-- Database: ${a}`),console.log();try{let l=i(),c=[],f=[];if(s==="postgres")f=(await l.unsafe(`
63
+ `)).map((T)=>T.table_name);if(c)y=y.filter((x)=>c.includes(x));if(y.length===0){console.log("-- No tables to dump");return}console.log(`-- Dumping ${y.length} table(s)`);let p=[];p.push("-- Database dump"),p.push(`-- Generated at: ${new Date().toISOString()}`),p.push(`-- Dialect: ${a}`),p.push("");for(let x of y){console.log(`-- Dumping table: ${x}`);let T=await f.selectFrom(x).execute();p.push(`-- Table: ${x}`),p.push(`-- Rows: ${T.length}`),p.push("");for(let R of T){let C=Object.keys(R),_=C.map((v)=>{let k=R[v];if(k===null||k===void 0)return"NULL";if(typeof k==="number")return String(k);return`'${String(k).replace(/'/g,"''")}'`});p.push(`INSERT INTO ${x} (${C.join(", ")}) VALUES (${_.join(", ")});`)}p.push("")}Wt(l,p.join(`
64
+ `)),console.log(),console.log(`-- \u2713 Database dump saved to: ${l}`)}catch(f){throw console.error("-- Failed to dump database:",f),f}}async function j(){let s=e.dialect||"postgres",a=e.database?.database||"unknown";console.log("-- Database Information"),console.log(`-- Dialect: ${s}`),console.log(`-- Database: ${a}`),console.log();try{let l=i(),c=[],f=[];if(s==="postgres")f=(await l.unsafe(`
65
65
  SELECT table_name
66
66
  FROM information_schema.tables
67
67
  WHERE table_schema = 'public'
@@ -79,29 +79,29 @@ Goodbye!`),ln.exit(0)}),a.prompt()}async function se(){return K()}import{existsS
79
79
  WHERE type = 'table'
80
80
  AND name NOT LIKE 'sqlite_%'
81
81
  ORDER BY name
82
- `)).map((x)=>x.name);for(let p of f)try{let x=await l.unsafe(`SELECT COUNT(*) as count FROM ${p}`),T=Number(x[0]?.count||0),E=0,C=0;if(s==="postgres"){let v=await l.unsafe(`
82
+ `)).map((x)=>x.name);for(let p of f)try{let x=await l.unsafe(`SELECT COUNT(*) as count FROM ${p}`),T=Number(x[0]?.count||0),R=0,C=0;if(s==="postgres"){let _=await l.unsafe(`
83
83
  SELECT COUNT(*) as count
84
84
  FROM information_schema.columns
85
85
  WHERE table_name = $1
86
- `,[p]);E=Number(v[0]?.count||0);let k=await l.unsafe(`
86
+ `,[p]);R=Number(_[0]?.count||0);let v=await l.unsafe(`
87
87
  SELECT COUNT(*) as count
88
88
  FROM pg_indexes
89
89
  WHERE tablename = $1
90
- `,[p]);C=Number(k[0]?.count||0)}else if(n(s)){let v=await l.unsafe(`
90
+ `,[p]);C=Number(v[0]?.count||0)}else if(n(s)){let _=await l.unsafe(`
91
91
  SELECT COUNT(*) as count
92
92
  FROM information_schema.columns
93
93
  WHERE table_name = ?
94
94
  AND table_schema = DATABASE()
95
- `,[p]);E=Number(v[0]?.count||0);let k=await l.unsafe(`
95
+ `,[p]);R=Number(_[0]?.count||0);let v=await l.unsafe(`
96
96
  SELECT COUNT(*) as count
97
97
  FROM information_schema.statistics
98
98
  WHERE table_name = ?
99
99
  AND table_schema = DATABASE()
100
- `,[p]);C=Number(k[0]?.count||0)}else if(s==="sqlite")E=(await l.unsafe(`PRAGMA table_info(${p})`)).length,C=(await l.unsafe(`PRAGMA index_list(${p})`)).length;c.push({name:p,rowCount:T,columns:E,indexes:C})}catch(x){console.error(`-- Error getting info for table ${p}:`,x)}let y=c.reduce((p,x)=>p+x.rowCount,0);if(console.log(`-- Total Tables: ${c.length}`),console.log(`-- Total Rows: ${y.toLocaleString()}`),console.log(),c.length>0){console.log("Tables:"),console.log();let p=Math.max(...c.map((E)=>E.name.length)),x=p+2,T="Table".padEnd(x)+"Rows".padStart(12)+"Columns".padStart(10)+"Indexes".padStart(10);console.log(T),console.log("-".repeat(T.length));for(let E of c){let C=E.name.padEnd(p+2),v=E.rowCount.toLocaleString().padStart(12),k=(E.columns||0).toString().padStart(10),L=(E.indexes||0).toString().padStart(10);console.log(`${C}${v}${k}${L}`)}}else console.log("-- No tables found");return{dialect:s,database:a,tables:c,totalTables:c.length,totalRows:y}}catch(l){throw console.error("-- Failed to get database info:",l),l}}async function ce(){return F()}async function j(s={}){let a=_(s.dialect),l=s.aggressive||!1;if(s.verbose)console.log(`Optimizing ${a} database${l?" (aggressive mode)":""}...`);try{if(a==="postgres"){if(s.tables&&s.tables.length>0)for(let c of s.tables){if(s.verbose)console.log(`Analyzing table: ${c}`);if(l)await r`VACUUM FULL ANALYZE ${r(c)}`;else await r`VACUUM ANALYZE ${r(c)}`}else{if(s.verbose)console.log("Running VACUUM and ANALYZE on all tables...");if(l)await r`VACUUM FULL`,await r`ANALYZE`;else await r`VACUUM ANALYZE`}console.log("\u2713 PostgreSQL optimization complete")}else if(n(a)){if(s.tables&&s.tables.length>0)for(let c of s.tables){if(s.verbose)console.log(`Optimizing table: ${c}`);await r`OPTIMIZE TABLE ${r(c)}`,await r`ANALYZE TABLE ${r(c)}`}else{let c=je(),f=await r`
100
+ `,[p]);C=Number(v[0]?.count||0)}else if(s==="sqlite")R=(await l.unsafe(`PRAGMA table_info(${p})`)).length,C=(await l.unsafe(`PRAGMA index_list(${p})`)).length;c.push({name:p,rowCount:T,columns:R,indexes:C})}catch(x){console.error(`-- Error getting info for table ${p}:`,x)}let y=c.reduce((p,x)=>p+x.rowCount,0);if(console.log(`-- Total Tables: ${c.length}`),console.log(`-- Total Rows: ${y.toLocaleString()}`),console.log(),c.length>0){console.log("Tables:"),console.log();let p=Math.max(...c.map((R)=>R.name.length)),x=p+2,T="Table".padEnd(x)+"Rows".padStart(12)+"Columns".padStart(10)+"Indexes".padStart(10);console.log(T),console.log("-".repeat(T.length));for(let R of c){let C=R.name.padEnd(p+2),_=R.rowCount.toLocaleString().padStart(12),v=(R.columns||0).toString().padStart(10),k=(R.indexes||0).toString().padStart(10);console.log(`${C}${_}${v}${k}`)}}else console.log("-- No tables found");return{dialect:s,database:a,tables:c,totalTables:c.length,totalRows:y}}catch(l){throw console.error("-- Failed to get database info:",l),l}}async function ue(){return j()}async function q(s={}){let a=I(s.dialect),l=s.aggressive||!1;if(s.verbose)console.log(`Optimizing ${a} database${l?" (aggressive mode)":""}...`);try{if(a==="postgres"){if(s.tables&&s.tables.length>0)for(let c of s.tables){if(s.verbose)console.log(`Analyzing table: ${c}`);if(l)await r`VACUUM FULL ANALYZE ${r(c)}`;else await r`VACUUM ANALYZE ${r(c)}`}else{if(s.verbose)console.log("Running VACUUM and ANALYZE on all tables...");if(l)await r`VACUUM FULL`,await r`ANALYZE`;else await r`VACUUM ANALYZE`}console.log("\u2713 PostgreSQL optimization complete")}else if(n(a)){if(s.tables&&s.tables.length>0)for(let c of s.tables){if(s.verbose)console.log(`Optimizing table: ${c}`);await r`OPTIMIZE TABLE ${r(c)}`,await r`ANALYZE TABLE ${r(c)}`}else{let c=je(),f=await r`
101
101
  SELECT table_name
102
102
  FROM information_schema.tables
103
103
  WHERE table_schema = ${c}
104
- `;for(let y of f){let p=y.table_name||y.TABLE_NAME;if(s.verbose)console.log(`Optimizing table: ${p}`);await r`OPTIMIZE TABLE ${r(p)}`,await r`ANALYZE TABLE ${r(p)}`}}console.log("\u2713 MySQL optimization complete")}else if(a==="sqlite"){if(s.verbose)console.log("Running VACUUM on SQLite database...");if(await r`VACUUM`,s.tables&&s.tables.length>0)for(let c of s.tables){if(s.verbose)console.log(`Analyzing table: ${c}`);await r`ANALYZE ${r(c)}`}else await r`ANALYZE`;if(l){if(s.verbose)console.log("Running aggressive SQLite optimizations...");await r`PRAGMA optimize`,await r`PRAGMA wal_checkpoint(TRUNCATE)`}console.log("\u2713 SQLite optimization complete")}else console.error(`Unsupported dialect: ${a}`)}catch(c){throw console.error("Error optimizing database:",c.message),c}}async function q(s={}){let a=_(s.dialect);if(s.verbose)console.log(`Wiping all tables from ${a} database...`);try{let l=[];if(a==="postgres")l=(await r`
104
+ `;for(let y of f){let p=y.table_name||y.TABLE_NAME;if(s.verbose)console.log(`Optimizing table: ${p}`);await r`OPTIMIZE TABLE ${r(p)}`,await r`ANALYZE TABLE ${r(p)}`}}console.log("\u2713 MySQL optimization complete")}else if(a==="sqlite"){if(s.verbose)console.log("Running VACUUM on SQLite database...");if(await r`VACUUM`,s.tables&&s.tables.length>0)for(let c of s.tables){if(s.verbose)console.log(`Analyzing table: ${c}`);await r`ANALYZE ${r(c)}`}else await r`ANALYZE`;if(l){if(s.verbose)console.log("Running aggressive SQLite optimizations...");await r`PRAGMA optimize`,await r`PRAGMA wal_checkpoint(TRUNCATE)`}console.log("\u2713 SQLite optimization complete")}else console.error(`Unsupported dialect: ${a}`)}catch(c){throw console.error("Error optimizing database:",c.message),c}}async function W(s={}){let a=I(s.dialect);if(s.verbose)console.log(`Wiping all tables from ${a} database...`);try{let l=[];if(a==="postgres")l=(await r`
105
105
  SELECT tablename
106
106
  FROM pg_tables
107
107
  WHERE schemaname = 'public'
@@ -114,7 +114,7 @@ Goodbye!`),ln.exit(0)}),a.prompt()}async function se(){return K()}import{existsS
114
114
  FROM sqlite_master
115
115
  WHERE type = 'table'
116
116
  AND name NOT LIKE 'sqlite_%'
117
- `).map((f)=>f.name);if(l.length===0){console.log("No tables found to drop.");return}if(s.verbose)console.log(`Found ${l.length} tables: ${l.join(", ")}`);if(a==="postgres")for(let c of l){if(s.verbose)console.log(`Dropping table: ${c}`);await r`DROP TABLE IF EXISTS ${r(c)} CASCADE`}else if(n(a)){await r`SET FOREIGN_KEY_CHECKS = 0`;for(let c of l){if(s.verbose)console.log(`Dropping table: ${c}`);await r`DROP TABLE IF EXISTS ${r(c)}`}await r`SET FOREIGN_KEY_CHECKS = 1`}else if(a==="sqlite"){await r`PRAGMA foreign_keys = OFF`;for(let c of l){if(s.verbose)console.log(`Dropping table: ${c}`);await r`DROP TABLE IF EXISTS ${r(c)}`}await r`PRAGMA foreign_keys = ON`}console.log(`\u2713 Dropped ${l.length} tables`)}catch(l){throw console.error("Error wiping database:",l.message),l}}async function ue(s){let c=await(i().raw([s]).simple()?.execute?.()??Promise.resolve([]));return console.log(JSON.stringify(c,null,2)),c}async function de(s,a={}){let l=i(),c=a.params?JSON.parse(a.params):void 0,f=await l.file(s,c);return console.log(JSON.stringify(f)),f}async function W(s,a={}){let l=e.dialect||"postgres",c=a.verbose??!0;if(c)console.log(`-- Inspecting table: ${s}`),console.log(`-- Dialect: ${l}`),console.log();try{let f=i(),y=[],p=[],x=await f.unsafe(`SELECT COUNT(*) as count FROM ${s}`),T=Number(x[0]?.count||0);if(l==="postgres"){let E=await f.unsafe(`
117
+ `).map((f)=>f.name);if(l.length===0){console.log("No tables found to drop.");return}if(s.verbose)console.log(`Found ${l.length} tables: ${l.join(", ")}`);if(a==="postgres")for(let c of l){if(s.verbose)console.log(`Dropping table: ${c}`);await r`DROP TABLE IF EXISTS ${r(c)} CASCADE`}else if(n(a)){await r`SET FOREIGN_KEY_CHECKS = 0`;for(let c of l){if(s.verbose)console.log(`Dropping table: ${c}`);await r`DROP TABLE IF EXISTS ${r(c)}`}await r`SET FOREIGN_KEY_CHECKS = 1`}else if(a==="sqlite"){await r`PRAGMA foreign_keys = OFF`;for(let c of l){if(s.verbose)console.log(`Dropping table: ${c}`);await r`DROP TABLE IF EXISTS ${r(c)}`}await r`PRAGMA foreign_keys = ON`}console.log(`\u2713 Dropped ${l.length} tables`)}catch(l){throw console.error("Error wiping database:",l.message),l}}async function de(s){let c=await(i().raw([s]).simple()?.execute?.()??Promise.resolve([]));return console.log(JSON.stringify(c,null,2)),c}async function fe(s,a={}){let l=i(),c=a.params?JSON.parse(a.params):void 0,f=await l.file(s,c);return console.log(JSON.stringify(f)),f}async function U(s,a={}){let l=e.dialect||"postgres",c=a.verbose??!0;if(c)console.log(`-- Inspecting table: ${s}`),console.log(`-- Dialect: ${l}`),console.log();try{let f=i(),y=[],p=[],x=await f.unsafe(`SELECT COUNT(*) as count FROM ${s}`),T=Number(x[0]?.count||0);if(l==="postgres"){let R=await f.unsafe(`
118
118
  SELECT
119
119
  c.column_name,
120
120
  c.data_type,
@@ -147,7 +147,7 @@ Goodbye!`),ln.exit(0)}),a.prompt()}async function se(){return K()}import{existsS
147
147
  ) fk ON c.column_name = fk.column_name
148
148
  WHERE c.table_name = $1
149
149
  ORDER BY c.ordinal_position
150
- `,[s]);for(let v of E)y.push({name:v.column_name,type:v.data_type,nullable:v.is_nullable==="YES",default:v.column_default,isPrimaryKey:v.is_primary_key,isForeignKey:v.is_foreign_key});let C=await f.unsafe(`
150
+ `,[s]);for(let _ of R)y.push({name:_.column_name,type:_.data_type,nullable:_.is_nullable==="YES",default:_.column_default,isPrimaryKey:_.is_primary_key,isForeignKey:_.is_foreign_key});let C=await f.unsafe(`
151
151
  SELECT
152
152
  i.indexname as name,
153
153
  i.indexdef,
@@ -156,7 +156,7 @@ Goodbye!`),ln.exit(0)}),a.prompt()}async function se(){return K()}import{existsS
156
156
  JOIN pg_class c ON c.relname = i.indexname
157
157
  JOIN pg_index ix ON ix.indexrelid = c.oid
158
158
  WHERE i.tablename = $1
159
- `,[s]);for(let v of C){let k=v.indexdef?.match(/\(([^)]+)\)/),B=(k?k[1]:"").split(",").map((X)=>X.trim());p.push({name:v.name,columns:B,unique:v.is_unique})}}else if(n(l)){let E=await f.unsafe(`
159
+ `,[s]);for(let _ of C){let v=_.indexdef?.match(/\(([^)]+)\)/),K=(v?v[1]:"").split(",").map((Z)=>Z.trim());p.push({name:_.name,columns:K,unique:_.is_unique})}}else if(n(l)){let R=await f.unsafe(`
160
160
  SELECT
161
161
  COLUMN_NAME as column_name,
162
162
  DATA_TYPE as data_type,
@@ -167,9 +167,9 @@ Goodbye!`),ln.exit(0)}),a.prompt()}async function se(){return K()}import{existsS
167
167
  WHERE TABLE_NAME = ?
168
168
  AND TABLE_SCHEMA = DATABASE()
169
169
  ORDER BY ORDINAL_POSITION
170
- `,[s]);for(let k of E)y.push({name:k.column_name,type:k.data_type,nullable:k.is_nullable==="YES",default:k.column_default,isPrimaryKey:k.column_key==="PRI",isForeignKey:k.column_key==="MUL"});let C=await f.unsafe(`
170
+ `,[s]);for(let v of R)y.push({name:v.column_name,type:v.data_type,nullable:v.is_nullable==="YES",default:v.column_default,isPrimaryKey:v.column_key==="PRI",isForeignKey:v.column_key==="MUL"});let C=await f.unsafe(`
171
171
  SHOW INDEXES FROM ${s}
172
- `),v=new Map;for(let k of C){let L=k.Key_name;if(!v.has(L))v.set(L,{columns:[],unique:k.Non_unique===0});v.get(L).columns.push(k.Column_name)}for(let[k,L]of v)p.push({name:k,columns:L.columns,unique:L.unique})}else if(l==="sqlite"){let E=await f.unsafe(`PRAGMA table_info(${s})`);for(let v of E)y.push({name:v.name,type:v.type,nullable:v.notnull===0,default:v.dflt_value,isPrimaryKey:v.pk===1});let C=await f.unsafe(`PRAGMA index_list(${s})`);for(let v of C){let k=await f.unsafe(`PRAGMA index_info(${v.name})`);p.push({name:v.name,columns:k.map((L)=>L.name),unique:v.unique===1})}}if(c){console.log(`Table: ${s}`),console.log(`Rows: ${T.toLocaleString()}`),console.log(),console.log("Columns:"),console.log();let E=Math.max(...y.map((B)=>B.name.length),10),C=Math.max(...y.map((B)=>B.type.length),10),v=E+2,k=C+2,L=`${"Name".padEnd(v)+"Type".padEnd(k)+"Nullable".padEnd(10)+"Default".padEnd(20)}Flags`;console.log(L),console.log("-".repeat(L.length));for(let B of y){let X=B.name.padEnd(v),Pe=B.type.padEnd(k),Be=(B.nullable?"YES":"NO").padEnd(10),Ve=String(B.default||"").padEnd(20),tt=[B.isPrimaryKey?"PK":"",B.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${X}${Pe}${Be}${Ve}${tt}`)}if(console.log(),p.length>0){console.log("Indexes:"),console.log();for(let B of p){let X=B.unique?" (UNIQUE)":"";console.log(` - ${B.name}${X}: [${B.columns.join(", ")}]`)}console.log()}}return{tableName:s,rowCount:T,columns:y,indexes:p}}catch(f){throw console.error(`-- Failed to inspect table ${s}:`,f),f}}async function fe(s,a={}){return W(s,a)}async function me(s,a={}){let l=await d({modelsDir:s}),c=Re(l);return console.log(JSON.stringify(c,null,2)),{models:l,schema:c}}function dt(s){let a=s.toLowerCase();if(/^bool|boolean|tinyint\(1\)/.test(a))return"boolean";if(/int|serial|numeric|decimal|double|real|float|money/.test(a))return"number";if(/timestamp|datetime|date|time/.test(a))return"datetime";if(/json/.test(a))return"json";return"string"}function Yr(s){if(/ies$/i.test(s))return s.replace(/ies$/i,"y");if(/ses$/i.test(s))return s.replace(/es$/i,"");if(/s$/i.test(s)&&!/ss$/i.test(s))return s.replace(/s$/i,"");return s}function Qr(s){return s.replace(/[-_\s]+/g," ").split(" ").filter(Boolean).map((a)=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}function He(s){return Qr(Yr(s))}async function Wn(s,a){if(a==="postgres")return(await s.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY table_name")).map((f)=>f.table_name);if(n(a))return(await s.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE' ORDER BY table_name")).map((f)=>f.table_name??f.TABLE_NAME);return(await s.unsafe("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")).map((c)=>c.name)}async function Wr(s,a,l){if(a==="sqlite")return(await s.unsafe(`PRAGMA table_info(${l})`)).map((y)=>({name:y.name,sqlType:String(y.type||""),nullable:Number(y.notnull)===0,isPrimaryKey:Number(y.pk)>0}));if(a==="postgres")return(await s.unsafe(`SELECT c.column_name, c.data_type, c.is_nullable,
172
+ `),_=new Map;for(let v of C){let k=v.Key_name;if(!_.has(k))_.set(k,{columns:[],unique:v.Non_unique===0});_.get(k).columns.push(v.Column_name)}for(let[v,k]of _)p.push({name:v,columns:k.columns,unique:k.unique})}else if(l==="sqlite"){let R=await f.unsafe(`PRAGMA table_info(${s})`);for(let _ of R)y.push({name:_.name,type:_.type,nullable:_.notnull===0,default:_.dflt_value,isPrimaryKey:_.pk===1});let C=await f.unsafe(`PRAGMA index_list(${s})`);for(let _ of C){let v=await f.unsafe(`PRAGMA index_info(${_.name})`);p.push({name:_.name,columns:v.map((k)=>k.name),unique:_.unique===1})}}if(c){console.log(`Table: ${s}`),console.log(`Rows: ${T.toLocaleString()}`),console.log(),console.log("Columns:"),console.log();let R=Math.max(...y.map((K)=>K.name.length),10),C=Math.max(...y.map((K)=>K.type.length),10),_=R+2,v=C+2,k=`${"Name".padEnd(_)+"Type".padEnd(v)+"Nullable".padEnd(10)+"Default".padEnd(20)}Flags`;console.log(k),console.log("-".repeat(k.length));for(let K of y){let Z=K.name.padEnd(_),_e=K.type.padEnd(v),Be=(K.nullable?"YES":"NO").padEnd(10),Ve=String(K.default||"").padEnd(20),et=[K.isPrimaryKey?"PK":"",K.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${Z}${_e}${Be}${Ve}${et}`)}if(console.log(),p.length>0){console.log("Indexes:"),console.log();for(let K of p){let Z=K.unique?" (UNIQUE)":"";console.log(` - ${K.name}${Z}: [${K.columns.join(", ")}]`)}console.log()}}return{tableName:s,rowCount:T,columns:y,indexes:p}}catch(f){throw console.error(`-- Failed to inspect table ${s}:`,f),f}}async function me(s,a={}){return U(s,a)}async function he(s,a={}){let l=await d({modelsDir:s}),c=Ae(l);return console.log(JSON.stringify(c,null,2)),{models:l,schema:c}}function dt(s){let a=s.toLowerCase();if(/^bool|boolean|tinyint\(1\)/.test(a))return"boolean";if(/int|serial|numeric|decimal|double|real|float|money/.test(a))return"number";if(/timestamp|datetime|date|time/.test(a))return"datetime";if(/json/.test(a))return"json";return"string"}function Qr(s){if(/ies$/i.test(s))return s.replace(/ies$/i,"y");if(/ses$/i.test(s))return s.replace(/es$/i,"");if(/s$/i.test(s)&&!/ss$/i.test(s))return s.replace(/s$/i,"");return s}function Wr(s){return s.replace(/[-_\s]+/g," ").split(" ").filter(Boolean).map((a)=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}function He(s){return Wr(Qr(s))}async function Wn(s,a){if(a==="postgres")return(await s.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY table_name")).map((f)=>f.table_name);if(n(a))return(await s.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE' ORDER BY table_name")).map((f)=>f.table_name??f.TABLE_NAME);return(await s.unsafe("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")).map((c)=>c.name)}async function Gr(s,a,l){if(a==="sqlite")return(await s.unsafe(`PRAGMA table_info(${l})`)).map((y)=>({name:y.name,sqlType:String(y.type||""),nullable:Number(y.notnull)===0,isPrimaryKey:Number(y.pk)>0}));if(a==="postgres")return(await s.unsafe(`SELECT c.column_name, c.data_type, c.is_nullable,
173
173
  (SELECT COUNT(*) FROM information_schema.table_constraints tc
174
174
  JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
175
175
  WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
@@ -187,12 +187,12 @@ Goodbye!`),ln.exit(0)}),a.prompt()}async function se(){return K()}import{existsS
187
187
  ${f}
188
188
  },
189
189
  })
190
- `}async function R(s={}){let a=e.dialect||"postgres",l=i(),c=s.tables?.length?s.tables:await Wn(l,a),f=[];for(let y of c){let p=await Wr(l,a,y);if(!p.length)continue;f.push({table:y,modelName:He(y),primaryKey:p.find((x)=>x.isPrimaryKey)?.name??"id",columns:p,source:ft(y,p)})}return f}function bn(s,a,l){if(l?.enumValues&&l.enumValues.length>0)return"enum";let c=String(s||"").toLowerCase().trim(),f=c.replace(/\(.*$/,"").replace(/\s+/g," ").trim();if(n(a)&&/^tinyint\(1\)/.test(c))return"boolean";if(/^bool/.test(f))return"boolean";if(f==="int8"||f==="bigint"||f==="bigserial")return"bigint";if(/^(?:int|integer|smallint|mediumint|serial|int2|int4|tinyint)/.test(f))return"integer";if(/^(?:varchar|character varying|nvarchar|nchar|char|character|bpchar)/.test(f)){let y=c.match(/\((\d+)\)/),p=y?Number(y[1]):void 0;if(n(a))return"string";return p!==void 0&&p>255?"text":"string"}if(/text|clob/.test(f))return"text";if(f==="float8"||/^double/.test(f))return"double";if(/^(?:real|float4|float)/.test(f))return"float";if(/^(?:numeric|decimal|money)/.test(f))return"decimal";if(f==="date")return"date";if(f==="timestamptz"||/\bwith time zone\b/.test(c))return"timestamptz";if(/^(?:timestamp|datetime)/.test(f))return"datetime";if(/^time/.test(f))return"string";if(/json/.test(f))return"json";if(/^enum/.test(f))return"enum";return"string"}function Gr(s,a,l){return bn(String(a||s||""),"mysql",{enumValues:l})}function zr(s){let a=String(s||"").trim().match(/^varchar\((\d+)\)/i);if(!a)return;let l=Number(a[1]);return Number.isSafeInteger(l)&&l>0?l:void 0}function jt(s){let a=String(s??"").toLowerCase().trim();if(a==="cascade"||a==="restrict"||a==="set null")return a;return}async function Hr(s,a){let l=await s.unsafe(`PRAGMA table_info(${JSON.stringify(a)})`),c=await s.unsafe(`PRAGMA index_list(${JSON.stringify(a)})`),f=await s.unsafe(`PRAGMA foreign_key_list(${JSON.stringify(a)})`),y=await s.unsafe("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",[a]),p=String(y?.[0]?.sql??""),x=new Map;for(let v of f)x.set(String(v.from),{table:String(v.table),column:String(v.to??"id"),onDelete:jt(v.on_delete),onUpdate:jt(v.on_update)});let T=[],E=new Set;for(let v of c){let k=String(v.origin??""),L=String(v.name??"");if(k==="pk"||L.startsWith("sqlite_autoindex_"))continue;let X=(await s.unsafe(`PRAGMA index_info(${JSON.stringify(L)})`)).map((Ve)=>String(Ve.name)).filter(Boolean);if(X.length===0)continue;let Pe=Number(v.unique)===1,Be=Number(v.partial)===1?await Xr(s,L):void 0;if(Pe&&X.length===1&&!Be)E.add(X[0]);T.push({name:L,columns:X,type:Pe?"unique":"index",...Be?{where:Be}:{}})}let C=l.map((v)=>{let k=String(v.name),L=Zr(p,k),B=Number(v.pk)>0,X=v.dflt_value,Pe=X!==null&&X!==void 0;return{name:k,type:bn(String(v.type??""),"sqlite",{enumValues:L}),isPrimaryKey:B,isUnique:E.has(k),isNullable:B?!1:Number(v.notnull)===0,hasDefault:Pe,defaultValue:Pe?hn(X):void 0,enumValues:L,references:x.get(k)}});return{table:a,columns:C,indexes:T}}async function Xr(s,a){let l=await s.unsafe("SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ?",[a]);return Jr(String(l?.[0]?.sql??""))}function Jr(s){let a=0,l=!1;for(let c=0;c<s.length;c++){let f=s[c];if(f==="'")l=!l;if(l)continue;if(f==="(")a++;else if(f===")")a--;else if(a===0&&/^where\b/i.test(s.slice(c,c+6))&&/[\s)]/.test(s[c-1]??""))return s.slice(c+5).trim().replace(/;\s*$/,"").trim()||void 0}return}function Zr(s,a){if(!s)return;let l=new RegExp(`(?:"${a}"|\`${a}\`|\\b${a}\\b)\\s+IN\\s*\\(([^)]*)\\)`,"i"),c=s.match(l);if(!c)return;let f=c[1].split(",").map((y)=>y.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((y)=>y.length>0);return f.length>0?f:void 0}function hn(s){if(typeof s==="number"||typeof s==="boolean")return s;return String(s)}async function Gn(s){let a=await s.unsafe(`SELECT t.typname AS type_name, e.enumlabel AS label
190
+ `}async function A(s={}){let a=e.dialect||"postgres",l=i(),c=s.tables?.length?s.tables:await Wn(l,a),f=[];for(let y of c){let p=await Gr(l,a,y);if(!p.length)continue;f.push({table:y,modelName:He(y),primaryKey:p.find((x)=>x.isPrimaryKey)?.name??"id",columns:p,source:ft(y,p)})}return f}function bn(s,a,l){if(l?.enumValues&&l.enumValues.length>0)return"enum";let c=String(s||"").toLowerCase().trim(),f=c.replace(/\(.*$/,"").replace(/\s+/g," ").trim();if(n(a)&&/^tinyint\(1\)/.test(c))return"boolean";if(/^bool/.test(f))return"boolean";if(f==="int8"||f==="bigint"||f==="bigserial")return"bigint";if(/^(?:int|integer|smallint|mediumint|serial|int2|int4|tinyint)/.test(f))return"integer";if(/^(?:varchar|character varying|nvarchar|nchar|char|character|bpchar)/.test(f)){let y=c.match(/\((\d+)\)/),p=y?Number(y[1]):void 0;if(n(a))return"string";return p!==void 0&&p>255?"text":"string"}if(/text|clob/.test(f))return"text";if(f==="float8"||/^double/.test(f))return"double";if(/^(?:real|float4|float)/.test(f))return"float";if(/^(?:numeric|decimal|money)/.test(f))return"decimal";if(f==="date")return"date";if(f==="timestamptz"||/\bwith time zone\b/.test(c))return"timestamptz";if(/^(?:timestamp|datetime)/.test(f))return"datetime";if(/^time/.test(f))return"string";if(/json/.test(f))return"json";if(/^enum/.test(f))return"enum";return"string"}function zr(s,a,l){return bn(String(a||s||""),"mysql",{enumValues:l})}function Hr(s){let a=String(s||"").trim().match(/^varchar\((\d+)\)/i);if(!a)return;let l=Number(a[1]);return Number.isSafeInteger(l)&&l>0?l:void 0}function jt(s){let a=String(s??"").toLowerCase().trim();if(a==="cascade"||a==="restrict"||a==="set null")return a;return}async function Xr(s,a){let l=await s.unsafe(`PRAGMA table_info(${JSON.stringify(a)})`),c=await s.unsafe(`PRAGMA index_list(${JSON.stringify(a)})`),f=await s.unsafe(`PRAGMA foreign_key_list(${JSON.stringify(a)})`),y=await s.unsafe("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",[a]),p=String(y?.[0]?.sql??""),x=new Map;for(let _ of f)x.set(String(_.from),{table:String(_.table),column:String(_.to??"id"),onDelete:jt(_.on_delete),onUpdate:jt(_.on_update)});let T=[],R=new Set;for(let _ of c){let v=String(_.origin??""),k=String(_.name??"");if(v==="pk"||k.startsWith("sqlite_autoindex_"))continue;let Z=(await s.unsafe(`PRAGMA index_info(${JSON.stringify(k)})`)).map((Ve)=>String(Ve.name)).filter(Boolean);if(Z.length===0)continue;let _e=Number(_.unique)===1,Be=Number(_.partial)===1?await Jr(s,k):void 0;if(_e&&Z.length===1&&!Be)R.add(Z[0]);T.push({name:k,columns:Z,type:_e?"unique":"index",...Be?{where:Be}:{}})}let C=l.map((_)=>{let v=String(_.name),k=ei(p,v),K=Number(_.pk)>0,Z=_.dflt_value,_e=Z!==null&&Z!==void 0;return{name:v,type:bn(String(_.type??""),"sqlite",{enumValues:k}),isPrimaryKey:K,isUnique:R.has(v),isNullable:K?!1:Number(_.notnull)===0,hasDefault:_e,defaultValue:_e?hn(Z):void 0,enumValues:k,references:x.get(v)}});return{table:a,columns:C,indexes:T}}async function Jr(s,a){let l=await s.unsafe("SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ?",[a]);return Zr(String(l?.[0]?.sql??""))}function Zr(s){let a=0,l=!1;for(let c=0;c<s.length;c++){let f=s[c];if(f==="'")l=!l;if(l)continue;if(f==="(")a++;else if(f===")")a--;else if(a===0&&/^where\b/i.test(s.slice(c,c+6))&&/[\s)]/.test(s[c-1]??""))return s.slice(c+5).trim().replace(/;\s*$/,"").trim()||void 0}return}function ei(s,a){if(!s)return;let l=new RegExp(`(?:"${a}"|\`${a}\`|\\b${a}\\b)\\s+IN\\s*\\(([^)]*)\\)`,"i"),c=s.match(l);if(!c)return;let f=c[1].split(",").map((y)=>y.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((y)=>y.length>0);return f.length>0?f:void 0}function hn(s){if(typeof s==="number"||typeof s==="boolean")return s;return String(s)}async function Gn(s){let a=await s.unsafe(`SELECT t.typname AS type_name, e.enumlabel AS label
191
191
  FROM pg_type t
192
192
  JOIN pg_enum e ON e.enumtypid = t.oid
193
193
  JOIN pg_namespace n ON n.oid = t.typnamespace
194
194
  WHERE n.nspname = 'public'
195
- ORDER BY t.typname, e.enumsortorder`),l=new Map;for(let c of a){let f=String(c.type_name),y=l.get(f);if(y)y.push(String(c.label));else l.set(f,[String(c.label)])}return l}function ei(s,a,l){let c=l.get(a),f=bn(String(s||a||""),"postgres",{enumValues:c});return c?{type:f,enumValues:c,enumTypeName:a}:{type:f}}function zn(s,a){let l=(y)=>{if(y===null||y===void 0||y==="")return;let p=Number(y);return Number.isSafeInteger(p)&&p>=0?p:void 0},c=l(s),f=l(a);return{...c!==void 0&&c>0?{precision:c}:{},...f!==void 0?{scale:f}:{}}}function ti(s){let a=String(s||"").trim().match(/^(?:decimal|numeric)\((\d+)(?:,(\d+))?\)/i);if(!a)return{};return zn(a[1],a[2]??0)}function ni(s){if(s===null||s===void 0||s==="")return;let a=Number(s);return Number.isSafeInteger(a)&&a>0?a:void 0}async function ri(s,a,l){let c=l??await Gn(s),f=await s.unsafe(`SELECT c.column_name, c.data_type, c.udt_name, c.is_nullable, c.column_default, c.character_maximum_length,
195
+ ORDER BY t.typname, e.enumsortorder`),l=new Map;for(let c of a){let f=String(c.type_name),y=l.get(f);if(y)y.push(String(c.label));else l.set(f,[String(c.label)])}return l}function ti(s,a,l){let c=l.get(a),f=bn(String(s||a||""),"postgres",{enumValues:c});return c?{type:f,enumValues:c,enumTypeName:a}:{type:f}}function zn(s,a){let l=(y)=>{if(y===null||y===void 0||y==="")return;let p=Number(y);return Number.isSafeInteger(p)&&p>=0?p:void 0},c=l(s),f=l(a);return{...c!==void 0&&c>0?{precision:c}:{},...f!==void 0?{scale:f}:{}}}function ni(s){let a=String(s||"").trim().match(/^(?:decimal|numeric)\((\d+)(?:,(\d+))?\)/i);if(!a)return{};return zn(a[1],a[2]??0)}function ri(s){if(s===null||s===void 0||s==="")return;let a=Number(s);return Number.isSafeInteger(a)&&a>0?a:void 0}async function ii(s,a,l){let c=l??await Gn(s),f=await s.unsafe(`SELECT c.column_name, c.data_type, c.udt_name, c.is_nullable, c.column_default, c.character_maximum_length,
196
196
  c.numeric_precision, c.numeric_scale,
197
197
  (SELECT COUNT(*) FROM information_schema.table_constraints tc
198
198
  JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
@@ -213,7 +213,7 @@ ${f}
213
213
  JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = tc.constraint_name
214
214
  JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name = tc.constraint_name
215
215
  JOIN information_schema.referential_constraints rc ON rc.constraint_name = tc.constraint_name
216
- WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = $1 AND tc.table_schema = 'public'`,[a]),x=new Map,T=new Map;for(let k of p){let L=String(k.constraint_name);T.set(L,(T.get(L)??0)+1)}for(let k of p){let L=String(k.column_name),B=x.get(L),X=String(k.constraint_name),Pe=T.get(X)===1?[...new Set([...B?.constraintNames??[],X])]:B?.constraintNames;x.set(L,B?{...B,constraintNames:Pe}:{table:String(k.ref_table),column:String(k.ref_column??"id"),onDelete:jt(k.delete_rule),onUpdate:jt(k.update_rule),constraintNames:Pe})}let{indexes:E,uniqueColumns:C}=Hn(a,y.map((k)=>({indexName:String(k.index_name),isUnique:k.is_unique===!0||k.is_unique==="t",isPrimary:k.is_primary===!0||k.is_primary==="t",column:String(k.column_name),where:k.where_clause?String(k.where_clause):void 0}))),v=f.map((k)=>{let L=String(k.column_name),B=Number(k.is_pk)>0,X=k.column_default==null?null:String(k.column_default),Pe=X!=null&&/nextval\(/i.test(X),Be=X!=null&&!Pe,Ve=ei(String(k.data_type??""),k.udt_name==null?"":String(k.udt_name),c);return{name:L,...Ve,maxLength:Ve.type==="string"?ni(k.character_maximum_length):void 0,...Ve.type==="decimal"?zn(k.numeric_precision,k.numeric_scale):{},isPrimaryKey:B,isUnique:C.has(L),isNullable:B?!1:String(k.is_nullable).toUpperCase()==="YES",hasDefault:Be,defaultValue:Be?hn(X):void 0,references:x.get(L)}});return{table:a,columns:v,indexes:E}}async function ii(s,a){let l=await s.unsafe(`SELECT column_name, data_type, column_type, is_nullable, column_default, column_key
216
+ WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = $1 AND tc.table_schema = 'public'`,[a]),x=new Map,T=new Map;for(let v of p){let k=String(v.constraint_name);T.set(k,(T.get(k)??0)+1)}for(let v of p){let k=String(v.column_name),K=x.get(k),Z=String(v.constraint_name),_e=T.get(Z)===1?[...new Set([...K?.constraintNames??[],Z])]:K?.constraintNames;x.set(k,K?{...K,constraintNames:_e}:{table:String(v.ref_table),column:String(v.ref_column??"id"),onDelete:jt(v.delete_rule),onUpdate:jt(v.update_rule),constraintNames:_e})}let{indexes:R,uniqueColumns:C}=Hn(a,y.map((v)=>({indexName:String(v.index_name),isUnique:v.is_unique===!0||v.is_unique==="t",isPrimary:v.is_primary===!0||v.is_primary==="t",column:String(v.column_name),where:v.where_clause?String(v.where_clause):void 0}))),_=f.map((v)=>{let k=String(v.column_name),K=Number(v.is_pk)>0,Z=v.column_default==null?null:String(v.column_default),_e=Z!=null&&/nextval\(/i.test(Z),Be=Z!=null&&!_e,Ve=ti(String(v.data_type??""),v.udt_name==null?"":String(v.udt_name),c);return{name:k,...Ve,maxLength:Ve.type==="string"?ri(v.character_maximum_length):void 0,...Ve.type==="decimal"?zn(v.numeric_precision,v.numeric_scale):{},isPrimaryKey:K,isUnique:C.has(k),isNullable:K?!1:String(v.is_nullable).toUpperCase()==="YES",hasDefault:Be,defaultValue:Be?hn(Z):void 0,references:x.get(k)}});return{table:a,columns:_,indexes:R}}async function si(s,a){let l=await s.unsafe(`SELECT column_name, data_type, column_type, is_nullable, column_default, column_key
217
217
  FROM information_schema.columns
218
218
  WHERE table_name = ? AND table_schema = DATABASE()
219
219
  ORDER BY ordinal_position`,[a]),c=await s.unsafe(`SELECT index_name, non_unique, seq_in_index, column_name
@@ -224,7 +224,7 @@ ${f}
224
224
  FROM information_schema.key_column_usage kcu
225
225
  JOIN information_schema.referential_constraints rc
226
226
  ON rc.constraint_name = kcu.constraint_name AND rc.constraint_schema = kcu.table_schema
227
- WHERE kcu.table_name = ? AND kcu.table_schema = DATABASE() AND kcu.referenced_table_name IS NOT NULL`,[a]),y=new Map,p=new Map;for(let C of f){let v=String(C.constraint_name??C.CONSTRAINT_NAME);p.set(v,(p.get(v)??0)+1)}for(let C of f){let v=String(C.column_name??C.COLUMN_NAME),k=y.get(v),L=String(C.constraint_name??C.CONSTRAINT_NAME),B=p.get(L)===1?[...new Set([...k?.constraintNames??[],L])]:k?.constraintNames;y.set(v,k?{...k,constraintNames:B}:{table:String(C.ref_table??C.REF_TABLE),column:String(C.ref_column??C.REF_COLUMN??"id"),onDelete:jt(C.delete_rule??C.DELETE_RULE),onUpdate:jt(C.update_rule??C.UPDATE_RULE),constraintNames:B})}let{indexes:x,uniqueColumns:T}=Hn(a,c.map((C)=>({indexName:String(C.index_name??C.INDEX_NAME),isUnique:Number(C.non_unique??C.NON_UNIQUE)===0,isPrimary:String(C.index_name??C.INDEX_NAME).toUpperCase()==="PRIMARY",column:String(C.column_name??C.COLUMN_NAME)}))),E=l.map((C)=>{let v=String(C.column_name??C.COLUMN_NAME),k=String(C.column_type??C.COLUMN_TYPE??""),L=si(k),X=String(C.column_key??C.COLUMN_KEY??"").toUpperCase()==="PRI",Pe=C.column_default??C.COLUMN_DEFAULT,Be=Pe!=null;return{name:v,type:Gr(C.data_type??C.DATA_TYPE,k,L),isPrimaryKey:X,isUnique:T.has(v),isNullable:X?!1:String(C.is_nullable??C.IS_NULLABLE).toUpperCase()==="YES",hasDefault:Be,defaultValue:Be?hn(Pe):void 0,enumValues:L,maxLength:zr(k),...ti(k),references:y.get(v)}});return{table:a,columns:E,indexes:x}}function si(s){let a=s.match(/^enum\((.*)\)$/i);if(!a)return;return a[1].split(",").map((l)=>l.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((l)=>l.length>0)}function Hn(s,a){let l=new Map;for(let y of a){if(y.isPrimary)continue;let p=l.get(y.indexName)??{isUnique:y.isUnique,isPrimary:y.isPrimary,columns:[],where:y.where};p.columns.push(y.column),l.set(y.indexName,p)}let c=[],f=new Set;for(let[y,p]of l){if(p.columns.length===0)continue;if(p.isUnique&&p.columns.length===1&&!p.where)f.add(p.columns[0]);c.push({name:y,columns:p.columns,type:p.isUnique?"unique":"index",where:p.where})}return{indexes:c,uniqueColumns:f}}async function Xn(s,a={}){let l=s||e.dialect||"postgres",c=i(),y=((a.tables?.length)?a.tables:await Wn(c,l)).filter((T)=>T!=="migrations"),p=l==="postgres"?await Gn(c):void 0,x=[];for(let T of y){let E;if(l==="sqlite")E=await Hr(c,T);else if(l==="postgres")E=await ri(c,T,p);else E=await ii(c,T);if(E.columns.length>0)x.push(E)}return{dialect:l,tables:x}}import{existsSync as Tn,mkdirSync as ai,writeFileSync as oi}from"fs";import{dirname as Jn,join as En}from"path";import Zn from"process";function li(s){let a=s;while(a!==Jn(a)){if(Tn(En(a,"package.json")))return a;a=Jn(a)}return Zn.cwd()}async function he(s,a={}){let l=li(Zn.cwd()),c=a.dir||En(l,"app/Models");if(!Tn(c))ai(c,{recursive:!0}),console.log(`-- Created models directory: ${c}`);let f=s.charAt(0).toUpperCase()+s.slice(1),y=a.table||`${s.toLowerCase()}s`,p=`${f}.ts`,x=En(c,p);if(Tn(x))throw console.error(`-- Model already exists: ${x}`),Error(`Model already exists: ${x}`);let E=a.timestamps!==!1?` created_at: { validation: { rule: v.date() } },
227
+ WHERE kcu.table_name = ? AND kcu.table_schema = DATABASE() AND kcu.referenced_table_name IS NOT NULL`,[a]),y=new Map,p=new Map;for(let C of f){let _=String(C.constraint_name??C.CONSTRAINT_NAME);p.set(_,(p.get(_)??0)+1)}for(let C of f){let _=String(C.column_name??C.COLUMN_NAME),v=y.get(_),k=String(C.constraint_name??C.CONSTRAINT_NAME),K=p.get(k)===1?[...new Set([...v?.constraintNames??[],k])]:v?.constraintNames;y.set(_,v?{...v,constraintNames:K}:{table:String(C.ref_table??C.REF_TABLE),column:String(C.ref_column??C.REF_COLUMN??"id"),onDelete:jt(C.delete_rule??C.DELETE_RULE),onUpdate:jt(C.update_rule??C.UPDATE_RULE),constraintNames:K})}let{indexes:x,uniqueColumns:T}=Hn(a,c.map((C)=>({indexName:String(C.index_name??C.INDEX_NAME),isUnique:Number(C.non_unique??C.NON_UNIQUE)===0,isPrimary:String(C.index_name??C.INDEX_NAME).toUpperCase()==="PRIMARY",column:String(C.column_name??C.COLUMN_NAME)}))),R=l.map((C)=>{let _=String(C.column_name??C.COLUMN_NAME),v=String(C.column_type??C.COLUMN_TYPE??""),k=ai(v),Z=String(C.column_key??C.COLUMN_KEY??"").toUpperCase()==="PRI",_e=C.column_default??C.COLUMN_DEFAULT,Be=_e!=null;return{name:_,type:zr(C.data_type??C.DATA_TYPE,v,k),isPrimaryKey:Z,isUnique:T.has(_),isNullable:Z?!1:String(C.is_nullable??C.IS_NULLABLE).toUpperCase()==="YES",hasDefault:Be,defaultValue:Be?hn(_e):void 0,enumValues:k,maxLength:Hr(v),...ni(v),references:y.get(_)}});return{table:a,columns:R,indexes:x}}function ai(s){let a=s.match(/^enum\((.*)\)$/i);if(!a)return;return a[1].split(",").map((l)=>l.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((l)=>l.length>0)}function Hn(s,a){let l=new Map;for(let y of a){if(y.isPrimary)continue;let p=l.get(y.indexName)??{isUnique:y.isUnique,isPrimary:y.isPrimary,columns:[],where:y.where};p.columns.push(y.column),l.set(y.indexName,p)}let c=[],f=new Set;for(let[y,p]of l){if(p.columns.length===0)continue;if(p.isUnique&&p.columns.length===1&&!p.where)f.add(p.columns[0]);c.push({name:y,columns:p.columns,type:p.isUnique?"unique":"index",where:p.where})}return{indexes:c,uniqueColumns:f}}async function Xn(s,a={}){let l=s||e.dialect||"postgres",c=i(),y=((a.tables?.length)?a.tables:await Wn(c,l)).filter((T)=>T!=="migrations"),p=l==="postgres"?await Gn(c):void 0,x=[];for(let T of y){let R;if(l==="sqlite")R=await Xr(c,T);else if(l==="postgres")R=await ii(c,T,p);else R=await si(c,T);if(R.columns.length>0)x.push(R)}return{dialect:l,tables:x}}import{existsSync as Tn,mkdirSync as oi,writeFileSync as li}from"fs";import{dirname as Jn,join as En}from"path";import Zn from"process";function ui(s){let a=s;while(a!==Jn(a)){if(Tn(En(a,"package.json")))return a;a=Jn(a)}return Zn.cwd()}async function ge(s,a={}){let l=ui(Zn.cwd()),c=a.dir||En(l,"app/Models");if(!Tn(c))oi(c,{recursive:!0}),console.log(`-- Created models directory: ${c}`);let f=s.charAt(0).toUpperCase()+s.slice(1),y=a.table||`${s.toLowerCase()}s`,p=`${f}.ts`,x=En(c,p);if(Tn(x))throw console.error(`-- Model already exists: ${x}`),Error(`Model already exists: ${x}`);let R=a.timestamps!==!1?` created_at: { validation: { rule: v.date() } },
228
228
  updated_at: { validation: { rule: v.date() } },`:"",C=`import { v } from '@stacksjs/ts-validation'
229
229
  import { defineModel } from 'bun-query-builder'
230
230
 
@@ -234,7 +234,7 @@ const model = defineModel({
234
234
  primaryKey: 'id',
235
235
  attributes: {
236
236
  id: { validation: { rule: v.integer() } },
237
- ${E}
237
+ ${R}
238
238
  // Add your model attributes here
239
239
  // Example:
240
240
  // name: { validation: { rule: v.string() } },
@@ -244,67 +244,67 @@ ${E}
244
244
  })
245
245
 
246
246
  export default model
247
- `;oi(x,C),console.log(`-- \u2713 Created model: ${x}`),console.log(`-- Table: ${y}`)}import{existsSync as It,mkdirSync as ar,mkdtempSync as fi,readdirSync as or,readFileSync as Gt,rmSync as lr,unlinkSync as Sn,writeFileSync as ur}from"fs";import{tmpdir as pi}from"os";import{isAbsolute as gi,join as At}from"path";import wn from"process";function un(s){let a=s.scale??Math.min(2,s.precision??2);return{precision:s.precision??Math.max(10,a),scale:a}}function Ft(s){let{precision:a,scale:l}=un(s);return`decimal(${a},${l})`}function ui(s){let a=2166136261;for(let l=0;l<s.length;l++)a^=s.charCodeAt(l),a=Math.imul(a,16777619)>>>0;return a.toString(36).padStart(7,"0").slice(-7)}function ci(s,a=63){if(s.length<=a)return s;let l=`_${ui(s)}`;return s.slice(0,a-l.length)+l}function Pt(s,a){let l=`${s}_`,c=a.startsWith(l)?a:`${l}${a}`;return ci(c)}class o{quoteIdentifier(s){return`\`${s.replace(/`/g,"``")}\``}getColumnType(s){switch(s.type){case"string":return`varchar(${s.maxLength??255})`;case"text":return"text";case"boolean":return"tinyint(1)";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return Ft(s);case"date":return"date";case"datetime":return"datetime";case"timestamptz":return"datetime";case"json":return"json";case"enum":if(s.enumValues&&s.enumValues.length>0)return`ENUM(${s.enumValues.map((l)=>`'${l.replace(/'/g,"''")}'`).join(", ")})`;return"text";default:return"text"}}getPrimaryKeyType(s){return this.getColumnType(s)}getAutoIncrementClause(s){if(s.isPrimaryKey&&(s.type==="integer"||s.type==="bigint"))return"auto_increment";return""}getDefaultValue(s){if(!s.hasDefault||s.defaultValue===void 0)return"";let a=s.defaultValue;if(typeof a==="string"){let l=a.toUpperCase();if(l==="UTC_TIMESTAMP")return"default (UTC_TIMESTAMP)";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(l))return`default ${l}`;let f=`'${a.replace(/'/g,"''")}'`;if(s.type==="text"||s.type==="json"||s.type==="enum"&&!s.enumValues?.length)return`default (${f})`;return`default ${f}`}else if(typeof a==="number"||typeof a==="bigint")return`default ${a}`;else if(typeof a==="boolean")return`default ${a?1:0}`;else if(a instanceof Date)return`default '${a.toISOString()}'`;return""}createEnumType(s,a){return""}foreignKeyClauses(s){return s.columns.filter((a)=>a.references).map((a)=>{let l=a.references,c=`${s.table}_${a.name}_fk`,f=`CONSTRAINT ${this.quoteIdentifier(c)} FOREIGN KEY (${this.quoteIdentifier(a.name)}) REFERENCES ${this.quoteIdentifier(l.table)}(${this.quoteIdentifier(l.column)})`;if(l.onDelete)f+=` ON DELETE ${l.onDelete.toUpperCase()}`;if(l.onUpdate)f+=` ON UPDATE ${l.onUpdate.toUpperCase()}`;return f})}createTable(s){let a=[...s.columns.map((l)=>this.renderColumn(l)),...this.foreignKeyClauses(s)];return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(s.table)} (
247
+ `;li(x,C),console.log(`-- \u2713 Created model: ${x}`),console.log(`-- Table: ${y}`)}import{existsSync as It,mkdirSync as or,mkdtempSync as gi,readdirSync as lr,readFileSync as Gt,rmSync as ur,unlinkSync as Sn,writeFileSync as cr}from"fs";import{tmpdir as yi}from"os";import{isAbsolute as bi,join as At}from"path";import wn from"process";function un(s){let a=s.scale??Math.min(2,s.precision??2);return{precision:s.precision??Math.max(10,a),scale:a}}function Ft(s){let{precision:a,scale:l}=un(s);return`decimal(${a},${l})`}function ci(s){let a=2166136261;for(let l=0;l<s.length;l++)a^=s.charCodeAt(l),a=Math.imul(a,16777619)>>>0;return a.toString(36).padStart(7,"0").slice(-7)}function di(s,a=63){if(s.length<=a)return s;let l=`_${ci(s)}`;return s.slice(0,a-l.length)+l}function Pt(s,a){let l=`${s}_`,c=a.startsWith(l)?a:`${l}${a}`;return di(c)}var er=new Set;function mi(s){if(er.has(s))return;er.add(s),console.warn(`[query-builder] ${s}: MySQL has no timezone-aware type that can hold a date past 2038, so \`timestamptz\` is stored as DATETIME, which the server never converts. Values this library writes are UTC, so they round-trip - but the column is only an instant by convention, and anything writing to it directly (a raw NOW(), another service, a restored dump) can break that. Declare \`datetime\` to say so explicitly.`)}class o{quoteIdentifier(s){return`\`${s.replace(/`/g,"``")}\``}getColumnType(s){switch(s.type){case"string":return`varchar(${s.maxLength??255})`;case"text":return"text";case"boolean":return"tinyint(1)";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return Ft(s);case"date":return"date";case"datetime":return"datetime";case"timestamptz":return mi(s.name),"datetime";case"json":return"json";case"enum":if(s.enumValues&&s.enumValues.length>0)return`ENUM(${s.enumValues.map((l)=>`'${l.replace(/'/g,"''")}'`).join(", ")})`;return"text";default:return"text"}}getPrimaryKeyType(s){return this.getColumnType(s)}getAutoIncrementClause(s){if(s.isPrimaryKey&&(s.type==="integer"||s.type==="bigint"))return"auto_increment";return""}getDefaultValue(s){if(!s.hasDefault||s.defaultValue===void 0)return"";let a=s.defaultValue;if(typeof a==="string"){let l=a.toUpperCase();if(l==="UTC_TIMESTAMP")return"default (UTC_TIMESTAMP)";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(l))return`default ${l}`;let f=`'${a.replace(/'/g,"''")}'`;if(s.type==="text"||s.type==="json"||s.type==="enum"&&!s.enumValues?.length)return`default (${f})`;return`default ${f}`}else if(typeof a==="number"||typeof a==="bigint")return`default ${a}`;else if(typeof a==="boolean")return`default ${a?1:0}`;else if(a instanceof Date)return`default '${a.toISOString()}'`;return""}createEnumType(s,a){return""}foreignKeyClauses(s){return s.columns.filter((a)=>a.references).map((a)=>{let l=a.references,c=`${s.table}_${a.name}_fk`,f=`CONSTRAINT ${this.quoteIdentifier(c)} FOREIGN KEY (${this.quoteIdentifier(a.name)}) REFERENCES ${this.quoteIdentifier(l.table)}(${this.quoteIdentifier(l.column)})`;if(l.onDelete)f+=` ON DELETE ${l.onDelete.toUpperCase()}`;if(l.onUpdate)f+=` ON UPDATE ${l.onUpdate.toUpperCase()}`;return f})}createTable(s){let a=[...s.columns.map((l)=>this.renderColumn(l)),...this.foreignKeyClauses(s)];return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(s.table)} (
248
248
  ${a.join(`,
249
249
  `)}
250
- ) DEFAULT CHARSET=utf8mb4;`}static KEY_PREFIX_CHARACTERS=255;static MAX_KEY_BYTES=3072;static BYTES_PER_CHARACTER=4;keyPartWidth(s){let a=this.getColumnType(s).toLowerCase();if(a.includes("text")||a.includes("blob")||a==="json")return{bytes:Number.POSITIVE_INFINITY,indexableWhole:!1};let l=a.match(/^(?:var)?char\((\d+)\)$/)?.[1];if(l!==void 0)return{bytes:Number(l)*o.BYTES_PER_CHARACTER,indexableWhole:!0};return{bytes:8,indexableWhole:!0}}keyParts(s,a,l){let c=a.columns.map((y)=>{let p=l?.find((E)=>E.name===y),x=p?this.keyPartWidth(p):{bytes:0,indexableWhole:!0},T=!x.indexableWhole;return{name:y,prefixed:T,bytes:T?o.KEY_PREFIX_CHARACTERS*o.BYTES_PER_CHARACTER:x.bytes,narrowable:!x.indexableWhole||x.bytes>o.KEY_PREFIX_CHARACTERS*o.BYTES_PER_CHARACTER}}),f=()=>c.reduce((y,p)=>y+p.bytes,0);while(f()>o.MAX_KEY_BYTES){let y=c.filter((p)=>p.narrowable&&!p.prefixed).sort((p,x)=>x.bytes-p.bytes)[0];if(!y)throw Error(`[migrations] Index '${a.name}' on table '${s}' needs ${f()} bytes of key, over MySQL's ${o.MAX_KEY_BYTES}. Every column in it is already at its ${o.KEY_PREFIX_CHARACTERS}-character prefix, so shorten a column or drop one from the index.`);y.prefixed=!0,y.bytes=o.KEY_PREFIX_CHARACTERS*o.BYTES_PER_CHARACTER}return c.map((y)=>y.prefixed?`${this.quoteIdentifier(y.name)}(${o.KEY_PREFIX_CHARACTERS})`:this.quoteIdentifier(y.name))}createIndex(s,a,l){if(a.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on MySQL. Index '${a.name}' on table '${s}' uses WHERE clause: ${a.where}`);let c=a.type==="unique"?"UNIQUE ":"",f=Pt(s,a.name),y=this.keyParts(s,a,l).join(", ");return`CREATE ${c}INDEX ${this.quoteIdentifier(f)} ON ${this.quoteIdentifier(s)} (${y});`}addForeignKey(s,a,l,c,f,y,p=[]){let x=`${s}_${a}_fk`,T=`ALTER TABLE ${this.quoteIdentifier(s)} ADD CONSTRAINT ${this.quoteIdentifier(x)} FOREIGN KEY (${this.quoteIdentifier(a)}) REFERENCES ${this.quoteIdentifier(l)}(${this.quoteIdentifier(c)})`;if(f)T+=` ON DELETE ${f.toUpperCase()}`;if(y)T+=` ON UPDATE ${y.toUpperCase()}`;let E=[...new Set(p)].map((C)=>`ALTER TABLE ${this.quoteIdentifier(s)} DROP FOREIGN KEY ${this.quoteIdentifier(C)};`).join(`
251
- `);return E?`${E}
250
+ ) DEFAULT CHARSET=utf8mb4;`}static KEY_PREFIX_CHARACTERS=255;static MAX_KEY_BYTES=3072;static BYTES_PER_CHARACTER=4;keyPartWidth(s){let a=this.getColumnType(s).toLowerCase();if(a.includes("text")||a.includes("blob")||a==="json")return{bytes:Number.POSITIVE_INFINITY,indexableWhole:!1};let l=a.match(/^(?:var)?char\((\d+)\)$/)?.[1];if(l!==void 0)return{bytes:Number(l)*o.BYTES_PER_CHARACTER,indexableWhole:!0};return{bytes:8,indexableWhole:!0}}keyParts(s,a,l){let c=a.columns.map((y)=>{let p=l?.find((R)=>R.name===y),x=p?this.keyPartWidth(p):{bytes:0,indexableWhole:!0},T=!x.indexableWhole;return{name:y,prefixed:T,bytes:T?o.KEY_PREFIX_CHARACTERS*o.BYTES_PER_CHARACTER:x.bytes,narrowable:!x.indexableWhole||x.bytes>o.KEY_PREFIX_CHARACTERS*o.BYTES_PER_CHARACTER}}),f=()=>c.reduce((y,p)=>y+p.bytes,0);while(f()>o.MAX_KEY_BYTES){let y=c.filter((p)=>p.narrowable&&!p.prefixed).sort((p,x)=>x.bytes-p.bytes)[0];if(!y)throw Error(`[migrations] Index '${a.name}' on table '${s}' needs ${f()} bytes of key, over MySQL's ${o.MAX_KEY_BYTES}. Every column in it is already at its ${o.KEY_PREFIX_CHARACTERS}-character prefix, so shorten a column or drop one from the index.`);y.prefixed=!0,y.bytes=o.KEY_PREFIX_CHARACTERS*o.BYTES_PER_CHARACTER}return c.map((y)=>y.prefixed?`${this.quoteIdentifier(y.name)}(${o.KEY_PREFIX_CHARACTERS})`:this.quoteIdentifier(y.name))}createIndex(s,a,l){if(a.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on MySQL. Index '${a.name}' on table '${s}' uses WHERE clause: ${a.where}`);let c=a.type==="unique"?"UNIQUE ":"",f=Pt(s,a.name),y=this.keyParts(s,a,l).join(", ");return`CREATE ${c}INDEX ${this.quoteIdentifier(f)} ON ${this.quoteIdentifier(s)} (${y});`}addForeignKey(s,a,l,c,f,y,p=[]){let x=`${s}_${a}_fk`,T=`ALTER TABLE ${this.quoteIdentifier(s)} ADD CONSTRAINT ${this.quoteIdentifier(x)} FOREIGN KEY (${this.quoteIdentifier(a)}) REFERENCES ${this.quoteIdentifier(l)}(${this.quoteIdentifier(c)})`;if(f)T+=` ON DELETE ${f.toUpperCase()}`;if(y)T+=` ON UPDATE ${y.toUpperCase()}`;let R=[...new Set(p)].map((C)=>`ALTER TABLE ${this.quoteIdentifier(s)} DROP FOREIGN KEY ${this.quoteIdentifier(C)};`).join(`
251
+ `);return R?`${R}
252
252
  ${T};`:`${T};`}addColumn(s,a){let l=this.getColumnType(a),c=[this.quoteIdentifier(a.name),l];if(!a.isNullable&&!a.isPrimaryKey)c.push("not null");let f=this.getDefaultValue(a);if(f)c.push(f);return`ALTER TABLE ${this.quoteIdentifier(s)} ADD COLUMN ${c.join(" ")};`}modifyColumn(s,a){let l=this.getColumnType(a),c=[this.quoteIdentifier(a.name),l];if(!a.isNullable&&!a.isPrimaryKey)c.push("not null");let f=this.getDefaultValue(a);if(f)c.push(f);let y=this.getAutoIncrementClause(a);if(y)c.push(y);return`ALTER TABLE ${this.quoteIdentifier(s)} MODIFY COLUMN ${c.join(" ")};`}renameColumn(s,a,l){return`ALTER TABLE ${this.quoteIdentifier(s)} RENAME COLUMN ${this.quoteIdentifier(a)} TO ${this.quoteIdentifier(l)};`}renameTable(s,a){return`RENAME TABLE ${this.quoteIdentifier(s)} TO ${this.quoteIdentifier(a)};`}rebuildTable(){throw Error("[migrations] rebuildTable is only implemented for SQLite; MySQL uses in-place ALTER.")}dropTable(s){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(s)}`}dropColumn(s,a){return`ALTER TABLE ${this.quoteIdentifier(s)} DROP COLUMN ${this.quoteIdentifier(a)};`}dropIndex(s,a){let l=Pt(s,a);return`DROP INDEX ${this.quoteIdentifier(l)} ON ${this.quoteIdentifier(s)};`}dropEnumType(s){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
253
253
  id INT AUTO_INCREMENT PRIMARY KEY,
254
254
  migration VARCHAR(255) NOT NULL UNIQUE,
255
255
  executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
256
- )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}jsonExtract(s,a){return`JSON_UNQUOTE(JSON_EXTRACT(${s}, CONCAT('$.', ${a})))`}dateBucket(s,a,l=0){let c=l===0?s:`DATE_ADD(${s}, INTERVAL ${l} HOUR)`;switch(a){case"hour":return`DATE_FORMAT(${c}, '%Y-%m-%dT%H:00:00.000Z')`;case"week":return`DATE_FORMAT(DATE_SUB(${c}, INTERVAL WEEKDAY(${c}) DAY), '%Y-%m-%dT00:00:00.000Z')`;case"month":return`DATE_FORMAT(${c}, '%Y-%m-01T00:00:00.000Z')`;case"year":return`DATE_FORMAT(${c}, '%Y-01-01T00:00:00.000Z')`;case"day":default:return`DATE_FORMAT(${c}, '%Y-%m-%dT00:00:00.000Z')`}}booleanLiteral(s){return s?"TRUE":"FALSE"}renderColumn(s){let a=this.getColumnType(s),l=[this.quoteIdentifier(s.name),a];if(s.isPrimaryKey){l.push("PRIMARY KEY");let f=this.getAutoIncrementClause(s);if(f)l.push(f)}if(!s.isNullable&&!s.isPrimaryKey)l.push("not null");let c=this.getDefaultValue(s);if(c)l.push(c);return l.join(" ")}}class ge{quoteIdentifier(s){return`"${s.replace(/"/g,'""')}"`}getColumnType(s){switch(s.type){case"string":return`varchar(${s.maxLength??255})`;case"text":return"text";case"boolean":return"boolean";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return Ft(s);case"date":return"date";case"datetime":return"timestamp";case"timestamptz":return"timestamptz";case"json":return"jsonb";case"enum":if(s.enumValues&&s.enumValues.length>0)return s.enumTypeName?this.quoteIdentifier(s.enumTypeName):"text";return"text";default:return"text"}}getPrimaryKeyType(s){switch(s.type){case"integer":return"SERIAL";case"bigint":return"BIGSERIAL";default:return this.getColumnType(s)}}getAutoIncrementClause(s){return""}getDefaultValue(s){if(!s.hasDefault||s.defaultValue===void 0)return"";let a=s.defaultValue;if(typeof a==="string"){let l=a.toUpperCase();if(l==="UTC_TIMESTAMP")return"default (now() AT TIME ZONE 'utc')";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(l))return`default ${l}`;return`default '${a.replace(/'/g,"''")}'`}else if(typeof a==="number"||typeof a==="bigint")return`default ${a}`;else if(typeof a==="boolean")return`default ${a?"true":"false"}`;else if(a instanceof Date)return`default '${a.toISOString()}'`;return""}createEnumType(s,a){let l=a.map((c)=>`'${c.replace(/'/g,"''")}'`).join(", ");return`CREATE TYPE ${this.quoteIdentifier(s)} AS ENUM (${l});`}addEnumValues(s,a){return a.map((l)=>`ALTER TYPE ${this.quoteIdentifier(s)} ADD VALUE IF NOT EXISTS '${l.replace(/'/g,"''")}';`).join(`
256
+ )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}jsonExtract(s,a){return`JSON_UNQUOTE(JSON_EXTRACT(${s}, CONCAT('$.', ${a})))`}dateBucket(s,a,l=0){let c=l===0?s:`DATE_ADD(${s}, INTERVAL ${l} HOUR)`;switch(a){case"hour":return`DATE_FORMAT(${c}, '%Y-%m-%dT%H:00:00.000Z')`;case"week":return`DATE_FORMAT(DATE_SUB(${c}, INTERVAL WEEKDAY(${c}) DAY), '%Y-%m-%dT00:00:00.000Z')`;case"month":return`DATE_FORMAT(${c}, '%Y-%m-01T00:00:00.000Z')`;case"year":return`DATE_FORMAT(${c}, '%Y-01-01T00:00:00.000Z')`;case"day":default:return`DATE_FORMAT(${c}, '%Y-%m-%dT00:00:00.000Z')`}}booleanLiteral(s){return s?"TRUE":"FALSE"}renderColumn(s){let a=this.getColumnType(s),l=[this.quoteIdentifier(s.name),a];if(s.isPrimaryKey){l.push("PRIMARY KEY");let f=this.getAutoIncrementClause(s);if(f)l.push(f)}if(!s.isNullable&&!s.isPrimaryKey)l.push("not null");let c=this.getDefaultValue(s);if(c)l.push(c);return l.join(" ")}}class pe{quoteIdentifier(s){return`"${s.replace(/"/g,'""')}"`}getColumnType(s){switch(s.type){case"string":return`varchar(${s.maxLength??255})`;case"text":return"text";case"boolean":return"boolean";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return Ft(s);case"date":return"date";case"datetime":return"timestamp";case"timestamptz":return"timestamptz";case"json":return"jsonb";case"enum":if(s.enumValues&&s.enumValues.length>0)return s.enumTypeName?this.quoteIdentifier(s.enumTypeName):"text";return"text";default:return"text"}}getPrimaryKeyType(s){switch(s.type){case"integer":return"SERIAL";case"bigint":return"BIGSERIAL";default:return this.getColumnType(s)}}getAutoIncrementClause(s){return""}getDefaultValue(s){if(!s.hasDefault||s.defaultValue===void 0)return"";let a=s.defaultValue;if(typeof a==="string"){let l=a.toUpperCase();if(l==="UTC_TIMESTAMP")return"default (now() AT TIME ZONE 'utc')";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(l))return`default ${l}`;return`default '${a.replace(/'/g,"''")}'`}else if(typeof a==="number"||typeof a==="bigint")return`default ${a}`;else if(typeof a==="boolean")return`default ${a?"true":"false"}`;else if(a instanceof Date)return`default '${a.toISOString()}'`;return""}createEnumType(s,a){let l=a.map((c)=>`'${c.replace(/'/g,"''")}'`).join(", ");return`CREATE TYPE ${this.quoteIdentifier(s)} AS ENUM (${l});`}addEnumValues(s,a){return a.map((l)=>`ALTER TYPE ${this.quoteIdentifier(s)} ADD VALUE IF NOT EXISTS '${l.replace(/'/g,"''")}';`).join(`
257
257
  `)}createTable(s){let a=s.columns.map((l)=>this.renderColumn(l)).join(`,
258
258
  `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(s.table)} (
259
259
  ${a}
260
- );`}createIndex(s,a){let l=a.type==="unique"?"UNIQUE ":"",c=Pt(s,a.name),f=a.columns.map((p)=>this.quoteIdentifier(p)).join(", "),y=a.where?` WHERE ${a.where}`:"";return`CREATE ${l}INDEX IF NOT EXISTS ${this.quoteIdentifier(c)} ON ${this.quoteIdentifier(s)} (${f})${y};`}addForeignKey(s,a,l,c,f,y,p=[]){let x=`${s}_${a}_fk`,T=`ALTER TABLE ${this.quoteIdentifier(s)} ADD CONSTRAINT ${this.quoteIdentifier(x)} FOREIGN KEY (${this.quoteIdentifier(a)}) REFERENCES ${this.quoteIdentifier(l)}(${this.quoteIdentifier(c)})`;if(f)T+=` ON DELETE ${f.toUpperCase()}`;if(y)T+=` ON UPDATE ${y.toUpperCase()}`;let E=[...new Set(p)].map((C)=>`ALTER TABLE ${this.quoteIdentifier(s)} DROP CONSTRAINT ${this.quoteIdentifier(C)};`).join(`
261
- `);return E?`${E}
262
- ${T};`:`${T};`}addColumn(s,a){let l=this.getColumnType(a),c=[this.quoteIdentifier(a.name),l];if(!a.isNullable&&!a.isPrimaryKey)c.push("not null");let f=this.getDefaultValue(a);if(f)c.push(f);return`ALTER TABLE ${this.quoteIdentifier(s)} ADD COLUMN ${c.join(" ")};`}modifyColumn(s,a,l){let c=this.getColumnType(a),f=this.quoteIdentifier(s),y=this.quoteIdentifier(a.name);if(l?.type==="enum"&&a.type==="enum"&&a.enumTypeName&&a.enumValues?.length&&er(l,a))return this.changeEnumValues(s,a,l);if(l&&this.getColumnType(l)===c&&!er(l,a)){let T=[];if(!a.isPrimaryKey&&l.isNullable!==a.isNullable)T.push(`ALTER TABLE ${f} ALTER COLUMN ${y} ${a.isNullable?"DROP NOT NULL":"SET NOT NULL"};`);let E=this.getDefaultValue(l),C=this.getDefaultValue(a);if(E!==C)T.push(C?`ALTER TABLE ${f} ALTER COLUMN ${y} SET ${C};`:`ALTER TABLE ${f} ALTER COLUMN ${y} DROP DEFAULT;`);if(T.length)return T.join(`
260
+ );`}createIndex(s,a){let l=a.type==="unique"?"UNIQUE ":"",c=Pt(s,a.name),f=a.columns.map((p)=>this.quoteIdentifier(p)).join(", "),y=a.where?` WHERE ${a.where}`:"";return`CREATE ${l}INDEX IF NOT EXISTS ${this.quoteIdentifier(c)} ON ${this.quoteIdentifier(s)} (${f})${y};`}addForeignKey(s,a,l,c,f,y,p=[]){let x=`${s}_${a}_fk`,T=`ALTER TABLE ${this.quoteIdentifier(s)} ADD CONSTRAINT ${this.quoteIdentifier(x)} FOREIGN KEY (${this.quoteIdentifier(a)}) REFERENCES ${this.quoteIdentifier(l)}(${this.quoteIdentifier(c)})`;if(f)T+=` ON DELETE ${f.toUpperCase()}`;if(y)T+=` ON UPDATE ${y.toUpperCase()}`;let R=[...new Set(p)].map((C)=>`ALTER TABLE ${this.quoteIdentifier(s)} DROP CONSTRAINT ${this.quoteIdentifier(C)};`).join(`
261
+ `);return R?`${R}
262
+ ${T};`:`${T};`}addColumn(s,a){let l=this.getColumnType(a),c=[this.quoteIdentifier(a.name),l];if(!a.isNullable&&!a.isPrimaryKey)c.push("not null");let f=this.getDefaultValue(a);if(f)c.push(f);return`ALTER TABLE ${this.quoteIdentifier(s)} ADD COLUMN ${c.join(" ")};`}modifyColumn(s,a,l){let c=this.getColumnType(a),f=this.quoteIdentifier(s),y=this.quoteIdentifier(a.name);if(l?.type==="enum"&&a.type==="enum"&&a.enumTypeName&&a.enumValues?.length&&tr(l,a))return this.changeEnumValues(s,a,l);if(l&&this.getColumnType(l)===c&&!tr(l,a)){let T=[];if(!a.isPrimaryKey&&l.isNullable!==a.isNullable)T.push(`ALTER TABLE ${f} ALTER COLUMN ${y} ${a.isNullable?"DROP NOT NULL":"SET NOT NULL"};`);let R=this.getDefaultValue(l),C=this.getDefaultValue(a);if(R!==C)T.push(C?`ALTER TABLE ${f} ALTER COLUMN ${y} SET ${C};`:`ALTER TABLE ${f} ALTER COLUMN ${y} DROP DEFAULT;`);if(T.length)return T.join(`
263
263
  `)}let p=[`ALTER TABLE ${f} ALTER COLUMN ${y} DROP DEFAULT;`,`ALTER TABLE ${f} ALTER COLUMN ${y} TYPE ${c} USING ${y}::${c};`];if(!a.isPrimaryKey)p.push(`ALTER TABLE ${f} ALTER COLUMN ${y} ${a.isNullable?"DROP NOT NULL":"SET NOT NULL"};`);let x=this.getDefaultValue(a);if(x)p.push(`ALTER TABLE ${f} ALTER COLUMN ${y} SET ${x};`);return p.join(`
264
- `)}changeEnumValues(s,a,l){let c=this.quoteIdentifier(s),f=this.quoteIdentifier(a.name),y=a.enumTypeName,p=l.enumTypeName??y,x=l.enumValues??[],T=a.enumValues??[],E=x.filter((B)=>!T.includes(B)),C=()=>{let B=[];if(!a.isPrimaryKey&&l.isNullable!==a.isNullable)B.push(`ALTER TABLE ${c} ALTER COLUMN ${f} ${a.isNullable?"DROP NOT NULL":"SET NOT NULL"};`);let X=this.getDefaultValue(l),Pe=this.getDefaultValue(a);if(X!==Pe)B.push(Pe?`ALTER TABLE ${c} ALTER COLUMN ${f} SET ${Pe};`:`ALTER TABLE ${c} ALTER COLUMN ${f} DROP DEFAULT;`);return B};if(E.length===0&&p===y){let B=T.filter((X)=>!x.includes(X));return[this.addEnumValues(p,B),...C()].filter(Boolean).join(`
265
- `)}let v=[],k=`${p}__qb_old`;if(p===y)v.push(`ALTER TYPE ${this.quoteIdentifier(p)} RENAME TO ${this.quoteIdentifier(k)};`);if(v.push(this.createEnumType(y,T)),v.push(`ALTER TABLE ${c} ALTER COLUMN ${f} DROP DEFAULT;`),v.push(`ALTER TABLE ${c} ALTER COLUMN ${f} TYPE ${this.quoteIdentifier(y)} USING ${f}::text::${this.quoteIdentifier(y)};`),!a.isPrimaryKey)v.push(`ALTER TABLE ${c} ALTER COLUMN ${f} ${a.isNullable?"DROP NOT NULL":"SET NOT NULL"};`);let L=this.getDefaultValue(a);if(L)v.push(`ALTER TABLE ${c} ALTER COLUMN ${f} SET ${L};`);if(p===y)v.push(`DROP TYPE ${this.quoteIdentifier(k)};`);return v.join(`
264
+ `)}changeEnumValues(s,a,l){let c=this.quoteIdentifier(s),f=this.quoteIdentifier(a.name),y=a.enumTypeName,p=l.enumTypeName??y,x=l.enumValues??[],T=a.enumValues??[],R=x.filter((K)=>!T.includes(K)),C=()=>{let K=[];if(!a.isPrimaryKey&&l.isNullable!==a.isNullable)K.push(`ALTER TABLE ${c} ALTER COLUMN ${f} ${a.isNullable?"DROP NOT NULL":"SET NOT NULL"};`);let Z=this.getDefaultValue(l),_e=this.getDefaultValue(a);if(Z!==_e)K.push(_e?`ALTER TABLE ${c} ALTER COLUMN ${f} SET ${_e};`:`ALTER TABLE ${c} ALTER COLUMN ${f} DROP DEFAULT;`);return K};if(R.length===0&&p===y){let K=T.filter((Z)=>!x.includes(Z));return[this.addEnumValues(p,K),...C()].filter(Boolean).join(`
265
+ `)}let _=[],v=`${p}__qb_old`;if(p===y)_.push(`ALTER TYPE ${this.quoteIdentifier(p)} RENAME TO ${this.quoteIdentifier(v)};`);if(_.push(this.createEnumType(y,T)),_.push(`ALTER TABLE ${c} ALTER COLUMN ${f} DROP DEFAULT;`),_.push(`ALTER TABLE ${c} ALTER COLUMN ${f} TYPE ${this.quoteIdentifier(y)} USING ${f}::text::${this.quoteIdentifier(y)};`),!a.isPrimaryKey)_.push(`ALTER TABLE ${c} ALTER COLUMN ${f} ${a.isNullable?"DROP NOT NULL":"SET NOT NULL"};`);let k=this.getDefaultValue(a);if(k)_.push(`ALTER TABLE ${c} ALTER COLUMN ${f} SET ${k};`);if(p===y)_.push(`DROP TYPE ${this.quoteIdentifier(v)};`);return _.join(`
266
266
  `)}renameColumn(s,a,l){return`ALTER TABLE ${this.quoteIdentifier(s)} RENAME COLUMN ${this.quoteIdentifier(a)} TO ${this.quoteIdentifier(l)};`}renameTable(s,a){return`ALTER TABLE ${this.quoteIdentifier(s)} RENAME TO ${this.quoteIdentifier(a)};`}rebuildTable(){throw Error("[migrations] rebuildTable is only implemented for SQLite; Postgres uses in-place ALTER.")}dropTable(s){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(s)} CASCADE`}dropColumn(s,a){return`ALTER TABLE ${this.quoteIdentifier(s)} DROP COLUMN ${this.quoteIdentifier(a)};`}dropIndex(s,a){let l=Pt(s,a);return`DROP INDEX IF EXISTS ${this.quoteIdentifier(l)};`}dropEnumType(s){return`DROP TYPE IF EXISTS ${this.quoteIdentifier(s)} CASCADE`}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
267
267
  id SERIAL PRIMARY KEY,
268
268
  migration VARCHAR(255) NOT NULL UNIQUE,
269
269
  executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
270
- )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES ($1)"}jsonExtract(s,a){return`(${s}::jsonb ->> ${a})`}dateBucket(s,a,l=0){let c=l===0?`${s}::timestamp`:`(${s}::timestamp ${l>=0?"+":"-"} interval '${Math.abs(l)} hours')`,f=a==="week"?`date_trunc('week', ${c})`:c;switch(a){case"hour":return`to_char(${f}, 'YYYY-MM-DD"T"HH24:00:00.000"Z"')`;case"month":return`to_char(${f}, 'YYYY-MM-01"T"00:00:00.000"Z"')`;case"year":return`to_char(${f}, 'YYYY-01-01"T"00:00:00.000"Z"')`;case"week":case"day":default:return`to_char(${f}, 'YYYY-MM-DD"T"00:00:00.000"Z"')`}}booleanLiteral(s){return s?"TRUE":"FALSE"}renderColumn(s){let a=s.isPrimaryKey?this.getPrimaryKeyType(s):this.getColumnType(s),l=[this.quoteIdentifier(s.name),a];if(s.isPrimaryKey)l.push("PRIMARY KEY");if(!s.isNullable&&!s.isPrimaryKey)l.push("not null");let c=this.getDefaultValue(s);if(c)l.push(c);if(s.references){let f=`REFERENCES ${this.quoteIdentifier(s.references.table)}(${this.quoteIdentifier(s.references.column)})`;if(s.references.onDelete)f+=` ON DELETE ${s.references.onDelete.toUpperCase()}`;if(s.references.onUpdate)f+=` ON UPDATE ${s.references.onUpdate.toUpperCase()}`;l.push(f)}return l.join(" ")}}function er(s,a){return JSON.stringify(s.enumValues??[])!==JSON.stringify(a.enumValues??[])}class pe extends o{createTable(s){let a=s.columns.map((y)=>this.renderColumn(y)).join(`,
270
+ )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES ($1)"}jsonExtract(s,a){return`(${s}::jsonb ->> ${a})`}dateBucket(s,a,l=0){let c=l===0?`${s}::timestamp`:`(${s}::timestamp ${l>=0?"+":"-"} interval '${Math.abs(l)} hours')`,f=a==="week"?`date_trunc('week', ${c})`:c;switch(a){case"hour":return`to_char(${f}, 'YYYY-MM-DD"T"HH24:00:00.000"Z"')`;case"month":return`to_char(${f}, 'YYYY-MM-01"T"00:00:00.000"Z"')`;case"year":return`to_char(${f}, 'YYYY-01-01"T"00:00:00.000"Z"')`;case"week":case"day":default:return`to_char(${f}, 'YYYY-MM-DD"T"00:00:00.000"Z"')`}}booleanLiteral(s){return s?"TRUE":"FALSE"}renderColumn(s){let a=s.isPrimaryKey?this.getPrimaryKeyType(s):this.getColumnType(s),l=[this.quoteIdentifier(s.name),a];if(s.isPrimaryKey)l.push("PRIMARY KEY");if(!s.isNullable&&!s.isPrimaryKey)l.push("not null");let c=this.getDefaultValue(s);if(c)l.push(c);if(s.references){let f=`REFERENCES ${this.quoteIdentifier(s.references.table)}(${this.quoteIdentifier(s.references.column)})`;if(s.references.onDelete)f+=` ON DELETE ${s.references.onDelete.toUpperCase()}`;if(s.references.onUpdate)f+=` ON UPDATE ${s.references.onUpdate.toUpperCase()}`;l.push(f)}return l.join(" ")}}function tr(s,a){return JSON.stringify(s.enumValues??[])!==JSON.stringify(a.enumValues??[])}class ye extends o{createTable(s){let a=s.columns.map((y)=>this.renderColumn(y)).join(`,
271
271
  `),l=[];if(s.tableKind!=="reference"){let y=s.shardKey?.length?s.shardKey:s.columns.filter((p)=>p.isPrimaryKey).map((p)=>p.name);if(y&&y.length>0)l.push(`SHARD KEY (${y.map((p)=>this.quoteIdentifier(p)).join(", ")})`)}if(s.tableKind!=="rowstore"&&s.tableKind!=="reference"){let y=s.sortKey?.length?s.sortKey:void 0;l.push(`SORT KEY (${(y??[]).map((p)=>this.quoteIdentifier(p)).join(", ")})`)}let c=[a,...l].join(`,
272
272
  `);return`CREATE${this.tableKindSuffix(s.tableKind)} TABLE IF NOT EXISTS ${this.quoteIdentifier(s.table)} (
273
273
  ${c}
274
- );`}tableKindSuffix(s){switch(s){case"rowstore":return" ROWSTORE";case"reference":return" REFERENCE";default:return""}}addForeignKey(){return""}createIndex(s,a,l){if(a.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on SingleStore. Index '${a.name}' on table '${s}' uses WHERE clause: ${a.where}`);return super.createIndex(s,a,l)}}class ye extends o{sharded;constructor(s=!0){super();this.sharded=s}getAutoIncrementClause(s){return this.sharded?"":super.getAutoIncrementClause(s)}renderColumn(s){if(!this.sharded||!s.references)return super.renderColumn(s);let{references:a,...l}=s;return super.renderColumn(l)}foreignKeyClauses(s){return this.sharded?[]:super.foreignKeyClauses(s)}createTable(s){return super.createTable(s)}addForeignKey(...s){return this.sharded?"":super.addForeignKey(...s)}createMigrationsTable(){if(!this.sharded)return super.createMigrationsTable();return`CREATE TABLE IF NOT EXISTS migrations (
274
+ );`}tableKindSuffix(s){switch(s){case"rowstore":return" ROWSTORE";case"reference":return" REFERENCE";default:return""}}addForeignKey(){return""}createIndex(s,a,l){if(a.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on SingleStore. Index '${a.name}' on table '${s}' uses WHERE clause: ${a.where}`);return super.createIndex(s,a,l)}}class be extends o{sharded;constructor(s=!0){super();this.sharded=s}getAutoIncrementClause(s){return this.sharded?"":super.getAutoIncrementClause(s)}renderColumn(s){if(!this.sharded||!s.references)return super.renderColumn(s);let{references:a,...l}=s;return super.renderColumn(l)}foreignKeyClauses(s){return this.sharded?[]:super.foreignKeyClauses(s)}createTable(s){return super.createTable(s)}addForeignKey(...s){return this.sharded?"":super.addForeignKey(...s)}createMigrationsTable(){if(!this.sharded)return super.createMigrationsTable();return`CREATE TABLE IF NOT EXISTS migrations (
275
275
  migration VARCHAR(255) NOT NULL PRIMARY KEY,
276
276
  executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
277
- )`}}class be{quoteIdentifier(s){return`"${s.replace(/"/g,'""')}"`}getColumnType(s){if(s.name.endsWith("_id")&&O(s.type))return"INTEGER";if(s.type==="enum"){if(s.enumValues&&s.enumValues.length>0){let a=s.enumValues.map((l)=>`'${l.replace(/'/g,"''")}'`).join(", ");return`TEXT CHECK (${this.quoteIdentifier(s.name)} IN (${a}))`}return"TEXT"}return _e(s.type)}getPrimaryKeyType(s){return this.getColumnType(s)}getAutoIncrementClause(s){if(s.isPrimaryKey&&(s.type==="integer"||s.type==="bigint"))return"AUTOINCREMENT";return""}getDefaultValue(s){if(!s.hasDefault||s.defaultValue===void 0)return"";let a=s.defaultValue;if(typeof a==="string"){if(a.toUpperCase()==="UTC_TIMESTAMP")return"default CURRENT_TIMESTAMP";if(["CURRENT_TIMESTAMP","CURRENT_DATE","CURRENT_TIME","NOW()","NULL","TRUE","FALSE"].includes(a.toUpperCase()))return`default ${a.toUpperCase()}`;return`default '${a.replace(/'/g,"''")}'`}else if(typeof a==="number"||typeof a==="bigint")return`default ${a}`;else if(typeof a==="boolean")return`default ${a?1:0}`;else if(a instanceof Date)return`default '${a.toISOString()}'`;return""}createEnumType(s,a){return""}createTable(s){let a=s.columns.map((l)=>this.renderColumn(l)).join(`,
277
+ )`}}class Te{quoteIdentifier(s){return`"${s.replace(/"/g,'""')}"`}getColumnType(s){if(s.name.endsWith("_id")&&O(s.type))return"INTEGER";if(s.type==="enum"){if(s.enumValues&&s.enumValues.length>0){let a=s.enumValues.map((l)=>`'${l.replace(/'/g,"''")}'`).join(", ");return`TEXT CHECK (${this.quoteIdentifier(s.name)} IN (${a}))`}return"TEXT"}return Ie(s.type)}getPrimaryKeyType(s){return this.getColumnType(s)}getAutoIncrementClause(s){if(s.isPrimaryKey&&(s.type==="integer"||s.type==="bigint"))return"AUTOINCREMENT";return""}getDefaultValue(s){if(!s.hasDefault||s.defaultValue===void 0)return"";let a=s.defaultValue;if(typeof a==="string"){if(a.toUpperCase()==="UTC_TIMESTAMP")return"default CURRENT_TIMESTAMP";if(["CURRENT_TIMESTAMP","CURRENT_DATE","CURRENT_TIME","NOW()","NULL","TRUE","FALSE"].includes(a.toUpperCase()))return`default ${a.toUpperCase()}`;return`default '${a.replace(/'/g,"''")}'`}else if(typeof a==="number"||typeof a==="bigint")return`default ${a}`;else if(typeof a==="boolean")return`default ${a?1:0}`;else if(a instanceof Date)return`default '${a.toISOString()}'`;return""}createEnumType(s,a){return""}createTable(s){let a=s.columns.map((l)=>this.renderColumn(l)).join(`,
278
278
  `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(s.table)} (
279
279
  ${a}
280
- );`}createIndex(s,a){let l=a.type==="unique"?"UNIQUE ":"",c=Pt(s,a.name),f=a.columns.map((p)=>this.quoteIdentifier(p)).join(", "),y=a.where?` WHERE ${a.where}`:"";return`CREATE ${l}INDEX IF NOT EXISTS ${this.quoteIdentifier(c)} ON ${this.quoteIdentifier(s)} (${f})${y};`}addForeignKey(s,a,l,c,f,y){return""}addColumn(s,a){let l=this.getColumnType(a),c=[this.quoteIdentifier(a.name),l];if(!a.isNullable&&!a.isPrimaryKey)c.push("not null");let f=this.getDefaultValue(a);if(f)c.push(f);return c.push(...this.referencesClause(a)),`ALTER TABLE ${this.quoteIdentifier(s)} ADD COLUMN ${c.join(" ")};`}modifyColumn(s,a){return`-- SQLite does not support ALTER COLUMN; a table rebuild is required to change ${this.quoteIdentifier(s)}.${this.quoteIdentifier(a.name)}`}renameColumn(s,a,l){return`ALTER TABLE ${this.quoteIdentifier(s)} RENAME COLUMN ${this.quoteIdentifier(a)} TO ${this.quoteIdentifier(l)};`}renameTable(s,a){return`ALTER TABLE ${this.quoteIdentifier(s)} RENAME TO ${this.quoteIdentifier(a)};`}rebuildTable(s){let{target:a,tempName:l,columnSource:c}=s,f=(E)=>this.quoteIdentifier(E),y=a.columns.map((E)=>this.renderColumn(E)).join(`,
280
+ );`}createIndex(s,a){let l=a.type==="unique"?"UNIQUE ":"",c=Pt(s,a.name),f=a.columns.map((p)=>this.quoteIdentifier(p)).join(", "),y=a.where?` WHERE ${a.where}`:"";return`CREATE ${l}INDEX IF NOT EXISTS ${this.quoteIdentifier(c)} ON ${this.quoteIdentifier(s)} (${f})${y};`}addForeignKey(s,a,l,c,f,y){return""}addColumn(s,a){let l=this.getColumnType(a),c=[this.quoteIdentifier(a.name),l];if(!a.isNullable&&!a.isPrimaryKey)c.push("not null");let f=this.getDefaultValue(a);if(f)c.push(f);return c.push(...this.referencesClause(a)),`ALTER TABLE ${this.quoteIdentifier(s)} ADD COLUMN ${c.join(" ")};`}modifyColumn(s,a){return`-- SQLite does not support ALTER COLUMN; a table rebuild is required to change ${this.quoteIdentifier(s)}.${this.quoteIdentifier(a.name)}`}renameColumn(s,a,l){return`ALTER TABLE ${this.quoteIdentifier(s)} RENAME COLUMN ${this.quoteIdentifier(a)} TO ${this.quoteIdentifier(l)};`}renameTable(s,a){return`ALTER TABLE ${this.quoteIdentifier(s)} RENAME TO ${this.quoteIdentifier(a)};`}rebuildTable(s){let{target:a,tempName:l,columnSource:c}=s,f=(R)=>this.quoteIdentifier(R),y=a.columns.map((R)=>this.renderColumn(R)).join(`,
281
281
  `),p=`CREATE TABLE ${f(l)} (
282
282
  ${y}
283
- );`,x=a.columns.map((E)=>E.name).filter((E)=>c[E]!==void 0),T=["PRAGMA foreign_keys=OFF;","BEGIN;",p];if(x.length>0){let E=x.map(f).join(", "),C=x.map((v)=>f(c[v])).join(", ");T.push(`INSERT INTO ${f(l)} (${E}) SELECT ${C} FROM ${f(a.table)};`)}T.push(`DROP TABLE ${f(a.table)};`),T.push(`ALTER TABLE ${f(l)} RENAME TO ${f(a.table)};`);for(let E of a.indexes)T.push(this.createIndex(a.table,E));return T.push("PRAGMA foreign_key_check;"),T.push("COMMIT;"),T.push("PRAGMA foreign_keys=ON;"),T.join(`
283
+ );`,x=a.columns.map((R)=>R.name).filter((R)=>c[R]!==void 0),T=["PRAGMA foreign_keys=OFF;","BEGIN;",p];if(x.length>0){let R=x.map(f).join(", "),C=x.map((_)=>f(c[_])).join(", ");T.push(`INSERT INTO ${f(l)} (${R}) SELECT ${C} FROM ${f(a.table)};`)}T.push(`DROP TABLE ${f(a.table)};`),T.push(`ALTER TABLE ${f(l)} RENAME TO ${f(a.table)};`);for(let R of a.indexes)T.push(this.createIndex(a.table,R));return T.push("PRAGMA foreign_key_check;"),T.push("COMMIT;"),T.push("PRAGMA foreign_keys=ON;"),T.join(`
284
284
  `)}dropTable(s){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(s)}`}dropColumn(s,a){return`ALTER TABLE ${this.quoteIdentifier(s)} DROP COLUMN ${this.quoteIdentifier(a)};`}dropIndex(s,a){let l=Pt(s,a);return`DROP INDEX IF EXISTS ${this.quoteIdentifier(l)};`}dropEnumType(s){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
285
285
  id INTEGER PRIMARY KEY AUTOINCREMENT,
286
286
  migration TEXT NOT NULL UNIQUE,
287
287
  executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
288
- )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}jsonExtract(s,a){return`json_extract(${s}, '$.' || ${a})`}dateBucket(s,a,l=0){let c=l===0?s:`datetime(${s}, '${l>=0?"+":"-"}${Math.abs(l)} hours')`;switch(a){case"hour":return`strftime('%Y-%m-%dT%H:00:00.000Z', ${c})`;case"week":return`strftime('%Y-%m-%dT00:00:00.000Z', ${c}, '-6 days', 'weekday 1')`;case"month":return`strftime('%Y-%m-01T00:00:00.000Z', ${c})`;case"year":return`strftime('%Y-01-01T00:00:00.000Z', ${c})`;case"day":default:return`strftime('%Y-%m-%dT00:00:00.000Z', ${c})`}}booleanLiteral(s){return s?"TRUE":"FALSE"}renderColumn(s){let a=this.getColumnType(s),l=[this.quoteIdentifier(s.name),a];if(s.isPrimaryKey){l.push("PRIMARY KEY");let f=this.getAutoIncrementClause(s);if(f)l.push(f)}if(!s.isNullable&&!s.isPrimaryKey)l.push("not null");let c=this.getDefaultValue(s);if(c)l.push(c);return l.push(...this.referencesClause(s)),l.join(" ")}referencesClause(s){if(!s.references)return[];let a=[`REFERENCES ${this.quoteIdentifier(s.references.table)}(${this.quoteIdentifier(s.references.column)})`];if(s.references.onDelete)a.push(`ON DELETE ${s.references.onDelete.toUpperCase()}`);if(s.references.onUpdate)a.push(`ON UPDATE ${s.references.onUpdate.toUpperCase()}`);return a}}function h(s,a={}){switch(s){case"postgres":return new ge;case"mysql":return new o;case"singlestore":return new pe;case"vitess":return new ye(a.vitessSharded??e.vitess?.sharded??!0);case"sqlite":return new be;default:throw Error(`Unsupported dialect: ${s}`)}}function mt(s){switch(s){case"text":return"text";case"string":case"enum":return"varchar";case"integer":case"bigint":return"integer";case"float":case"double":case"decimal":return"fractional";case"boolean":return"boolean";case"date":case"datetime":case"timestamptz":return"date";case"json":return"json";default:return"other"}}function ht(s){let a=String(s??"").toLowerCase().trim();if(/^(?:bool|boolean|bit)\b/.test(a)||a==="tinyint(1)")return"boolean";if(/^(?:json|jsonb)\b/.test(a))return"json";if(/^(?:bytea|blob|binary|varbinary)\b/.test(a))return"binary";if(/^(?:date|time|timestamp|datetime)\b/.test(a))return"date";if(/(?:^|\b)(?:varchar|character varying|nvarchar|char)\b/.test(a))return"varchar";if(/^(?:text|longtext|mediumtext|tinytext|clob|citext)\b/.test(a))return"text";if(/^(?:decimal|numeric|real|double|money)\b/.test(a)||/^float\d*\b/.test(a))return"fractional";if(/^(?:integer|bigint|smallint|tinyint|serial|bigserial|smallserial|mediumint)\b/.test(a)||/^int\d*\b/.test(a))return"integer";return"other"}function gt(s,a,l){if(s===a)return!0;if(l==="sqlite"){if(s==="boolean"&&a==="integer")return!0;if((s==="date"||s==="json")&&a==="text")return!0}if(n(l)&&s==="boolean"&&a==="integer")return!0;if(s==="varchar"&&a==="text")return!0;if(s==="integer"&&a==="fractional")return!0;if(s==="other"||a==="other")return!0;return!1}async function Qe(s,a={}){let l=a.dialect??e.dialect,c=s.tables.map((E)=>E.table),f=await R({tables:c}),y=new Map(f.map((E)=>[E.table.toLowerCase(),E])),p=[],x=[],T=[];for(let E of s.tables){let C=y.get(E.table.toLowerCase());if(!C){p.push(E.table);continue}let v=new Map(C.columns.map((k)=>[k.name.toLowerCase(),k]));for(let k of E.columns){let L=v.get(k.name.toLowerCase()),B=mt(k.type);if(!L){x.push({table:E.table,column:k.name,expected:B});continue}let X=ht(L.sqlType);if(!gt(B,X,l))T.push({table:E.table,column:k.name,expected:B,actual:X,actualSqlType:L.sqlType})}}return{missingTables:p,missingColumns:x,typeMismatches:T,clean:p.length===0&&x.length===0&&T.length===0}}function Ge(s){if(s.clean)return"";let a=[];if(s.missingTables.length>0)a.push(` Missing tables: ${s.missingTables.join(", ")}`);for(let f of s.missingColumns.slice(0,10))a.push(` \u2022 ${f.table}.${f.column} is missing (models declare ${f.expected})`);for(let f of s.typeMismatches.slice(0,10))a.push(` \u2022 ${f.table}.${f.column} is ${f.actualSqlType}, models declare ${f.expected}`);let l=Math.min(s.missingColumns.length,10)+Math.min(s.typeMismatches.length,10),c=s.missingColumns.length+s.typeMismatches.length;if(c>l)a.push(` + ${c-l} more`);return["The live schema does not match the models.",...a,"","Migrations will NOT fix this on their own: the runner only applies files that have","not run yet, and a corrected `CREATE TABLE IF NOT EXISTS` is a no-op against a table","that already exists. Regenerate and apply the difference, or rebuild the schema."].join(`
289
- `)}import{existsSync as di}from"fs";import{dirname as tr,isAbsolute as mi,join as rr}from"path";import nr from"process";function Dn(s=nr.cwd()){let a=s;while(a!==tr(a)){if(di(rr(a,"package.json")))return a;a=tr(a)}return nr.cwd()}function Ot(s,a="database/migrations"){let l=a||"database/migrations";return mi(l)?l:rr(s??Dn(),l)}async function yi(s,a,l){if(l.length===0)return;let c=pr(Vt());try{await gr(s,a);for(let f of l)await cn(s,f,a),Le(`-- \u2713 Recorded applied migration: ${f}`)}catch(f){Le(`-- Could not record applied migrations (the schema change itself succeeded): ${f instanceof Error?f.message:String(f)}`)}}function cr(s){try{return kt(Gt(s,"utf8"))}catch{return!1}}function bi(s){let a=s instanceof Error?s.message:String(s);return/duplicate column name/i.test(a)||/duplicate key name/i.test(a)||/duplicate foreign key constraint name/i.test(a)||/\balready exists\b/i.test(a)}function Le(s){if(e.verbose)console.log(s)}function dr(s){return At(s,e.snapshotDir||".qb")}function qn(s,a){return At(dr(s),`model-snapshot.${a}.json`)}function mr(s,a){let l=qn(s,a);if(!It(l))return;try{let c=Gt(l,"utf8"),f=JSON.parse(c);if(f?.plan&&Array.isArray(f.plan.tables)&&f.plan.dialect)return f.plan;if(Array.isArray(f?.tables)&&f?.dialect)return f;Le("-- Invalid snapshot format, treating as no previous state");return}catch(c){Le(`-- Could not load snapshot, treating as no previous state: ${c instanceof Error?c.message:String(c)}`);return}}function fr(s,a,l){let c=qn(s,a),f=dr(s),y=Rt(l);if(It(c))try{let x=JSON.parse(Gt(c,"utf8"));if(x?.hash===y&&x?.dialect===a&&x?.plan){Le("-- Model snapshot unchanged");return}}catch{}if(!It(f))ar(f,{recursive:!0}),Le(`-- Created snapshot directory: ${f}`);let p={plan:l,hash:y,dialect:a,updatedAt:new Date().toISOString()};ur(c,JSON.stringify(p,null,2)),Le(`-- Model snapshot saved to ${c}`)}function pt(s,a={}){let l=a.dialect??s.dialect;fr(a.workspaceRoot??Vt(),l,s)}function Vt(){return Dn()}function pr(s){let a=Ot(s,e.migrationDir);if(!It(a))ar(a,{recursive:!0}),Le(`-- Created SQL directory: ${a}`);return a}async function S(s,a={}){if(await I(),!s)s=At(wn.cwd(),"app/Models");let l=a.dialect||e.dialect||"postgres",c=Vt(),f=await d({modelsDir:s}),y=z(f,{dialect:l,vitessSharded:a.vitessSharded}),p,x=!1;if(!a.full){if(!a.fromDb)if(p=mr(c,l),p)Le("-- Comparing with stored model snapshot");else{let X=At(s,`.qb-migrations.${l}.json`),Pe=String(a.state||X);if(It(Pe))try{let Be=Gt(Pe,"utf8"),Ve=JSON.parse(Be);if(p=Ve?.plan&&Ve.plan.tables?Ve.plan:Ve?.tables?Ve:void 0,p)Le("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}}if(!p)try{let X=await Xn(l),Pe=new Set(y.tables.map((Ve)=>Ve.table)),Be=X.tables.filter((Ve)=>Pe.has(Ve.table));if(Be.length>0)p={dialect:X.dialect,tables:Be},x=!0,Le(`-- ${a.fromDb?"Diffing against the live database as requested":"No snapshot; reconciling against live database"} (${Be.length} matching table${Be.length===1?"":"s"})`);else if(a.fromDb)Le("-- The live database has none of the model tables; generating full migration")}catch(X){if(a.fromDb)throw Error(`generateMigration({ fromDb: true }) could not introspect the live database: ${X instanceof Error?X.message:String(X)}`);Le(`-- Could not introspect live database, treating as no previous state: ${X instanceof Error?X.message:String(X)}`)}if(!p)Le("-- No previous snapshot found, generating full migration")}else Le("-- Full migration requested, ignoring any previous state");let T=!a.dryRun,E=a.full?hi(y,T):Xe(p,y,{applyRenames:a.applyRenames,write:T,preserveUnknownColumns:x}),{statements:C,operations:v}=E,k=T?xt():[],L=C.join(`
290
- `),B=C.some((X)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(X));if(a.apply){let X=fi(At(pi(),"qb-migrate-")),Pe=At(X,"migration.sql");try{if(B){ur(Pe,L);let Be=i();await Be.file(Pe),Le("-- Migration applied"),await yi(Be,l,k)}else Le("-- No changes; nothing to apply")}catch(Be){throw console.error("-- Migration failed:",Be),Be}finally{lr(X,{recursive:!0,force:!0})}}if(!a.dryRun)fr(c,l,y);return{sql:L,sqlStatements:C,hasChanges:B,plan:y,operations:v,files:E.files}}function hi(s,a){let{statements:l,files:c}=Ae(s);if(a)Y(c,{deterministic:!0});let f=s.tables.map((y)=>({kind:"create_table",table:y.table,destructive:!1,sql:""}));return{statements:l,operations:f,files:c}}function Ti(s,a){if(s===void 0)return[pr(a)];let l=Array.isArray(s)?s:[s];if(l.length===0)throw Error("executeMigration was given an empty list of directories. Pass at least one directory, or omit the argument to use the configured migrationDir.");return l.map((c)=>gi(c)?c:At(a,c))}function xi(s){let a=new Map;for(let l of s){if(!It(l))throw Error(`Migration directory not found: ${l}`);for(let c of or(l).filter((f)=>f.endsWith(".sql"))){let f=a.get(c);if(f!==void 0)throw Error(`Duplicate migration file name across directories: "${c}" appears in both ${f} and ${At(l,c)}. Migrations are recorded by file name, so names must be unique across every directory in a run.`);a.set(c,At(l,c))}}return[...a].map(([l,c])=>({name:l,path:c})).sort((l,c)=>l.name<c.name?-1:l.name>c.name?1:0)}var ir="bun-query-builder:migrate",Ei=/\bCONCURRENTLY\b|^\s*VACUUM\b|^\s*BEGIN\s*(?:;|TRANSACTION\b)|^\s*PRAGMA\s+foreign_keys\b/im;function sr(s){return s==="postgres"||s==="sqlite"}async function Di(s,a){if(s==="sqlite")return await a();let l=i(),c;try{c=await l.reserve()}catch{return await a()}let f=!1;try{return await c.advisoryLock(ir),f=!0,await a()}finally{try{if(f)await c.advisoryUnlock(ir)}finally{c.release?.()}}}async function A(s,a={}){return(await Je(s,a)).ok}async function Je(s,a={}){await I();let l=Vt(),c=e.dialect||"postgres",f=xi(Ti(s,l)),y=[];if(f.length===0)Le("-- No migration files found to execute");else Le(`-- Found ${f.length} script files to execute`),await Si(f,c,y);let p=a.auditDrift??!0,T=p==="always"||p===!0&&y.length>0?await Ri(l,c,a):void 0;return{ok:!0,executed:y,...T?{drift:T}:{}}}async function Ri(s,a,l){let c=l.plan??mr(s,a);if(!c||c.dialect!==a||c.tables.length===0){Le("-- No model snapshot to audit the schema against; skipping the drift check");return}let f;try{f=await Qe(c,{dialect:a})}catch(y){let p=`-- Could not audit the schema after migrating: ${y instanceof Error?y.message:String(y)}`;if(l.strict)throw Error(p.replace(/^-- /,""));Le(p);return}if(!f.clean){let y=Ge(f);if(l.strict)throw Error(`Migrations were applied, but ${y.charAt(0).toLowerCase()}${y.slice(1)}`);console.warn(`-- ${y.split(`
288
+ )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}jsonExtract(s,a){return`json_extract(${s}, '$.' || ${a})`}dateBucket(s,a,l=0){let c=l===0?s:`datetime(${s}, '${l>=0?"+":"-"}${Math.abs(l)} hours')`;switch(a){case"hour":return`strftime('%Y-%m-%dT%H:00:00.000Z', ${c})`;case"week":return`strftime('%Y-%m-%dT00:00:00.000Z', ${c}, '-6 days', 'weekday 1')`;case"month":return`strftime('%Y-%m-01T00:00:00.000Z', ${c})`;case"year":return`strftime('%Y-01-01T00:00:00.000Z', ${c})`;case"day":default:return`strftime('%Y-%m-%dT00:00:00.000Z', ${c})`}}booleanLiteral(s){return s?"TRUE":"FALSE"}renderColumn(s){let a=this.getColumnType(s),l=[this.quoteIdentifier(s.name),a];if(s.isPrimaryKey){l.push("PRIMARY KEY");let f=this.getAutoIncrementClause(s);if(f)l.push(f)}if(!s.isNullable&&!s.isPrimaryKey)l.push("not null");let c=this.getDefaultValue(s);if(c)l.push(c);return l.push(...this.referencesClause(s)),l.join(" ")}referencesClause(s){if(!s.references)return[];let a=[`REFERENCES ${this.quoteIdentifier(s.references.table)}(${this.quoteIdentifier(s.references.column)})`];if(s.references.onDelete)a.push(`ON DELETE ${s.references.onDelete.toUpperCase()}`);if(s.references.onUpdate)a.push(`ON UPDATE ${s.references.onUpdate.toUpperCase()}`);return a}}function h(s,a={}){switch(s){case"postgres":return new pe;case"mysql":return new o;case"singlestore":return new ye;case"vitess":return new be(a.vitessSharded??e.vitess?.sharded??!0);case"sqlite":return new Te;default:throw Error(`Unsupported dialect: ${s}`)}}function mt(s){switch(s){case"text":return"text";case"string":case"enum":return"varchar";case"integer":case"bigint":return"integer";case"float":case"double":case"decimal":return"fractional";case"boolean":return"boolean";case"date":case"datetime":return"date";case"timestamptz":return"timestamptz";case"json":return"json";default:return"other"}}function ht(s,a){let l=String(s??"").toLowerCase().trim();if(/^(?:bool|boolean|bit)\b/.test(l)||l==="tinyint(1)")return"boolean";if(/^(?:json|jsonb)\b/.test(l))return"json";if(/^(?:bytea|blob|binary|varbinary)\b/.test(l))return"binary";if(/\bwith time zone\b/.test(l)||/^timestamptz\b/.test(l))return"timestamptz";if(n(a)&&/^timestamp\b/.test(l))return"timestamptz";if(/^(?:date|time|timestamp|datetime)\b/.test(l))return"date";if(/(?:^|\b)(?:varchar|character varying|nvarchar|char)\b/.test(l))return"varchar";if(/^(?:text|longtext|mediumtext|tinytext|clob|citext)\b/.test(l))return"text";if(/^(?:decimal|numeric|real|double|money)\b/.test(l)||/^float\d*\b/.test(l))return"fractional";if(/^(?:integer|bigint|smallint|tinyint|serial|bigserial|smallserial|mediumint)\b/.test(l)||/^int\d*\b/.test(l))return"integer";return"other"}function gt(s,a,l){if(s===a)return!0;if(l==="sqlite"){if(s==="boolean"&&a==="integer")return!0;if((s==="date"||s==="timestamptz"||s==="json")&&a==="text")return!0;if(s==="date"&&a==="timestamptz"||s==="timestamptz"&&a==="date")return!0}if(n(l)&&s==="boolean"&&a==="integer")return!0;if(n(l)&&s==="timestamptz"&&a==="date")return!0;if(s==="varchar"&&a==="text")return!0;if(s==="integer"&&a==="fractional")return!0;if(s==="other"||a==="other")return!0;return!1}async function Qe(s,a={}){let l=a.dialect??e.dialect,c=s.tables.map((R)=>R.table),f=await A({tables:c}),y=new Map(f.map((R)=>[R.table.toLowerCase(),R])),p=[],x=[],T=[];for(let R of s.tables){let C=y.get(R.table.toLowerCase());if(!C){p.push(R.table);continue}let _=new Map(C.columns.map((v)=>[v.name.toLowerCase(),v]));for(let v of R.columns){let k=_.get(v.name.toLowerCase()),K=mt(v.type);if(!k){x.push({table:R.table,column:v.name,expected:K});continue}let Z=ht(k.sqlType,l);if(!gt(K,Z,l))T.push({table:R.table,column:v.name,expected:K,actual:Z,actualSqlType:k.sqlType})}}return{missingTables:p,missingColumns:x,typeMismatches:T,clean:p.length===0&&x.length===0&&T.length===0}}function Ge(s){if(s.clean)return"";let a=[];if(s.missingTables.length>0)a.push(` Missing tables: ${s.missingTables.join(", ")}`);for(let f of s.missingColumns.slice(0,10))a.push(` \u2022 ${f.table}.${f.column} is missing (models declare ${f.expected})`);for(let f of s.typeMismatches.slice(0,10))a.push(` \u2022 ${f.table}.${f.column} is ${f.actualSqlType}, models declare ${f.expected}`);let l=Math.min(s.missingColumns.length,10)+Math.min(s.typeMismatches.length,10),c=s.missingColumns.length+s.typeMismatches.length;if(c>l)a.push(` + ${c-l} more`);return["The live schema does not match the models.",...a,"","Migrations will NOT fix this on their own: the runner only applies files that have","not run yet, and a corrected `CREATE TABLE IF NOT EXISTS` is a no-op against a table","that already exists. Regenerate and apply the difference, or rebuild the schema."].join(`
289
+ `)}import{existsSync as fi}from"fs";import{dirname as nr,isAbsolute as pi,join as ir}from"path";import rr from"process";function Dn(s=rr.cwd()){let a=s;while(a!==nr(a)){if(fi(ir(a,"package.json")))return a;a=nr(a)}return rr.cwd()}function Ot(s,a="database/migrations"){let l=a||"database/migrations";return pi(l)?l:ir(s??Dn(),l)}async function hi(s,a,l){if(l.length===0)return;let c=gr(Vt());try{await yr(s,a);for(let f of l)await cn(s,f,a),Le(`-- \u2713 Recorded applied migration: ${f}`)}catch(f){Le(`-- Could not record applied migrations (the schema change itself succeeded): ${f instanceof Error?f.message:String(f)}`)}}function dr(s){try{return kt(Gt(s,"utf8"))}catch{return!1}}function Ti(s){let a=s instanceof Error?s.message:String(s);return/duplicate column name/i.test(a)||/duplicate key name/i.test(a)||/duplicate foreign key constraint name/i.test(a)||/\balready exists\b/i.test(a)}function Le(s){if(e.verbose)console.log(s)}function mr(s){return At(s,e.snapshotDir||".qb")}function qn(s,a){return At(mr(s),`model-snapshot.${a}.json`)}function fr(s,a){let l=qn(s,a);if(!It(l))return;try{let c=Gt(l,"utf8"),f=JSON.parse(c);if(f?.plan&&Array.isArray(f.plan.tables)&&f.plan.dialect)return f.plan;if(Array.isArray(f?.tables)&&f?.dialect)return f;Le("-- Invalid snapshot format, treating as no previous state");return}catch(c){Le(`-- Could not load snapshot, treating as no previous state: ${c instanceof Error?c.message:String(c)}`);return}}function pr(s,a,l){let c=qn(s,a),f=mr(s),y=Rt(l);if(It(c))try{let x=JSON.parse(Gt(c,"utf8"));if(x?.hash===y&&x?.dialect===a&&x?.plan){Le("-- Model snapshot unchanged");return}}catch{}if(!It(f))or(f,{recursive:!0}),Le(`-- Created snapshot directory: ${f}`);let p={plan:l,hash:y,dialect:a,updatedAt:new Date().toISOString()};cr(c,JSON.stringify(p,null,2)),Le(`-- Model snapshot saved to ${c}`)}function pt(s,a={}){let l=a.dialect??s.dialect;pr(a.workspaceRoot??Vt(),l,s)}function Vt(){return Dn()}function gr(s){let a=Ot(s,e.migrationDir);if(!It(a))or(a,{recursive:!0}),Le(`-- Created SQL directory: ${a}`);return a}async function S(s,a={}){if(await L(),!s)s=At(wn.cwd(),"app/Models");let l=a.dialect||e.dialect||"postgres",c=Vt(),f=await d({modelsDir:s}),y=Y(f,{dialect:l,vitessSharded:a.vitessSharded}),p,x=!1;if(!a.full){if(!a.fromDb)if(p=fr(c,l),p)Le("-- Comparing with stored model snapshot");else{let Z=At(s,`.qb-migrations.${l}.json`),_e=String(a.state||Z);if(It(_e))try{let Be=Gt(_e,"utf8"),Ve=JSON.parse(Be);if(p=Ve?.plan&&Ve.plan.tables?Ve.plan:Ve?.tables?Ve:void 0,p)Le("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}}if(!p)try{let Z=await Xn(l),_e=new Set(y.tables.map((Ve)=>Ve.table)),Be=Z.tables.filter((Ve)=>_e.has(Ve.table));if(Be.length>0)p={dialect:Z.dialect,tables:Be},x=!0,Le(`-- ${a.fromDb?"Diffing against the live database as requested":"No snapshot; reconciling against live database"} (${Be.length} matching table${Be.length===1?"":"s"})`);else if(a.fromDb)Le("-- The live database has none of the model tables; generating full migration")}catch(Z){if(a.fromDb)throw Error(`generateMigration({ fromDb: true }) could not introspect the live database: ${Z instanceof Error?Z.message:String(Z)}`);Le(`-- Could not introspect live database, treating as no previous state: ${Z instanceof Error?Z.message:String(Z)}`)}if(!p)Le("-- No previous snapshot found, generating full migration")}else Le("-- Full migration requested, ignoring any previous state");let T=!a.dryRun,R=a.full?xi(y,T):Xe(p,y,{applyRenames:a.applyRenames,write:T,preserveUnknownColumns:x}),{statements:C,operations:_}=R,v=T?xt():[],k=C.join(`
290
+ `),K=C.some((Z)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(Z));if(a.apply){let Z=gi(At(yi(),"qb-migrate-")),_e=At(Z,"migration.sql");try{if(K){cr(_e,k);let Be=i();await Be.file(_e),Le("-- Migration applied"),await hi(Be,l,v)}else Le("-- No changes; nothing to apply")}catch(Be){throw console.error("-- Migration failed:",Be),Be}finally{ur(Z,{recursive:!0,force:!0})}}if(!a.dryRun)pr(c,l,y);return{sql:k,sqlStatements:C,hasChanges:K,plan:y,operations:_,files:R.files}}function xi(s,a){let{statements:l,files:c}=Ne(s);if(a)X(c,{deterministic:!0});let f=s.tables.map((y)=>({kind:"create_table",table:y.table,destructive:!1,sql:""}));return{statements:l,operations:f,files:c}}function Ei(s,a){if(s===void 0)return[gr(a)];let l=Array.isArray(s)?s:[s];if(l.length===0)throw Error("executeMigration was given an empty list of directories. Pass at least one directory, or omit the argument to use the configured migrationDir.");return l.map((c)=>bi(c)?c:At(a,c))}function Di(s){let a=new Map;for(let l of s){if(!It(l))throw Error(`Migration directory not found: ${l}`);for(let c of lr(l).filter((f)=>f.endsWith(".sql"))){let f=a.get(c);if(f!==void 0)throw Error(`Duplicate migration file name across directories: "${c}" appears in both ${f} and ${At(l,c)}. Migrations are recorded by file name, so names must be unique across every directory in a run.`);a.set(c,At(l,c))}}return[...a].map(([l,c])=>({name:l,path:c})).sort((l,c)=>l.name<c.name?-1:l.name>c.name?1:0)}var sr="bun-query-builder:migrate",Ri=/\bCONCURRENTLY\b|^\s*VACUUM\b|^\s*BEGIN\s*(?:;|TRANSACTION\b)|^\s*PRAGMA\s+foreign_keys\b/im;function ar(s){return s==="postgres"||s==="sqlite"}async function Si(s,a){if(s==="sqlite")return await a();let l=i(),c;try{c=await l.reserve()}catch{return await a()}let f=!1;try{return await c.advisoryLock(sr),f=!0,await a()}finally{try{if(f)await c.advisoryUnlock(sr)}finally{c.release?.()}}}async function N(s,a={}){return(await Je(s,a)).ok}async function Je(s,a={}){await L();let l=Vt(),c=e.dialect||"postgres",f=Di(Ei(s,l)),y=[];if(f.length===0)Le("-- No migration files found to execute");else Le(`-- Found ${f.length} script files to execute`),await Ai(f,c,y);let p=a.auditDrift??!0,T=p==="always"||p===!0&&y.length>0?await Mi(l,c,a):void 0;return{ok:!0,executed:y,...T?{drift:T}:{}}}async function Mi(s,a,l){let c=l.plan??fr(s,a);if(!c||c.dialect!==a||c.tables.length===0){Le("-- No model snapshot to audit the schema against; skipping the drift check");return}let f;try{f=await Qe(c,{dialect:a})}catch(y){let p=`-- Could not audit the schema after migrating: ${y instanceof Error?y.message:String(y)}`;if(l.strict)throw Error(p.replace(/^-- /,""));Le(p);return}if(!f.clean){let y=Ge(f);if(l.strict)throw Error(`Migrations were applied, but ${y.charAt(0).toLowerCase()}${y.slice(1)}`);console.warn(`-- ${y.split(`
291
291
  `).join(`
292
- -- `)}`)}else Le("-- Schema matches the models");return f}async function Si(s,a,l){try{let c=i();await Di(a,async()=>{await gr(c,a);let f=await Ci(c,a),y=s.filter((p)=>!f.includes(p.name));if(y.length===0){Le("-- No pending migrations to execute");return}Le(`-- Executing ${y.length} migration${y.length===1?"":"s"}`);for(let{name:p,path:x}of y){Le(`-- Executing: ${p}`);try{if(sr(a)&&!Ei.test(Gt(x,"utf-8")))await c.transaction(async(E)=>{await E.file(x),await cn(E,p,a)});else if(await c.file(x),await cn(c,p,a),!sr(a))Le(`-- (${a} commits DDL implicitly, so ${p} was not applied atomically)`);else Le(`-- (${p} contains a statement that cannot run in a transaction, so it was not applied atomically)`);l.push(p),Le(`-- \u2713 Migration ${p} executed and recorded`)}catch(T){if(cr(x)&&bi(T)){await cn(c,p,a),l.push(p),Le(`-- \u2713 Migration ${p} was already applied; recorded it (${T instanceof Error?T.message:String(T)})`);continue}throw console.error(`-- \u2717 Migration ${p} failed:`,T),T}}Le("-- All migrations executed successfully")})}catch(c){throw console.error("-- Migration execution failed:",c),c}}async function N(s,a={}){if(await I(),!s)s=At(wn.cwd(),"app/Models");let l=a.dialect||e.dialect||"postgres",c=h(l),f=Vt(),y=async(p)=>{let x=c.dropTable(p);await ot(async(T)=>{if(l==="sqlite")await T.unsafe("PRAGMA foreign_keys = OFF").execute();if(l==="mysql"||l==="vitess")await T.unsafe("SET FOREIGN_KEY_CHECKS = 0").execute();try{await T.unsafe(x).execute()}finally{if(l==="sqlite")await T.unsafe("PRAGMA foreign_keys = ON").execute();if(l==="mysql"||l==="vitess")await T.unsafe("SET FOREIGN_KEY_CHECKS = 1").execute()}})};try{try{await y("migrations"),Le("-- Dropped migrations table")}catch(T){console.error(T)}let p=[],x=[];try{let T=await d({modelsDir:s}),E=z(T,{dialect:l});p=E.tables.map((v)=>v.table);let C=new Set;for(let v of E.tables)for(let k of v.columns)if(k.type==="enum"&&k.enumValues&&k.enumValues.length>0){let L=`${v.table}_${k.name}_type`;C.add(L)}x=Array.from(C)}catch(T){console.error(T),p=[],x=[]}if(p.length===0)Le("-- No tables found to drop");else{Le(`-- Dropping ${p.length} tables: ${p.join(", ")}`);for(let T of p.reverse())try{await y(T),Le(`-- Dropped table: ${T}`)}catch(E){console.error(E),Le(`-- Table ${T} may not exist, skipping drop`)}}if(x.length>0){Le(`-- Dropping ${x.length} enum types: ${x.join(", ")}`);for(let T of x)try{let E=c.dropEnumType(T);if(E)await ot(async(C)=>{await C.unsafe(E).execute(),Le(`-- Dropped enum type: ${T}`)})}catch(E){console.error(E),Le(`-- Enum type ${T} may not exist, skipping drop`)}}else Le("-- No enum types found to drop");if(p.length>0&&!a.preserveMigrationState)try{await Mi(s,f,a)}catch(T){console.error(T),Le("-- Could not clean up migration files")}else if(p.length===0)Le("-- No models directory found; keeping committed migration files in place");else Le("-- Preserving migration files and model snapshot for fresh replay");if(!a.preserveMigrationState)try{await wi(f)}catch(T){console.error(T),Le("-- Could not clear generated directory")}return Le("-- Database reset completed successfully"),!0}catch(p){return console.error("-- Database reset failed:",p),!1}}async function Mi(s,a,l={}){if(!s)s=At(wn.cwd(),"app/Models");if(!a)a=Vt();let c=String(l.dialect||e.dialect||"postgres"),f=qn(a,c);if(It(f))Sn(f),Le(`-- Removed model snapshot file: ${f}`);let y=At(s,`.qb-migrations.${c}.json`),p=String(l.state||y);if(It(p))Sn(p),Le(`-- Removed legacy migration state file: ${p}`);Ai(Ot(a,e.migrationDir))}function Ai(s){if(!It(s))return;let a=0,l=[];for(let c of or(s).filter((f)=>f.endsWith(".sql"))){if(!cr(At(s,c))){l.push(c);continue}Sn(At(s,c)),Le(`-- Removed generated migration file: ${c}`),a+=1}if(Le(`-- Cleaned up ${a} generated migration file${a===1?"":"s"} from migrations directory`),l.length>0)Le(`-- Kept ${l.length} hand-written migration${l.length===1?"":"s"}: ${l.slice(0,5).join(", ")}${l.length>5?`, +${l.length-5} more`:""}`)}async function wi(s){if(!s)s=Vt();let a=At(s,"generated");if(It(a))try{lr(a,{recursive:!0,force:!0}),Le("-- Cleared generated directory")}catch(l){console.error("-- Failed to clear generated directory:",l)}}async function gr(s,a){let c=h(a).createMigrationsTable();try{await s.unsafe(c).execute(),Le("-- Migrations table ready")}catch(f){throw console.error("-- Failed to create migrations table:",f),f}}async function Ci(s,a){let l=h(a);try{return(await s.unsafe(l.getExecutedMigrationsQuery()).execute()).map((f)=>f.migration)}catch(c){return console.error("-- Failed to get executed migrations:",c),[]}}async function cn(s,a,l){let c=h(l);try{Le(`-- Recording migration: ${a}`),await s.unsafe(c.recordMigrationQuery(),[a]).execute(),Le(`-- Successfully recorded migration: ${a}`)}catch(f){throw console.error(`-- Failed to record migration ${a}:`,f),f}}async function Te(s,a={}){return S(s,a)}import{existsSync as yr,readFileSync as Ni,unlinkSync as $i}from"fs";import{join as _i}from"path";function Pi(s){let a=[],l="",c=null;for(let f=0;f<s.length;f++){let y=s[f];if(c){if(l+=y,y===c)if(s[f+1]===c)l+=s[f+1],f++;else c=null;continue}if(y==="'"||y==='"'||y==="`"){c=y,l+=y;continue}if(y==="-"&&s[f+1]==="-"){let p=s.indexOf(`
293
- `,f);f=p===-1?s.length:p;continue}if(y==="/"&&s[f+1]==="*"){let p=s.indexOf("*/",f+2);f=p===-1?s.length:p+1;continue}if(y===";"){if(l.trim())a.push(l.trim());l="";continue}l+=y}if(l.trim())a.push(l.trim());return a}function vi(s,a=e.dialect){let l=(y)=>n(a)?`\`${y}\``:`"${y}"`,c=[],f=[];for(let y of Pi(s)){let p;if(p=/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?/i.exec(y))c.push(`DROP TABLE IF EXISTS ${l(p[1])}`);else if(p=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+CONSTRAINT\s+["`']?(\w+)["`']?([\s\S]*)$/i.exec(y))if(a==="sqlite")f.push(y);else if(n(a)&&/\bFOREIGN\s+KEY\b/i.test(p[3]??""))c.push(`ALTER TABLE ${l(p[1])} DROP FOREIGN KEY ${l(p[2])}`);else c.push(`ALTER TABLE ${l(p[1])} DROP CONSTRAINT ${l(p[2])}`);else if(p=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+(?:COLUMN\s+["`']?(\w+)["`']?|["`'](\w+)["`']|(\w+))/i.exec(y)){let x=p[2]??p[3]??p[4];if(p[4]&&/^(?:PRIMARY|UNIQUE|INDEX|KEY|FOREIGN|CHECK|FULLTEXT|SPATIAL)$/i.test(p[4]))f.push(y);else c.push(`ALTER TABLE ${l(p[1])} DROP COLUMN ${l(x)}`)}else if(p=/^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?(?:\s+ON\s+["`']?(\w+)["`']?)?/i.exec(y))c.push(n(a)&&p[2]?`DROP INDEX ${l(p[1])} ON ${l(p[2])}`:`DROP INDEX IF EXISTS ${l(p[1])}`);else f.push(y)}return{down:c.reverse(),skipped:f}}async function we(s={}){let a=s.steps||1,l=s.reverseSchema!==!1;console.log("-- Rolling back migrations"),console.log(`-- Steps: ${a}`),console.log();try{let c=i(),f=[];try{f=await c.unsafe(`
292
+ -- `)}`)}else Le("-- Schema matches the models");return f}async function Ai(s,a,l){try{let c=i();await Si(a,async()=>{await yr(c,a);let f=await $i(c,a),y=s.filter((p)=>!f.includes(p.name));if(y.length===0){Le("-- No pending migrations to execute");return}Le(`-- Executing ${y.length} migration${y.length===1?"":"s"}`);for(let{name:p,path:x}of y){Le(`-- Executing: ${p}`);try{if(ar(a)&&!Ri.test(Gt(x,"utf-8")))await c.transaction(async(R)=>{await R.file(x),await cn(R,p,a)});else if(await c.file(x),await cn(c,p,a),!ar(a))Le(`-- (${a} commits DDL implicitly, so ${p} was not applied atomically)`);else Le(`-- (${p} contains a statement that cannot run in a transaction, so it was not applied atomically)`);l.push(p),Le(`-- \u2713 Migration ${p} executed and recorded`)}catch(T){if(dr(x)&&Ti(T)){await cn(c,p,a),l.push(p),Le(`-- \u2713 Migration ${p} was already applied; recorded it (${T instanceof Error?T.message:String(T)})`);continue}throw console.error(`-- \u2717 Migration ${p} failed:`,T),T}}Le("-- All migrations executed successfully")})}catch(c){throw console.error("-- Migration execution failed:",c),c}}async function M(s,a={}){if(await L(),!s)s=At(wn.cwd(),"app/Models");let l=a.dialect||e.dialect||"postgres",c=h(l),f=Vt(),y=async(p)=>{let x=c.dropTable(p);await ot(async(T)=>{if(l==="sqlite")await T.unsafe("PRAGMA foreign_keys = OFF").execute();if(l==="mysql"||l==="vitess")await T.unsafe("SET FOREIGN_KEY_CHECKS = 0").execute();try{await T.unsafe(x).execute()}finally{if(l==="sqlite")await T.unsafe("PRAGMA foreign_keys = ON").execute();if(l==="mysql"||l==="vitess")await T.unsafe("SET FOREIGN_KEY_CHECKS = 1").execute()}})};try{try{await y("migrations"),Le("-- Dropped migrations table")}catch(T){console.error(T)}let p=[],x=[];try{let T=await d({modelsDir:s}),R=Y(T,{dialect:l});p=R.tables.map((_)=>_.table);let C=new Set;for(let _ of R.tables)for(let v of _.columns)if(v.type==="enum"&&v.enumValues&&v.enumValues.length>0){let k=`${_.table}_${v.name}_type`;C.add(k)}x=Array.from(C)}catch(T){console.error(T),p=[],x=[]}if(p.length===0)Le("-- No tables found to drop");else{Le(`-- Dropping ${p.length} tables: ${p.join(", ")}`);for(let T of p.reverse())try{await y(T),Le(`-- Dropped table: ${T}`)}catch(R){console.error(R),Le(`-- Table ${T} may not exist, skipping drop`)}}if(x.length>0){Le(`-- Dropping ${x.length} enum types: ${x.join(", ")}`);for(let T of x)try{let R=c.dropEnumType(T);if(R)await ot(async(C)=>{await C.unsafe(R).execute(),Le(`-- Dropped enum type: ${T}`)})}catch(R){console.error(R),Le(`-- Enum type ${T} may not exist, skipping drop`)}}else Le("-- No enum types found to drop");if(p.length>0&&!a.preserveMigrationState)try{await wi(s,f,a)}catch(T){console.error(T),Le("-- Could not clean up migration files")}else if(p.length===0)Le("-- No models directory found; keeping committed migration files in place");else Le("-- Preserving migration files and model snapshot for fresh replay");if(!a.preserveMigrationState)try{await Ni(f)}catch(T){console.error(T),Le("-- Could not clear generated directory")}return Le("-- Database reset completed successfully"),!0}catch(p){return console.error("-- Database reset failed:",p),!1}}async function wi(s,a,l={}){if(!s)s=At(wn.cwd(),"app/Models");if(!a)a=Vt();let c=String(l.dialect||e.dialect||"postgres"),f=qn(a,c);if(It(f))Sn(f),Le(`-- Removed model snapshot file: ${f}`);let y=At(s,`.qb-migrations.${c}.json`),p=String(l.state||y);if(It(p))Sn(p),Le(`-- Removed legacy migration state file: ${p}`);Ci(Ot(a,e.migrationDir))}function Ci(s){if(!It(s))return;let a=0,l=[];for(let c of lr(s).filter((f)=>f.endsWith(".sql"))){if(!dr(At(s,c))){l.push(c);continue}Sn(At(s,c)),Le(`-- Removed generated migration file: ${c}`),a+=1}if(Le(`-- Cleaned up ${a} generated migration file${a===1?"":"s"} from migrations directory`),l.length>0)Le(`-- Kept ${l.length} hand-written migration${l.length===1?"":"s"}: ${l.slice(0,5).join(", ")}${l.length>5?`, +${l.length-5} more`:""}`)}async function Ni(s){if(!s)s=Vt();let a=At(s,"generated");if(It(a))try{ur(a,{recursive:!0,force:!0}),Le("-- Cleared generated directory")}catch(l){console.error("-- Failed to clear generated directory:",l)}}async function yr(s,a){let c=h(a).createMigrationsTable();try{await s.unsafe(c).execute(),Le("-- Migrations table ready")}catch(f){throw console.error("-- Failed to create migrations table:",f),f}}async function $i(s,a){let l=h(a);try{return(await s.unsafe(l.getExecutedMigrationsQuery()).execute()).map((f)=>f.migration)}catch(c){return console.error("-- Failed to get executed migrations:",c),[]}}async function cn(s,a,l){let c=h(l);try{Le(`-- Recording migration: ${a}`),await s.unsafe(c.recordMigrationQuery(),[a]).execute(),Le(`-- Successfully recorded migration: ${a}`)}catch(f){throw console.error(`-- Failed to record migration ${a}:`,f),f}}async function we(s,a={}){return S(s,a)}import{existsSync as br,readFileSync as _i,unlinkSync as Pi}from"fs";import{join as vi}from"path";function ki(s){let a=[],l="",c=null;for(let f=0;f<s.length;f++){let y=s[f];if(c){if(l+=y,y===c)if(s[f+1]===c)l+=s[f+1],f++;else c=null;continue}if(y==="'"||y==='"'||y==="`"){c=y,l+=y;continue}if(y==="-"&&s[f+1]==="-"){let p=s.indexOf(`
293
+ `,f);f=p===-1?s.length:p;continue}if(y==="/"&&s[f+1]==="*"){let p=s.indexOf("*/",f+2);f=p===-1?s.length:p+1;continue}if(y===";"){if(l.trim())a.push(l.trim());l="";continue}l+=y}if(l.trim())a.push(l.trim());return a}function Ii(s,a=e.dialect){let l=(y)=>n(a)?`\`${y}\``:`"${y}"`,c=[],f=[];for(let y of ki(s)){let p;if(p=/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?/i.exec(y))c.push(`DROP TABLE IF EXISTS ${l(p[1])}`);else if(p=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+CONSTRAINT\s+["`']?(\w+)["`']?([\s\S]*)$/i.exec(y))if(a==="sqlite")f.push(y);else if(n(a)&&/\bFOREIGN\s+KEY\b/i.test(p[3]??""))c.push(`ALTER TABLE ${l(p[1])} DROP FOREIGN KEY ${l(p[2])}`);else c.push(`ALTER TABLE ${l(p[1])} DROP CONSTRAINT ${l(p[2])}`);else if(p=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+(?:COLUMN\s+["`']?(\w+)["`']?|["`'](\w+)["`']|(\w+))/i.exec(y)){let x=p[2]??p[3]??p[4];if(p[4]&&/^(?:PRIMARY|UNIQUE|INDEX|KEY|FOREIGN|CHECK|FULLTEXT|SPATIAL)$/i.test(p[4]))f.push(y);else c.push(`ALTER TABLE ${l(p[1])} DROP COLUMN ${l(x)}`)}else if(p=/^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?(?:\s+ON\s+["`']?(\w+)["`']?)?/i.exec(y))c.push(n(a)&&p[2]?`DROP INDEX ${l(p[1])} ON ${l(p[2])}`:`DROP INDEX IF EXISTS ${l(p[1])}`);else f.push(y)}return{down:c.reverse(),skipped:f}}async function Se(s={}){let a=s.steps||1,l=s.reverseSchema!==!1;console.log("-- Rolling back migrations"),console.log(`-- Steps: ${a}`),console.log();try{let c=i(),f=[];try{f=await c.unsafe(`
294
294
  SELECT migration, executed_at
295
295
  FROM migrations
296
296
  ORDER BY executed_at DESC, migration DESC
297
- `)}catch(T){console.log("-- Migrations table not found. Nothing to rollback.",T);return}if(f.length===0){console.log("-- No migrations to rollback");return}let y=f.slice(0,a);console.log(`-- Found ${f.length} executed migrations`),console.log(`-- Rolling back ${y.length} migration(s):`),console.log();for(let T of y)console.log(` - ${T.migration}`);console.log();let p=Ot(void 0,e.migrationDir),x=!1;for(let T of y)try{let E=_i(p,T.migration);if(l&&yr(E)){let v=Ni(E,"utf8"),{down:k,skipped:L}=vi(v);for(let B of k)await c.unsafe(B),console.log(`-- \u21A9 ${B}`),x=!0;if(L.length>0)console.log(`-- \u26A0\uFE0F ${L.length} statement(s) in ${T.migration} could not be auto-reversed (data/complex DDL) \u2014 reverse manually.`)}let C=`DELETE FROM migrations WHERE migration = ${t(1)}`;if(await c.unsafe(C,[T.migration]),console.log(`-- \u2713 Removed migration record: ${T.migration}`),s.deleteFiles&&yr(E))$i(E),console.log(`-- \uD83D\uDDD1\uFE0F Deleted migration file: ${T.migration}`)}catch(E){throw console.error(`-- \u2717 Failed to rollback migration ${T.migration}:`,E),E}if(console.log(),l)console.log(x?"-- \u2713 Reverse DDL executed for the rolled-back migration(s).":"-- \u26A0\uFE0F No reversible DDL found; only migration records were removed.");else console.log("-- \u26A0\uFE0F reverseSchema disabled: only migration records were removed.")}catch(c){throw console.error("-- Rollback failed:",c),c}}import{existsSync as ki,readdirSync as Ii}from"fs";async function U(){let s=e.dialect||"postgres",a=h(s),l=Ot(void 0,e.migrationDir);if(console.log("-- Migration Status"),console.log(`-- Dialect: ${s}`),console.log(`-- SQL directory: ${l}`),console.log(),!ki(l))return console.log("-- No SQL directory found. No migrations have been created yet."),[];let f=Ii(l).filter((y)=>y.endsWith(".sql")).sort();if(f.length===0)return console.log("-- No migration files found"),[];try{let y=i(),p=[];try{p=await y.unsafe(a.getExecutedMigrationsQuery())}catch(v){console.log("-- Migrations table not found. All migrations are pending.",v),console.log()}let x=new Map(p.map((v)=>[v.migration,v.executed_at])),T=f.map((v)=>({file:v,status:x.has(v)?"executed":"pending",executedAt:x.get(v)})),E=T.filter((v)=>v.status==="executed"),C=T.filter((v)=>v.status==="pending");if(console.log(`-- Total migrations: ${f.length}`),console.log(`-- Executed: ${E.length}`),console.log(`-- Pending: ${C.length}`),console.log(),E.length>0){console.log("\u2713 Executed Migrations:");for(let v of E)console.log(` - ${v.file} ${v.executedAt?`(${new Date(v.executedAt).toLocaleString()})`:""}`);console.log()}if(C.length>0){console.log("\u25CB Pending Migrations:");for(let v of C)console.log(` - ${v.file}`);console.log()}return T}catch(y){throw console.error("-- Failed to get migration status:",y),y}}async function Se(){return U()}import{readdirSync as Oi}from"fs";import{extname as Kn,join as br}from"path";import qi from"process";async function V(s,a={}){let l=a.dir||br(qi.cwd(),"app/Models");try{let c=Oi(l),f=c.find((C)=>C.replace(Kn(C),"").toLowerCase()===s.toLowerCase());if(!f){console.error(`Model "${s}" not found in ${l}`),console.log(`Available models: ${c.filter((C)=>[".ts",".js"].includes(Kn(C))).map((C)=>C.replace(Kn(C),"")).join(", ")}`);return}let p=await import(br(l,f)),x=p.default||p[Object.keys(p)[0]];if(!x||!x.name){console.error(`Invalid model file: ${f}`);return}let T={name:x.name,table:x.table||`${x.name.toLowerCase()}s`,primaryKey:x.primaryKey||"id",attributes:x.attributes||{},relations:x.relations,scopes:x.scopes,indexes:x.indexes,timestamps:x.timestamps!==!1,softDeletes:x.softDeletes===!0},E=[];if(x.beforeCreate)E.push("beforeCreate");if(x.afterCreate)E.push("afterCreate");if(x.beforeUpdate)E.push("beforeUpdate");if(x.afterUpdate)E.push("afterUpdate");if(x.beforeDelete)E.push("beforeDelete");if(x.afterDelete)E.push("afterDelete");if(E.length>0)T.hooks=E;if(a.json)return console.log(JSON.stringify(T,null,2)),T;console.log(`
297
+ `)}catch(T){console.log("-- Migrations table not found. Nothing to rollback.",T);return}if(f.length===0){console.log("-- No migrations to rollback");return}let y=f.slice(0,a);console.log(`-- Found ${f.length} executed migrations`),console.log(`-- Rolling back ${y.length} migration(s):`),console.log();for(let T of y)console.log(` - ${T.migration}`);console.log();let p=Ot(void 0,e.migrationDir),x=!1;for(let T of y)try{let R=vi(p,T.migration);if(l&&br(R)){let _=_i(R,"utf8"),{down:v,skipped:k}=Ii(_);for(let K of v)await c.unsafe(K),console.log(`-- \u21A9 ${K}`),x=!0;if(k.length>0)console.log(`-- \u26A0\uFE0F ${k.length} statement(s) in ${T.migration} could not be auto-reversed (data/complex DDL) \u2014 reverse manually.`)}let C=`DELETE FROM migrations WHERE migration = ${t(1)}`;if(await c.unsafe(C,[T.migration]),console.log(`-- \u2713 Removed migration record: ${T.migration}`),s.deleteFiles&&br(R))Pi(R),console.log(`-- \uD83D\uDDD1\uFE0F Deleted migration file: ${T.migration}`)}catch(R){throw console.error(`-- \u2717 Failed to rollback migration ${T.migration}:`,R),R}if(console.log(),l)console.log(x?"-- \u2713 Reverse DDL executed for the rolled-back migration(s).":"-- \u26A0\uFE0F No reversible DDL found; only migration records were removed.");else console.log("-- \u26A0\uFE0F reverseSchema disabled: only migration records were removed.")}catch(c){throw console.error("-- Rollback failed:",c),c}}import{existsSync as Oi,readdirSync as qi}from"fs";async function V(){let s=e.dialect||"postgres",a=h(s),l=Ot(void 0,e.migrationDir);if(console.log("-- Migration Status"),console.log(`-- Dialect: ${s}`),console.log(`-- SQL directory: ${l}`),console.log(),!Oi(l))return console.log("-- No SQL directory found. No migrations have been created yet."),[];let f=qi(l).filter((y)=>y.endsWith(".sql")).sort();if(f.length===0)return console.log("-- No migration files found"),[];try{let y=i(),p=[];try{p=await y.unsafe(a.getExecutedMigrationsQuery())}catch(_){console.log("-- Migrations table not found. All migrations are pending.",_),console.log()}let x=new Map(p.map((_)=>[_.migration,_.executed_at])),T=f.map((_)=>({file:_,status:x.has(_)?"executed":"pending",executedAt:x.get(_)})),R=T.filter((_)=>_.status==="executed"),C=T.filter((_)=>_.status==="pending");if(console.log(`-- Total migrations: ${f.length}`),console.log(`-- Executed: ${R.length}`),console.log(`-- Pending: ${C.length}`),console.log(),R.length>0){console.log("\u2713 Executed Migrations:");for(let _ of R)console.log(` - ${_.file} ${_.executedAt?`(${new Date(_.executedAt).toLocaleString()})`:""}`);console.log()}if(C.length>0){console.log("\u25CB Pending Migrations:");for(let _ of C)console.log(` - ${_.file}`);console.log()}return T}catch(y){throw console.error("-- Failed to get migration status:",y),y}}async function De(){return V()}import{readdirSync as Li}from"fs";import{extname as Kn,join as hr}from"path";import Ki from"process";async function H(s,a={}){let l=a.dir||hr(Ki.cwd(),"app/Models");try{let c=Li(l),f=c.find((C)=>C.replace(Kn(C),"").toLowerCase()===s.toLowerCase());if(!f){console.error(`Model "${s}" not found in ${l}`),console.log(`Available models: ${c.filter((C)=>[".ts",".js"].includes(Kn(C))).map((C)=>C.replace(Kn(C),"")).join(", ")}`);return}let p=await import(hr(l,f)),x=p.default||p[Object.keys(p)[0]];if(!x||!x.name){console.error(`Invalid model file: ${f}`);return}let T={name:x.name,table:x.table||`${x.name.toLowerCase()}s`,primaryKey:x.primaryKey||"id",attributes:x.attributes||{},relations:x.relations,scopes:x.scopes,indexes:x.indexes,timestamps:x.timestamps!==!1,softDeletes:x.softDeletes===!0},R=[];if(x.beforeCreate)R.push("beforeCreate");if(x.afterCreate)R.push("afterCreate");if(x.beforeUpdate)R.push("beforeUpdate");if(x.afterUpdate)R.push("afterUpdate");if(x.beforeDelete)R.push("beforeDelete");if(x.afterDelete)R.push("afterDelete");if(R.length>0)T.hooks=R;if(a.json)return console.log(JSON.stringify(T,null,2)),T;console.log(`
298
298
  \uD83D\uDCE6 Model: ${T.name}`),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(`Table: ${T.table}`),console.log(`Primary Key: ${T.primaryKey}`),console.log(`Timestamps: ${T.timestamps?"\u2713":"\u2717"}`),console.log(`Soft Deletes: ${T.softDeletes?"\u2713":"\u2717"}`),console.log(`
299
- \uD83D\uDCCB Attributes (${Object.keys(T.attributes).length}):`);for(let[C,v]of Object.entries(T.attributes)){let k=v.type||"string",L=v.required?"(required)":"",B=v.unique?"(unique)":"",X=v.default!==void 0?`= ${JSON.stringify(v.default)}`:"";console.log(` \u2022 ${C}: ${k} ${L} ${B} ${X}`.trim())}if(T.relations&&Object.keys(T.relations).length>0){console.log(`
300
- \uD83D\uDD17 Relations (${Object.keys(T.relations).length}):`);for(let[C,v]of Object.entries(T.relations)){let k=v.type||"unknown",L=v.model||v.table||"unknown";console.log(` \u2022 ${C}: ${k} \u2192 ${L}`)}}if(T.scopes&&Object.keys(T.scopes).length>0){console.log(`
299
+ \uD83D\uDCCB Attributes (${Object.keys(T.attributes).length}):`);for(let[C,_]of Object.entries(T.attributes)){let v=_.type||"string",k=_.required?"(required)":"",K=_.unique?"(unique)":"",Z=_.default!==void 0?`= ${JSON.stringify(_.default)}`:"";console.log(` \u2022 ${C}: ${v} ${k} ${K} ${Z}`.trim())}if(T.relations&&Object.keys(T.relations).length>0){console.log(`
300
+ \uD83D\uDD17 Relations (${Object.keys(T.relations).length}):`);for(let[C,_]of Object.entries(T.relations)){let v=_.type||"unknown",k=_.model||_.table||"unknown";console.log(` \u2022 ${C}: ${v} \u2192 ${k}`)}}if(T.scopes&&Object.keys(T.scopes).length>0){console.log(`
301
301
  \uD83D\uDD0D Scopes (${Object.keys(T.scopes).length}):`);for(let C of Object.keys(T.scopes))console.log(` \u2022 ${C}()`)}if(T.hooks&&T.hooks.length>0){console.log(`
302
302
  \uD83E\uDE9D Hooks (${T.hooks.length}):`);for(let C of T.hooks)console.log(` \u2022 ${C}`)}if(T.indexes&&T.indexes.length>0){console.log(`
303
- \uD83D\uDCC7 Indexes (${T.indexes.length}):`);for(let C of T.indexes){let v=Array.isArray(C.columns)?C.columns.join(", "):C.columns,k=C.unique?"(unique)":"";console.log(` \u2022 ${C.name||"unnamed"}: [${v}] ${k}`.trim())}}return console.log(),T}catch(c){throw console.error(`Error loading model "${s}":`,c.message),c}}async function De(){let a=await i().ping();return console.log(a?"OK":"NOT READY"),a}import{readdirSync as Li,readFileSync as hr,statSync as Ki}from"fs";import{extname as Tr,join as Bi}from"path";async function H(s,a={}){let l=[];try{let c=Ki(s),f=[];if(c.isDirectory())f=Li(s).filter((T)=>Tr(T)===".sql").map((T)=>Bi(s,T));else if(c.isFile()&&Tr(s)===".sql")f=[s];else return console.error("Path must be a .sql file or directory containing .sql files"),l;if(f.length===0)return console.log("No .sql files found"),l;if(a.verbose)console.log(`Analyzing ${f.length} SQL file(s)...
304
- `);for(let x of f)try{let T=hr(x,"utf8").trim();if(!T){if(a.verbose)console.log(`\u2298 ${x}: empty file`);continue}if(a.verbose)console.log(`\uD83D\uDCC4 ${x}`),console.log(` Query: ${T.substring(0,60)}${T.length>60?"...":""}`);let E=await r`EXPLAIN ${r.unsafe(T)}`;if(l.push({file:x,query:T,plan:Array.isArray(E)?E:[E]}),a.verbose&&!a.json){if(console.log(" Plan:"),Array.isArray(E))for(let C of E)if(typeof C==="string")console.log(` ${C}`);else if(C["QUERY PLAN"])console.log(` ${C["QUERY PLAN"]}`);else if(C.plan)console.log(` ${JSON.stringify(C.plan)}`);else console.log(` ${JSON.stringify(C)}`);console.log()}}catch(T){if(l.push({file:x,query:hr(x,"utf8").trim(),plan:[],error:T.message}),a.verbose)console.log(` \u2717 Error: ${T.message}
305
- `)}let y=l.filter((x)=>!x.error).length,p=l.filter((x)=>x.error).length;if(a.verbose)console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(`Summary: ${y} successful, ${p} failed`);if(a.json)console.log(JSON.stringify(l,null,2));return l}catch(c){throw console.error("Error explaining queries:",c.message),c}}import{writeFileSync as Ui}from"fs";import{join as Fi}from"path";import Vi from"process";async function Q(s={}){let a=s.dir||Fi(Vi.cwd(),"app/Models"),l=s.format||"mermaid";try{let c=await d({modelsDir:a});if(!c||Object.keys(c).length===0)return console.error("No models found"),"";let f="";if(l==="mermaid")f=ji(c);else if(l==="dot")f=Yi(c);else return console.error(`Unsupported format: ${l}`),"";if(s.output)Ui(s.output,f,"utf8"),console.log(`\u2713 Diagram written to: ${s.output}`);else console.log(f);return f}catch(c){throw console.error("Error generating diagram:",c.message),c}}function ji(s){let a=["erDiagram"];for(let[l,c]of Object.entries(s)){let f=c.table||`${l.toLowerCase()}s`,y=c.attributes||{};a.push(` ${f} {`);for(let[p,x]of Object.entries(y)){let T=x.type||"string",E=c.primaryKey===p?"PK":"",C=x.unique?"UK":"",v=[E,C].filter(Boolean).join(","),k=v?` "${v}"`:"";a.push(` ${T} ${p}${k}`)}a.push(" }")}for(let[l,c]of Object.entries(s)){let f=c.table||`${l.toLowerCase()}s`,y=c.relations||{};for(let[p,x]of Object.entries(y)){let{type:T,model:E}=x,C=s[E]?.table||`${E?.toLowerCase()}s`||"unknown",v="";if(T==="hasOne")v="||--||";else if(T==="hasMany")v="||--o{";else if(T==="belongsTo")v="}o--||";else if(T==="belongsToMany"||T==="manyToMany")v="}o--o{";else v="||--||";a.push(` ${f} ${v} ${C} : "${p}"`)}}return a.join(`
306
- `)}function Yi(s){let a=["digraph schema {"," rankdir=LR;"," node [shape=record];",""];for(let[l,c]of Object.entries(s)){let f=c.table||`${l.toLowerCase()}s`,y=c.attributes||{},p=[];for(let[T,E]of Object.entries(y)){let C=E.type||"string",v=c.primaryKey===T?" (PK)":"",k=E.unique?" (UK)":"";p.push(`${T}: ${C}${v}${k}`)}let x=`${p.join("\\l")}\\l`;a.push(` ${f} [label="{${f}|${x}}"];`)}a.push("");for(let[l,c]of Object.entries(s)){let f=c.table||`${l.toLowerCase()}s`,y=c.relations||{};for(let[p,x]of Object.entries(y)){let{type:T,model:E}=x,C=s[E]?.table||`${E?.toLowerCase()}s`||"unknown",v="";if(T==="hasOne")v="arrowhead=none, arrowtail=normal";else if(T==="hasMany")v="arrowhead=crow, arrowtail=none";else if(T==="belongsTo")v="arrowhead=normal, arrowtail=none";else if(T==="belongsToMany"||T==="manyToMany")v="arrowhead=crow, arrowtail=crow";a.push(` ${f} -> ${C} [label="${p}", ${v}];`)}}return a.push("}"),a.join(`
307
- `)}import{existsSync as dn,mkdirSync as Qi,readdirSync as Wi,writeFileSync as Gi}from"fs";import{dirname as xr,join as Lt}from"path";import Ht from"process";function mn(s){let a=s;while(a!==xr(a)){if(dn(Lt(a,"package.json")))return a;a=xr(a)}return Ht.cwd()}async function Er(s){if(!dn(s))return console.log(`-- Seeders directory not found: ${s}`),[];let l=Wi(s).sort((f,y)=>f.localeCompare(y)).filter((f)=>(f.endsWith(".ts")||f.endsWith(".js"))&&f!=="index.ts"&&f!=="index.js"),c=[];for(let f of l){let y=Lt(s,f);try{let p=await import(y),x=p.default||p[Object.keys(p)[0]];if(x&&typeof x==="function"){let T=new x;if(T&&typeof T.run==="function")c.push({name:f.replace(/\.(ts|js)$/,""),className:String(x.name||""),instance:T})}}catch(p){console.error(`-- Failed to load seeder ${f}:`,p)}}return c.sort((f,y)=>f.instance.order-y.instance.order),c}async function M(s={}){let a=mn(Ht.cwd()),l=s.seedersDir||Lt(a,"database/seeders"),c=s.verbose??!0;if(c)console.log("-- Running seeders..."),console.log(`-- Seeders directory: ${l}`);let f=await Er(l);if(f.length===0){console.log("-- No seeders found");return}if(c)console.log(`-- Found ${f.length} seeder(s)`);let y=i();for(let{name:p,instance:x}of f)try{if(c)console.log(`-- Seeding: ${p}`);if(await x.run(y),c)console.log(`-- \u2713 Seeded: ${p}`)}catch(T){throw console.error(`-- \u2717 Failed to seed ${p}:`,T),T}if(c)console.log("-- All seeders completed successfully")}async function G(s,a={}){let l=mn(Ht.cwd()),c=Lt(l,"database/seeders"),f=a.verbose??!0;if(f)console.log(`-- Running seeder: ${s}`);let y=await Er(c),p=y.find((T)=>T.className===s)??y.find((T)=>T.name===s);if(!p){let T=y.map((E)=>E.className||E.name).join(", ")||"none";throw console.error(`-- Seeder not found: ${s}. Available: ${T}`),Error(`Seeder not found: ${s}. Available: ${T}`)}let x=i();try{if(await p.instance.run(x),f)console.log(`-- \u2713 Seeder completed: ${s}`)}catch(T){throw console.error(`-- \u2717 Seeder failed: ${s}`,T),T}}async function Ee(s){let a=mn(Ht.cwd()),l=Lt(a,"database/seeders");if(!dn(l))Qi(l,{recursive:!0}),console.log(`-- Created seeders directory: ${l}`);let f=`${s.replace(/Seeder$/i,"")}Seeder`,y=`${f}.ts`,p=Lt(l,y);if(dn(p))throw console.error(`-- Seeder already exists: ${p}`),Error(`Seeder already exists: ${p}`);let x=`import type { QueryBuilder } from 'bun-query-builder'
303
+ \uD83D\uDCC7 Indexes (${T.indexes.length}):`);for(let C of T.indexes){let _=Array.isArray(C.columns)?C.columns.join(", "):C.columns,v=C.unique?"(unique)":"";console.log(` \u2022 ${C.name||"unnamed"}: [${_}] ${v}`.trim())}}return console.log(),T}catch(c){throw console.error(`Error loading model "${s}":`,c.message),c}}async function Ee(){let a=await i().ping();return console.log(a?"OK":"NOT READY"),a}import{readdirSync as Bi,readFileSync as Tr,statSync as Ui}from"fs";import{extname as xr,join as Fi}from"path";async function Q(s,a={}){let l=[];try{let c=Ui(s),f=[];if(c.isDirectory())f=Bi(s).filter((T)=>xr(T)===".sql").map((T)=>Fi(s,T));else if(c.isFile()&&xr(s)===".sql")f=[s];else return console.error("Path must be a .sql file or directory containing .sql files"),l;if(f.length===0)return console.log("No .sql files found"),l;if(a.verbose)console.log(`Analyzing ${f.length} SQL file(s)...
304
+ `);for(let x of f)try{let T=Tr(x,"utf8").trim();if(!T){if(a.verbose)console.log(`\u2298 ${x}: empty file`);continue}if(a.verbose)console.log(`\uD83D\uDCC4 ${x}`),console.log(` Query: ${T.substring(0,60)}${T.length>60?"...":""}`);let R=await r`EXPLAIN ${r.unsafe(T)}`;if(l.push({file:x,query:T,plan:Array.isArray(R)?R:[R]}),a.verbose&&!a.json){if(console.log(" Plan:"),Array.isArray(R))for(let C of R)if(typeof C==="string")console.log(` ${C}`);else if(C["QUERY PLAN"])console.log(` ${C["QUERY PLAN"]}`);else if(C.plan)console.log(` ${JSON.stringify(C.plan)}`);else console.log(` ${JSON.stringify(C)}`);console.log()}}catch(T){if(l.push({file:x,query:Tr(x,"utf8").trim(),plan:[],error:T.message}),a.verbose)console.log(` \u2717 Error: ${T.message}
305
+ `)}let y=l.filter((x)=>!x.error).length,p=l.filter((x)=>x.error).length;if(a.verbose)console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(`Summary: ${y} successful, ${p} failed`);if(a.json)console.log(JSON.stringify(l,null,2));return l}catch(c){throw console.error("Error explaining queries:",c.message),c}}import{writeFileSync as Vi}from"fs";import{join as ji}from"path";import Yi from"process";async function G(s={}){let a=s.dir||ji(Yi.cwd(),"app/Models"),l=s.format||"mermaid";try{let c=await d({modelsDir:a});if(!c||Object.keys(c).length===0)return console.error("No models found"),"";let f="";if(l==="mermaid")f=Qi(c);else if(l==="dot")f=Wi(c);else return console.error(`Unsupported format: ${l}`),"";if(s.output)Vi(s.output,f,"utf8"),console.log(`\u2713 Diagram written to: ${s.output}`);else console.log(f);return f}catch(c){throw console.error("Error generating diagram:",c.message),c}}function Qi(s){let a=["erDiagram"];for(let[l,c]of Object.entries(s)){let f=c.table||`${l.toLowerCase()}s`,y=c.attributes||{};a.push(` ${f} {`);for(let[p,x]of Object.entries(y)){let T=x.type||"string",R=c.primaryKey===p?"PK":"",C=x.unique?"UK":"",_=[R,C].filter(Boolean).join(","),v=_?` "${_}"`:"";a.push(` ${T} ${p}${v}`)}a.push(" }")}for(let[l,c]of Object.entries(s)){let f=c.table||`${l.toLowerCase()}s`,y=c.relations||{};for(let[p,x]of Object.entries(y)){let{type:T,model:R}=x,C=s[R]?.table||`${R?.toLowerCase()}s`||"unknown",_="";if(T==="hasOne")_="||--||";else if(T==="hasMany")_="||--o{";else if(T==="belongsTo")_="}o--||";else if(T==="belongsToMany"||T==="manyToMany")_="}o--o{";else _="||--||";a.push(` ${f} ${_} ${C} : "${p}"`)}}return a.join(`
306
+ `)}function Wi(s){let a=["digraph schema {"," rankdir=LR;"," node [shape=record];",""];for(let[l,c]of Object.entries(s)){let f=c.table||`${l.toLowerCase()}s`,y=c.attributes||{},p=[];for(let[T,R]of Object.entries(y)){let C=R.type||"string",_=c.primaryKey===T?" (PK)":"",v=R.unique?" (UK)":"";p.push(`${T}: ${C}${_}${v}`)}let x=`${p.join("\\l")}\\l`;a.push(` ${f} [label="{${f}|${x}}"];`)}a.push("");for(let[l,c]of Object.entries(s)){let f=c.table||`${l.toLowerCase()}s`,y=c.relations||{};for(let[p,x]of Object.entries(y)){let{type:T,model:R}=x,C=s[R]?.table||`${R?.toLowerCase()}s`||"unknown",_="";if(T==="hasOne")_="arrowhead=none, arrowtail=normal";else if(T==="hasMany")_="arrowhead=crow, arrowtail=none";else if(T==="belongsTo")_="arrowhead=normal, arrowtail=none";else if(T==="belongsToMany"||T==="manyToMany")_="arrowhead=crow, arrowtail=crow";a.push(` ${f} -> ${C} [label="${p}", ${_}];`)}}return a.push("}"),a.join(`
307
+ `)}import{existsSync as dn,mkdirSync as Gi,readdirSync as zi,writeFileSync as Hi}from"fs";import{dirname as Er,join as Lt}from"path";import Ht from"process";function mn(s){let a=s;while(a!==Er(a)){if(dn(Lt(a,"package.json")))return a;a=Er(a)}return Ht.cwd()}async function Dr(s){if(!dn(s))return console.log(`-- Seeders directory not found: ${s}`),[];let l=zi(s).sort((f,y)=>f.localeCompare(y)).filter((f)=>(f.endsWith(".ts")||f.endsWith(".js"))&&f!=="index.ts"&&f!=="index.js"),c=[];for(let f of l){let y=Lt(s,f);try{let p=await import(y),x=p.default||p[Object.keys(p)[0]];if(x&&typeof x==="function"){let T=new x;if(T&&typeof T.run==="function")c.push({name:f.replace(/\.(ts|js)$/,""),className:String(x.name||""),instance:T})}}catch(p){console.error(`-- Failed to load seeder ${f}:`,p)}}return c.sort((f,y)=>f.instance.order-y.instance.order),c}async function P(s={}){let a=mn(Ht.cwd()),l=s.seedersDir||Lt(a,"database/seeders"),c=s.verbose??!0;if(c)console.log("-- Running seeders..."),console.log(`-- Seeders directory: ${l}`);let f=await Dr(l);if(f.length===0){console.log("-- No seeders found");return}if(c)console.log(`-- Found ${f.length} seeder(s)`);let y=i();for(let{name:p,instance:x}of f)try{if(c)console.log(`-- Seeding: ${p}`);if(await x.run(y),c)console.log(`-- \u2713 Seeded: ${p}`)}catch(T){throw console.error(`-- \u2717 Failed to seed ${p}:`,T),T}if(c)console.log("-- All seeders completed successfully")}async function J(s,a={}){let l=mn(Ht.cwd()),c=Lt(l,"database/seeders"),f=a.verbose??!0;if(f)console.log(`-- Running seeder: ${s}`);let y=await Dr(c),p=y.find((T)=>T.className===s)??y.find((T)=>T.name===s);if(!p){let T=y.map((R)=>R.className||R.name).join(", ")||"none";throw console.error(`-- Seeder not found: ${s}. Available: ${T}`),Error(`Seeder not found: ${s}. Available: ${T}`)}let x=i();try{if(await p.instance.run(x),f)console.log(`-- \u2713 Seeder completed: ${s}`)}catch(T){throw console.error(`-- \u2717 Seeder failed: ${s}`,T),T}}async function $e(s){let a=mn(Ht.cwd()),l=Lt(a,"database/seeders");if(!dn(l))Gi(l,{recursive:!0}),console.log(`-- Created seeders directory: ${l}`);let f=`${s.replace(/Seeder$/i,"")}Seeder`,y=`${f}.ts`,p=Lt(l,y);if(dn(p))throw console.error(`-- Seeder already exists: ${p}`),Error(`Seeder already exists: ${p}`);let x=`import type { QueryBuilder } from 'bun-query-builder'
308
308
  import { Seeder } from 'bun-query-builder'
309
309
  import { faker } from '@stacksjs/ts-faker'
310
310
 
@@ -349,7 +349,7 @@ export default class ${f} extends Seeder {
349
349
  return 100
350
350
  }
351
351
  }
352
- `;Gi(p,x),console.log(`-- \u2713 Created seeder: ${p}`)}async function $e(s={}){let a=mn(Ht.cwd()),l=s.modelsDir||Lt(a,"app/Models"),c=s.seedersDir||Lt(a,"database/seeders"),f=s.verbose??!0;try{let{resetDatabase:y,generateMigration:p,executeMigration:x}=await import("./chunk-jam15bp2.js");if(f)console.log("-- Refreshing database...");if(await y(l),f)console.log("-- Running migrations...");if(await p(l,{full:!0}),await x(),f)console.log("-- Running seeders...");if(await M({seedersDir:c,verbose:f}),f)console.log("-- \u2713 Database refreshed successfully")}catch(y){throw console.error("-- \u2717 Database refresh failed:",y),y}}function xe(s,a,l={}){let c=d({modelsDir:s}),f=Re(c);if(e.debug)e.debug.captureText=!0;let y=i({schema:f}),p=y.selectFrom(a).limit(Number(l.limit||10)).toText?.()??"";return console.log(p||"[query]"),{sql:p,qb:y,schema:f}}async function ve(s,a={}){let l=i(),c=a.params?JSON.parse(a.params):void 0,f=await l.unsafe(s,c);return console.log(JSON.stringify(f)),f}import{existsSync as zi}from"fs";import{dirname as Dr,join as Rr}from"path";import Sr from"process";function Hi(s){let a=s;while(a!==Dr(a)){if(zi(Rr(a,"package.json")))return a;a=Dr(a)}return Sr.cwd()}async function J(s){if(!s)s=Rr(Hi(Sr.cwd()),"app/Models");let a=e.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${s}`),console.log(`-- Dialect: ${a}`),console.log();let l=[];try{let c=await d({modelsDir:s}),f=z(c,{dialect:a}),y=i(),p=[];if(a==="sqlite")p=(await y.unsafe(`
352
+ `;Hi(p,x),console.log(`-- \u2713 Created seeder: ${p}`)}async function xe(s={}){let a=mn(Ht.cwd()),l=s.modelsDir||Lt(a,"app/Models"),c=s.seedersDir||Lt(a,"database/seeders"),f=s.verbose??!0;try{let{resetDatabase:y,generateMigration:p,executeMigration:x}=await import("./chunk-12t4k0mz.js");if(f)console.log("-- Refreshing database...");if(await y(l),f)console.log("-- Running migrations...");if(await p(l,{full:!0}),await x(),f)console.log("-- Running seeders...");if(await P({seedersDir:c,verbose:f}),f)console.log("-- \u2713 Database refreshed successfully")}catch(y){throw console.error("-- \u2717 Database refresh failed:",y),y}}function ve(s,a,l={}){let c=d({modelsDir:s}),f=Ae(c);if(e.debug)e.debug.captureText=!0;let y=i({schema:f}),p=y.selectFrom(a).limit(Number(l.limit||10)).toText?.()??"";return console.log(p||"[query]"),{sql:p,qb:y,schema:f}}async function ke(s,a={}){let l=i(),c=a.params?JSON.parse(a.params):void 0,f=await l.unsafe(s,c);return console.log(JSON.stringify(f)),f}import{existsSync as Xi}from"fs";import{dirname as Rr,join as Sr}from"path";import Mr from"process";function Ji(s){let a=s;while(a!==Rr(a)){if(Xi(Sr(a,"package.json")))return a;a=Rr(a)}return Mr.cwd()}async function z(s){if(!s)s=Sr(Ji(Mr.cwd()),"app/Models");let a=e.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${s}`),console.log(`-- Dialect: ${a}`),console.log();let l=[];try{let c=await d({modelsDir:s}),f=Y(c,{dialect:a}),y=i(),p=[];if(a==="sqlite")p=(await y.unsafe(`
353
353
  SELECT name FROM sqlite_master
354
354
  WHERE type = 'table'
355
355
  AND name NOT LIKE 'sqlite_%'
@@ -366,26 +366,26 @@ export default class ${f} extends Seeder {
366
366
  WHERE table_schema = DATABASE()
367
367
  AND table_type = 'BASE TABLE'
368
368
  AND table_name != 'migrations'
369
- `)).map((C)=>C.table_name);let x=f.tables.map((E)=>E.table);for(let E of x)if(!p.includes(E))l.push({type:"missing_table",severity:"error",table:E,message:`Table '${E}' defined in models but not found in database`});for(let E of p)if(!x.includes(E))l.push({type:"extra_table",severity:"warning",table:E,message:`Table '${E}' exists in database but not defined in models`});for(let E of f.tables){if(!p.includes(E.table))continue;let C=[];if(a==="sqlite")C=(await y.unsafe(`PRAGMA table_info(${E.table})`)).map((B)=>({name:B.name,type:B.type.toLowerCase()}));else if(a==="postgres")C=(await y.unsafe(`
369
+ `)).map((C)=>C.table_name);let x=f.tables.map((R)=>R.table);for(let R of x)if(!p.includes(R))l.push({type:"missing_table",severity:"error",table:R,message:`Table '${R}' defined in models but not found in database`});for(let R of p)if(!x.includes(R))l.push({type:"extra_table",severity:"warning",table:R,message:`Table '${R}' exists in database but not defined in models`});for(let R of f.tables){if(!p.includes(R.table))continue;let C=[];if(a==="sqlite")C=(await y.unsafe(`PRAGMA table_info(${R.table})`)).map((K)=>({name:K.name,type:K.type.toLowerCase()}));else if(a==="postgres")C=(await y.unsafe(`
370
370
  SELECT column_name, data_type
371
371
  FROM information_schema.columns
372
372
  WHERE table_name = $1
373
- `,[E.table])).map((B)=>({name:B.column_name,type:B.data_type.toLowerCase()}));else if(n(a))C=(await y.unsafe(`
373
+ `,[R.table])).map((K)=>({name:K.column_name,type:K.data_type.toLowerCase()}));else if(n(a))C=(await y.unsafe(`
374
374
  SELECT column_name, data_type
375
375
  FROM information_schema.columns
376
376
  WHERE table_name = ?
377
377
  AND table_schema = DATABASE()
378
- `,[E.table])).map((B)=>({name:B.column_name,type:B.data_type.toLowerCase()}));let v=C.map((L)=>L.name),k=E.columns.map((L)=>L.name);for(let L of E.columns)if(!v.includes(L.name))l.push({type:"missing_column",severity:"error",table:E.table,column:L.name,expected:L.type,message:`Column '${E.table}.${L.name}' defined in model but not found in database`});for(let L of C)if(!k.includes(L.name))l.push({type:"extra_column",severity:"warning",table:E.table,column:L.name,actual:L.type,message:`Column '${E.table}.${L.name}' exists in database but not defined in model`});for(let L of E.columns){let B=C.find((X)=>X.name===L.name);if(B){let X=(Ve)=>Ve.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim(),Pe=X(L.type),Be=X(B.type);if(Pe!==Be)l.push({type:"type_mismatch",severity:"warning",table:E.table,column:L.name,expected:L.type,actual:B.type,message:`Column '${E.table}.${L.name}' type mismatch: expected '${L.type}', found '${B.type}'`})}}}let T=l.filter((E)=>E.severity==="error").length===0;if(T&&l.length===0)console.log("\u2713 Schema is valid - no issues found"),console.log();else{console.log(`-- Found ${l.length} issue(s)`),console.log();let E=l.filter((v)=>v.severity==="error"),C=l.filter((v)=>v.severity==="warning");if(E.length>0){console.log(`\u2717 Errors (${E.length}):`);for(let v of E)console.log(` - ${v.message}`);console.log()}if(C.length>0){console.log(`\u26A0 Warnings (${C.length}):`);for(let v of C)console.log(` - ${v.message}`);console.log()}if(!T)console.log("-- Recommendation: Run migrations to sync the database schema"),console.log("-- qb migrate ./app/Models --apply")}return{valid:T,issues:l}}catch(c){throw console.error("-- Schema validation failed:",c),c}}async function ke(s){return J(s)}async function Ce(s={}){let a=Number(s.attempts||10),l=Number(s.delay||100),c=i();try{return await c.waitForReady({attempts:a,delayMs:l}),console.log("READY"),!0}catch{throw console.error("NOT READY"),Error("Database not ready")}}class D{driver;client;tableName;indexName;entityType;keyConditions=[];filterConditions=[];projectionAttrs=[];limitValue;scanForward=!0;consistentReadValue=!1;startKey;constructor(s){this.driver=u(s.config),this.client=s.client,this.tableName=s.config.tableName??""}table(s){return this.tableName=s,this}index(s){return this.indexName=s,this}entity(s){return this.entityType=s,this}whereKey(s,a,l){return this.keyConditions.push({attribute:s,operator:a,value:l}),this}wherePartitionKey(s,a){return this.whereKey(s,"=",a)}whereSortKey(s,a){return this.whereKey(s,"=",a)}whereSortKeyBeginsWith(s,a){return this.keyConditions.push({attribute:s,operator:"begins_with",value:a}),this}whereSortKeyBetween(s,a,l){return this.keyConditions.push({attribute:s,operator:"BETWEEN",values:[a,l]}),this}where(s,a,l){return this.filterConditions.push({attribute:s,operator:a,value:l}),this}whereEquals(s,a){return this.where(s,"=",a)}whereLessThan(s,a){return this.where(s,"<",a)}whereLessThanOrEqual(s,a){return this.where(s,"<=",a)}whereGreaterThan(s,a){return this.where(s,">",a)}whereGreaterThanOrEqual(s,a){return this.where(s,">=",a)}whereBetween(s,a,l){return this.filterConditions.push({attribute:s,operator:"BETWEEN",values:[a,l]}),this}whereBeginsWith(s,a){return this.filterConditions.push({attribute:s,operator:"begins_with",value:a}),this}whereContains(s,a){return this.where(s,"contains",a)}whereExists(s){return this.where(s,"attribute_exists")}whereNotExists(s){return this.where(s,"attribute_not_exists")}whereIn(s,a){return this.filterConditions.push({attribute:s,operator:"IN",values:a}),this}select(...s){return this.projectionAttrs.push(...s),this}limit(s){return this.limitValue=s,this}ascending(){return this.scanForward=!0,this}descending(){return this.scanForward=!1,this}consistentRead(s=!0){return this.consistentReadValue=s,this}startFrom(s){return this.startKey=s,this}buildQueryParams(){return this.driver.buildQueryParams({tableName:this.tableName,indexName:this.indexName,keyConditions:this.keyConditions,filterConditions:this.filterConditions.length>0?this.filterConditions:void 0,projectionAttributes:this.projectionAttrs.length>0?this.projectionAttrs:void 0,limit:this.limitValue,scanIndexForward:this.scanForward,exclusiveStartKey:this.startKey,consistentRead:this.consistentReadValue})}buildScanParams(){return this.driver.buildScanParams({tableName:this.tableName,indexName:this.indexName,filterConditions:this.filterConditions.length>0?this.filterConditions:void 0,projectionAttributes:this.projectionAttrs.length>0?this.projectionAttrs:void 0,limit:this.limitValue,exclusiveStartKey:this.startKey,consistentRead:this.consistentReadValue})}toQueryRequest(){let s=this.buildQueryParams(),a={TableName:s.tableName,ExpressionAttributeNames:{},ExpressionAttributeValues:{}};if(s.indexName)a.IndexName=s.indexName;let l=0;if(s.keyConditions.length>0){let c=[];for(let f of s.keyConditions){let y=`#key${l}`;if(a.ExpressionAttributeNames[y]=f.attribute,f.operator==="begins_with"){let p=`:keyval${l}`;a.ExpressionAttributeValues[p]=this.driver.marshall({v:f.value}).v,c.push(`begins_with(${y}, ${p})`)}else if(f.operator==="BETWEEN"){let p=`:keyval${l}a`,x=`:keyval${l}b`;a.ExpressionAttributeValues[p]=this.driver.marshall({v:f.values?.[0]}).v,a.ExpressionAttributeValues[x]=this.driver.marshall({v:f.values?.[1]}).v,c.push(`${y} BETWEEN ${p} AND ${x}`)}else{let p=`:keyval${l}`;a.ExpressionAttributeValues[p]=this.driver.marshall({v:f.value}).v,c.push(`${y} ${f.operator} ${p}`)}l++}a.KeyConditionExpression=c.join(" AND ")}if(s.filterConditions&&s.filterConditions.length>0){let c=[];for(let f of s.filterConditions){let y=`#flt${l}`;if(a.ExpressionAttributeNames[y]=f.attribute,f.operator==="attribute_exists")c.push(`attribute_exists(${y})`);else if(f.operator==="attribute_not_exists")c.push(`attribute_not_exists(${y})`);else if(f.operator==="begins_with"||f.operator==="contains"){let p=`:fltval${l}`;a.ExpressionAttributeValues[p]=this.driver.marshall({v:f.value}).v,c.push(`${f.operator}(${y}, ${p})`)}else if(f.operator==="BETWEEN"){let p=`:fltval${l}a`,x=`:fltval${l}b`;a.ExpressionAttributeValues[p]=this.driver.marshall({v:f.values?.[0]}).v,a.ExpressionAttributeValues[x]=this.driver.marshall({v:f.values?.[1]}).v,c.push(`${y} BETWEEN ${p} AND ${x}`)}else if(f.operator==="IN"){let p=(f.values??[]).map((x,T)=>`:fltval${l}_${T}`);f.values?.forEach((x,T)=>{a.ExpressionAttributeValues[`:fltval${l}_${T}`]=this.driver.marshall({v:x}).v}),c.push(`${y} IN (${p.join(", ")})`)}else{let p=`:fltval${l}`;a.ExpressionAttributeValues[p]=this.driver.marshall({v:f.value}).v,c.push(`${y} ${f.operator} ${p}`)}l++}a.FilterExpression=c.join(" AND ")}if(s.projectionAttributes&&s.projectionAttributes.length>0){let c=[];for(let f of s.projectionAttributes){let y=`#proj${l}`;a.ExpressionAttributeNames[y]=f,c.push(y),l++}a.ProjectionExpression=c.join(", ")}if(s.limit!==void 0)a.Limit=s.limit;if(s.scanIndexForward!==void 0)a.ScanIndexForward=s.scanIndexForward;if(s.exclusiveStartKey)a.ExclusiveStartKey=this.driver.marshall(s.exclusiveStartKey);if(s.consistentRead)a.ConsistentRead=s.consistentRead;if(Object.keys(a.ExpressionAttributeNames).length===0)delete a.ExpressionAttributeNames;if(Object.keys(a.ExpressionAttributeValues).length===0)delete a.ExpressionAttributeValues;return a}toScanRequest(){let s=this.buildScanParams(),a={TableName:s.tableName};if(s.indexName)a.IndexName=s.indexName;if(s.filterConditions&&s.filterConditions.length>0){let{expression:l,expressionAttributeNames:c,expressionAttributeValues:f}=this.driver.buildFilterExpression(s.filterConditions);a.FilterExpression=l,a.ExpressionAttributeNames=c,a.ExpressionAttributeValues=f}if(s.projectionAttributes&&s.projectionAttributes.length>0){let{expression:l,expressionAttributeNames:c}=this.driver.buildProjectionExpression(s.projectionAttributes);a.ProjectionExpression=l,a.ExpressionAttributeNames={...a.ExpressionAttributeNames,...c}}if(s.limit!==void 0)a.Limit=s.limit;if(s.exclusiveStartKey)a.ExclusiveStartKey=this.driver.marshall(s.exclusiveStartKey);if(s.consistentRead)a.ConsistentRead=s.consistentRead;return a}async query(){if(!this.client)throw Error("DynamoDB client not provided. Pass a client in options or use toQueryRequest() to get the request params.");let s=this.toQueryRequest(),a=await this.client.query(s);return{items:a.Items?.map((l)=>this.driver.unmarshall(l)),count:a.Count,scannedCount:a.ScannedCount,lastEvaluatedKey:a.LastEvaluatedKey?this.driver.unmarshall(a.LastEvaluatedKey):void 0,consumedCapacity:a.ConsumedCapacity}}async scan(){if(!this.client)throw Error("DynamoDB client not provided. Pass a client in options or use toScanRequest() to get the request params.");let s=this.toScanRequest(),a=await this.client.scan(s);return{items:a.Items?.map((l)=>this.driver.unmarshall(l)),count:a.Count,scannedCount:a.ScannedCount,lastEvaluatedKey:a.LastEvaluatedKey?this.driver.unmarshall(a.LastEvaluatedKey):void 0,consumedCapacity:a.ConsumedCapacity}}async getAll(){let s=[],a;do{if(a)this.startFrom(a);let l=this.keyConditions.length>0?await this.query():await this.scan();if(l.items)s.push(...l.items);a=l.lastEvaluatedKey}while(a);return s}async first(){return this.limit(1),(this.keyConditions.length>0?await this.query():await this.scan()).items?.[0]}async count(){if(!this.client)throw Error("DynamoDB client not provided");let s=this.keyConditions.length>0?this.toQueryRequest():this.toScanRequest();return s.Select="COUNT",(this.keyConditions.length>0?await this.client.query(s):await this.client.scan(s)).Count??0}reset(){return this.indexName=void 0,this.entityType=void 0,this.keyConditions=[],this.filterConditions=[],this.projectionAttrs=[],this.limitValue=void 0,this.scanForward=!0,this.consistentReadValue=!1,this.startKey=void 0,this}}class g{driver;client;tableName;itemData={};keyData={};updateExpressions={};conditionExpr;returnValuesOption="NONE";constructor(s){this.driver=u(s.config),this.client=s.client,this.tableName=s.config.tableName??""}table(s){return this.tableName=s,this}key(s){return this.keyData=s,this}item(s){return this.itemData=s,this}set(s,a){if(!this.updateExpressions.set)this.updateExpressions.set={};return this.updateExpressions.set[s]=a,this}setMany(s){if(!this.updateExpressions.set)this.updateExpressions.set={};return Object.assign(this.updateExpressions.set,s),this}remove(s){if(!this.updateExpressions.remove)this.updateExpressions.remove=[];return this.updateExpressions.remove.push(s),this}add(s,a){if(!this.updateExpressions.add)this.updateExpressions.add={};return this.updateExpressions.add[s]=a,this}deleteFromSet(s,a){if(!this.updateExpressions.delete)this.updateExpressions.delete={};return this.updateExpressions.delete[s]=a,this}condition(s){return this.conditionExpr=s,this}ifNotExists(s="pk"){return this.conditionExpr=`attribute_not_exists(${s})`,this}ifExists(s="pk"){return this.conditionExpr=`attribute_exists(${s})`,this}returnOld(){return this.returnValuesOption="ALL_OLD",this}returnNew(){return this.returnValuesOption="ALL_NEW",this}toPutRequest(){let s={TableName:this.tableName,Item:this.driver.marshall(this.itemData)};if(this.conditionExpr)s.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")s.ReturnValues=this.returnValuesOption;return s}toUpdateRequest(){let s={TableName:this.tableName,Key:this.driver.marshall(this.keyData)},{expression:a,expressionAttributeNames:l,expressionAttributeValues:c}=this.driver.buildUpdateExpression(this.updateExpressions);if(a)s.UpdateExpression=a,s.ExpressionAttributeNames=l,s.ExpressionAttributeValues=c;if(this.conditionExpr)s.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")s.ReturnValues=this.returnValuesOption;return s}toDeleteRequest(){let s={TableName:this.tableName,Key:this.driver.marshall(this.keyData)};if(this.conditionExpr)s.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")s.ReturnValues=this.returnValuesOption;return s}toGetRequest(){return{TableName:this.tableName,Key:this.driver.marshall(this.keyData)}}async put(){if(!this.client)throw Error("DynamoDB client not provided");let s=this.toPutRequest(),a=await this.client.putItem(s);if(a.Attributes)return this.driver.unmarshall(a.Attributes);return}async update(){if(!this.client)throw Error("DynamoDB client not provided");let s=this.toUpdateRequest(),a=await this.client.updateItem(s);if(a.Attributes)return this.driver.unmarshall(a.Attributes);return}async delete(){if(!this.client)throw Error("DynamoDB client not provided");let s=this.toDeleteRequest(),a=await this.client.deleteItem(s);if(a.Attributes)return this.driver.unmarshall(a.Attributes);return}async get(){if(!this.client)throw Error("DynamoDB client not provided");let s=this.toGetRequest(),a=await this.client.getItem(s);if(a.Item)return this.driver.unmarshall(a.Item);return}}function $n(s){return new D(s)}function xn(s){return new g(s)}function vn(s){let a=u(s.config);return{query:()=>new D(s),item:()=>new g(s),driver:a,registerEntity:(l)=>a.registerEntity(l),buildKey:(l,c)=>a.buildPrimaryKey(l,c)}}class yt{config;entities=new Map;pkAttribute;skAttribute;typeAttribute;constructor(s){this.config=s,this.pkAttribute=s.pkAttribute??"pk",this.skAttribute=s.skAttribute??"sk",this.typeAttribute=s.typeAttribute??"_type";for(let a of s.entities)this.entities.set(a.name,a)}getEntity(s){return this.entities.get(s)}registerEntity(s){this.entities.set(s.name,s)}buildKey(s,a){let l=this.entities.get(s);if(!l)throw Error(`Entity not found: ${s}`);let c=this.interpolatePattern(l.pkPattern,a),f=this.interpolatePattern(l.skPattern,a);return{pk:c,sk:f}}buildGSIKey(s,a,l){let c=this.entities.get(s);if(!c)throw Error(`Entity not found: ${s}`);let f=c.indexes?.find((x)=>x.name===a);if(!f)throw Error(`GSI not found: ${a} for entity ${s}`);let y=this.interpolatePattern(f.pkPattern,l),p=f.skPattern?this.interpolatePattern(f.skPattern,l):void 0;return{pk:y,sk:p}}createItem(s,a){let{pk:l,sk:c}=this.buildKey(s,a),f=this.entities.get(s),y={[this.pkAttribute]:l,[this.skAttribute]:c,[this.typeAttribute]:s,...a};if(f.indexes)for(let p of f.indexes){let x=this.buildGSIKey(s,p.name,a),T=this.config.indexes?.find((E)=>E.name===p.name);if(T){if(y[T.pkAttribute]=x.pk,T.skAttribute&&x.sk)y[T.skAttribute]=x.sk}}return y}parseEntityType(s){if(s[this.typeAttribute])return s[this.typeAttribute];let a=s[this.pkAttribute];if(!a)return;for(let[l,c]of this.entities){let f=c.pkPattern.split("${")[0];if(a.startsWith(f))return l}return}parseItem(s){let a=this.parseEntityType(s);if(!a)return;let{[this.pkAttribute]:l,[this.skAttribute]:c,[this.typeAttribute]:f,...y}=s;return{type:a,data:y}}getEntityPrefix(s){let a=this.entities.get(s);if(!a)throw Error(`Entity not found: ${s}`);return a.pkPattern.split("${")[0]}generateTableDefinition(){let s=[{name:this.pkAttribute,type:"S"},{name:this.skAttribute,type:"S"}],a=[];if(this.config.indexes)for(let l of this.config.indexes){if(!s.find((c)=>c.name===l.pkAttribute))s.push({name:l.pkAttribute,type:"S"});if(l.skAttribute&&!s.find((c)=>c.name===l.skAttribute))s.push({name:l.skAttribute,type:"S"});a.push({indexName:l.name,keySchema:{partitionKey:l.pkAttribute,sortKey:l.skAttribute},projection:{type:"ALL"}})}return{tableName:this.config.tableName,keySchema:{partitionKey:this.pkAttribute,sortKey:this.skAttribute},attributeDefinitions:s,globalSecondaryIndexes:a.length>0?a:void 0,billingMode:"PAY_PER_REQUEST"}}interpolatePattern(s,a){return s.replace(/\$\{(\w+)\}/g,(l,c)=>{if(!(c in a))throw Error(`Missing value for pattern key: ${c}`);return String(a[c])})}}class bt{manager;entityName;options;constructor(s,a,l){this.manager=s,this.entityName=a,this.options=l}async create(s){let a=this.manager.createItem(this.entityName,s),l=new g(this.options).table(this.options.config.tableName).item(a).ifNotExists("pk");if(this.options.client)await l.put();return s}async get(s){let{pk:a,sk:l}=this.manager.buildKey(this.entityName,s),c=new g(this.options).table(this.options.config.tableName).key({pk:a,sk:l});if(!this.options.client)throw Error("DynamoDB client not provided");let f=await c.get();if(!f)return;return this.manager.parseItem(f)?.data}async update(s,a){let{pk:l,sk:c}=this.manager.buildKey(this.entityName,s),f=new g(this.options).table(this.options.config.tableName).key({pk:l,sk:c}).setMany(a).ifExists("pk").returnNew();if(!this.options.client)throw Error("DynamoDB client not provided");let y=await f.update();if(!y)return;return this.manager.parseItem(y)?.data}async delete(s){let{pk:a,sk:l}=this.manager.buildKey(this.entityName,s),c=new g(this.options).table(this.options.config.tableName).key({pk:a,sk:l});if(!this.options.client)throw Error("DynamoDB client not provided");return await c.delete(),!0}query(){return new Tt(this.manager,this.entityName,this.options)}async findAll(){let s=this.manager.typeAttribute??"_type",a=new D(this.options).table(this.options.config.tableName).whereEquals(s,this.entityName);if(!this.options.client)throw Error("DynamoDB client not provided");return(await a.getAll()).map((c)=>this.manager.parseItem(c)).filter((c)=>c!==void 0).map((c)=>c.data)}}class Tt{manager;entityName;options;builder;pkValue;skConditions=[];constructor(s,a,l){this.manager=s,this.entityName=a,this.options=l,this.builder=new D(l).table(l.config.tableName)}wherePartitionKey(s){let{pk:a}=this.manager.buildKey(this.entityName,s);this.pkValue=a;let l=this.manager.pkAttribute??"pk";return this.builder.wherePartitionKey(l,a),this}whereSortKey(s){let{sk:a}=this.manager.buildKey(this.entityName,s),l=this.manager.skAttribute??"sk";return this.builder.whereSortKey(l,a),this}whereSortKeyBeginsWith(s){let a=this.manager.skAttribute??"sk";return this.builder.whereSortKeyBeginsWith(a,s),this}useIndex(s,a){let l=this.manager.buildGSIKey(this.entityName,s,a),c=this.manager.config.indexes?.find((f)=>f.name===s);if(!c)throw Error(`GSI configuration not found: ${s}`);return this.builder.index(s),this.builder.wherePartitionKey(c.pkAttribute,l.pk),this}where(s,a,l){return this.builder.where(s,a,l),this}select(...s){return this.builder.select(...s),this}limit(s){return this.builder.limit(s),this}descending(){return this.builder.descending(),this}async execute(){if(!this.options.client)throw Error("DynamoDB client not provided");return((await this.builder.query()).items??[]).map((a)=>this.manager.parseItem(a)).filter((a)=>a!==void 0).map((a)=>a.data)}async first(){return this.limit(1),(await this.execute())[0]}}function wt(s){return new yt(s)}function St(s,a,l){return new bt(s,a,l)}var kn={simpleEntity:(s,a="id")=>({name:s,pkPattern:`${s.toUpperCase()}#\${${a}}`,skPattern:"METADATA",keyFields:[a]}),oneToMany:(s,a,l="id",c="id")=>({parent:{name:s,pkPattern:`${s.toUpperCase()}#\${${l}}`,skPattern:"METADATA",keyFields:[l]},child:{name:a,pkPattern:`${s.toUpperCase()}#\${${l}}`,skPattern:`${a.toUpperCase()}#\${${c}}`,keyFields:[l,c]}}),manyToMany:(s,a,l="id",c="relatedId")=>({entity:{name:s,pkPattern:`${s.toUpperCase()}#\${${l}}`,skPattern:"METADATA",keyFields:[l]},relation:{name:a,pkPattern:`${s.toUpperCase()}#\${${l}}`,skPattern:`${a.toUpperCase()}#\${${c}}`,keyFields:[l,c],indexes:[{name:"GSI1",pkPattern:`${s.toUpperCase()}#\${${c}}`,skPattern:`${a.toUpperCase()}#\${${l}}`}]}}),hierarchical:(s,a="rootId",l="path")=>({name:s,pkPattern:`ROOT#\${${a}}`,skPattern:`PATH#\${${l}}`,keyFields:[a,l]})};function Dt(s,a){let l={};for(let[c,f]of Object.entries(s))if(f)l[c]=f.replace(/\{([^}]+)\}/g,(y,p)=>a[p]!==void 0?String(a[p]):`{${p}}`);return l}async function Jt(s){return{models:new Map}}function Cn(s){return s}function Rn(s){return s}function An(s){return s}function Nn(s){return s}class Et{config;driver;singleTableManager;models=new Map;queryBuilderOptions;constructor(s){this.config={pkAttribute:"pk",skAttribute:"sk",entityTypeAttribute:"_et",keyDelimiter:"#",...s};let a={region:s.region,endpoint:s.endpoint,credentials:s.credentials,tableName:s.tableName};this.driver=u(a);let l={tableName:s.tableName,pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,indexes:this.buildGSIConfig(),entities:[]};this.singleTableManager=wt(l),this.queryBuilderOptions={config:a}}setClient(s){return this.queryBuilderOptions.client=s,this}async discoverModels(){if(!this.config.modelsPath)throw Error("modelsPath must be configured to use discoverModels()");let s=await Jt({queryBuilder:{modelsPath:this.config.modelsPath},singleTable:{pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,delimiter:this.config.keyDelimiter}}),a=[];for(let[,l]of s.models)this.registerParsedModel(l),a.push(l);return a}registerModel(s){let a=this.parseWithTooling(s);return this.registerParsedModel(a)}registerParsedModel(s){this.models.set(s.name,s);let a=this.toSingleTableEntity(s);this.singleTableManager.registerEntity(a);let l=this.toEntityMapping(s);return this.driver.registerEntity(l),s}registerModels(s){return s.map((a)=>this.registerModel(a))}getModel(s){return this.models.get(s)}getAllModels(){return Array.from(this.models.values())}repository(s){if(!this.models.get(s))throw Error(`Model not found: ${s}`);return St(this.singleTableManager,s,this.queryBuilderOptions)}query(s){if(!this.models.get(s))throw Error(`Model not found: ${s}`);return new D(this.queryBuilderOptions).table(this.config.tableName).entity(s)}item(s){if(!this.models.get(s))throw Error(`Model not found: ${s}`);return new g(this.queryBuilderOptions).table(this.config.tableName)}buildKey(s,a){let l=this.models.get(s);if(!l)throw Error(`Model not found: ${s}`);let c=Dt(l.keyPatterns,a);return{pk:c.pk,sk:c.sk}}createItem(s,a){let l=this.models.get(s);if(!l)throw Error(`Model not found: ${s}`);let c=Dt(l.keyPatterns,a),{pk:f,sk:y}=c,p={[this.config.pkAttribute]:f,[this.config.skAttribute]:y,[this.config.entityTypeAttribute]:l.name,...a};if(l.hasTimestamps){let x=new Date().toISOString();if(!p.createdAt)p.createdAt=x;p.updatedAt=x}if(l.hasVersioning){if(!p._v)p._v=1}return p}parseItem(s){let a=s[this.config.entityTypeAttribute];if(!a)return;let{[this.config.pkAttribute]:l,[this.config.skAttribute]:c,[this.config.entityTypeAttribute]:f,...y}=s;return{type:a,data:y}}getDriver(){return this.driver}getSingleTableManager(){return this.singleTableManager}generateTableDefinition(){return this.singleTableManager.generateTableDefinition()}generateAccessPatterns(s){let a=this.models.get(s);if(!a)throw Error(`Model not found: ${s}`);return a.accessPatterns}parseWithTooling(s){let a=s.name.toUpperCase(),l=s.primaryKey??"id",c=this.config.keyDelimiter,f=this.parseAttributes(s),y=this.parseRelationships(s,l),p={pk:`${a}${c}{${l}}`,sk:`${a}${c}{${l}}`,...this.deriveGSIKeyPatterns(a,l,c,y)},x=this.deriveAccessPatterns(s.name,a,l,y);return{name:s.name,entityType:a,primaryKey:l,attributes:f,relationships:y,keyPatterns:p,accessPatterns:x,traits:s.traits??{},hasTimestamps:s.traits?.useTimestamps??!1,hasSoftDeletes:s.traits?.useSoftDeletes??!1,hasUuid:s.traits?.useUuid??!1,hasTtl:s.traits?.useTtl??!1,hasVersioning:s.traits?.useVersioning??!1,original:s}}parseAttributes(s){let a=[];if(a.push({name:s.primaryKey??"id",fillable:!1,required:!0,nullable:!1,unique:!0,hidden:!1,dynamoDbType:"S"}),s.attributes)for(let[l,c]of Object.entries(s.attributes))a.push({name:l,fillable:c.fillable??!0,required:c.required??!1,nullable:c.nullable??!0,unique:c.unique??!1,hidden:c.hidden??!1,defaultValue:c.default,cast:c.cast,dynamoDbType:this.inferDynamoDBType(c)});if(s.traits?.useTimestamps)a.push({name:"createdAt",fillable:!1,required:!0,nullable:!1,unique:!1,hidden:!1,dynamoDbType:"S"},{name:"updatedAt",fillable:!1,required:!0,nullable:!1,unique:!1,hidden:!1,dynamoDbType:"S"});if(s.traits?.useSoftDeletes)a.push({name:"deletedAt",fillable:!1,required:!1,nullable:!0,unique:!1,hidden:!1,dynamoDbType:"S"});return a}inferDynamoDBType(s){if(s.cast){let a=s.cast.toLowerCase();if(["integer","int","float","double","decimal","number"].includes(a))return"N";if(["boolean","bool"].includes(a))return"BOOL";if(["array","list"].includes(a))return"L";if(["object","json","map"].includes(a))return"M"}if(s.validation?.rule){let a=String(s.validation.rule);if(a.includes("integer")||a.includes("numeric")||a.includes("number"))return"N";if(a.includes("boolean"))return"BOOL";if(a.includes("array"))return"L";if(a.includes("object"))return"M"}return"S"}parseRelationships(s,a){let l=[];if(s.hasOne)for(let c of s.hasOne)l.push({type:"hasOne",relatedModel:c,foreignKey:`${s.name.toLowerCase()}Id`,localKey:a,requiresGsi:!0});if(s.hasMany)for(let c of s.hasMany)l.push({type:"hasMany",relatedModel:c,foreignKey:`${s.name.toLowerCase()}Id`,localKey:a,requiresGsi:!1});if(s.belongsTo)for(let c of s.belongsTo)l.push({type:"belongsTo",relatedModel:c,foreignKey:`${c.toLowerCase()}Id`,localKey:a,requiresGsi:!0});if(s.belongsToMany){let c=Array.isArray(s.belongsToMany)?s.belongsToMany:Object.values(s.belongsToMany);for(let f of c){let y=typeof f==="string"?f:f?.model;if(!y)continue;let p=[s.name,y].sort();l.push({type:"belongsToMany",relatedModel:y,foreignKey:`${s.name.toLowerCase()}Id`,localKey:a,pivotEntity:p.join(""),requiresGsi:!0})}}return l}deriveGSIKeyPatterns(s,a,l,c){let f={},y=1;for(let p of c)if(p.requiresGsi&&y<=5)f[`gsi${y}pk`]=`${p.relatedModel.toUpperCase()}${l}{${p.foreignKey}}`,f[`gsi${y}sk`]=`${s}${l}{${a}}`,p.gsiIndex=y,y++;return f}deriveAccessPatterns(s,a,l,c){let f=[];f.push({name:`Get ${s} by ID`,description:`Retrieve a single ${s} by its primary key`,entityType:a,operation:"get",index:"main",keyCondition:"pk = :pk AND sk = :sk",examplePk:`${a}#123`,exampleSk:`${a}#123`,efficient:!0}),f.push({name:`List all ${s}s`,description:`Scan all ${s} entities`,entityType:a,operation:"scan",index:"scan",keyCondition:"_et = :entityType",examplePk:a,efficient:!1});for(let y of c){if(y.type==="hasMany")f.push({name:`Get ${y.relatedModel}s for ${s}`,description:`Query ${y.relatedModel}s related to a ${s}`,entityType:a,operation:"query",index:"main",keyCondition:"pk = :pk AND begins_with(sk, :skPrefix)",examplePk:`${a}#123`,exampleSk:`${y.relatedModel.toUpperCase()}#`,efficient:!0});if(y.gsiIndex){let p=`GSI${y.gsiIndex}`;f.push({name:`Get ${s}s by ${y.relatedModel}`,description:`Query ${s}s by their related ${y.relatedModel}`,entityType:a,operation:"query",index:p,keyCondition:`gsi${y.gsiIndex}pk = :pk`,examplePk:`${y.relatedModel.toUpperCase()}#123`,efficient:!0})}}return f}toSingleTableEntity(s){let a=this.extractKeyFields(s.keyPatterns.pk);return{name:s.name,pkPattern:s.keyPatterns.pk,skPattern:s.keyPatterns.sk,keyFields:a,indexes:this.extractGSIPatterns(s.keyPatterns)}}extractKeyFields(s){let a=s.match(/\{([^}]+)\}/g);if(!a)return[];return a.map((l)=>l.slice(1,-1))}extractGSIPatterns(s){let a=[];for(let l=1;l<=5;l++){let c=`gsi${l}pk`,f=`gsi${l}sk`;if(s[c])a.push({name:`GSI${l}`,pkPattern:s[c],skPattern:s[f]})}return a.length>0?a:void 0}toEntityMapping(s){return{entityType:s.name,pkPattern:s.keyPatterns.pk,skPattern:s.keyPatterns.sk}}buildGSIConfig(){let s=this.config.gsiConfig??{},a=[];if(s.gsi1pk)a.push({name:"GSI1",pkAttribute:s.gsi1pk,skAttribute:s.gsi1sk});if(s.gsi2pk)a.push({name:"GSI2",pkAttribute:s.gsi2pk,skAttribute:s.gsi2sk});if(s.gsi3pk)a.push({name:"GSI3",pkAttribute:s.gsi3pk,skAttribute:s.gsi3sk});return a}}function Mn(s){return new Et(s)}function On(s){return s.accessPatterns}function Pn(s,a="#"){let l=s.name.toUpperCase(),c=s.primaryKey??"id";return{name:s.name,pkPattern:`${l}${a}\${${c}}`,skPattern:`${l}${a}\${${c}}`}}function Re(s){let a={};for(let l of Object.keys(s)){let c=s[l],f=c.definition??c.getDefinition?.()??c,y=w(f),p=f.attributes??{},x={};for(let T of Object.keys(p))x[T]=void 0;a[y]={columns:x,primaryKey:f.primaryKey??"id"}}return a}import{readdirSync as Xi}from"fs";import{basename as Mr,extname as Ar,isAbsolute as Ji,join as wr}from"path";import Zi from"process";var es=new Set([".ts",".mts",".cts",".js",".mjs",".cjs"]);function ts(s){let a=Ar(s);if(!es.has(a))return!1;let l=Mr(s,a);if(l.startsWith("_")||l==="index")return!1;return!l.endsWith(".d")}function ns(s){if(!s||typeof s!=="object")return!1;let a=s;return typeof a.name==="string"||typeof a.table==="string"}function Cr(s){let a=[],l=Xi(s,{withFileTypes:!0}).sort((c,f)=>c.name.localeCompare(f.name));for(let c of l){let f=wr(s,c.name);if(c.isDirectory()){a.push(...Cr(f));continue}if(ts(c.name))a.push(f)}return a}async function d(s){let a=s.cwd??Zi.cwd(),l=Ji(s.modelsDir)?s.modelsDir:wr(a,s.modelsDir),c={};for(let f of Cr(l)){let y=`?t=${Date.now()}-${Math.random().toString(36).slice(2)}`,p=await import(`${f}${y}`),x=p.default??p,T=x.definition??x.getDefinition?.()??x;if(!ns(T))continue;let E=T.name??Mr(f,Ar(f));c[E]={...T,name:E}}return c}function $t(s){let a={},l={},c={},f={},y={},p={};for(let x of Object.keys(s)){let T=s[x],E=T.definition??T.getDefinition?.()??T,C=w(E);a[x]=C,l[C]=x,c[C]=E.primaryKey??"id";let v=[];for(let[Pe,Be]of Object.entries(E.attributes??{}))if(/^(?:datetime|timestamp|timestamptz|date)$/i.test(String(Be?.type??"")))v.push(Pe);let k=E.traits??{};if(k.useTimestamps??k.timestampable)v.push("created_at","updated_at");if(v.length>0)p[C]=[...new Set(v)];let L=(Pe)=>{if(!Pe)return{};let Be={};if(Array.isArray(Pe)){for(let Ve of Pe){let tt=Ie(Ve);if(tt)Be[tt.model]=tt.model}return Be}if(typeof Pe==="object"){for(let[Ve,tt]of Object.entries(Pe)){let Ze=Ie(tt);if(Ze)Be[Ve]=Ze.model}return Be}return{}},B=(Pe)=>{if(!Pe)return{};if(Array.isArray(Pe)){let Be={};for(let Ve of Pe)if(typeof Ve==="string")Be[Ve]=Ve;else if(Ve&&typeof Ve==="object"&&typeof Ve.model==="string")Be[Ve.model]=Ve;return Be}return Pe},X=(Pe)=>{if(!Pe)return{};return Pe};if(f[C]={hasOne:L(E.hasOne),hasMany:L(E.hasMany),belongsTo:L(E.belongsTo),belongsToMany:B(E.belongsToMany),hasOneThrough:X(E.hasOneThrough),hasManyThrough:X(E.hasManyThrough),morphOne:L(E.morphOne),morphMany:L(E.morphMany),morphTo:E.morphTo,morphToMany:L(E.morphToMany),morphedByMany:L(E.morphedByMany)},E.scopes&&typeof E.scopes==="object"){y[C]={};for(let Pe of Object.keys(E.scopes)){let Be=E.scopes[Pe];if(typeof Be==="function")y[C][Pe]=Be}}}return{modelToTable:a,tableToModel:l,primaryKeys:c,relations:f,scopes:y,models:s,temporalColumns:p}}import{existsSync as Qn,mkdirSync as rs,readdirSync as is,readFileSync as ss,writeFileSync as as}from"fs";import{dirname as Nr,join as gn}from"path";import Or from"process";function Mt(s){if(e.verbose)console.log(s)}function Kt(s){return s.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").toLowerCase()}function Un(s){return m(e.relations?.singularizeStrategy)(s)}var pn=0,rn=0,fn=0,Vn=!0,yn=[],sn=null;function xt(){return[...yn]}function os(s){let a=s;while(a!==Nr(a)){if(Qn(gn(a,"package.json")))return a;a=Nr(a)}return Or.cwd()}function ls(){let s=os(Or.cwd()),a=Ot(s,e.migrationDir);if(!Qn(a))rs(a,{recursive:!0}),Mt(`-- Created SQL directory: ${a}`);return a}var vt="-- qb:generated";function kt(s){return s.trimStart().startsWith(vt)}function Ct(s){return s.split(`
378
+ `,[R.table])).map((K)=>({name:K.column_name,type:K.data_type.toLowerCase()}));let _=C.map((k)=>k.name),v=R.columns.map((k)=>k.name);for(let k of R.columns)if(!_.includes(k.name))l.push({type:"missing_column",severity:"error",table:R.table,column:k.name,expected:k.type,message:`Column '${R.table}.${k.name}' defined in model but not found in database`});for(let k of C)if(!v.includes(k.name))l.push({type:"extra_column",severity:"warning",table:R.table,column:k.name,actual:k.type,message:`Column '${R.table}.${k.name}' exists in database but not defined in model`});for(let k of R.columns){let K=C.find((Z)=>Z.name===k.name);if(K){let Z=(Ve)=>Ve.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim(),_e=Z(k.type),Be=Z(K.type);if(_e!==Be)l.push({type:"type_mismatch",severity:"warning",table:R.table,column:k.name,expected:k.type,actual:K.type,message:`Column '${R.table}.${k.name}' type mismatch: expected '${k.type}', found '${K.type}'`})}}}let T=l.filter((R)=>R.severity==="error").length===0;if(T&&l.length===0)console.log("\u2713 Schema is valid - no issues found"),console.log();else{console.log(`-- Found ${l.length} issue(s)`),console.log();let R=l.filter((_)=>_.severity==="error"),C=l.filter((_)=>_.severity==="warning");if(R.length>0){console.log(`\u2717 Errors (${R.length}):`);for(let _ of R)console.log(` - ${_.message}`);console.log()}if(C.length>0){console.log(`\u26A0 Warnings (${C.length}):`);for(let _ of C)console.log(` - ${_.message}`);console.log()}if(!T)console.log("-- Recommendation: Run migrations to sync the database schema"),console.log("-- qb migrate ./app/Models --apply")}return{valid:T,issues:l}}catch(c){throw console.error("-- Schema validation failed:",c),c}}async function Ce(s){return z(s)}async function Re(s={}){let a=Number(s.attempts||10),l=Number(s.delay||100),c=i();try{return await c.waitForReady({attempts:a,delayMs:l}),console.log("READY"),!0}catch{throw console.error("NOT READY"),Error("Database not ready")}}class D{driver;client;tableName;indexName;entityType;keyConditions=[];filterConditions=[];projectionAttrs=[];limitValue;scanForward=!0;consistentReadValue=!1;startKey;constructor(s){this.driver=u(s.config),this.client=s.client,this.tableName=s.config.tableName??""}table(s){return this.tableName=s,this}index(s){return this.indexName=s,this}entity(s){return this.entityType=s,this}whereKey(s,a,l){return this.keyConditions.push({attribute:s,operator:a,value:l}),this}wherePartitionKey(s,a){return this.whereKey(s,"=",a)}whereSortKey(s,a){return this.whereKey(s,"=",a)}whereSortKeyBeginsWith(s,a){return this.keyConditions.push({attribute:s,operator:"begins_with",value:a}),this}whereSortKeyBetween(s,a,l){return this.keyConditions.push({attribute:s,operator:"BETWEEN",values:[a,l]}),this}where(s,a,l){return this.filterConditions.push({attribute:s,operator:a,value:l}),this}whereEquals(s,a){return this.where(s,"=",a)}whereLessThan(s,a){return this.where(s,"<",a)}whereLessThanOrEqual(s,a){return this.where(s,"<=",a)}whereGreaterThan(s,a){return this.where(s,">",a)}whereGreaterThanOrEqual(s,a){return this.where(s,">=",a)}whereBetween(s,a,l){return this.filterConditions.push({attribute:s,operator:"BETWEEN",values:[a,l]}),this}whereBeginsWith(s,a){return this.filterConditions.push({attribute:s,operator:"begins_with",value:a}),this}whereContains(s,a){return this.where(s,"contains",a)}whereExists(s){return this.where(s,"attribute_exists")}whereNotExists(s){return this.where(s,"attribute_not_exists")}whereIn(s,a){return this.filterConditions.push({attribute:s,operator:"IN",values:a}),this}select(...s){return this.projectionAttrs.push(...s),this}limit(s){return this.limitValue=s,this}ascending(){return this.scanForward=!0,this}descending(){return this.scanForward=!1,this}consistentRead(s=!0){return this.consistentReadValue=s,this}startFrom(s){return this.startKey=s,this}buildQueryParams(){return this.driver.buildQueryParams({tableName:this.tableName,indexName:this.indexName,keyConditions:this.keyConditions,filterConditions:this.filterConditions.length>0?this.filterConditions:void 0,projectionAttributes:this.projectionAttrs.length>0?this.projectionAttrs:void 0,limit:this.limitValue,scanIndexForward:this.scanForward,exclusiveStartKey:this.startKey,consistentRead:this.consistentReadValue})}buildScanParams(){return this.driver.buildScanParams({tableName:this.tableName,indexName:this.indexName,filterConditions:this.filterConditions.length>0?this.filterConditions:void 0,projectionAttributes:this.projectionAttrs.length>0?this.projectionAttrs:void 0,limit:this.limitValue,exclusiveStartKey:this.startKey,consistentRead:this.consistentReadValue})}toQueryRequest(){let s=this.buildQueryParams(),a={TableName:s.tableName,ExpressionAttributeNames:{},ExpressionAttributeValues:{}};if(s.indexName)a.IndexName=s.indexName;let l=0;if(s.keyConditions.length>0){let c=[];for(let f of s.keyConditions){let y=`#key${l}`;if(a.ExpressionAttributeNames[y]=f.attribute,f.operator==="begins_with"){let p=`:keyval${l}`;a.ExpressionAttributeValues[p]=this.driver.marshall({v:f.value}).v,c.push(`begins_with(${y}, ${p})`)}else if(f.operator==="BETWEEN"){let p=`:keyval${l}a`,x=`:keyval${l}b`;a.ExpressionAttributeValues[p]=this.driver.marshall({v:f.values?.[0]}).v,a.ExpressionAttributeValues[x]=this.driver.marshall({v:f.values?.[1]}).v,c.push(`${y} BETWEEN ${p} AND ${x}`)}else{let p=`:keyval${l}`;a.ExpressionAttributeValues[p]=this.driver.marshall({v:f.value}).v,c.push(`${y} ${f.operator} ${p}`)}l++}a.KeyConditionExpression=c.join(" AND ")}if(s.filterConditions&&s.filterConditions.length>0){let c=[];for(let f of s.filterConditions){let y=`#flt${l}`;if(a.ExpressionAttributeNames[y]=f.attribute,f.operator==="attribute_exists")c.push(`attribute_exists(${y})`);else if(f.operator==="attribute_not_exists")c.push(`attribute_not_exists(${y})`);else if(f.operator==="begins_with"||f.operator==="contains"){let p=`:fltval${l}`;a.ExpressionAttributeValues[p]=this.driver.marshall({v:f.value}).v,c.push(`${f.operator}(${y}, ${p})`)}else if(f.operator==="BETWEEN"){let p=`:fltval${l}a`,x=`:fltval${l}b`;a.ExpressionAttributeValues[p]=this.driver.marshall({v:f.values?.[0]}).v,a.ExpressionAttributeValues[x]=this.driver.marshall({v:f.values?.[1]}).v,c.push(`${y} BETWEEN ${p} AND ${x}`)}else if(f.operator==="IN"){let p=(f.values??[]).map((x,T)=>`:fltval${l}_${T}`);f.values?.forEach((x,T)=>{a.ExpressionAttributeValues[`:fltval${l}_${T}`]=this.driver.marshall({v:x}).v}),c.push(`${y} IN (${p.join(", ")})`)}else{let p=`:fltval${l}`;a.ExpressionAttributeValues[p]=this.driver.marshall({v:f.value}).v,c.push(`${y} ${f.operator} ${p}`)}l++}a.FilterExpression=c.join(" AND ")}if(s.projectionAttributes&&s.projectionAttributes.length>0){let c=[];for(let f of s.projectionAttributes){let y=`#proj${l}`;a.ExpressionAttributeNames[y]=f,c.push(y),l++}a.ProjectionExpression=c.join(", ")}if(s.limit!==void 0)a.Limit=s.limit;if(s.scanIndexForward!==void 0)a.ScanIndexForward=s.scanIndexForward;if(s.exclusiveStartKey)a.ExclusiveStartKey=this.driver.marshall(s.exclusiveStartKey);if(s.consistentRead)a.ConsistentRead=s.consistentRead;if(Object.keys(a.ExpressionAttributeNames).length===0)delete a.ExpressionAttributeNames;if(Object.keys(a.ExpressionAttributeValues).length===0)delete a.ExpressionAttributeValues;return a}toScanRequest(){let s=this.buildScanParams(),a={TableName:s.tableName};if(s.indexName)a.IndexName=s.indexName;if(s.filterConditions&&s.filterConditions.length>0){let{expression:l,expressionAttributeNames:c,expressionAttributeValues:f}=this.driver.buildFilterExpression(s.filterConditions);a.FilterExpression=l,a.ExpressionAttributeNames=c,a.ExpressionAttributeValues=f}if(s.projectionAttributes&&s.projectionAttributes.length>0){let{expression:l,expressionAttributeNames:c}=this.driver.buildProjectionExpression(s.projectionAttributes);a.ProjectionExpression=l,a.ExpressionAttributeNames={...a.ExpressionAttributeNames,...c}}if(s.limit!==void 0)a.Limit=s.limit;if(s.exclusiveStartKey)a.ExclusiveStartKey=this.driver.marshall(s.exclusiveStartKey);if(s.consistentRead)a.ConsistentRead=s.consistentRead;return a}async query(){if(!this.client)throw Error("DynamoDB client not provided. Pass a client in options or use toQueryRequest() to get the request params.");let s=this.toQueryRequest(),a=await this.client.query(s);return{items:a.Items?.map((l)=>this.driver.unmarshall(l)),count:a.Count,scannedCount:a.ScannedCount,lastEvaluatedKey:a.LastEvaluatedKey?this.driver.unmarshall(a.LastEvaluatedKey):void 0,consumedCapacity:a.ConsumedCapacity}}async scan(){if(!this.client)throw Error("DynamoDB client not provided. Pass a client in options or use toScanRequest() to get the request params.");let s=this.toScanRequest(),a=await this.client.scan(s);return{items:a.Items?.map((l)=>this.driver.unmarshall(l)),count:a.Count,scannedCount:a.ScannedCount,lastEvaluatedKey:a.LastEvaluatedKey?this.driver.unmarshall(a.LastEvaluatedKey):void 0,consumedCapacity:a.ConsumedCapacity}}async getAll(){let s=[],a;do{if(a)this.startFrom(a);let l=this.keyConditions.length>0?await this.query():await this.scan();if(l.items)s.push(...l.items);a=l.lastEvaluatedKey}while(a);return s}async first(){return this.limit(1),(this.keyConditions.length>0?await this.query():await this.scan()).items?.[0]}async count(){if(!this.client)throw Error("DynamoDB client not provided");let s=this.keyConditions.length>0?this.toQueryRequest():this.toScanRequest();return s.Select="COUNT",(this.keyConditions.length>0?await this.client.query(s):await this.client.scan(s)).Count??0}reset(){return this.indexName=void 0,this.entityType=void 0,this.keyConditions=[],this.filterConditions=[],this.projectionAttrs=[],this.limitValue=void 0,this.scanForward=!0,this.consistentReadValue=!1,this.startKey=void 0,this}}class g{driver;client;tableName;itemData={};keyData={};updateExpressions={};conditionExpr;returnValuesOption="NONE";constructor(s){this.driver=u(s.config),this.client=s.client,this.tableName=s.config.tableName??""}table(s){return this.tableName=s,this}key(s){return this.keyData=s,this}item(s){return this.itemData=s,this}set(s,a){if(!this.updateExpressions.set)this.updateExpressions.set={};return this.updateExpressions.set[s]=a,this}setMany(s){if(!this.updateExpressions.set)this.updateExpressions.set={};return Object.assign(this.updateExpressions.set,s),this}remove(s){if(!this.updateExpressions.remove)this.updateExpressions.remove=[];return this.updateExpressions.remove.push(s),this}add(s,a){if(!this.updateExpressions.add)this.updateExpressions.add={};return this.updateExpressions.add[s]=a,this}deleteFromSet(s,a){if(!this.updateExpressions.delete)this.updateExpressions.delete={};return this.updateExpressions.delete[s]=a,this}condition(s){return this.conditionExpr=s,this}ifNotExists(s="pk"){return this.conditionExpr=`attribute_not_exists(${s})`,this}ifExists(s="pk"){return this.conditionExpr=`attribute_exists(${s})`,this}returnOld(){return this.returnValuesOption="ALL_OLD",this}returnNew(){return this.returnValuesOption="ALL_NEW",this}toPutRequest(){let s={TableName:this.tableName,Item:this.driver.marshall(this.itemData)};if(this.conditionExpr)s.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")s.ReturnValues=this.returnValuesOption;return s}toUpdateRequest(){let s={TableName:this.tableName,Key:this.driver.marshall(this.keyData)},{expression:a,expressionAttributeNames:l,expressionAttributeValues:c}=this.driver.buildUpdateExpression(this.updateExpressions);if(a)s.UpdateExpression=a,s.ExpressionAttributeNames=l,s.ExpressionAttributeValues=c;if(this.conditionExpr)s.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")s.ReturnValues=this.returnValuesOption;return s}toDeleteRequest(){let s={TableName:this.tableName,Key:this.driver.marshall(this.keyData)};if(this.conditionExpr)s.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")s.ReturnValues=this.returnValuesOption;return s}toGetRequest(){return{TableName:this.tableName,Key:this.driver.marshall(this.keyData)}}async put(){if(!this.client)throw Error("DynamoDB client not provided");let s=this.toPutRequest(),a=await this.client.putItem(s);if(a.Attributes)return this.driver.unmarshall(a.Attributes);return}async update(){if(!this.client)throw Error("DynamoDB client not provided");let s=this.toUpdateRequest(),a=await this.client.updateItem(s);if(a.Attributes)return this.driver.unmarshall(a.Attributes);return}async delete(){if(!this.client)throw Error("DynamoDB client not provided");let s=this.toDeleteRequest(),a=await this.client.deleteItem(s);if(a.Attributes)return this.driver.unmarshall(a.Attributes);return}async get(){if(!this.client)throw Error("DynamoDB client not provided");let s=this.toGetRequest(),a=await this.client.getItem(s);if(a.Item)return this.driver.unmarshall(a.Item);return}}function $n(s){return new D(s)}function xn(s){return new g(s)}function vn(s){let a=u(s.config);return{query:()=>new D(s),item:()=>new g(s),driver:a,registerEntity:(l)=>a.registerEntity(l),buildKey:(l,c)=>a.buildPrimaryKey(l,c)}}class yt{config;entities=new Map;pkAttribute;skAttribute;typeAttribute;constructor(s){this.config=s,this.pkAttribute=s.pkAttribute??"pk",this.skAttribute=s.skAttribute??"sk",this.typeAttribute=s.typeAttribute??"_type";for(let a of s.entities)this.entities.set(a.name,a)}getEntity(s){return this.entities.get(s)}registerEntity(s){this.entities.set(s.name,s)}buildKey(s,a){let l=this.entities.get(s);if(!l)throw Error(`Entity not found: ${s}`);let c=this.interpolatePattern(l.pkPattern,a),f=this.interpolatePattern(l.skPattern,a);return{pk:c,sk:f}}buildGSIKey(s,a,l){let c=this.entities.get(s);if(!c)throw Error(`Entity not found: ${s}`);let f=c.indexes?.find((x)=>x.name===a);if(!f)throw Error(`GSI not found: ${a} for entity ${s}`);let y=this.interpolatePattern(f.pkPattern,l),p=f.skPattern?this.interpolatePattern(f.skPattern,l):void 0;return{pk:y,sk:p}}createItem(s,a){let{pk:l,sk:c}=this.buildKey(s,a),f=this.entities.get(s),y={[this.pkAttribute]:l,[this.skAttribute]:c,[this.typeAttribute]:s,...a};if(f.indexes)for(let p of f.indexes){let x=this.buildGSIKey(s,p.name,a),T=this.config.indexes?.find((R)=>R.name===p.name);if(T){if(y[T.pkAttribute]=x.pk,T.skAttribute&&x.sk)y[T.skAttribute]=x.sk}}return y}parseEntityType(s){if(s[this.typeAttribute])return s[this.typeAttribute];let a=s[this.pkAttribute];if(!a)return;for(let[l,c]of this.entities){let f=c.pkPattern.split("${")[0];if(a.startsWith(f))return l}return}parseItem(s){let a=this.parseEntityType(s);if(!a)return;let{[this.pkAttribute]:l,[this.skAttribute]:c,[this.typeAttribute]:f,...y}=s;return{type:a,data:y}}getEntityPrefix(s){let a=this.entities.get(s);if(!a)throw Error(`Entity not found: ${s}`);return a.pkPattern.split("${")[0]}generateTableDefinition(){let s=[{name:this.pkAttribute,type:"S"},{name:this.skAttribute,type:"S"}],a=[];if(this.config.indexes)for(let l of this.config.indexes){if(!s.find((c)=>c.name===l.pkAttribute))s.push({name:l.pkAttribute,type:"S"});if(l.skAttribute&&!s.find((c)=>c.name===l.skAttribute))s.push({name:l.skAttribute,type:"S"});a.push({indexName:l.name,keySchema:{partitionKey:l.pkAttribute,sortKey:l.skAttribute},projection:{type:"ALL"}})}return{tableName:this.config.tableName,keySchema:{partitionKey:this.pkAttribute,sortKey:this.skAttribute},attributeDefinitions:s,globalSecondaryIndexes:a.length>0?a:void 0,billingMode:"PAY_PER_REQUEST"}}interpolatePattern(s,a){return s.replace(/\$\{(\w+)\}/g,(l,c)=>{if(!(c in a))throw Error(`Missing value for pattern key: ${c}`);return String(a[c])})}}class bt{manager;entityName;options;constructor(s,a,l){this.manager=s,this.entityName=a,this.options=l}async create(s){let a=this.manager.createItem(this.entityName,s),l=new g(this.options).table(this.options.config.tableName).item(a).ifNotExists("pk");if(this.options.client)await l.put();return s}async get(s){let{pk:a,sk:l}=this.manager.buildKey(this.entityName,s),c=new g(this.options).table(this.options.config.tableName).key({pk:a,sk:l});if(!this.options.client)throw Error("DynamoDB client not provided");let f=await c.get();if(!f)return;return this.manager.parseItem(f)?.data}async update(s,a){let{pk:l,sk:c}=this.manager.buildKey(this.entityName,s),f=new g(this.options).table(this.options.config.tableName).key({pk:l,sk:c}).setMany(a).ifExists("pk").returnNew();if(!this.options.client)throw Error("DynamoDB client not provided");let y=await f.update();if(!y)return;return this.manager.parseItem(y)?.data}async delete(s){let{pk:a,sk:l}=this.manager.buildKey(this.entityName,s),c=new g(this.options).table(this.options.config.tableName).key({pk:a,sk:l});if(!this.options.client)throw Error("DynamoDB client not provided");return await c.delete(),!0}query(){return new Tt(this.manager,this.entityName,this.options)}async findAll(){let s=this.manager.typeAttribute??"_type",a=new D(this.options).table(this.options.config.tableName).whereEquals(s,this.entityName);if(!this.options.client)throw Error("DynamoDB client not provided");return(await a.getAll()).map((c)=>this.manager.parseItem(c)).filter((c)=>c!==void 0).map((c)=>c.data)}}class Tt{manager;entityName;options;builder;pkValue;skConditions=[];constructor(s,a,l){this.manager=s,this.entityName=a,this.options=l,this.builder=new D(l).table(l.config.tableName)}wherePartitionKey(s){let{pk:a}=this.manager.buildKey(this.entityName,s);this.pkValue=a;let l=this.manager.pkAttribute??"pk";return this.builder.wherePartitionKey(l,a),this}whereSortKey(s){let{sk:a}=this.manager.buildKey(this.entityName,s),l=this.manager.skAttribute??"sk";return this.builder.whereSortKey(l,a),this}whereSortKeyBeginsWith(s){let a=this.manager.skAttribute??"sk";return this.builder.whereSortKeyBeginsWith(a,s),this}useIndex(s,a){let l=this.manager.buildGSIKey(this.entityName,s,a),c=this.manager.config.indexes?.find((f)=>f.name===s);if(!c)throw Error(`GSI configuration not found: ${s}`);return this.builder.index(s),this.builder.wherePartitionKey(c.pkAttribute,l.pk),this}where(s,a,l){return this.builder.where(s,a,l),this}select(...s){return this.builder.select(...s),this}limit(s){return this.builder.limit(s),this}descending(){return this.builder.descending(),this}async execute(){if(!this.options.client)throw Error("DynamoDB client not provided");return((await this.builder.query()).items??[]).map((a)=>this.manager.parseItem(a)).filter((a)=>a!==void 0).map((a)=>a.data)}async first(){return this.limit(1),(await this.execute())[0]}}function wt(s){return new yt(s)}function St(s,a,l){return new bt(s,a,l)}var kn={simpleEntity:(s,a="id")=>({name:s,pkPattern:`${s.toUpperCase()}#\${${a}}`,skPattern:"METADATA",keyFields:[a]}),oneToMany:(s,a,l="id",c="id")=>({parent:{name:s,pkPattern:`${s.toUpperCase()}#\${${l}}`,skPattern:"METADATA",keyFields:[l]},child:{name:a,pkPattern:`${s.toUpperCase()}#\${${l}}`,skPattern:`${a.toUpperCase()}#\${${c}}`,keyFields:[l,c]}}),manyToMany:(s,a,l="id",c="relatedId")=>({entity:{name:s,pkPattern:`${s.toUpperCase()}#\${${l}}`,skPattern:"METADATA",keyFields:[l]},relation:{name:a,pkPattern:`${s.toUpperCase()}#\${${l}}`,skPattern:`${a.toUpperCase()}#\${${c}}`,keyFields:[l,c],indexes:[{name:"GSI1",pkPattern:`${s.toUpperCase()}#\${${c}}`,skPattern:`${a.toUpperCase()}#\${${l}}`}]}}),hierarchical:(s,a="rootId",l="path")=>({name:s,pkPattern:`ROOT#\${${a}}`,skPattern:`PATH#\${${l}}`,keyFields:[a,l]})};function Dt(s,a){let l={};for(let[c,f]of Object.entries(s))if(f)l[c]=f.replace(/\{([^}]+)\}/g,(y,p)=>a[p]!==void 0?String(a[p]):`{${p}}`);return l}async function Jt(s){return{models:new Map}}function Cn(s){return s}function Rn(s){return s}function An(s){return s}function Nn(s){return s}class Et{config;driver;singleTableManager;models=new Map;queryBuilderOptions;constructor(s){this.config={pkAttribute:"pk",skAttribute:"sk",entityTypeAttribute:"_et",keyDelimiter:"#",...s};let a={region:s.region,endpoint:s.endpoint,credentials:s.credentials,tableName:s.tableName};this.driver=u(a);let l={tableName:s.tableName,pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,indexes:this.buildGSIConfig(),entities:[]};this.singleTableManager=wt(l),this.queryBuilderOptions={config:a}}setClient(s){return this.queryBuilderOptions.client=s,this}async discoverModels(){if(!this.config.modelsPath)throw Error("modelsPath must be configured to use discoverModels()");let s=await Jt({queryBuilder:{modelsPath:this.config.modelsPath},singleTable:{pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,delimiter:this.config.keyDelimiter}}),a=[];for(let[,l]of s.models)this.registerParsedModel(l),a.push(l);return a}registerModel(s){let a=this.parseWithTooling(s);return this.registerParsedModel(a)}registerParsedModel(s){this.models.set(s.name,s);let a=this.toSingleTableEntity(s);this.singleTableManager.registerEntity(a);let l=this.toEntityMapping(s);return this.driver.registerEntity(l),s}registerModels(s){return s.map((a)=>this.registerModel(a))}getModel(s){return this.models.get(s)}getAllModels(){return Array.from(this.models.values())}repository(s){if(!this.models.get(s))throw Error(`Model not found: ${s}`);return St(this.singleTableManager,s,this.queryBuilderOptions)}query(s){if(!this.models.get(s))throw Error(`Model not found: ${s}`);return new D(this.queryBuilderOptions).table(this.config.tableName).entity(s)}item(s){if(!this.models.get(s))throw Error(`Model not found: ${s}`);return new g(this.queryBuilderOptions).table(this.config.tableName)}buildKey(s,a){let l=this.models.get(s);if(!l)throw Error(`Model not found: ${s}`);let c=Dt(l.keyPatterns,a);return{pk:c.pk,sk:c.sk}}createItem(s,a){let l=this.models.get(s);if(!l)throw Error(`Model not found: ${s}`);let c=Dt(l.keyPatterns,a),{pk:f,sk:y}=c,p={[this.config.pkAttribute]:f,[this.config.skAttribute]:y,[this.config.entityTypeAttribute]:l.name,...a};if(l.hasTimestamps){let x=new Date().toISOString();if(!p.createdAt)p.createdAt=x;p.updatedAt=x}if(l.hasVersioning){if(!p._v)p._v=1}return p}parseItem(s){let a=s[this.config.entityTypeAttribute];if(!a)return;let{[this.config.pkAttribute]:l,[this.config.skAttribute]:c,[this.config.entityTypeAttribute]:f,...y}=s;return{type:a,data:y}}getDriver(){return this.driver}getSingleTableManager(){return this.singleTableManager}generateTableDefinition(){return this.singleTableManager.generateTableDefinition()}generateAccessPatterns(s){let a=this.models.get(s);if(!a)throw Error(`Model not found: ${s}`);return a.accessPatterns}parseWithTooling(s){let a=s.name.toUpperCase(),l=s.primaryKey??"id",c=this.config.keyDelimiter,f=this.parseAttributes(s),y=this.parseRelationships(s,l),p={pk:`${a}${c}{${l}}`,sk:`${a}${c}{${l}}`,...this.deriveGSIKeyPatterns(a,l,c,y)},x=this.deriveAccessPatterns(s.name,a,l,y);return{name:s.name,entityType:a,primaryKey:l,attributes:f,relationships:y,keyPatterns:p,accessPatterns:x,traits:s.traits??{},hasTimestamps:s.traits?.useTimestamps??!1,hasSoftDeletes:s.traits?.useSoftDeletes??!1,hasUuid:s.traits?.useUuid??!1,hasTtl:s.traits?.useTtl??!1,hasVersioning:s.traits?.useVersioning??!1,original:s}}parseAttributes(s){let a=[];if(a.push({name:s.primaryKey??"id",fillable:!1,required:!0,nullable:!1,unique:!0,hidden:!1,dynamoDbType:"S"}),s.attributes)for(let[l,c]of Object.entries(s.attributes))a.push({name:l,fillable:c.fillable??!0,required:c.required??!1,nullable:c.nullable??!0,unique:c.unique??!1,hidden:c.hidden??!1,defaultValue:c.default,cast:c.cast,dynamoDbType:this.inferDynamoDBType(c)});if(s.traits?.useTimestamps)a.push({name:"createdAt",fillable:!1,required:!0,nullable:!1,unique:!1,hidden:!1,dynamoDbType:"S"},{name:"updatedAt",fillable:!1,required:!0,nullable:!1,unique:!1,hidden:!1,dynamoDbType:"S"});if(s.traits?.useSoftDeletes)a.push({name:"deletedAt",fillable:!1,required:!1,nullable:!0,unique:!1,hidden:!1,dynamoDbType:"S"});return a}inferDynamoDBType(s){if(s.cast){let a=s.cast.toLowerCase();if(["integer","int","float","double","decimal","number"].includes(a))return"N";if(["boolean","bool"].includes(a))return"BOOL";if(["array","list"].includes(a))return"L";if(["object","json","map"].includes(a))return"M"}if(s.validation?.rule){let a=String(s.validation.rule);if(a.includes("integer")||a.includes("numeric")||a.includes("number"))return"N";if(a.includes("boolean"))return"BOOL";if(a.includes("array"))return"L";if(a.includes("object"))return"M"}return"S"}parseRelationships(s,a){let l=[];if(s.hasOne)for(let c of s.hasOne)l.push({type:"hasOne",relatedModel:c,foreignKey:`${s.name.toLowerCase()}Id`,localKey:a,requiresGsi:!0});if(s.hasMany)for(let c of s.hasMany)l.push({type:"hasMany",relatedModel:c,foreignKey:`${s.name.toLowerCase()}Id`,localKey:a,requiresGsi:!1});if(s.belongsTo)for(let c of s.belongsTo)l.push({type:"belongsTo",relatedModel:c,foreignKey:`${c.toLowerCase()}Id`,localKey:a,requiresGsi:!0});if(s.belongsToMany){let c=Array.isArray(s.belongsToMany)?s.belongsToMany:Object.values(s.belongsToMany);for(let f of c){let y=typeof f==="string"?f:f?.model;if(!y)continue;let p=[s.name,y].sort();l.push({type:"belongsToMany",relatedModel:y,foreignKey:`${s.name.toLowerCase()}Id`,localKey:a,pivotEntity:p.join(""),requiresGsi:!0})}}return l}deriveGSIKeyPatterns(s,a,l,c){let f={},y=1;for(let p of c)if(p.requiresGsi&&y<=5)f[`gsi${y}pk`]=`${p.relatedModel.toUpperCase()}${l}{${p.foreignKey}}`,f[`gsi${y}sk`]=`${s}${l}{${a}}`,p.gsiIndex=y,y++;return f}deriveAccessPatterns(s,a,l,c){let f=[];f.push({name:`Get ${s} by ID`,description:`Retrieve a single ${s} by its primary key`,entityType:a,operation:"get",index:"main",keyCondition:"pk = :pk AND sk = :sk",examplePk:`${a}#123`,exampleSk:`${a}#123`,efficient:!0}),f.push({name:`List all ${s}s`,description:`Scan all ${s} entities`,entityType:a,operation:"scan",index:"scan",keyCondition:"_et = :entityType",examplePk:a,efficient:!1});for(let y of c){if(y.type==="hasMany")f.push({name:`Get ${y.relatedModel}s for ${s}`,description:`Query ${y.relatedModel}s related to a ${s}`,entityType:a,operation:"query",index:"main",keyCondition:"pk = :pk AND begins_with(sk, :skPrefix)",examplePk:`${a}#123`,exampleSk:`${y.relatedModel.toUpperCase()}#`,efficient:!0});if(y.gsiIndex){let p=`GSI${y.gsiIndex}`;f.push({name:`Get ${s}s by ${y.relatedModel}`,description:`Query ${s}s by their related ${y.relatedModel}`,entityType:a,operation:"query",index:p,keyCondition:`gsi${y.gsiIndex}pk = :pk`,examplePk:`${y.relatedModel.toUpperCase()}#123`,efficient:!0})}}return f}toSingleTableEntity(s){let a=this.extractKeyFields(s.keyPatterns.pk);return{name:s.name,pkPattern:s.keyPatterns.pk,skPattern:s.keyPatterns.sk,keyFields:a,indexes:this.extractGSIPatterns(s.keyPatterns)}}extractKeyFields(s){let a=s.match(/\{([^}]+)\}/g);if(!a)return[];return a.map((l)=>l.slice(1,-1))}extractGSIPatterns(s){let a=[];for(let l=1;l<=5;l++){let c=`gsi${l}pk`,f=`gsi${l}sk`;if(s[c])a.push({name:`GSI${l}`,pkPattern:s[c],skPattern:s[f]})}return a.length>0?a:void 0}toEntityMapping(s){return{entityType:s.name,pkPattern:s.keyPatterns.pk,skPattern:s.keyPatterns.sk}}buildGSIConfig(){let s=this.config.gsiConfig??{},a=[];if(s.gsi1pk)a.push({name:"GSI1",pkAttribute:s.gsi1pk,skAttribute:s.gsi1sk});if(s.gsi2pk)a.push({name:"GSI2",pkAttribute:s.gsi2pk,skAttribute:s.gsi2sk});if(s.gsi3pk)a.push({name:"GSI3",pkAttribute:s.gsi3pk,skAttribute:s.gsi3sk});return a}}function Mn(s){return new Et(s)}function Pn(s){return s.accessPatterns}function On(s,a="#"){let l=s.name.toUpperCase(),c=s.primaryKey??"id";return{name:s.name,pkPattern:`${l}${a}\${${c}}`,skPattern:`${l}${a}\${${c}}`}}function Ae(s){let a={};for(let l of Object.keys(s)){let c=s[l],f=c.definition??c.getDefinition?.()??c,y=w(f),p=f.attributes??{},x={};for(let T of Object.keys(p))x[T]=void 0;a[y]={columns:x,primaryKey:f.primaryKey??"id"}}return a}import{readdirSync as Zi}from"fs";import{basename as Ar,extname as wr,isAbsolute as es,join as Cr}from"path";import ts from"process";var ns=new Set([".ts",".mts",".cts",".js",".mjs",".cjs"]);function rs(s){let a=wr(s);if(!ns.has(a))return!1;let l=Ar(s,a);if(l.startsWith("_")||l==="index")return!1;return!l.endsWith(".d")}function is(s){if(!s||typeof s!=="object")return!1;let a=s;return typeof a.name==="string"||typeof a.table==="string"}function Nr(s){let a=[],l=Zi(s,{withFileTypes:!0}).sort((c,f)=>c.name.localeCompare(f.name));for(let c of l){let f=Cr(s,c.name);if(c.isDirectory()){a.push(...Nr(f));continue}if(rs(c.name))a.push(f)}return a}async function d(s){let a=s.cwd??ts.cwd(),l=es(s.modelsDir)?s.modelsDir:Cr(a,s.modelsDir),c={};for(let f of Nr(l)){let y=`?t=${Date.now()}-${Math.random().toString(36).slice(2)}`,p=await import(`${f}${y}`),x=p.default??p,T=x.definition??x.getDefinition?.()??x;if(!is(T))continue;let R=T.name??Ar(f,wr(f));c[R]={...T,name:R}}return c}function $t(s){let a={},l={},c={},f={},y={},p={};for(let x of Object.keys(s)){let T=s[x],R=T.definition??T.getDefinition?.()??T,C=w(R);a[x]=C,l[C]=x,c[C]=R.primaryKey??"id";let _=[];for(let[_e,Be]of Object.entries(R.attributes??{}))if(/^(?:datetime|timestamp|timestamptz|date)$/i.test(String(Be?.type??"")))_.push(_e);let v=R.traits??{};if(v.useTimestamps??v.timestampable)_.push("created_at","updated_at");if(_.length>0)p[C]=[...new Set(_)];let k=(_e)=>{if(!_e)return{};let Be={};if(Array.isArray(_e)){for(let Ve of _e){let et=E(Ve);if(et)Be[et.relationName??et.model]=et.model}return Be}if(typeof _e==="object"){for(let[Ve,et]of Object.entries(_e)){let Ze=E(et);if(Ze)Be[Ve]=Ze.model}return Be}return{}},K=(_e)=>{if(!_e)return{};if(Array.isArray(_e)){let Be={};for(let Ve of _e)if(typeof Ve==="string")Be[Ve]=Ve;else if(Ve&&typeof Ve==="object"&&typeof Ve.model==="string")Be[Ve.model]=Ve;return Be}return _e},Z=(_e)=>{if(!_e)return{};return _e};if(f[C]={hasOne:k(R.hasOne),hasMany:k(R.hasMany),belongsTo:k(R.belongsTo),belongsToMany:K(R.belongsToMany),hasOneThrough:Z(R.hasOneThrough),hasManyThrough:Z(R.hasManyThrough),morphOne:k(R.morphOne),morphMany:k(R.morphMany),morphTo:R.morphTo,morphToMany:k(R.morphToMany),morphedByMany:k(R.morphedByMany)},R.scopes&&typeof R.scopes==="object"){y[C]={};for(let _e of Object.keys(R.scopes)){let Be=R.scopes[_e];if(typeof Be==="function")y[C][_e]=Be}}}return{modelToTable:a,tableToModel:l,primaryKeys:c,relations:f,scopes:y,models:s,temporalColumns:p}}import{existsSync as Qn,mkdirSync as ss,readdirSync as as,readFileSync as os,writeFileSync as ls}from"fs";import{dirname as $r,join as gn}from"path";import qr from"process";function Mt(s){if(e.verbose)console.log(s)}function Kt(s){return s.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").toLowerCase()}function Un(s){return m(e.relations?.singularizeStrategy)(s)}var pn=0,rn=0,fn=0,Vn=!0,yn=[],sn=null;function xt(){return[...yn]}function us(s){let a=s;while(a!==$r(a)){if(Qn(gn(a,"package.json")))return a;a=$r(a)}return qr.cwd()}function cs(){let s=us(qr.cwd()),a=Ot(s,e.migrationDir);if(!Qn(a))ss(a,{recursive:!0}),Mt(`-- Created SQL directory: ${a}`);return a}var vt="-- qb:generated";function kt(s){return s.trimStart().startsWith(vt)}function Ct(s){return s.split(`
379
379
  `).filter((a)=>!a.trimStart().startsWith("--")).join(`
380
- `).replace(/\s+/g," ").trim().replace(/;+$/,"")}function us(s){let a=new Set,l;try{l=is(s).filter((c)=>c.endsWith(".sql"))}catch{return a}for(let c of l)try{a.add(Ct(ss(gn(s,c),"utf8")))}catch{}return a}function cs(s,a){if(!s)return!1;let l=ls();if(sn===null)sn=us(l);let c=Ct(s);if(c.length>0&&sn.has(c))return Mt(`-- Migration already in the corpus, not writing it again: ${a}`),!1;pn++;let f=Vn?String(pn).padStart(10,"0"):String(Math.floor(Date.now()/1000)+pn),y=`${f}-${a}.sql`;if(!Vn){let x=Number(f);while(Qn(gn(l,y)))x+=1,f=String(x),y=`${f}-${a}.sql`}let p=gn(l,y);return as(p,`${vt}
381
- ${s}`),Mt(`-- Migration file created: ${y}`),rn++,yn.push(y),sn?.add(c),!0}function zt(s,a){return s==="integer"&&a==="bigint"||s==="string"&&a==="text"}function $r(s){if(s.endsWith("_id"))return"bigint";if(s.endsWith("_at"))return"datetime";if(s.startsWith("is_")||s.startsWith("has_"))return"boolean";return}function _r(s){if(typeof s==="string"||typeof s==="number"||typeof s==="boolean"||typeof s==="bigint"||s instanceof Date)return s;return}function ds(s){if(s&&typeof s==="object"&&"name"in s){let a=s;if(a.name==="enum"||a.getRules&&Array.isArray(a.getRules())){if(a.enumValues&&Array.isArray(a.enumValues))return a.enumValues.map((l)=>String(l));if(a._values&&Array.isArray(a._values))return a._values.map((l)=>String(l));if(a.values&&Array.isArray(a.values))return a.values.map((l)=>String(l))}}if(s&&typeof s==="object"){let a=s,l=a.allowedValues||a.enumValues||a._values||a.values;if(Array.isArray(l)&&l.length>0)return l.map((c)=>String(c))}return}function jn(s){if(!s?.rules||!Array.isArray(s.rules))return;for(let a of s.rules)if(a?.name==="max"||a?.name==="maxLength"){if(a.params&&typeof a.params.max==="number")return a.params.max;if(Array.isArray(a.args)&&typeof a.args[0]==="number")return a.args[0];if(typeof a.value==="number")return a.value;if(typeof a.expectedValue==="number")return a.expectedValue}return}var Yn=767;function qr(s){if(typeof s!=="string")return;let a=s.trim().toLowerCase().match(/^(?:decimal|numeric)\s*\(\s*(\d+)\s*(?:,\s*(\d+)\s*)?\)$/);if(!a)return;return{precision:Number(a[1]),scale:a[2]===void 0?void 0:Number(a[2])}}function ms(s){let a=s;if(!a||typeof a!=="object")return{};let l=(y)=>typeof y==="number"?y:void 0,c=l(a.precision),f=l(a.scale);if(Array.isArray(a.rules)){for(let y of a.rules)if(y?.name==="precision")c??=l(y.params?.precision)??l(y.args?.[0]),f??=l(y.params?.scale)??l(y.args?.[1]);else if(y?.name==="scale")f??=l(y.params?.scale)??l(y.args?.[0])}return{precision:c,scale:f}}function fs(s,a){let l=qr(a?.type)??{},c=ms(a?.validation?.rule),f=a?.precision??l.precision??c.precision,y=a?.scale??l.scale??c.scale;if(f!==void 0&&(!Number.isInteger(f)||f<1||f>1000))throw Error(`[migrations] Attribute "${s}": decimal precision must be an integer from 1 to 1000, got ${f}`);if(y!==void 0&&(!Number.isInteger(y)||y<0))throw Error(`[migrations] Attribute "${s}": decimal scale must be a non-negative integer, got ${y}`);if(f!==void 0&&y!==void 0&&y>f)throw Error(`[migrations] Attribute "${s}": decimal scale (${y}) cannot exceed precision (${f})`);return{precision:f,scale:y}}function ps(s){if(!s||typeof s!=="object")return;let a=s;if(a.name)switch(String(a.name).toLowerCase()){case"string":{let c=jn(a);return c&&c>Yn?"text":"string"}case"text":return"text";case"integer":case"int":return"integer";case"bigint":return"bigint";case"float":return"float";case"number":return"integer";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum"}if(a.type){let l=String(a.type).toLowerCase();if(l==="string"||l==="text")return"string";if(l==="integer"||l==="int")return"integer";if(l==="bigint")return"bigint";if(l==="float")return"float";if(l==="number")return"integer";if(l==="boolean")return"boolean";if(l==="date")return"date";if(l==="datetime")return"datetime";if(l==="timestamptz"||l==="timestamp_tz")return"timestamptz";if(l==="json")return"json"}return}function Pr(s){if(typeof s!=="string")return;if(qr(s))return"decimal";switch(s.trim().toLowerCase().replace(/[\s-]+/g,"_")){case"varchar":case"string":return"string";case"text":return"text";case"bool":case"boolean":return"boolean";case"int":case"integer":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"number":case"numeric":case"decimal":return"decimal";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamp_tz":case"timestamptz":case"timestamp_with_time_zone":return"timestamptz";case"json":case"jsonb":return"json";case"enum":return"enum";default:return}}function z(s,a){let l=$t(s),c=[];for(let x of Object.keys(s)){let T=s[x],E=w(T),C=T.primaryKey??"id",v=T.autoIncrement!==!1,k=T.attributes??{},L=[],B=[];if(!k[C])L.push({name:Kt(C),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});let X=new Map,Pe=P(T.belongsTo).length>0,Be=new Set(Object.keys(k).map((ee)=>Kt(ee))),Ve=new Set;for(let ee of Be){if(!ee.endsWith("_type"))continue;let Ke=`${ee.slice(0,-5)}_id`;if(Be.has(Ke))Ve.add(Ke)}for(let ee of P(T.belongsTo)){let Ke=ee.foreignKey??`${Kt(ee.model)}_id`,et=l.modelToTable[ee.model];if(et)X.set(Ke,{table:et,onDelete:ee.onDelete})}for(let ee of Object.keys(k)){let Ke=k[ee],et=Kt(ee),ct=Boolean(Ke.validation?.rule?.isRequired),ut=ee===C?!1:Ke.nullable??!(Ke.required??ct),We,Oe,qe=ee===C;if(We=Pr(Ke.type)??ps(Ke.validation?.rule),We==="string"){let rt=jn(Ke.validation?.rule);if(rt&&rt>Yn)We="text"}if(!We||We==="enum"){let rt=ds(Ke.validation?.rule);if(rt&&rt.length>0)We="enum",Oe=rt}if(!We)We=$r(et);if(!We){let rt=_r(Ke.default);if(typeof rt==="string")We=rt.length>255?"text":"string";else if(typeof rt==="number")We=Number.isInteger(rt)?"integer":"float";else if(typeof rt==="boolean")We="boolean";else if(typeof rt==="bigint")We="bigint";else if(rt instanceof Date)We="datetime"}if(!We)We=qe?"bigint":"string";let Fe=fs(ee,Ke),st=Fe.precision!==void 0||Fe.scale!==void 0;if(st&&We!=="decimal"&&Pr(Ke.type)===void 0)We="decimal";let Nt=We==="string"?jn(Ke.validation?.rule):void 0,qt={name:et,type:We,isPrimaryKey:qe,isUnique:Boolean(Ke.unique),isNullable:ut,hasDefault:typeof Ke.default<"u",defaultValue:_r(Ke.default),enumValues:Oe,maxLength:typeof Nt==="number"&&Nt>0&&Nt<=Yn?Nt:void 0};if(We==="decimal"&&st){if(Fe.precision!==void 0)qt.precision=Fe.precision;if(Fe.scale!==void 0)qt.scale=Fe.scale}if(et.endsWith("_id")&&Ke.foreignKey!==!1&&!Ve.has(et))if(typeof Ke.foreignKey==="object"&&Ke.foreignKey!==null){let rt=Ke.foreignKey;if(qt.references={table:rt.table,column:rt.column??"id",onDelete:rt.onDelete,onUpdate:rt.onUpdate},rt.nullable!==void 0)qt.isNullable=rt.nullable}else{let rt=X.get(et),Ut=et.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(at,on,Br)=>Br.toUpperCase()),Qt=rt?.table??(Pe?void 0:l.modelToTable[Ut]);if(Qt){let at=l.primaryKeys[Qt]??"id";qt.references={table:Qt,column:at,onDelete:rt?.onDelete}}}L.push(qt)}let tt=P(T.belongsTo);for(let ee of tt){let Ke=ee.foreignKey??`${Kt(ee.model)}_id`;if(L.some((ut)=>ut.name===Ke))continue;let et=l.modelToTable[ee.model],ct=et?l.primaryKeys[et]??"id":void 0;L.push({name:Ke,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:et&&ct&&!Ve.has(Ke)?{table:et,column:ct,onDelete:ee.onDelete}:void 0})}let Ze=T.traits;if(Ze?.useTimestamps??Ze?.timestampable??!1){if(!L.some((ee)=>ee.name==="created_at"))L.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:b});if(!L.some((ee)=>ee.name==="updated_at"))L.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(Ze?.useSoftDeletes??Ze?.softDeletable??!1){if(!L.some((ee)=>ee.name==="deleted_at"))L.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(Ze?.useUuid??!1){if(!L.some((ee)=>ee.name==="uuid"))L.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let ee of T.indexes??[])B.push({name:ee.name,columns:ee.columns.map((Ke)=>Kt(Ke)),type:ee.unique?"unique":"index",where:ee.where});for(let ee of L)if(ee.isUnique&&!ee.isPrimaryKey)B.push({name:`${E}_${ee.name}_unique`,columns:[ee.name],type:"unique"});let it=Array.isArray(T.shardKey)?T.shardKey.map(Kt):void 0,lt=Array.isArray(T.sortKey)?T.sortKey.map(Kt):void 0,Ue=T.tableKind;c.push({table:E,columns:L,indexes:B,shardKey:it,sortKey:lt,tableKind:Ue})}let f=new Set(c.map((x)=>x.table));function y(x){if(!f.has(x.table))f.add(x.table),c.push(x)}for(let x of Object.keys(s)){let T=s[x],E=T?.traits??{},C=w(T),v=Un(C);if(E.likeable){let k=typeof E.likeable==="object"?E.likeable:{},L=k.table||`${C}_likes`,B=k.foreignKey||`${v}_id`;y({table:L,columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"user_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"users",column:"id"}},{name:B,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:C,column:"id"}},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:b},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:`${L}_user_target_unique`,columns:["user_id",B],type:"unique"}]})}if(E.taggable)y({table:"taggables",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"order",type:"integer",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:0},{name:"is_active",type:"boolean",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:!0},{name:"taggable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"taggable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:b},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggables_target_index",columns:["taggable_id","taggable_type"],type:"index"},{name:"taggables_type_slug_unique",columns:["taggable_type","slug"],type:"unique"}]}),y({table:"taggable_models",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"tag_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"taggables",column:"id"}},{name:"taggable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"taggable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:b},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggable_models_owner_unique",columns:["tag_id","taggable_id","taggable_type"],type:"unique"},{name:"taggable_models_target_index",columns:["taggable_id","taggable_type"],type:"index"}]});if(E.categorizable)y({table:"categorizables",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"is_active",type:"boolean",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:!0},{name:"categorizable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:b},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizables_type_slug_unique",columns:["categorizable_type","slug"],type:"unique"}]}),y({table:"categorizable_models",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"category_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"categorizables",column:"id"}},{name:"categorizable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"categorizable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:b},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizable_models_owner_unique",columns:["category_id","categorizable_id","categorizable_type"],type:"unique"},{name:"categorizable_models_target_index",columns:["categorizable_id","categorizable_type"],type:"index"}]})}for(let x of Object.keys(s)){let T=s[x],E=T?.belongsToMany;if(!E||typeof E!=="object"||Array.isArray(E))continue;let C=w(T),v=Un(C);for(let[k,L]of Object.entries(E)){let B=L;if(!B||typeof B!=="object")continue;if(B.through)continue;let X=B.pivot;if(!X||!X.columns&&!X.timestamps&&!X.uniques)continue;let Pe=B.model,Ve=s[Pe]?.table||`${String(Pe).toLowerCase()}s`,tt=Un(Ve),Ze=B.table||[v,tt].sort().join("_"),Z=B.foreignKey||`${v}_id`,nt=B.relatedKey||`${tt}_id`,_t=new Set([Z,nt,...Object.keys(X.columns??{})]),it=new Set;for(let et of _t){if(!et.endsWith("_type"))continue;let ct=`${et.slice(0,-5)}_id`;if(_t.has(ct))it.add(ct)}let lt=(et,ct)=>it.has(et)?void 0:{table:ct,column:"id"},Ue=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:Z,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:lt(Z,C)},{name:nt,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:lt(nt,Ve)}];if(X.columns)for(let[et,ct]of Object.entries(X.columns)){let ut=ct,We=$r(et)??"string";Ue.push({name:et,type:We,isPrimaryKey:!1,isUnique:!1,isNullable:ut?.nullable??!1,hasDefault:ut?.default!==void 0,defaultValue:ut?.default})}if(X.timestamps)Ue.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:b}),Ue.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1});let ee=[],Ke=X.uniques&&X.uniques.length>0?X.uniques:[[Z,nt]];for(let et=0;et<Ke.length;et++){let ct=Ke[et];ee.push({name:`${Ze}_${ct.join("_")}_unique${et>0?`_${et}`:""}`,columns:[...ct],type:"unique"})}y({table:Ze,columns:Ue,indexes:ee})}}let p=new Map(c.map((x)=>[x.table,x]));for(let x of c)for(let T of x.columns){if(!T.references)continue;let E=p.get(T.references.table)?.columns.find((C)=>C.name===T.references.column);if(!E||T.type===E.type)continue;T.type=E.type,T.maxLength=E.maxLength,T.precision=E.precision,T.scale=E.scale,T.enumValues=E.enumValues,T.enumTypeName=E.enumTypeName}return{dialect:a.dialect,vitessSharded:a.vitessSharded,tables:c}}function Y(s,a){pn=0,rn=0,fn=0,yn=[],sn=null,Vn=a.deterministic;for(let c of s)cs(c.sql,c.name);if(rn+fn===0)Mt("-- Nothing to migrate");else{let c=[];if(rn>0)c.push(`${rn} created`);if(fn>0)c.push(`${fn} updated`);Mt(`-- Migration files: ${c.join(", ")}`)}return[...yn]}function Ae(s){let a=[],l=[],c=h(s.dialect,{vitessSharded:s.vitessSharded}),{tables:f,deferredForeignKeys:y}=Lr(s.tables,s.dialect);for(let[p,x]of f.entries()){let T={...x,columns:x.columns.map((k)=>y.has(Bt(x.table,k.name))?{...k,references:void 0}:k)},E=[],C=new Set;for(let k of T.columns)if(k.type==="enum"&&k.enumValues&&k.enumValues.length>0){let L=`${T.table}_${k.name}_type`;if(k.enumTypeName=L,!C.has(L)){let B=c.createEnumType(L,k.enumValues);if(B)E.push(B);C.add(L)}}let v=c.createTable(T);E.push(v);for(let k of T.indexes)E.push(c.createIndex(T.table,k,T.columns));if(p===f.length-1)for(let k of f)for(let L of k.columns){if(!L.references||!y.has(Bt(k.table,L.name)))continue;let B=c.addForeignKey(k.table,L.name,L.references.table,L.references.column,L.references.onDelete,L.references.onUpdate);if(B)E.push(B)}a.push(...E),l.push({name:`create-${T.table}-table`,sql:E.join(`
380
+ `).replace(/\s+/g," ").trim().replace(/;+$/,"")}function ds(s){let a=new Set,l;try{l=as(s).filter((c)=>c.endsWith(".sql"))}catch{return a}for(let c of l)try{a.add(Ct(os(gn(s,c),"utf8")))}catch{}return a}function ms(s,a){if(!s)return!1;let l=cs();if(sn===null)sn=ds(l);let c=Ct(s);if(c.length>0&&sn.has(c))return Mt(`-- Migration already in the corpus, not writing it again: ${a}`),!1;pn++;let f=Vn?String(pn).padStart(10,"0"):String(Math.floor(Date.now()/1000)+pn),y=`${f}-${a}.sql`;if(!Vn){let x=Number(f);while(Qn(gn(l,y)))x+=1,f=String(x),y=`${f}-${a}.sql`}let p=gn(l,y);return ls(p,`${vt}
381
+ ${s}`),Mt(`-- Migration file created: ${y}`),rn++,yn.push(y),sn?.add(c),!0}function zt(s,a){return s==="integer"&&a==="bigint"||s==="string"&&a==="text"}function _r(s){if(s.endsWith("_id"))return"bigint";if(s.endsWith("_at"))return"datetime";if(s.startsWith("is_")||s.startsWith("has_"))return"boolean";return}function Pr(s){if(typeof s==="string"||typeof s==="number"||typeof s==="boolean"||typeof s==="bigint"||s instanceof Date)return s;return}function fs(s){if(s&&typeof s==="object"&&"name"in s){let a=s;if(a.name==="enum"||a.getRules&&Array.isArray(a.getRules())){if(a.enumValues&&Array.isArray(a.enumValues))return a.enumValues.map((l)=>String(l));if(a._values&&Array.isArray(a._values))return a._values.map((l)=>String(l));if(a.values&&Array.isArray(a.values))return a.values.map((l)=>String(l))}}if(s&&typeof s==="object"){let a=s,l=a.allowedValues||a.enumValues||a._values||a.values;if(Array.isArray(l)&&l.length>0)return l.map((c)=>String(c))}return}function jn(s){if(!s?.rules||!Array.isArray(s.rules))return;for(let a of s.rules)if(a?.name==="max"||a?.name==="maxLength"){if(a.params&&typeof a.params.max==="number")return a.params.max;if(Array.isArray(a.args)&&typeof a.args[0]==="number")return a.args[0];if(typeof a.value==="number")return a.value;if(typeof a.expectedValue==="number")return a.expectedValue}return}var Yn=767;function Lr(s){if(typeof s!=="string")return;let a=s.trim().toLowerCase().match(/^(?:decimal|numeric)\s*\(\s*(\d+)\s*(?:,\s*(\d+)\s*)?\)$/);if(!a)return;return{precision:Number(a[1]),scale:a[2]===void 0?void 0:Number(a[2])}}function ps(s){let a=s;if(!a||typeof a!=="object")return{};let l=(y)=>typeof y==="number"?y:void 0,c=l(a.precision),f=l(a.scale);if(Array.isArray(a.rules)){for(let y of a.rules)if(y?.name==="precision")c??=l(y.params?.precision)??l(y.args?.[0]),f??=l(y.params?.scale)??l(y.args?.[1]);else if(y?.name==="scale")f??=l(y.params?.scale)??l(y.args?.[0])}return{precision:c,scale:f}}function gs(s,a){let l=Lr(a?.type)??{},c=ps(a?.validation?.rule),f=a?.precision??l.precision??c.precision,y=a?.scale??l.scale??c.scale;if(f!==void 0&&(!Number.isInteger(f)||f<1||f>1000))throw Error(`[migrations] Attribute "${s}": decimal precision must be an integer from 1 to 1000, got ${f}`);if(y!==void 0&&(!Number.isInteger(y)||y<0))throw Error(`[migrations] Attribute "${s}": decimal scale must be a non-negative integer, got ${y}`);if(f!==void 0&&y!==void 0&&y>f)throw Error(`[migrations] Attribute "${s}": decimal scale (${y}) cannot exceed precision (${f})`);return{precision:f,scale:y}}function ys(s){if(!s||typeof s!=="object")return;let a=s;if(a.name)switch(String(a.name).toLowerCase()){case"string":{let c=jn(a);return c&&c>Yn?"text":"string"}case"text":return"text";case"integer":case"int":return"integer";case"bigint":return"bigint";case"float":return"float";case"number":return"integer";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum"}if(a.type){let l=String(a.type).toLowerCase();if(l==="string"||l==="text")return"string";if(l==="integer"||l==="int")return"integer";if(l==="bigint")return"bigint";if(l==="float")return"float";if(l==="number")return"integer";if(l==="boolean")return"boolean";if(l==="date")return"date";if(l==="datetime")return"datetime";if(l==="timestamptz"||l==="timestamp_tz")return"timestamptz";if(l==="json")return"json"}return}function vr(s){if(typeof s!=="string")return;if(Lr(s))return"decimal";switch(s.trim().toLowerCase().replace(/[\s-]+/g,"_")){case"varchar":case"string":return"string";case"text":return"text";case"bool":case"boolean":return"boolean";case"int":case"integer":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"number":case"numeric":case"decimal":return"decimal";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamp_tz":case"timestamptz":case"timestamp_with_time_zone":return"timestamptz";case"json":case"jsonb":return"json";case"enum":return"enum";default:return}}function Y(s,a){let l=$t(s),c=[];for(let x of Object.keys(s)){let T=s[x],R=w(T),C=T.primaryKey??"id",_=T.autoIncrement!==!1,v=T.attributes??{},k=[],K=[];if(!v[C])k.push({name:Kt(C),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});let Z=new Map,_e=B(T.belongsTo).length>0,Be=new Set(Object.keys(v).map((te)=>Kt(te))),Ve=new Set;for(let te of Be){if(!te.endsWith("_type"))continue;let Ke=`${te.slice(0,-5)}_id`;if(Be.has(Ke))Ve.add(Ke)}for(let te of B(T.belongsTo)){let Ke=te.foreignKey??`${Kt(te.model)}_id`,tt=l.modelToTable[te.model];if(tt)Z.set(Ke,{table:tt,onDelete:te.onDelete})}for(let te of Object.keys(v)){let Ke=v[te],tt=Kt(te),ct=Boolean(Ke.validation?.rule?.isRequired),ut=te===C?!1:Ke.nullable??!(Ke.required??ct),We,Oe,qe=te===C;if(We=vr(Ke.type)??ys(Ke.validation?.rule),We==="string"){let rt=jn(Ke.validation?.rule);if(rt&&rt>Yn)We="text"}if(!We||We==="enum"){let rt=fs(Ke.validation?.rule);if(rt&&rt.length>0)We="enum",Oe=rt}if(!We)We=_r(tt);if(!We){let rt=Pr(Ke.default);if(typeof rt==="string")We=rt.length>255?"text":"string";else if(typeof rt==="number")We=Number.isInteger(rt)?"integer":"float";else if(typeof rt==="boolean")We="boolean";else if(typeof rt==="bigint")We="bigint";else if(rt instanceof Date)We="datetime"}if(!We)We=qe?"bigint":"string";let Fe=gs(te,Ke),st=Fe.precision!==void 0||Fe.scale!==void 0;if(st&&We!=="decimal"&&vr(Ke.type)===void 0)We="decimal";let Nt=We==="string"?jn(Ke.validation?.rule):void 0,qt={name:tt,type:We,isPrimaryKey:qe,isUnique:Boolean(Ke.unique),isNullable:ut,hasDefault:typeof Ke.default<"u",defaultValue:Pr(Ke.default),enumValues:Oe,maxLength:typeof Nt==="number"&&Nt>0&&Nt<=Yn?Nt:void 0};if(We==="decimal"&&st){if(Fe.precision!==void 0)qt.precision=Fe.precision;if(Fe.scale!==void 0)qt.scale=Fe.scale}if(tt.endsWith("_id")&&Ke.foreignKey!==!1&&!Ve.has(tt))if(typeof Ke.foreignKey==="object"&&Ke.foreignKey!==null){let rt=Ke.foreignKey;if(qt.references={table:rt.table,column:rt.column??"id",onDelete:rt.onDelete,onUpdate:rt.onUpdate},rt.nullable!==void 0)qt.isNullable=rt.nullable}else{let rt=Z.get(tt),Ut=tt.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(at,on,Ur)=>Ur.toUpperCase()),Qt=rt?.table??(_e?void 0:l.modelToTable[Ut]);if(Qt){let at=l.primaryKeys[Qt]??"id";qt.references={table:Qt,column:at,onDelete:rt?.onDelete}}}k.push(qt)}let et=B(T.belongsTo);for(let te of et){let Ke=te.foreignKey??`${Kt(te.model)}_id`;if(k.some((ut)=>ut.name===Ke))continue;let tt=l.modelToTable[te.model],ct=tt?l.primaryKeys[tt]??"id":void 0;k.push({name:Ke,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:tt&&ct&&!Ve.has(Ke)?{table:tt,column:ct,onDelete:te.onDelete}:void 0})}let Ze=T.traits;if(Ze?.useTimestamps??Ze?.timestampable??!1){if(!k.some((te)=>te.name==="created_at"))k.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:b});if(!k.some((te)=>te.name==="updated_at"))k.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(Ze?.useSoftDeletes??Ze?.softDeletable??!1){if(!k.some((te)=>te.name==="deleted_at"))k.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(Ze?.useUuid??!1){if(!k.some((te)=>te.name==="uuid"))k.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let te of T.indexes??[])K.push({name:te.name,columns:te.columns.map((Ke)=>Kt(Ke)),type:te.unique?"unique":"index",where:te.where});for(let te of k)if(te.isUnique&&!te.isPrimaryKey)K.push({name:`${R}_${te.name}_unique`,columns:[te.name],type:"unique"});let it=Array.isArray(T.shardKey)?T.shardKey.map(Kt):void 0,lt=Array.isArray(T.sortKey)?T.sortKey.map(Kt):void 0,Ue=T.tableKind;c.push({table:R,columns:k,indexes:K,shardKey:it,sortKey:lt,tableKind:Ue})}let f=new Set(c.map((x)=>x.table));function y(x){if(!f.has(x.table))f.add(x.table),c.push(x)}for(let x of Object.keys(s)){let T=s[x],R=T?.traits??{},C=w(T),_=Un(C);if(R.likeable){let v=typeof R.likeable==="object"?R.likeable:{},k=v.table||`${C}_likes`,K=v.foreignKey||`${_}_id`;y({table:k,columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"user_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"users",column:"id"}},{name:K,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:C,column:"id"}},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:b},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:`${k}_user_target_unique`,columns:["user_id",K],type:"unique"}]})}if(R.taggable)y({table:"taggables",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"order",type:"integer",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:0},{name:"is_active",type:"boolean",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:!0},{name:"taggable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"taggable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:b},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggables_target_index",columns:["taggable_id","taggable_type"],type:"index"},{name:"taggables_type_slug_unique",columns:["taggable_type","slug"],type:"unique"}]}),y({table:"taggable_models",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"tag_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"taggables",column:"id"}},{name:"taggable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"taggable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:b},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggable_models_owner_unique",columns:["tag_id","taggable_id","taggable_type"],type:"unique"},{name:"taggable_models_target_index",columns:["taggable_id","taggable_type"],type:"index"}]});if(R.categorizable)y({table:"categorizables",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"is_active",type:"boolean",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:!0},{name:"categorizable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:b},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizables_type_slug_unique",columns:["categorizable_type","slug"],type:"unique"}]}),y({table:"categorizable_models",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"category_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"categorizables",column:"id"}},{name:"categorizable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"categorizable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:b},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizable_models_owner_unique",columns:["category_id","categorizable_id","categorizable_type"],type:"unique"},{name:"categorizable_models_target_index",columns:["categorizable_id","categorizable_type"],type:"index"}]})}for(let x of Object.keys(s)){let T=s[x],R=T?.belongsToMany;if(!R||typeof R!=="object"||Array.isArray(R))continue;let C=w(T),_=Un(C);for(let[v,k]of Object.entries(R)){let K=k;if(!K||typeof K!=="object")continue;if(K.through)continue;let Z=K.pivot;if(!Z||!Z.columns&&!Z.timestamps&&!Z.uniques)continue;let _e=K.model,Ve=s[_e]?.table||`${String(_e).toLowerCase()}s`,et=Un(Ve),Ze=K.table||[_,et].sort().join("_"),ee=K.foreignKey||`${_}_id`,nt=K.relatedKey||`${et}_id`,_t=new Set([ee,nt,...Object.keys(Z.columns??{})]),it=new Set;for(let tt of _t){if(!tt.endsWith("_type"))continue;let ct=`${tt.slice(0,-5)}_id`;if(_t.has(ct))it.add(ct)}let lt=(tt,ct)=>it.has(tt)?void 0:{table:ct,column:"id"},Ue=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:ee,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:lt(ee,C)},{name:nt,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:lt(nt,Ve)}];if(Z.columns)for(let[tt,ct]of Object.entries(Z.columns)){let ut=ct,We=_r(tt)??"string";Ue.push({name:tt,type:We,isPrimaryKey:!1,isUnique:!1,isNullable:ut?.nullable??!1,hasDefault:ut?.default!==void 0,defaultValue:ut?.default})}if(Z.timestamps)Ue.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:b}),Ue.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1});let te=[],Ke=Z.uniques&&Z.uniques.length>0?Z.uniques:[[ee,nt]];for(let tt=0;tt<Ke.length;tt++){let ct=Ke[tt];te.push({name:`${Ze}_${ct.join("_")}_unique${tt>0?`_${tt}`:""}`,columns:[...ct],type:"unique"})}y({table:Ze,columns:Ue,indexes:te})}}let p=new Map(c.map((x)=>[x.table,x]));for(let x of c)for(let T of x.columns){if(!T.references)continue;let R=p.get(T.references.table)?.columns.find((C)=>C.name===T.references.column);if(!R||T.type===R.type)continue;T.type=R.type,T.maxLength=R.maxLength,T.precision=R.precision,T.scale=R.scale,T.enumValues=R.enumValues,T.enumTypeName=R.enumTypeName}return{dialect:a.dialect,vitessSharded:a.vitessSharded,tables:c}}function X(s,a){pn=0,rn=0,fn=0,yn=[],sn=null,Vn=a.deterministic;for(let c of s)ms(c.sql,c.name);if(rn+fn===0)Mt("-- Nothing to migrate");else{let c=[];if(rn>0)c.push(`${rn} created`);if(fn>0)c.push(`${fn} updated`);Mt(`-- Migration files: ${c.join(", ")}`)}return[...yn]}function Ne(s){let a=[],l=[],c=h(s.dialect,{vitessSharded:s.vitessSharded}),{tables:f,deferredForeignKeys:y}=Kr(s.tables,s.dialect);for(let[p,x]of f.entries()){let T={...x,columns:x.columns.map((v)=>y.has(Bt(x.table,v.name))?{...v,references:void 0}:v)},R=[],C=new Set;for(let v of T.columns)if(v.type==="enum"&&v.enumValues&&v.enumValues.length>0){let k=`${T.table}_${v.name}_type`;if(v.enumTypeName=k,!C.has(k)){let K=c.createEnumType(k,v.enumValues);if(K)R.push(K);C.add(k)}}let _=c.createTable(T);R.push(_);for(let v of T.indexes)R.push(c.createIndex(T.table,v,T.columns));if(p===f.length-1)for(let v of f)for(let k of v.columns){if(!k.references||!y.has(Bt(v.table,k.name)))continue;let K=c.addForeignKey(v.table,k.name,k.references.table,k.references.column,k.references.onDelete,k.references.onUpdate);if(K)R.push(K)}a.push(...R),l.push({name:`create-${T.table}-table`,sql:R.join(`
382
382
 
383
- `)})}return{statements:a,files:l}}function Yt(s,a={}){let{statements:l,files:c}=Ae(s);if(a.write===!0&&!a.dryRun)Y(c,{deterministic:!0});return l}function Bt(s,a){return`${s}\x00${a}`}function Lr(s,a){if(a==="sqlite"||s.length<2)return{tables:s,deferredForeignKeys:new Set};let l=new Map(s.map((T)=>[T.table,T])),c=new Map;for(let T of s)c.set(T.table,new Set(T.columns.map((E)=>E.references?.table).filter((E)=>Boolean(E&&E!==T.table&&l.has(E)))));let f=[],y=new Set;while(f.length<s.length){let T=s.find((E)=>!y.has(E.table)&&[...c.get(E.table)??[]].every((C)=>y.has(C)));if(!T)break;f.push(T),y.add(T.table)}let p=new Set(s.filter((T)=>!y.has(T.table)).map((T)=>T.table)),x=new Set;for(let T of s){if(!p.has(T.table))continue;for(let E of T.columns)if(E.references&&p.has(E.references.table)&&E.references.table!==T.table)x.add(Bt(T.table,E.name))}return f.push(...s.filter((T)=>p.has(T.table))),{tables:f,deferredForeignKeys:x}}function Bn(s){return Yt(s).join(`
383
+ `)})}return{statements:a,files:l}}function Yt(s,a={}){let{statements:l,files:c}=Ne(s);if(a.write===!0&&!a.dryRun)X(c,{deterministic:!0});return l}function Bt(s,a){return`${s}\x00${a}`}function Kr(s,a){if(a==="sqlite"||s.length<2)return{tables:s,deferredForeignKeys:new Set};let l=new Map(s.map((T)=>[T.table,T])),c=new Map;for(let T of s)c.set(T.table,new Set(T.columns.map((R)=>R.references?.table).filter((R)=>Boolean(R&&R!==T.table&&l.has(R)))));let f=[],y=new Set;while(f.length<s.length){let T=s.find((R)=>!y.has(R.table)&&[...c.get(R.table)??[]].every((C)=>y.has(C)));if(!T)break;f.push(T),y.add(T.table)}let p=new Set(s.filter((T)=>!y.has(T.table)).map((T)=>T.table)),x=new Set;for(let T of s){if(!p.has(T.table))continue;for(let R of T.columns)if(R.references&&p.has(R.references.table)&&R.references.table!==T.table)x.add(Bt(T.table,R.name))}return f.push(...s.filter((T)=>p.has(T.table))),{tables:f,deferredForeignKeys:x}}function Bn(s){return Yt(s).join(`
384
384
  `)}function _n(s,a){return en(s,a).join(`
385
- `)}function Rt(s){let a=Ur("crypto");function l(f){if(f==null||typeof f!=="object"||f instanceof Date)return f;if(Array.isArray(f))return f.map((p)=>l(p));let y={};for(let p of Object.keys(f).sort())y[p]=l(f[p]);return y}let c=JSON.stringify(l(s));return a.createHash("sha256").update(c).digest("hex")}function vr(s){let a={};for(let l of s)a[l.table]=l;return a}function nn(s){let a={};for(let l of s)a[l.name]=l;return a}function ze(s,a){if(a==="sqlite"){if(s.name.endsWith("_id")&&O(s.type))return"INTEGER";switch(s.type){case"string":case"text":case"date":case"datetime":case"timestamptz":case"json":case"enum":return"TEXT";case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}if(a==="mysql"||a==="vitess"||a==="singlestore")switch(s.type){case"string":return`VARCHAR(${s.maxLength??255})`;case"text":return"TEXT";case"boolean":return"TINYINT(1)";case"integer":return"INTEGER";case"bigint":return"BIGINT";case"float":return"REAL";case"double":return"DOUBLE";case"decimal":return Ft(s).toUpperCase();case"date":return"DATE";case"datetime":case"timestamptz":return"DATETIME";case"json":return"JSON";case"enum":return"ENUM";default:return s.type}if(s.type==="string")return`varchar(${s.maxLength??255})`;if(s.type==="decimal")return Ft(s);return s.type}function Xt(s,a){if(s.type==="string"&&a.type==="string")return(a.maxLength??255)<(s.maxLength??255);if(s.type==="decimal"&&a.type==="decimal"){let l=un(s),c=un(a);return c.scale<l.scale||c.precision-c.scale<l.precision-l.scale}if(s.type==="enum"&&a.type==="enum")return(s.enumValues??[]).some((l)=>!(a.enumValues??[]).includes(l));return!1}var b="UTC_TIMESTAMP";function Ye(s,a){if(!s.hasDefault||s.defaultValue===void 0)return;let l=s.defaultValue;if(l instanceof Date)return l.toISOString();if(typeof l==="boolean")return l?"1":"0";if(typeof l==="bigint"||typeof l==="number")return String(l);let c=String(l).trim();if(c=c.replace(/::[\w ]+$/i,"").trim(),c.startsWith("'")&&c.endsWith("'")||c.startsWith('"')&&c.endsWith('"'))c=c.slice(1,-1);let f=c.toUpperCase();if(["UTC_TIMESTAMP","UTC_TIMESTAMP()","(UTC_TIMESTAMP)","(UTC_TIMESTAMP())","TIMEZONE('UTC', NOW())","TIMEZONE('UTC'::TEXT, NOW())","(NOW() AT TIME ZONE 'UTC')","NOW() AT TIME ZONE 'UTC'"].includes(f.replace(/\s+/g," ")))return b;if(a==="sqlite"&&f==="CURRENT_TIMESTAMP")return b;if(["CURRENT_TIMESTAMP","NOW()","CURRENT_DATE","CURRENT_TIME","NULL","TRUE","FALSE"].includes(f))return f==="NOW()"?"CURRENT_TIMESTAMP":f;if(s.type==="boolean"){if(/^(?:1|t|true|yes)$/i.test(c))return"1";if(/^(?:0|f|false|no)$/i.test(c))return"0"}if(/^-?\d+(?:\.\d+)?$/.test(c))return String(Number(c));return c}function gs(s,a,l){if(ze(s,l)!==ze(a,l))return!0;if(s.isNullable!==a.isNullable)return!0;if(s.hasDefault!==a.hasDefault)return!0;if(Ye(s,l)!==Ye(a,l))return!0;if(s.isUnique!==a.isUnique)return!0;if(s.type==="enum"&&a.type==="enum"){let c=(s.enumValues||[]).slice().sort().join(","),f=(a.enumValues||[]).slice().sort().join(",");if(c!==f)return!0}return!1}function kr(s,a){return JSON.stringify([ze(s,a),s.isPrimaryKey,s.isUnique,s.isNullable,s.hasDefault,Ye(s,a)??null,(s.enumValues??[]).slice().sort(),s.references?[s.references.table,s.references.column,s.references.onDelete??null,s.references.onUpdate??null]:null])}function ys(s,a,l){let c=Object.keys(s).filter((C)=>!a[C]),f=Object.keys(a).filter((C)=>!s[C]),y=new Map,p=new Map;for(let C of c){let v=kr(s[C],l),k=y.get(v)??[];k.push(C),y.set(v,k)}for(let C of f){let v=kr(a[C],l),k=p.get(v)??[];k.push(C),p.set(v,k)}let x=[],T=new Set,E=new Set;for(let[C,v]of y){let k=p.get(C);if(v.length===1&&k&&k.length===1)x.push({from:v[0],to:k[0]}),T.add(v[0]),E.add(k[0])}return{renames:x,removed:c.filter((C)=>!T.has(C)),added:f.filter((C)=>!E.has(C))}}function bs(s){if(!s?.references||!s.hasDefault)return!1;let a=s.defaultValue;return a!==void 0&&a!==null&&String(a).toUpperCase()!=="NULL"}function hs(s){return!s.isPrimaryKey&&!s.isNullable&&!(s.hasDefault&&s.defaultValue!==void 0)}function Ir(s,a){if(!hs(a))return{column:a};let l=`${s}.${a.name} is NOT NULL in the model but has no default, so rows already in "${s}" would have no value for it. It is added as NULLABLE. Backfill it, then give the attribute a default or regenerate from the live database (fromDb) to apply NOT NULL.`;return{column:{...a,isNullable:!0},warning:l}}function Ts(s,a){let l=s.columns.find((c)=>c.name===a);if(l&&(l.isPrimaryKey||l.isUnique||l.references))return!0;return s.indexes.some((c)=>c.columns.includes(a))}function xs(s,a){if(Boolean(s)!==Boolean(a))return!0;if(!s||!a)return!1;if((s.constraintNames?.length??0)>1)return!0;let l=(c)=>(c??"no action").toLowerCase();return s.table!==a.table||s.column!==a.column||l(s.onDelete)!==l(a.onDelete)||l(s.onUpdate)!==l(a.onUpdate)}function Kr(s,a){return`${s.type}:${Pt(a,s.name)}:${s.columns.join(",")}:${Zt(s.where)}`}function Zt(s){if(!s||!s.trim())return"";return s.trim().split(/('(?:[^']|'')*')/).map((l,c)=>{if(c%2===1)return l;return l.replace(/::\s*(?:character varying|bit varying|double precision|timestamp(?:\s*\(\d+\))?(?:\s+with(?:out)?\s+time\s+zone)?|time(?:\s+with(?:out)?\s+time\s+zone)?|"?[a-z_][\w$]*"?(?:\s*\(\d+(?:\s*,\s*\d+)?\))?)(?:\[\])?/gi,"").replace(/"/g,"").toLowerCase().replace(/!=/g,"<>").replace(/[()]/g," ").replace(/\s+/g," ").replace(/<>\s*all\s*array\s*\[/g," not in ").replace(/=\s*any\s*array\s*\[/g," in ").replace(/([\w.]+) between (\S+) and (\S+)/g,"$1 >= $2 and $1 <= $3").replace(/[[\]]/g," ").replace(/\s+/g,"")}).join("")}function Fn(s,a){let l={};for(let c of s)l[Kr(c,a)]=c;return l}function Xe(s,a,l={}){if(!s||s.dialect!==a.dialect){let{statements:tt,files:Ze}=Ae(a);if(l.write===!0&&!l.dryRun)Y(Ze,{deterministic:!0});let Z=a.tables.map((nt)=>({kind:"create_table",table:nt.table,destructive:!1,sql:""}));return{statements:tt,operations:Z,files:Ze}}let c=l.applyRenames!==!1,f=l.preserveUnknownColumns===!0,y=[],p=(tt,Ze)=>{if(tt)y.push({name:Ze,sql:tt})},x=[],T=[],E=h(a.dialect,{vitessSharded:a.vitessSharded}),C=a.dialect,v=vr(s.tables),k=vr(a.tables);for(let tt of Object.keys(v))if(!k[tt]){let Ze=E.dropTable(tt);x.push(Ze),T.push({kind:"drop_table",table:tt,destructive:!0,sql:Ze}),p(Ze,`drop-${tt}-table`),Mt(`-- Detected dropped table: ${tt}`)}let L=Object.keys(k).filter((tt)=>!v[tt]).map((tt)=>k[tt]),{tables:B,deferredForeignKeys:X}=Lr(L,C);for(let[tt,Ze]of B.entries()){let Z={...Ze,columns:Ze.columns.map((Ue)=>X.has(Bt(Ze.table,Ue.name))?{...Ue,references:void 0}:Ue)},nt=[],_t=new Set;for(let Ue of Z.columns)if(Ue.type==="enum"&&Ue.enumValues&&Ue.enumValues.length>0){let ee=`${Z.table}_${Ue.name}_type`;if(Ue.enumTypeName=ee,!_t.has(ee)){let Ke=E.createEnumType(ee,Ue.enumValues);if(Ke)nt.push(Ke);_t.add(ee)}}let it=E.createTable(Z);nt.push(it);for(let Ue of Z.indexes){let ee=E.createIndex(Z.table,Ue,Z.columns);nt.push(ee),T.push({kind:"create_index",table:Z.table,column:Ue.name,destructive:!1,sql:ee})}for(let Ue of Ze.columns)if(Ue.references&&!X.has(Bt(Ze.table,Ue.name)))T.push({kind:"add_foreign_key",table:Ze.table,column:Ue.name,destructive:!1,sql:it});if(tt===B.length-1)for(let Ue of B)for(let ee of Ue.columns){if(!ee.references||!X.has(Bt(Ue.table,ee.name)))continue;let Ke=E.addForeignKey(Ue.table,ee.name,ee.references.table,ee.references.column,ee.references.onDelete,ee.references.onUpdate);if(!Ke)continue;nt.push(Ke),T.push({kind:"add_foreign_key",table:Ue.table,column:ee.name,destructive:!1,sql:Ke})}x.push(...nt),T.push({kind:"create_table",table:Z.table,destructive:!1,sql:it});let lt=nt.join(`
385
+ `)}function Rt(s){let a=Fr("crypto");function l(f){if(f==null||typeof f!=="object"||f instanceof Date)return f;if(Array.isArray(f))return f.map((p)=>l(p));let y={};for(let p of Object.keys(f).sort())y[p]=l(f[p]);return y}let c=JSON.stringify(l(s));return a.createHash("sha256").update(c).digest("hex")}function kr(s){let a={};for(let l of s)a[l.table]=l;return a}function nn(s){let a={};for(let l of s)a[l.name]=l;return a}function ze(s,a){if(a==="sqlite"){if(s.name.endsWith("_id")&&O(s.type))return"INTEGER";switch(s.type){case"string":case"text":case"date":case"datetime":case"timestamptz":case"json":case"enum":return"TEXT";case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}if(a==="mysql"||a==="vitess"||a==="singlestore")switch(s.type){case"string":return`VARCHAR(${s.maxLength??255})`;case"text":return"TEXT";case"boolean":return"TINYINT(1)";case"integer":return"INTEGER";case"bigint":return"BIGINT";case"float":return"REAL";case"double":return"DOUBLE";case"decimal":return Ft(s).toUpperCase();case"date":return"DATE";case"datetime":case"timestamptz":return"DATETIME";case"json":return"JSON";case"enum":return"ENUM";default:return s.type}if(s.type==="string")return`varchar(${s.maxLength??255})`;if(s.type==="decimal")return Ft(s);return s.type}function Xt(s,a){if(s.type==="string"&&a.type==="string")return(a.maxLength??255)<(s.maxLength??255);if(s.type==="decimal"&&a.type==="decimal"){let l=un(s),c=un(a);return c.scale<l.scale||c.precision-c.scale<l.precision-l.scale}if(s.type==="enum"&&a.type==="enum")return(s.enumValues??[]).some((l)=>!(a.enumValues??[]).includes(l));return!1}var b="UTC_TIMESTAMP";function Ye(s,a){if(!s.hasDefault||s.defaultValue===void 0)return;let l=s.defaultValue;if(l instanceof Date)return l.toISOString();if(typeof l==="boolean")return l?"1":"0";if(typeof l==="bigint"||typeof l==="number")return String(l);let c=String(l).trim();if(c=c.replace(/::[\w ]+$/i,"").trim(),c.startsWith("'")&&c.endsWith("'")||c.startsWith('"')&&c.endsWith('"'))c=c.slice(1,-1);let f=c.toUpperCase();if(["UTC_TIMESTAMP","UTC_TIMESTAMP()","(UTC_TIMESTAMP)","(UTC_TIMESTAMP())","TIMEZONE('UTC', NOW())","TIMEZONE('UTC'::TEXT, NOW())","(NOW() AT TIME ZONE 'UTC')","NOW() AT TIME ZONE 'UTC'"].includes(f.replace(/\s+/g," ")))return b;if(a==="sqlite"&&f==="CURRENT_TIMESTAMP")return b;if(["CURRENT_TIMESTAMP","NOW()","CURRENT_DATE","CURRENT_TIME","NULL","TRUE","FALSE"].includes(f))return f==="NOW()"?"CURRENT_TIMESTAMP":f;if(s.type==="boolean"){if(/^(?:1|t|true|yes)$/i.test(c))return"1";if(/^(?:0|f|false|no)$/i.test(c))return"0"}if(/^-?\d+(?:\.\d+)?$/.test(c))return String(Number(c));return c}function bs(s,a,l){if(ze(s,l)!==ze(a,l))return!0;if(s.isNullable!==a.isNullable)return!0;if(s.hasDefault!==a.hasDefault)return!0;if(Ye(s,l)!==Ye(a,l))return!0;if(s.isUnique!==a.isUnique)return!0;if(s.type==="enum"&&a.type==="enum"){let c=(s.enumValues||[]).slice().sort().join(","),f=(a.enumValues||[]).slice().sort().join(",");if(c!==f)return!0}return!1}function Ir(s,a){return JSON.stringify([ze(s,a),s.isPrimaryKey,s.isUnique,s.isNullable,s.hasDefault,Ye(s,a)??null,(s.enumValues??[]).slice().sort(),s.references?[s.references.table,s.references.column,s.references.onDelete??null,s.references.onUpdate??null]:null])}function hs(s,a,l){let c=Object.keys(s).filter((C)=>!a[C]),f=Object.keys(a).filter((C)=>!s[C]),y=new Map,p=new Map;for(let C of c){let _=Ir(s[C],l),v=y.get(_)??[];v.push(C),y.set(_,v)}for(let C of f){let _=Ir(a[C],l),v=p.get(_)??[];v.push(C),p.set(_,v)}let x=[],T=new Set,R=new Set;for(let[C,_]of y){let v=p.get(C);if(_.length===1&&v&&v.length===1)x.push({from:_[0],to:v[0]}),T.add(_[0]),R.add(v[0])}return{renames:x,removed:c.filter((C)=>!T.has(C)),added:f.filter((C)=>!R.has(C))}}function Ts(s){if(!s?.references||!s.hasDefault)return!1;let a=s.defaultValue;return a!==void 0&&a!==null&&String(a).toUpperCase()!=="NULL"}function xs(s){return!s.isPrimaryKey&&!s.isNullable&&!(s.hasDefault&&s.defaultValue!==void 0)}function Or(s,a){if(!xs(a))return{column:a};let l=`${s}.${a.name} is NOT NULL in the model but has no default, so rows already in "${s}" would have no value for it. It is added as NULLABLE. Backfill it, then give the attribute a default or regenerate from the live database (fromDb) to apply NOT NULL.`;return{column:{...a,isNullable:!0},warning:l}}function Es(s,a){let l=s.columns.find((c)=>c.name===a);if(l&&(l.isPrimaryKey||l.isUnique||l.references))return!0;return s.indexes.some((c)=>c.columns.includes(a))}function Ds(s,a){if(Boolean(s)!==Boolean(a))return!0;if(!s||!a)return!1;if((s.constraintNames?.length??0)>1)return!0;let l=(c)=>(c??"no action").toLowerCase();return s.table!==a.table||s.column!==a.column||l(s.onDelete)!==l(a.onDelete)||l(s.onUpdate)!==l(a.onUpdate)}function Br(s,a){return`${s.type}:${Pt(a,s.name)}:${s.columns.join(",")}:${Zt(s.where)}`}function Zt(s){if(!s||!s.trim())return"";return s.trim().split(/('(?:[^']|'')*')/).map((l,c)=>{if(c%2===1)return l;return l.replace(/::\s*(?:character varying|bit varying|double precision|timestamp(?:\s*\(\d+\))?(?:\s+with(?:out)?\s+time\s+zone)?|time(?:\s+with(?:out)?\s+time\s+zone)?|"?[a-z_][\w$]*"?(?:\s*\(\d+(?:\s*,\s*\d+)?\))?)(?:\[\])?/gi,"").replace(/"/g,"").toLowerCase().replace(/!=/g,"<>").replace(/[()]/g," ").replace(/\s+/g," ").replace(/<>\s*all\s*array\s*\[/g," not in ").replace(/=\s*any\s*array\s*\[/g," in ").replace(/([\w.]+) between (\S+) and (\S+)/g,"$1 >= $2 and $1 <= $3").replace(/[[\]]/g," ").replace(/\s+/g,"")}).join("")}function Fn(s,a){let l={};for(let c of s)l[Br(c,a)]=c;return l}function Xe(s,a,l={}){if(!s||s.dialect!==a.dialect){let{statements:et,files:Ze}=Ne(a);if(l.write===!0&&!l.dryRun)X(Ze,{deterministic:!0});let ee=a.tables.map((nt)=>({kind:"create_table",table:nt.table,destructive:!1,sql:""}));return{statements:et,operations:ee,files:Ze}}let c=l.applyRenames!==!1,f=l.preserveUnknownColumns===!0,y=[],p=(et,Ze)=>{if(et)y.push({name:Ze,sql:et})},x=[],T=[],R=h(a.dialect,{vitessSharded:a.vitessSharded}),C=a.dialect,_=kr(s.tables),v=kr(a.tables);for(let et of Object.keys(_))if(!v[et]){let Ze=R.dropTable(et);x.push(Ze),T.push({kind:"drop_table",table:et,destructive:!0,sql:Ze}),p(Ze,`drop-${et}-table`),Mt(`-- Detected dropped table: ${et}`)}let k=Object.keys(v).filter((et)=>!_[et]).map((et)=>v[et]),{tables:K,deferredForeignKeys:Z}=Kr(k,C);for(let[et,Ze]of K.entries()){let ee={...Ze,columns:Ze.columns.map((Ue)=>Z.has(Bt(Ze.table,Ue.name))?{...Ue,references:void 0}:Ue)},nt=[],_t=new Set;for(let Ue of ee.columns)if(Ue.type==="enum"&&Ue.enumValues&&Ue.enumValues.length>0){let te=`${ee.table}_${Ue.name}_type`;if(Ue.enumTypeName=te,!_t.has(te)){let Ke=R.createEnumType(te,Ue.enumValues);if(Ke)nt.push(Ke);_t.add(te)}}let it=R.createTable(ee);nt.push(it);for(let Ue of ee.indexes){let te=R.createIndex(ee.table,Ue,ee.columns);nt.push(te),T.push({kind:"create_index",table:ee.table,column:Ue.name,destructive:!1,sql:te})}for(let Ue of Ze.columns)if(Ue.references&&!Z.has(Bt(Ze.table,Ue.name)))T.push({kind:"add_foreign_key",table:Ze.table,column:Ue.name,destructive:!1,sql:it});if(et===K.length-1)for(let Ue of K)for(let te of Ue.columns){if(!te.references||!Z.has(Bt(Ue.table,te.name)))continue;let Ke=R.addForeignKey(Ue.table,te.name,te.references.table,te.references.column,te.references.onDelete,te.references.onUpdate);if(!Ke)continue;nt.push(Ke),T.push({kind:"add_foreign_key",table:Ue.table,column:te.name,destructive:!1,sql:Ke})}x.push(...nt),T.push({kind:"create_table",table:ee.table,destructive:!1,sql:it});let lt=nt.join(`
386
386
 
387
- `);p(lt,`create-${Z.table}-table`)}let Pe=new Set,Be=new Set;for(let tt of Object.keys(k)){let Ze=v[tt],Z=k[tt];if(!Ze)continue;let nt=nn(Ze.columns),_t=nn(Z.columns);for(let it of Object.keys(_t)){let lt=_t[it];if(lt.type!=="enum"||!lt.enumValues||lt.enumValues.length===0)continue;let Ue=`${Z.table}_${lt.name}_type`;lt.enumTypeName=Ue;let ee=nt[it];if(ee?.type==="enum"){let Ke=ee.enumValues??[],et=lt.enumValues.filter((We)=>!Ke.includes(We)),ct=Ke.filter((We)=>!lt.enumValues.includes(We)),ut=ee.enumTypeName??Ue;if(E.addEnumValues&&Ke.length>0&&et.length>0&&ct.length===0&&ut===Ue){let We=E.addEnumValues(ut,et);x.push(We),T.push({kind:"add_enum_value",table:Z.table,column:lt.name,destructive:!1,sql:We}),p(We,`alter-${ut}-enum`),Mt(`-- Detected new enum value(s) on ${Z.table}.${lt.name}: ${et.join(", ")}`),Be.add(Bt(Z.table,lt.name))}continue}if(!Pe.has(Ue)){let Ke=E.createEnumType(Ue,lt.enumValues);if(Ke)x.push(Ke),T.push({kind:"create_enum",table:Z.table,column:lt.name,destructive:!1,sql:Ke}),p(Ke,`create-${Ue}-enum`);Pe.add(Ue)}}}for(let tt of Object.keys(k)){let Ze=v[tt],Z=k[tt];if(!Ze)continue;let nt=nn(Ze.columns),_t=Fn(Ze.indexes,Ze.table),it=nn(Z.columns),lt=Fn(Z.indexes,Z.table),Ue=[],ee=Object.keys(nt).filter((Oe)=>!it[Oe]),Ke=Object.keys(it).filter((Oe)=>!nt[Oe]);if(c&&!f){let Oe=ys(nt,it,C);Ue=Oe.renames,ee=Oe.removed,Ke=Oe.added}if(f){let Oe=ee.map((st)=>nt[st]),qe=new Set(Z.indexes.map((st)=>Pt(Z.table,st.name))),Fe=Ze.indexes.filter((st)=>!lt[Kr(st,Ze.table)]&&!qe.has(Pt(Ze.table,st.name)));if(Oe.length>0||Fe.length>0){if(Oe.length>0)Mt(`-- Keeping ${Oe.length} column(s) on "${Z.table}" no model declares: ${ee.join(", ")} \u2014 reconciled from the database, where an undeclared column is out of scope rather than removed`);if(Fe.length>0)Mt(`-- Keeping ${Fe.length} index(es) on "${Z.table}" no model declares: ${Fe.map((st)=>st.name).join(", ")} \u2014 reconciled from the database, where an undeclared index is out of scope rather than removed`);Z={...Z,columns:[...Z.columns,...Oe],indexes:[...Z.indexes,...Fe]},it=nn(Z.columns),lt=Fn(Z.indexes,Z.table)}ee=[]}for(let Oe of Object.keys(nt))if(it[Oe]&&Be.has(Bt(Z.table,Oe)))nt[Oe]={...nt[Oe],enumValues:it[Oe].enumValues};let et=Object.keys(it).filter((Oe)=>nt[Oe]&&gs(nt[Oe],it[Oe],C)),ct=Object.keys(it).filter((Oe)=>nt[Oe]&&xs(nt[Oe].references,it[Oe].references));if(C==="sqlite"){if(et.length>0||ct.length>0||ee.some((qe)=>Ts(Ze,qe))||Ke.some((qe)=>bs(it[qe]))){let qe={},Fe=new Map(Ue.map((at)=>[at.to,at.from])),st=[],Nt=[];for(let at of Z.columns)if(nt[at.name])qe[at.name]=at.name,Nt.push(at);else if(Fe.has(at.name))qe[at.name]=Fe.get(at.name),Nt.push(at);else{let on=Ir(Z.table,at);if(on.warning)st.push(on.warning);Nt.push(on.column)}let qt=st.length>0?{...Z,columns:Nt}:Z,rt=`_qb_tmp_${Z.table}`,an=0;while((v[rt]||k[rt])&&an<100)an+=1,rt=`_qb_tmp_${Z.table}_${an}`;let Ut=E.rebuildTable({target:qt,tempName:rt,columnSource:qe});x.push(Ut);let Qt=et.some((at)=>nt[at].type!==it[at].type);if(T.push({kind:"rebuild_table",table:Z.table,destructive:ee.length>0||Qt,sql:Ut,...st.length>0?{warning:st.join(" ")}:{}}),l.write===!0&&!l.dryRun)st.forEach((at)=>console.warn(`-- ${at}`));for(let at of Ue)T.push({kind:"rename_column",table:Z.table,from:at.from,to:at.to,destructive:!1,confidence:"high",sql:Ut});for(let at of ee)T.push({kind:"drop_column",table:Z.table,column:at,destructive:!0,sql:Ut});Mt(`-- Detected SQLite table rebuild required: ${Z.table}`),p(`${st.map((at)=>`-- qb: ${at}
388
- `).join("")}${Ut}`,`alter-${Z.table}-table`);continue}}let ut=[],We=!1;for(let Oe of Object.keys(_t))if(!lt[Oe]){let qe=_t[Oe],Fe=E.dropIndex(Z.table,qe.name);ut.push(Fe),x.push(Fe),T.push({kind:"drop_index",table:Z.table,column:qe.name,destructive:!1,sql:Fe}),Mt(`-- Detected dropped index: ${qe.name} from ${Z.table}`),We=!0}for(let Oe of Ue){let qe=E.renameColumn(Z.table,Oe.from,Oe.to);ut.push(qe),x.push(qe),T.push({kind:"rename_column",table:Z.table,from:Oe.from,to:Oe.to,destructive:!1,confidence:"high",sql:qe}),Mt(`-- Detected renamed column: ${Z.table}.${Oe.from} -> ${Oe.to}`),We=!0}for(let Oe of ee){let qe=E.dropColumn(Z.table,Oe);ut.push(qe),x.push(qe),T.push({kind:"drop_column",table:Z.table,column:Oe,destructive:!0,sql:qe}),Mt(`-- Detected dropped column: ${Z.table}.${Oe}`),We=!0}for(let Oe of et){let qe=nt[Oe],Fe=it[Oe],st=E.modifyColumn(Z.table,Fe,qe);ut.push(st),x.push(st),T.push({kind:"modify_column",table:Z.table,column:Oe,destructive:qe.type!==Fe.type&&!zt(qe.type,Fe.type)||Xt(qe,Fe),sql:st}),Mt(`-- Detected column change: ${Z.table}.${Oe} (${qe.type} -> ${Fe.type})`),We=!0}for(let Oe of ct){let qe=it[Oe];if(!qe.references)continue;let Fe=E.addForeignKey(Z.table,qe.name,qe.references.table,qe.references.column,qe.references.onDelete,qe.references.onUpdate,nt[Oe].references?.constraintNames);if(!Fe)continue;ut.push(Fe),x.push(Fe),T.push({kind:"add_foreign_key",table:Z.table,column:Oe,destructive:!1,sql:Fe}),Mt(`-- Detected foreign-key change: ${Z.table}.${Oe} -> ${qe.references.table}(${qe.references.column})`),We=!0}for(let Oe of Ke){let{column:qe,warning:Fe}=Ir(Z.table,it[Oe]),st=E.addColumn(Z.table,qe);if(ut.push(Fe?`-- qb: ${Fe}
389
- ${st}`:st),x.push(st),T.push({kind:"add_column",table:Z.table,column:qe.name,destructive:!1,sql:st,...Fe?{warning:Fe}:{}}),Mt(`-- Detected new column: ${Z.table}.${qe.name}`),Fe&&l.write===!0&&!l.dryRun)console.warn(`-- ${Fe}`);if(We=!0,qe.references){let Nt=E.addForeignKey(Z.table,qe.name,qe.references.table,qe.references.column,qe.references.onDelete,qe.references.onUpdate);if(Nt)ut.push(Nt),x.push(Nt),T.push({kind:"add_foreign_key",table:Z.table,column:qe.name,destructive:!1,sql:Nt})}}for(let Oe of Object.keys(lt))if(!_t[Oe]){let qe=lt[Oe],Fe=E.createIndex(Z.table,qe,Z.columns);ut.push(Fe),x.push(Fe),T.push({kind:"create_index",table:Z.table,column:qe.name,destructive:!1,sql:Fe}),Mt(`-- Detected new index: ${qe.name} in ${Z.table}`),We=!0}if(We){let Oe=ut.join(`
387
+ `);p(lt,`create-${ee.table}-table`)}let _e=new Set,Be=new Set;for(let et of Object.keys(v)){let Ze=_[et],ee=v[et];if(!Ze)continue;let nt=nn(Ze.columns),_t=nn(ee.columns);for(let it of Object.keys(_t)){let lt=_t[it];if(lt.type!=="enum"||!lt.enumValues||lt.enumValues.length===0)continue;let Ue=`${ee.table}_${lt.name}_type`;lt.enumTypeName=Ue;let te=nt[it];if(te?.type==="enum"){let Ke=te.enumValues??[],tt=lt.enumValues.filter((We)=>!Ke.includes(We)),ct=Ke.filter((We)=>!lt.enumValues.includes(We)),ut=te.enumTypeName??Ue;if(R.addEnumValues&&Ke.length>0&&tt.length>0&&ct.length===0&&ut===Ue){let We=R.addEnumValues(ut,tt);x.push(We),T.push({kind:"add_enum_value",table:ee.table,column:lt.name,destructive:!1,sql:We}),p(We,`alter-${ut}-enum`),Mt(`-- Detected new enum value(s) on ${ee.table}.${lt.name}: ${tt.join(", ")}`),Be.add(Bt(ee.table,lt.name))}continue}if(!_e.has(Ue)){let Ke=R.createEnumType(Ue,lt.enumValues);if(Ke)x.push(Ke),T.push({kind:"create_enum",table:ee.table,column:lt.name,destructive:!1,sql:Ke}),p(Ke,`create-${Ue}-enum`);_e.add(Ue)}}}for(let et of Object.keys(v)){let Ze=_[et],ee=v[et];if(!Ze)continue;let nt=nn(Ze.columns),_t=Fn(Ze.indexes,Ze.table),it=nn(ee.columns),lt=Fn(ee.indexes,ee.table),Ue=[],te=Object.keys(nt).filter((Oe)=>!it[Oe]),Ke=Object.keys(it).filter((Oe)=>!nt[Oe]);if(c&&!f){let Oe=hs(nt,it,C);Ue=Oe.renames,te=Oe.removed,Ke=Oe.added}if(f){let Oe=te.map((st)=>nt[st]),qe=new Set(ee.indexes.map((st)=>Pt(ee.table,st.name))),Fe=Ze.indexes.filter((st)=>!lt[Br(st,Ze.table)]&&!qe.has(Pt(Ze.table,st.name)));if(Oe.length>0||Fe.length>0){if(Oe.length>0)Mt(`-- Keeping ${Oe.length} column(s) on "${ee.table}" no model declares: ${te.join(", ")} \u2014 reconciled from the database, where an undeclared column is out of scope rather than removed`);if(Fe.length>0)Mt(`-- Keeping ${Fe.length} index(es) on "${ee.table}" no model declares: ${Fe.map((st)=>st.name).join(", ")} \u2014 reconciled from the database, where an undeclared index is out of scope rather than removed`);ee={...ee,columns:[...ee.columns,...Oe],indexes:[...ee.indexes,...Fe]},it=nn(ee.columns),lt=Fn(ee.indexes,ee.table)}te=[]}for(let Oe of Object.keys(nt))if(it[Oe]&&Be.has(Bt(ee.table,Oe)))nt[Oe]={...nt[Oe],enumValues:it[Oe].enumValues};let tt=Object.keys(it).filter((Oe)=>nt[Oe]&&bs(nt[Oe],it[Oe],C)),ct=Object.keys(it).filter((Oe)=>nt[Oe]&&Ds(nt[Oe].references,it[Oe].references));if(C==="sqlite"){if(tt.length>0||ct.length>0||te.some((qe)=>Es(Ze,qe))||Ke.some((qe)=>Ts(it[qe]))){let qe={},Fe=new Map(Ue.map((at)=>[at.to,at.from])),st=[],Nt=[];for(let at of ee.columns)if(nt[at.name])qe[at.name]=at.name,Nt.push(at);else if(Fe.has(at.name))qe[at.name]=Fe.get(at.name),Nt.push(at);else{let on=Or(ee.table,at);if(on.warning)st.push(on.warning);Nt.push(on.column)}let qt=st.length>0?{...ee,columns:Nt}:ee,rt=`_qb_tmp_${ee.table}`,an=0;while((_[rt]||v[rt])&&an<100)an+=1,rt=`_qb_tmp_${ee.table}_${an}`;let Ut=R.rebuildTable({target:qt,tempName:rt,columnSource:qe});x.push(Ut);let Qt=tt.some((at)=>nt[at].type!==it[at].type);if(T.push({kind:"rebuild_table",table:ee.table,destructive:te.length>0||Qt,sql:Ut,...st.length>0?{warning:st.join(" ")}:{}}),l.write===!0&&!l.dryRun)st.forEach((at)=>console.warn(`-- ${at}`));for(let at of Ue)T.push({kind:"rename_column",table:ee.table,from:at.from,to:at.to,destructive:!1,confidence:"high",sql:Ut});for(let at of te)T.push({kind:"drop_column",table:ee.table,column:at,destructive:!0,sql:Ut});Mt(`-- Detected SQLite table rebuild required: ${ee.table}`),p(`${st.map((at)=>`-- qb: ${at}
388
+ `).join("")}${Ut}`,`alter-${ee.table}-table`);continue}}let ut=[],We=!1;for(let Oe of Object.keys(_t))if(!lt[Oe]){let qe=_t[Oe],Fe=R.dropIndex(ee.table,qe.name);ut.push(Fe),x.push(Fe),T.push({kind:"drop_index",table:ee.table,column:qe.name,destructive:!1,sql:Fe}),Mt(`-- Detected dropped index: ${qe.name} from ${ee.table}`),We=!0}for(let Oe of Ue){let qe=R.renameColumn(ee.table,Oe.from,Oe.to);ut.push(qe),x.push(qe),T.push({kind:"rename_column",table:ee.table,from:Oe.from,to:Oe.to,destructive:!1,confidence:"high",sql:qe}),Mt(`-- Detected renamed column: ${ee.table}.${Oe.from} -> ${Oe.to}`),We=!0}for(let Oe of te){let qe=R.dropColumn(ee.table,Oe);ut.push(qe),x.push(qe),T.push({kind:"drop_column",table:ee.table,column:Oe,destructive:!0,sql:qe}),Mt(`-- Detected dropped column: ${ee.table}.${Oe}`),We=!0}for(let Oe of tt){let qe=nt[Oe],Fe=it[Oe],st=R.modifyColumn(ee.table,Fe,qe);ut.push(st),x.push(st),T.push({kind:"modify_column",table:ee.table,column:Oe,destructive:qe.type!==Fe.type&&!zt(qe.type,Fe.type)||Xt(qe,Fe),sql:st}),Mt(`-- Detected column change: ${ee.table}.${Oe} (${qe.type} -> ${Fe.type})`),We=!0}for(let Oe of ct){let qe=it[Oe];if(!qe.references)continue;let Fe=R.addForeignKey(ee.table,qe.name,qe.references.table,qe.references.column,qe.references.onDelete,qe.references.onUpdate,nt[Oe].references?.constraintNames);if(!Fe)continue;ut.push(Fe),x.push(Fe),T.push({kind:"add_foreign_key",table:ee.table,column:Oe,destructive:!1,sql:Fe}),Mt(`-- Detected foreign-key change: ${ee.table}.${Oe} -> ${qe.references.table}(${qe.references.column})`),We=!0}for(let Oe of Ke){let{column:qe,warning:Fe}=Or(ee.table,it[Oe]),st=R.addColumn(ee.table,qe);if(ut.push(Fe?`-- qb: ${Fe}
389
+ ${st}`:st),x.push(st),T.push({kind:"add_column",table:ee.table,column:qe.name,destructive:!1,sql:st,...Fe?{warning:Fe}:{}}),Mt(`-- Detected new column: ${ee.table}.${qe.name}`),Fe&&l.write===!0&&!l.dryRun)console.warn(`-- ${Fe}`);if(We=!0,qe.references){let Nt=R.addForeignKey(ee.table,qe.name,qe.references.table,qe.references.column,qe.references.onDelete,qe.references.onUpdate);if(Nt)ut.push(Nt),x.push(Nt),T.push({kind:"add_foreign_key",table:ee.table,column:qe.name,destructive:!1,sql:Nt})}}for(let Oe of Object.keys(lt))if(!_t[Oe]){let qe=lt[Oe],Fe=R.createIndex(ee.table,qe,ee.columns);ut.push(Fe),x.push(Fe),T.push({kind:"create_index",table:ee.table,column:qe.name,destructive:!1,sql:Fe}),Mt(`-- Detected new index: ${qe.name} in ${ee.table}`),We=!0}if(We){let Oe=ut.join(`
390
390
 
391
- `);p(Oe,`alter-${Z.table}-table`)}}if(l.write===!0&&!l.dryRun)Y(y,{deterministic:!1});return{statements:x.length===0?["-- No changes detected"]:x,operations:T,files:y}}function en(s,a,l={}){return Xe(s,a,l).statements}function In(s){return s}class tn{get order(){return 100}get description(){return}}function Ln(s){return s}export{te,ne,re,ie,K,se,ae,oe,le,F,ce,j,q,ue,de,W,fe,me,dt,He,ft,R,he,o,ge,pe,ye,be,h,mt,ht,gt,Qe,Ge,pt,S,A,Je,N,Te,we,U,Se,V,De,H,Q,M,G,Ee,$e,xe,ve,J,ke,Ce,D,g,$n,xn,vn,yt,bt,Tt,wt,St,kn,Dt,Jt,Cn,Rn,An,Nn,Et,Mn,On,Pn,Re,d,$t,xt,vt,kt,Ct,zt,z,Y,Ae,Yt,Bn,_n,Rt,ze,Xt,b,Ye,Zt,Xe,en,In,tn,Ln};
391
+ `);p(Oe,`alter-${ee.table}-table`)}}if(l.write===!0&&!l.dryRun)X(y,{deterministic:!1});return{statements:x.length===0?["-- No changes detected"]:x,operations:T,files:y}}function en(s,a,l={}){return Xe(s,a,l).statements}function In(s){return s}class tn{get order(){return 100}get description(){return}}function Ln(s){return s}export{ne,re,ie,se,F,ae,oe,le,ce,j,ue,q,W,de,fe,U,me,he,dt,He,ft,A,ge,o,pe,ye,be,Te,h,mt,ht,gt,Qe,Ge,pt,S,N,Je,M,we,Se,V,De,H,Ee,Q,G,P,J,$e,xe,ve,ke,z,Ce,Re,D,g,$n,xn,vn,yt,bt,Tt,wt,St,kn,Dt,Jt,Cn,Rn,An,Nn,Et,Mn,Pn,On,Ae,d,$t,xt,vt,kt,Ct,zt,Y,X,Ne,Yt,Bn,_n,Rt,ze,Xt,b,Ye,Zt,Xe,en,In,tn,Ln};