bun-query-builder 0.2.70 → 0.3.0

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.
@@ -0,0 +1,383 @@
1
+ // @bun
2
+ import{n,e,B,t,P,Be,Ge,r,b,f}from"./chunk-hjgcemhy.js";import{i,xe,ve}from"./chunk-c7m701dd.js";import{M,Ae,Me,N}from"./chunk-cxpaxq2p.js";import{c}from"./chunk-3xpe6b57.js";var Ar=import.meta.require;import{existsSync as Nt,mkdirSync as yr,mkdtempSync as qi,readdirSync as br,readFileSync as Ht,rmSync as hr,unlinkSync as vn,writeFileSync as Tr}from"fs";import{tmpdir as Ki}from"os";import{isAbsolute as Li,join as wt}from"path";import kn from"process";function wr(s){let o=2166136261;for(let l=0;l<s.length;l++)o^=s.charCodeAt(l),o=Math.imul(o,16777619)>>>0;return o.toString(36).padStart(7,"0").slice(-7)}function Cr(s,o=63){if(s.length<=o)return s;let l=`_${wr(s)}`;return s.slice(0,o-l.length)+l}function Ct(s,o){let l=`${s}_`,d=o.startsWith(l)?o:`${l}${o}`;return Cr(d)}class a{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"decimal(10,2)";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 o=s.defaultValue;if(typeof o==="string"){let l=o.toUpperCase();if(l==="UTC_TIMESTAMP")return"default (UTC_TIMESTAMP)";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(l))return`default ${l}`;let g=`'${o.replace(/'/g,"''")}'`;if(s.type==="text"||s.type==="json"||s.type==="enum"&&!s.enumValues?.length)return`default (${g})`;return`default ${g}`}else if(typeof o==="number"||typeof o==="bigint")return`default ${o}`;else if(typeof o==="boolean")return`default ${o?1:0}`;else if(o instanceof Date)return`default '${o.toISOString()}'`;return""}createEnumType(s,o){return""}foreignKeyClauses(s){return s.columns.filter((o)=>o.references).map((o)=>{let l=o.references,d=`${s.table}_${o.name}_fk`,g=`CONSTRAINT ${this.quoteIdentifier(d)} FOREIGN KEY (${this.quoteIdentifier(o.name)}) REFERENCES ${this.quoteIdentifier(l.table)}(${this.quoteIdentifier(l.column)})`;if(l.onDelete)g+=` ON DELETE ${l.onDelete.toUpperCase()}`;if(l.onUpdate)g+=` ON UPDATE ${l.onUpdate.toUpperCase()}`;return g})}createTable(s){let o=[...s.columns.map((l)=>this.renderColumn(l)),...this.foreignKeyClauses(s)];return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(s.table)} (
3
+ ${o.join(`,
4
+ `)}
5
+ ) DEFAULT CHARSET=utf8mb4;`}static KEY_PREFIX_CHARACTERS=255;static MAX_KEY_BYTES=3072;static BYTES_PER_CHARACTER=4;keyPartWidth(s){let o=this.getColumnType(s).toLowerCase();if(o.includes("text")||o.includes("blob")||o==="json")return{bytes:Number.POSITIVE_INFINITY,indexableWhole:!1};let l=o.match(/^(?:var)?char\((\d+)\)$/)?.[1];if(l!==void 0)return{bytes:Number(l)*a.BYTES_PER_CHARACTER,indexableWhole:!0};return{bytes:8,indexableWhole:!0}}keyParts(s,o,l){let d=o.columns.map((x)=>{let y=l?.find((S)=>S.name===x),E=y?this.keyPartWidth(y):{bytes:0,indexableWhole:!0},D=!E.indexableWhole;return{name:x,prefixed:D,bytes:D?a.KEY_PREFIX_CHARACTERS*a.BYTES_PER_CHARACTER:E.bytes,narrowable:!E.indexableWhole||E.bytes>a.KEY_PREFIX_CHARACTERS*a.BYTES_PER_CHARACTER}}),g=()=>d.reduce((x,y)=>x+y.bytes,0);while(g()>a.MAX_KEY_BYTES){let x=d.filter((y)=>y.narrowable&&!y.prefixed).sort((y,E)=>E.bytes-y.bytes)[0];if(!x)throw Error(`[migrations] Index '${o.name}' on table '${s}' needs ${g()} bytes of key, over MySQL's ${a.MAX_KEY_BYTES}. Every column in it is already at its ${a.KEY_PREFIX_CHARACTERS}-character prefix, so shorten a column or drop one from the index.`);x.prefixed=!0,x.bytes=a.KEY_PREFIX_CHARACTERS*a.BYTES_PER_CHARACTER}return d.map((x)=>x.prefixed?`${this.quoteIdentifier(x.name)}(${a.KEY_PREFIX_CHARACTERS})`:this.quoteIdentifier(x.name))}createIndex(s,o,l){if(o.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on MySQL. Index '${o.name}' on table '${s}' uses WHERE clause: ${o.where}`);let d=o.type==="unique"?"UNIQUE ":"",g=Ct(s,o.name),x=this.keyParts(s,o,l).join(", ");return`CREATE ${d}INDEX ${this.quoteIdentifier(g)} ON ${this.quoteIdentifier(s)} (${x});`}addForeignKey(s,o,l,d,g,x,y=[]){let E=`${s}_${o}_fk`,D=`ALTER TABLE ${this.quoteIdentifier(s)} ADD CONSTRAINT ${this.quoteIdentifier(E)} FOREIGN KEY (${this.quoteIdentifier(o)}) REFERENCES ${this.quoteIdentifier(l)}(${this.quoteIdentifier(d)})`;if(g)D+=` ON DELETE ${g.toUpperCase()}`;if(x)D+=` ON UPDATE ${x.toUpperCase()}`;let S=[...new Set(y)].map((v)=>`ALTER TABLE ${this.quoteIdentifier(s)} DROP FOREIGN KEY ${this.quoteIdentifier(v)};`).join(`
6
+ `);return S?`${S}
7
+ ${D};`:`${D};`}addColumn(s,o){let l=this.getColumnType(o),d=[this.quoteIdentifier(o.name),l];if(!o.isNullable&&!o.isPrimaryKey)d.push("not null");let g=this.getDefaultValue(o);if(g)d.push(g);return`ALTER TABLE ${this.quoteIdentifier(s)} ADD COLUMN ${d.join(" ")};`}modifyColumn(s,o){let l=this.getColumnType(o),d=[this.quoteIdentifier(o.name),l];if(!o.isNullable&&!o.isPrimaryKey)d.push("not null");let g=this.getDefaultValue(o);if(g)d.push(g);let x=this.getAutoIncrementClause(o);if(x)d.push(x);return`ALTER TABLE ${this.quoteIdentifier(s)} MODIFY COLUMN ${d.join(" ")};`}renameColumn(s,o,l){return`ALTER TABLE ${this.quoteIdentifier(s)} RENAME COLUMN ${this.quoteIdentifier(o)} TO ${this.quoteIdentifier(l)};`}renameTable(s,o){return`RENAME TABLE ${this.quoteIdentifier(s)} TO ${this.quoteIdentifier(o)};`}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,o){return`ALTER TABLE ${this.quoteIdentifier(s)} DROP COLUMN ${this.quoteIdentifier(o)};`}dropIndex(s,o){let l=Ct(s,o);return`DROP INDEX ${this.quoteIdentifier(l)} ON ${this.quoteIdentifier(s)};`}dropEnumType(s){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
8
+ id INT AUTO_INCREMENT PRIMARY KEY,
9
+ migration VARCHAR(255) NOT NULL UNIQUE,
10
+ executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
11
+ )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}jsonExtract(s,o){return`JSON_UNQUOTE(JSON_EXTRACT(${s}, CONCAT('$.', ${o})))`}dateBucket(s,o,l=0){let d=l===0?s:`DATE_ADD(${s}, INTERVAL ${l} HOUR)`;switch(o){case"hour":return`DATE_FORMAT(${d}, '%Y-%m-%dT%H:00:00.000Z')`;case"week":return`DATE_FORMAT(DATE_SUB(${d}, INTERVAL WEEKDAY(${d}) DAY), '%Y-%m-%dT00:00:00.000Z')`;case"month":return`DATE_FORMAT(${d}, '%Y-%m-01T00:00:00.000Z')`;case"year":return`DATE_FORMAT(${d}, '%Y-01-01T00:00:00.000Z')`;case"day":default:return`DATE_FORMAT(${d}, '%Y-%m-%dT00:00:00.000Z')`}}booleanLiteral(s){return s?"TRUE":"FALSE"}renderColumn(s){let o=this.getColumnType(s),l=[this.quoteIdentifier(s.name),o];if(s.isPrimaryKey){l.push("PRIMARY KEY");let g=this.getAutoIncrementClause(s);if(g)l.push(g)}if(!s.isNullable&&!s.isPrimaryKey)l.push("not null");let d=this.getDefaultValue(s);if(d)l.push(d);return l.join(" ")}}class ce{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"decimal(10,2)";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 o=s.defaultValue;if(typeof o==="string"){let l=o.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 '${o.replace(/'/g,"''")}'`}else if(typeof o==="number"||typeof o==="bigint")return`default ${o}`;else if(typeof o==="boolean")return`default ${o?"true":"false"}`;else if(o instanceof Date)return`default '${o.toISOString()}'`;return""}createEnumType(s,o){let l=o.map((d)=>`'${d.replace(/'/g,"''")}'`).join(", ");return`CREATE TYPE ${this.quoteIdentifier(s)} AS ENUM (${l});`}createTable(s){let o=s.columns.map((l)=>this.renderColumn(l)).join(`,
12
+ `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(s.table)} (
13
+ ${o}
14
+ );`}createIndex(s,o){let l=o.type==="unique"?"UNIQUE ":"",d=Ct(s,o.name),g=o.columns.map((y)=>this.quoteIdentifier(y)).join(", "),x=o.where?` WHERE ${o.where}`:"";return`CREATE ${l}INDEX IF NOT EXISTS ${this.quoteIdentifier(d)} ON ${this.quoteIdentifier(s)} (${g})${x};`}addForeignKey(s,o,l,d,g,x,y=[]){let E=`${s}_${o}_fk`,D=`ALTER TABLE ${this.quoteIdentifier(s)} ADD CONSTRAINT ${this.quoteIdentifier(E)} FOREIGN KEY (${this.quoteIdentifier(o)}) REFERENCES ${this.quoteIdentifier(l)}(${this.quoteIdentifier(d)})`;if(g)D+=` ON DELETE ${g.toUpperCase()}`;if(x)D+=` ON UPDATE ${x.toUpperCase()}`;let S=[...new Set(y)].map((v)=>`ALTER TABLE ${this.quoteIdentifier(s)} DROP CONSTRAINT ${this.quoteIdentifier(v)};`).join(`
15
+ `);return S?`${S}
16
+ ${D};`:`${D};`}addColumn(s,o){let l=this.getColumnType(o),d=[this.quoteIdentifier(o.name),l];if(!o.isNullable&&!o.isPrimaryKey)d.push("not null");let g=this.getDefaultValue(o);if(g)d.push(g);return`ALTER TABLE ${this.quoteIdentifier(s)} ADD COLUMN ${d.join(" ")};`}modifyColumn(s,o){let l=this.getColumnType(o),d=this.quoteIdentifier(s),g=this.quoteIdentifier(o.name),x=[`ALTER TABLE ${d} ALTER COLUMN ${g} DROP DEFAULT;`,`ALTER TABLE ${d} ALTER COLUMN ${g} TYPE ${l} USING ${g}::${l};`];if(!o.isPrimaryKey)x.push(`ALTER TABLE ${d} ALTER COLUMN ${g} ${o.isNullable?"DROP NOT NULL":"SET NOT NULL"};`);let y=this.getDefaultValue(o);if(y)x.push(`ALTER TABLE ${d} ALTER COLUMN ${g} SET ${y};`);return x.join(`
17
+ `)}renameColumn(s,o,l){return`ALTER TABLE ${this.quoteIdentifier(s)} RENAME COLUMN ${this.quoteIdentifier(o)} TO ${this.quoteIdentifier(l)};`}renameTable(s,o){return`ALTER TABLE ${this.quoteIdentifier(s)} RENAME TO ${this.quoteIdentifier(o)};`}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,o){return`ALTER TABLE ${this.quoteIdentifier(s)} DROP COLUMN ${this.quoteIdentifier(o)};`}dropIndex(s,o){let l=Ct(s,o);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 (
18
+ id SERIAL PRIMARY KEY,
19
+ migration VARCHAR(255) NOT NULL UNIQUE,
20
+ executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
21
+ )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES ($1)"}jsonExtract(s,o){return`(${s}::jsonb ->> ${o})`}dateBucket(s,o,l=0){let d=l===0?`${s}::timestamp`:`(${s}::timestamp ${l>=0?"+":"-"} interval '${Math.abs(l)} hours')`,g=o==="week"?`date_trunc('week', ${d})`:d;switch(o){case"hour":return`to_char(${g}, 'YYYY-MM-DD"T"HH24:00:00.000"Z"')`;case"month":return`to_char(${g}, 'YYYY-MM-01"T"00:00:00.000"Z"')`;case"year":return`to_char(${g}, 'YYYY-01-01"T"00:00:00.000"Z"')`;case"week":case"day":default:return`to_char(${g}, 'YYYY-MM-DD"T"00:00:00.000"Z"')`}}booleanLiteral(s){return s?"TRUE":"FALSE"}renderColumn(s){let o=s.isPrimaryKey?this.getPrimaryKeyType(s):this.getColumnType(s),l=[this.quoteIdentifier(s.name),o];if(s.isPrimaryKey)l.push("PRIMARY KEY");if(!s.isNullable&&!s.isPrimaryKey)l.push("not null");let d=this.getDefaultValue(s);if(d)l.push(d);if(s.references){let g=`REFERENCES ${this.quoteIdentifier(s.references.table)}(${this.quoteIdentifier(s.references.column)})`;if(s.references.onDelete)g+=` ON DELETE ${s.references.onDelete.toUpperCase()}`;if(s.references.onUpdate)g+=` ON UPDATE ${s.references.onUpdate.toUpperCase()}`;l.push(g)}return l.join(" ")}}class ue extends a{createTable(s){let o=s.columns.map((x)=>this.renderColumn(x)).join(`,
22
+ `),l=[];if(s.tableKind!=="reference"){let x=s.shardKey?.length?s.shardKey:s.columns.filter((y)=>y.isPrimaryKey).map((y)=>y.name);if(x&&x.length>0)l.push(`SHARD KEY (${x.map((y)=>this.quoteIdentifier(y)).join(", ")})`)}if(s.tableKind!=="rowstore"&&s.tableKind!=="reference"){let x=s.sortKey?.length?s.sortKey:void 0;l.push(`SORT KEY (${(x??[]).map((y)=>this.quoteIdentifier(y)).join(", ")})`)}let d=[o,...l].join(`,
23
+ `);return`CREATE${this.tableKindSuffix(s.tableKind)} TABLE IF NOT EXISTS ${this.quoteIdentifier(s.table)} (
24
+ ${d}
25
+ );`}tableKindSuffix(s){switch(s){case"rowstore":return" ROWSTORE";case"reference":return" REFERENCE";default:return""}}addForeignKey(){return""}createIndex(s,o,l){if(o.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on SingleStore. Index '${o.name}' on table '${s}' uses WHERE clause: ${o.where}`);return super.createIndex(s,o,l)}}class de extends a{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:o,...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 (
26
+ migration VARCHAR(255) NOT NULL PRIMARY KEY,
27
+ executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
28
+ )`}}class fe{quoteIdentifier(s){return`"${s.replace(/"/g,'""')}"`}getColumnType(s){if(s.name.endsWith("_id")&&M(s.type))return"INTEGER";if(s.type==="enum"){if(s.enumValues&&s.enumValues.length>0){let o=s.enumValues.map((l)=>`'${l.replace(/'/g,"''")}'`).join(", ");return`TEXT CHECK (${this.quoteIdentifier(s.name)} IN (${o}))`}return"TEXT"}return Ae(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 o=s.defaultValue;if(typeof o==="string"){if(o.toUpperCase()==="UTC_TIMESTAMP")return"default CURRENT_TIMESTAMP";if(["CURRENT_TIMESTAMP","CURRENT_DATE","CURRENT_TIME","NOW()","NULL","TRUE","FALSE"].includes(o.toUpperCase()))return`default ${o.toUpperCase()}`;return`default '${o.replace(/'/g,"''")}'`}else if(typeof o==="number"||typeof o==="bigint")return`default ${o}`;else if(typeof o==="boolean")return`default ${o?1:0}`;else if(o instanceof Date)return`default '${o.toISOString()}'`;return""}createEnumType(s,o){return""}createTable(s){let o=s.columns.map((l)=>this.renderColumn(l)).join(`,
29
+ `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(s.table)} (
30
+ ${o}
31
+ );`}createIndex(s,o){let l=o.type==="unique"?"UNIQUE ":"",d=Ct(s,o.name),g=o.columns.map((y)=>this.quoteIdentifier(y)).join(", "),x=o.where?` WHERE ${o.where}`:"";return`CREATE ${l}INDEX IF NOT EXISTS ${this.quoteIdentifier(d)} ON ${this.quoteIdentifier(s)} (${g})${x};`}addForeignKey(s,o,l,d,g,x){return""}addColumn(s,o){let l=this.getColumnType(o),d=[this.quoteIdentifier(o.name),l];if(!o.isNullable&&!o.isPrimaryKey)d.push("not null");let g=this.getDefaultValue(o);if(g)d.push(g);return d.push(...this.referencesClause(o)),`ALTER TABLE ${this.quoteIdentifier(s)} ADD COLUMN ${d.join(" ")};`}modifyColumn(s,o){return`-- SQLite does not support ALTER COLUMN; a table rebuild is required to change ${this.quoteIdentifier(s)}.${this.quoteIdentifier(o.name)}`}renameColumn(s,o,l){return`ALTER TABLE ${this.quoteIdentifier(s)} RENAME COLUMN ${this.quoteIdentifier(o)} TO ${this.quoteIdentifier(l)};`}renameTable(s,o){return`ALTER TABLE ${this.quoteIdentifier(s)} RENAME TO ${this.quoteIdentifier(o)};`}rebuildTable(s){let{target:o,tempName:l,columnSource:d}=s,g=(S)=>this.quoteIdentifier(S),x=o.columns.map((S)=>this.renderColumn(S)).join(`,
32
+ `),y=`CREATE TABLE ${g(l)} (
33
+ ${x}
34
+ );`,E=o.columns.map((S)=>S.name).filter((S)=>d[S]!==void 0),D=["PRAGMA foreign_keys=OFF;","BEGIN;",y];if(E.length>0){let S=E.map(g).join(", "),v=E.map((Q)=>g(d[Q])).join(", ");D.push(`INSERT INTO ${g(l)} (${S}) SELECT ${v} FROM ${g(o.table)};`)}D.push(`DROP TABLE ${g(o.table)};`),D.push(`ALTER TABLE ${g(l)} RENAME TO ${g(o.table)};`);for(let S of o.indexes)D.push(this.createIndex(o.table,S));return D.push("PRAGMA foreign_key_check;"),D.push("COMMIT;"),D.push("PRAGMA foreign_keys=ON;"),D.join(`
35
+ `)}dropTable(s){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(s)}`}dropColumn(s,o){return`ALTER TABLE ${this.quoteIdentifier(s)} DROP COLUMN ${this.quoteIdentifier(o)};`}dropIndex(s,o){let l=Ct(s,o);return`DROP INDEX IF EXISTS ${this.quoteIdentifier(l)};`}dropEnumType(s){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
36
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
37
+ migration TEXT NOT NULL UNIQUE,
38
+ executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
39
+ )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}jsonExtract(s,o){return`json_extract(${s}, '$.' || ${o})`}dateBucket(s,o,l=0){let d=l===0?s:`datetime(${s}, '${l>=0?"+":"-"}${Math.abs(l)} hours')`;switch(o){case"hour":return`strftime('%Y-%m-%dT%H:00:00.000Z', ${d})`;case"week":return`strftime('%Y-%m-%dT00:00:00.000Z', ${d}, '-6 days', 'weekday 1')`;case"month":return`strftime('%Y-%m-01T00:00:00.000Z', ${d})`;case"year":return`strftime('%Y-01-01T00:00:00.000Z', ${d})`;case"day":default:return`strftime('%Y-%m-%dT00:00:00.000Z', ${d})`}}booleanLiteral(s){return s?"TRUE":"FALSE"}renderColumn(s){let o=this.getColumnType(s),l=[this.quoteIdentifier(s.name),o];if(s.isPrimaryKey){l.push("PRIMARY KEY");let g=this.getAutoIncrementClause(s);if(g)l.push(g)}if(!s.isNullable&&!s.isPrimaryKey)l.push("not null");let d=this.getDefaultValue(s);if(d)l.push(d);return l.push(...this.referencesClause(s)),l.join(" ")}referencesClause(s){if(!s.references)return[];let o=[`REFERENCES ${this.quoteIdentifier(s.references.table)}(${this.quoteIdentifier(s.references.column)})`];if(s.references.onDelete)o.push(`ON DELETE ${s.references.onDelete.toUpperCase()}`);if(s.references.onUpdate)o.push(`ON UPDATE ${s.references.onUpdate.toUpperCase()}`);return o}}function m(s,o={}){switch(s){case"postgres":return new ce;case"mysql":return new a;case"singlestore":return new ue;case"vitess":return new de(o.vitessSharded??e.vitess?.sharded??!0);case"sqlite":return new fe;default:throw Error(`Unsupported dialect: ${s}`)}}async function J(s={}){let o=s.iterations||1000,l=s.operations?.split(",")||["select","insert","update","delete","count"];console.log("-- Running Query Builder Benchmarks"),console.log(`-- Iterations: ${o}`),console.log(`-- Operations: ${l.join(", ")}`),console.log();let d=i();console.log("-- Setting up test table...");try{await r.unsafe("DROP TABLE IF EXISTS bench_users").execute(),await r.unsafe(`
40
+ CREATE TABLE bench_users (
41
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
42
+ name TEXT NOT NULL,
43
+ email TEXT NOT NULL,
44
+ active INTEGER DEFAULT 1,
45
+ created_at TEXT
46
+ )
47
+ `).execute();for(let y=0;y<100;y++)await r.unsafe(`
48
+ INSERT INTO bench_users (name, email, created_at)
49
+ VALUES (?, ?, ?)
50
+ `,[`User ${y}`,`user${y}@example.com`,new Date().toISOString()]).execute();console.log("-- \u2713 Test table ready with 100 rows"),console.log()}catch(y){throw console.error("-- Failed to setup test table:",y),y}let g=[];if(l.includes("select")){let y=[];for(let E=0;E<o;E++){let D=performance.now();await d.selectFrom("bench_users").where({active:1}).limit(10).execute(),y.push(performance.now()-D)}g.push({operation:"SELECT with WHERE + LIMIT",avgTime:y.reduce((E,D)=>E+D,0)/y.length,minTime:Math.min(...y),maxTime:Math.max(...y),iterations:o})}if(l.includes("select")){let y=[];for(let E=0;E<o;E++){let D=performance.now();await d.selectFrom("bench_users").where({id:1}).first(),y.push(performance.now()-D)}g.push({operation:"SELECT by ID (first)",avgTime:y.reduce((E,D)=>E+D,0)/y.length,minTime:Math.min(...y),maxTime:Math.max(...y),iterations:o})}if(l.includes("count")){let y=[];for(let E=0;E<o;E++){let D=performance.now();await d.selectFrom("bench_users").count(),y.push(performance.now()-D)}g.push({operation:"COUNT",avgTime:y.reduce((E,D)=>E+D,0)/y.length,minTime:Math.min(...y),maxTime:Math.max(...y),iterations:o})}if(l.includes("insert")){let y=[];for(let E=0;E<o;E++){let D=performance.now();await d.insertInto("bench_users").values({name:`Bench User ${E}`,email:`bench${E}@example.com`,created_at:new Date().toISOString()}).execute(),y.push(performance.now()-D)}g.push({operation:"INSERT",avgTime:y.reduce((E,D)=>E+D,0)/y.length,minTime:Math.min(...y),maxTime:Math.max(...y),iterations:o})}if(l.includes("update")){let y=[];for(let E=0;E<o;E++){let D=performance.now();await d.updateTable("bench_users").set({active:0}).where({id:1}).execute(),y.push(performance.now()-D)}g.push({operation:"UPDATE by ID",avgTime:y.reduce((E,D)=>E+D,0)/y.length,minTime:Math.min(...y),maxTime:Math.max(...y),iterations:o})}if(l.includes("delete")){let y=[],E=[];for(let D=0;D<o;D++){let S=await d.insertInto("bench_users").values({name:"To Delete",email:`delete${D}@example.com`,created_at:new Date().toISOString()}).execute();E.push(S)}for(let D=0;D<o;D++){let S=performance.now();await d.deleteFrom("bench_users").where({id:E[D]}).execute(),y.push(performance.now()-S)}g.push({operation:"DELETE by ID",avgTime:y.reduce((D,S)=>D+S,0)/y.length,minTime:Math.min(...y),maxTime:Math.max(...y),iterations:o})}console.log("-- Benchmark Results"),console.log();let x=Math.max(...g.map((y)=>y.operation.length));console.log("Operation".padEnd(x+2)+"Avg (ms)".padStart(12)+"Min (ms)".padStart(12)+"Max (ms)".padStart(12)+"Ops/sec".padStart(12)),console.log("-".repeat(x+2+12+12+12+12));for(let y of g){let E=y.operation.padEnd(x+2),D=y.avgTime.toFixed(3).padStart(12),S=y.minTime.toFixed(3).padStart(12),v=y.maxTime.toFixed(3).padStart(12),Q=(1000/y.avgTime).toFixed(0).padStart(12);console.log(`${E}${D}${S}${v}${Q}`)}console.log();try{await r.unsafe("DROP TABLE IF EXISTS bench_users").execute(),console.log("-- \u2713 Cleanup complete")}catch(y){console.error("-- Warning: Failed to cleanup test table:",y)}}async function z(){console.log("-- Clearing query cache..."),xe(),console.log("-- \u2713 Query cache cleared")}async function Y(){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 X(s={}){if(console.log("-- Configuring query cache..."),console.log(),s.size!==void 0){let o=Number(s.size);if(Number.isNaN(o)||o<=0)throw console.error("-- Error: Cache size must be a positive number"),Error("Invalid cache size");ve(o),console.log(`-- \u2713 Cache max size set to: ${o}`)}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 Xt from"process";import{createInterface as Nr}from"readline";async function O(){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(),o=Nr({input:Xt.stdin,output:Xt.stdout,prompt:"qb> "}),l="",d=!1,g=`
51
+ Available Commands:
52
+ .help Show this help message
53
+ .exit Exit the console
54
+ .tables List all tables
55
+ .clear Clear the screen
56
+
57
+ Query Examples:
58
+ qb.selectFrom('users').where({ active: true }).limit(10).execute()
59
+ qb.selectFrom('users').count()
60
+ qb.insertInto('users').values({ name: 'John' }).execute()
61
+ qb.selectFrom('users').where('id', '=', 1).first()
62
+ qb.unsafe("SELECT * FROM users WHERE id = $1", [1]).execute()
63
+
64
+ Tips:
65
+ - Use 'qb' to access the query builder
66
+ - Use 'await' for async operations
67
+ - Multi-line input: end with \\ to continue on next line
68
+ - Press Enter on an empty line to execute multi-line input
69
+ `,x=async(E)=>{try{let v=await new(Object.getPrototypeOf(async()=>{})).constructor("qb",`return (${E})`)(s);if(v!==void 0)if(Array.isArray(v))console.log(`-- ${v.length} row(s) returned`),console.table(v);else if(typeof v==="object"&&v!==null)console.log(v);else console.log(v)}catch(D){console.error("Error:",D.message)}},y=async(E)=>{let D=E.trim();if(D.startsWith(".")){let S=D.toLowerCase();if(S===".exit"||S===".quit")console.log("Goodbye!"),o.close(),Xt.exit(0);else if(S===".help")console.log(g);else if(S===".clear")console.clear();else if(S===".tables")try{let v=await s.unsafe(`
70
+ SELECT name FROM sqlite_master
71
+ WHERE type = 'table'
72
+ AND name NOT LIKE 'sqlite_%'
73
+ ORDER BY name
74
+ `);if(v.length>0){console.log("Tables:");for(let Q of v)console.log(` - ${Q.name}`)}else console.log("No tables found")}catch(v){console.error("Error listing tables:",v.message)}else console.log(`Unknown command: ${D}`),console.log("Type .help for available commands");return}if(D.endsWith("\\")){d=!0,l+=`${D.slice(0,-1)}
75
+ `;return}if(d){if(D==="")await x(l),l="",d=!1;else l+=`${D}
76
+ `;return}if(D)await x(D)};o.on("line",async(E)=>{await y(E),o.prompt()}),o.on("SIGINT",()=>{if(d)console.log(`
77
+ -- Multi-line input cancelled`),l="",d=!1,o.prompt();else console.log(`
78
+ -- Type .exit to quit`),o.prompt()}),o.on("close",()=>{console.log(`
79
+ Goodbye!`),Xt.exit(0)}),o.prompt()}async function Z(){return O()}import{existsSync as _r,readFileSync as $r,writeFileSync as Qt}from"fs";async function ee(s,o={}){let l=o.format||"json",d=o.output||`${s}.${l}`,g=o.limit;if(console.log(`-- Exporting data from table: ${s}`),console.log(`-- Format: ${l}`),console.log(`-- Output: ${d}`),g)console.log(`-- Limit: ${g} rows`);console.log();try{let y=i().selectFrom(s);if(g)y=y.limit(g);let E=await y.execute();if(console.log(`-- Retrieved ${E.length} rows`),l==="json")Qt(d,JSON.stringify(E,null,2)),console.log(`-- \u2713 Exported to JSON: ${d}`);else if(l==="csv"){if(E.length===0){Qt(d,""),console.log(`-- \u2713 Exported to CSV: ${d} (empty)`);return}let D=Object.keys(E[0]),S=[D.join(",")];for(let v of E){let Q=D.map((G)=>{let Re=v[G];if(Re===null||Re===void 0)return"";let Ne=String(Re);if(Ne.includes(",")||Ne.includes('"')||Ne.includes(`
80
+ `))return`"${Ne.replace(/"/g,'""')}"`;return Ne});S.push(Q.join(","))}Qt(d,S.join(`
81
+ `)),console.log(`-- \u2713 Exported to CSV: ${d}`)}else if(l==="sql"){let D=[];for(let S of E){let v=Object.keys(S),Q=v.map((G)=>{let Re=S[G];if(Re===null||Re===void 0)return"NULL";if(typeof Re==="number")return String(Re);return`'${String(Re).replace(/'/g,"''")}'`});D.push(`INSERT INTO ${s} (${v.join(", ")}) VALUES (${Q.join(", ")});`)}Qt(d,D.join(`
82
+ `)),console.log(`-- \u2713 Exported to SQL: ${d}`)}}catch(x){throw console.error(`-- Failed to export data from ${s}:`,x),x}}async function te(s,o,l={}){if(!_r(o))throw console.error(`-- File not found: ${o}`),Error(`File not found: ${o}`);let d=l.format||(o.endsWith(".json")?"json":"csv"),g=l.truncate??!1;console.log(`-- Importing data into table: ${s}`),console.log(`-- Format: ${d}`),console.log(`-- File: ${o}`),console.log(`-- Truncate: ${g}`),console.log();try{let x=i();if(g)await x.deleteFrom(s).execute(),console.log("-- Table truncated");let y=$r(o,"utf8"),E=[];if(d==="json"){if(E=JSON.parse(y),!Array.isArray(E))throw TypeError("JSON file must contain an array of objects")}else if(d==="csv"){let v=y.split(`
83
+ `).filter((G)=>G.trim());if(v.length<2){console.log("-- No data to import (CSV is empty or has only headers)");return}let Q=v[0].split(",").map((G)=>G.trim());for(let G=1;G<v.length;G++){let Re=v[G].split(",").map((Ce)=>Ce.trim()),Ne={};for(let Ce=0;Ce<Q.length;Ce++){let _e=Re[Ce];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);Ne[Q[Ce]]=_e}E.push(Ne)}}if(E.length===0){console.log("-- No data to import");return}let D=100,S=0;for(let v=0;v<E.length;v+=D){let Q=E.slice(v,v+D);await x.insertInto(s).values(Q).execute(),S+=Q.length,console.log(`-- Imported ${S}/${E.length} rows...`)}console.log(`-- \u2713 Successfully imported ${E.length} rows`)}catch(x){throw console.error(`-- Failed to import data into ${s}:`,x),x}}async function ne(s={}){let o=e.dialect||"postgres",l=s.output||`dump-${Date.now()}.sql`,d=s.tables?.split(",").map((g)=>g.trim());if(console.log("-- Dumping database"),console.log(`-- Dialect: ${o}`),console.log(`-- Output: ${l}`),d)console.log(`-- Tables: ${d.join(", ")}`);console.log();try{let g=i(),x=[];if(o==="sqlite")x=(await g.unsafe(`
84
+ SELECT name FROM sqlite_master
85
+ WHERE type = 'table'
86
+ AND name NOT LIKE 'sqlite_%'
87
+ ORDER BY name
88
+ `)).map((D)=>D.name);else if(o==="postgres")x=(await g.unsafe(`
89
+ SELECT table_name
90
+ FROM information_schema.tables
91
+ WHERE table_schema = 'public'
92
+ AND table_type = 'BASE TABLE'
93
+ ORDER BY table_name
94
+ `)).map((D)=>D.table_name);else if(n(o))x=(await g.unsafe(`
95
+ SELECT table_name
96
+ FROM information_schema.tables
97
+ WHERE table_schema = DATABASE()
98
+ AND table_type = 'BASE TABLE'
99
+ ORDER BY table_name
100
+ `)).map((D)=>D.table_name);if(d)x=x.filter((E)=>d.includes(E));if(x.length===0){console.log("-- No tables to dump");return}console.log(`-- Dumping ${x.length} table(s)`);let y=[];y.push("-- Database dump"),y.push(`-- Generated at: ${new Date().toISOString()}`),y.push(`-- Dialect: ${o}`),y.push("");for(let E of x){console.log(`-- Dumping table: ${E}`);let D=await g.selectFrom(E).execute();y.push(`-- Table: ${E}`),y.push(`-- Rows: ${D.length}`),y.push("");for(let S of D){let v=Object.keys(S),Q=v.map((G)=>{let Re=S[G];if(Re===null||Re===void 0)return"NULL";if(typeof Re==="number")return String(Re);return`'${String(Re).replace(/'/g,"''")}'`});y.push(`INSERT INTO ${E} (${v.join(", ")}) VALUES (${Q.join(", ")});`)}y.push("")}Qt(l,y.join(`
101
+ `)),console.log(),console.log(`-- \u2713 Database dump saved to: ${l}`)}catch(g){throw console.error("-- Failed to dump database:",g),g}}async function _(){let s=e.dialect||"postgres",o=e.database?.database||"unknown";console.log("-- Database Information"),console.log(`-- Dialect: ${s}`),console.log(`-- Database: ${o}`),console.log();try{let l=i(),d=[],g=[];if(s==="postgres")g=(await l.unsafe(`
102
+ SELECT table_name
103
+ FROM information_schema.tables
104
+ WHERE table_schema = 'public'
105
+ AND table_type = 'BASE TABLE'
106
+ ORDER BY table_name
107
+ `)).map((E)=>E.table_name);else if(n(s))g=(await l.unsafe(`
108
+ SELECT table_name
109
+ FROM information_schema.tables
110
+ WHERE table_schema = DATABASE()
111
+ AND table_type = 'BASE TABLE'
112
+ ORDER BY table_name
113
+ `)).map((E)=>E.table_name);else if(s==="sqlite")g=(await l.unsafe(`
114
+ SELECT name
115
+ FROM sqlite_master
116
+ WHERE type = 'table'
117
+ AND name NOT LIKE 'sqlite_%'
118
+ ORDER BY name
119
+ `)).map((E)=>E.name);for(let y of g)try{let E=await l.unsafe(`SELECT COUNT(*) as count FROM ${y}`),D=Number(E[0]?.count||0),S=0,v=0;if(s==="postgres"){let Q=await l.unsafe(`
120
+ SELECT COUNT(*) as count
121
+ FROM information_schema.columns
122
+ WHERE table_name = $1
123
+ `,[y]);S=Number(Q[0]?.count||0);let G=await l.unsafe(`
124
+ SELECT COUNT(*) as count
125
+ FROM pg_indexes
126
+ WHERE tablename = $1
127
+ `,[y]);v=Number(G[0]?.count||0)}else if(n(s)){let Q=await l.unsafe(`
128
+ SELECT COUNT(*) as count
129
+ FROM information_schema.columns
130
+ WHERE table_name = ?
131
+ AND table_schema = DATABASE()
132
+ `,[y]);S=Number(Q[0]?.count||0);let G=await l.unsafe(`
133
+ SELECT COUNT(*) as count
134
+ FROM information_schema.statistics
135
+ WHERE table_name = ?
136
+ AND table_schema = DATABASE()
137
+ `,[y]);v=Number(G[0]?.count||0)}else if(s==="sqlite")S=(await l.unsafe(`PRAGMA table_info(${y})`)).length,v=(await l.unsafe(`PRAGMA index_list(${y})`)).length;d.push({name:y,rowCount:D,columns:S,indexes:v})}catch(E){console.error(`-- Error getting info for table ${y}:`,E)}let x=d.reduce((y,E)=>y+E.rowCount,0);if(console.log(`-- Total Tables: ${d.length}`),console.log(`-- Total Rows: ${x.toLocaleString()}`),console.log(),d.length>0){console.log("Tables:"),console.log();let y=Math.max(...d.map((S)=>S.name.length)),E=y+2,D="Table".padEnd(E)+"Rows".padStart(12)+"Columns".padStart(10)+"Indexes".padStart(10);console.log(D),console.log("-".repeat(D.length));for(let S of d){let v=S.name.padEnd(y+2),Q=S.rowCount.toLocaleString().padStart(12),G=(S.columns||0).toString().padStart(10),Re=(S.indexes||0).toString().padStart(10);console.log(`${v}${Q}${G}${Re}`)}}else console.log("-- No tables found");return{dialect:s,database:o,tables:d,totalTables:d.length,totalRows:x}}catch(l){throw console.error("-- Failed to get database info:",l),l}}async function re(){return _()}async function I(s={}){let o=B(s.dialect),l=s.aggressive||!1;if(s.verbose)console.log(`Optimizing ${o} database${l?" (aggressive mode)":""}...`);try{if(o==="postgres"){if(s.tables&&s.tables.length>0)for(let d of s.tables){if(s.verbose)console.log(`Analyzing table: ${d}`);if(l)await r`VACUUM FULL ANALYZE ${r(d)}`;else await r`VACUUM ANALYZE ${r(d)}`}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(o)){if(s.tables&&s.tables.length>0)for(let d of s.tables){if(s.verbose)console.log(`Optimizing table: ${d}`);await r`OPTIMIZE TABLE ${r(d)}`,await r`ANALYZE TABLE ${r(d)}`}else{let d=Be(),g=await r`
138
+ SELECT table_name
139
+ FROM information_schema.tables
140
+ WHERE table_schema = ${d}
141
+ `;for(let x of g){let y=x.table_name||x.TABLE_NAME;if(s.verbose)console.log(`Optimizing table: ${y}`);await r`OPTIMIZE TABLE ${r(y)}`,await r`ANALYZE TABLE ${r(y)}`}}console.log("\u2713 MySQL optimization complete")}else if(o==="sqlite"){if(s.verbose)console.log("Running VACUUM on SQLite database...");if(await r`VACUUM`,s.tables&&s.tables.length>0)for(let d of s.tables){if(s.verbose)console.log(`Analyzing table: ${d}`);await r`ANALYZE ${r(d)}`}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: ${o}`)}catch(d){throw console.error("Error optimizing database:",d.message),d}}async function L(s={}){let o=B(s.dialect);if(s.verbose)console.log(`Wiping all tables from ${o} database...`);try{let l=[];if(o==="postgres")l=(await r`
142
+ SELECT tablename
143
+ FROM pg_tables
144
+ WHERE schemaname = 'public'
145
+ `).map((g)=>g.tablename);else if(n(o)){let d=Be();l=(await r`
146
+ SELECT table_name
147
+ FROM information_schema.tables
148
+ WHERE table_schema = ${d}
149
+ `).map((x)=>x.table_name||x.TABLE_NAME)}else if(o==="sqlite")l=(await r`
150
+ SELECT name
151
+ FROM sqlite_master
152
+ WHERE type = 'table'
153
+ AND name NOT LIKE 'sqlite_%'
154
+ `).map((g)=>g.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(o==="postgres")for(let d of l){if(s.verbose)console.log(`Dropping table: ${d}`);await r`DROP TABLE IF EXISTS ${r(d)} CASCADE`}else if(n(o)){await r`SET FOREIGN_KEY_CHECKS = 0`;for(let d of l){if(s.verbose)console.log(`Dropping table: ${d}`);await r`DROP TABLE IF EXISTS ${r(d)}`}await r`SET FOREIGN_KEY_CHECKS = 1`}else if(o==="sqlite"){await r`PRAGMA foreign_keys = OFF`;for(let d of l){if(s.verbose)console.log(`Dropping table: ${d}`);await r`DROP TABLE IF EXISTS ${r(d)}`}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 ie(s){let d=await(i().raw([s]).simple()?.execute?.()??Promise.resolve([]));return console.log(JSON.stringify(d,null,2)),d}async function se(s,o={}){let l=i(),d=o.params?JSON.parse(o.params):void 0,g=await l.file(s,d);return console.log(JSON.stringify(g)),g}async function K(s,o={}){let l=e.dialect||"postgres",d=o.verbose??!0;if(d)console.log(`-- Inspecting table: ${s}`),console.log(`-- Dialect: ${l}`),console.log();try{let g=i(),x=[],y=[],E=await g.unsafe(`SELECT COUNT(*) as count FROM ${s}`),D=Number(E[0]?.count||0);if(l==="postgres"){let S=await g.unsafe(`
155
+ SELECT
156
+ c.column_name,
157
+ c.data_type,
158
+ c.is_nullable,
159
+ c.column_default,
160
+ CASE
161
+ WHEN pk.column_name IS NOT NULL THEN true
162
+ ELSE false
163
+ END as is_primary_key,
164
+ CASE
165
+ WHEN fk.column_name IS NOT NULL THEN true
166
+ ELSE false
167
+ END as is_foreign_key
168
+ FROM information_schema.columns c
169
+ LEFT JOIN (
170
+ SELECT ku.column_name
171
+ FROM information_schema.table_constraints tc
172
+ JOIN information_schema.key_column_usage ku
173
+ ON tc.constraint_name = ku.constraint_name
174
+ WHERE tc.constraint_type = 'PRIMARY KEY'
175
+ AND tc.table_name = $1
176
+ ) pk ON c.column_name = pk.column_name
177
+ LEFT JOIN (
178
+ SELECT ku.column_name
179
+ FROM information_schema.table_constraints tc
180
+ JOIN information_schema.key_column_usage ku
181
+ ON tc.constraint_name = ku.constraint_name
182
+ WHERE tc.constraint_type = 'FOREIGN KEY'
183
+ AND tc.table_name = $1
184
+ ) fk ON c.column_name = fk.column_name
185
+ WHERE c.table_name = $1
186
+ ORDER BY c.ordinal_position
187
+ `,[s]);for(let Q of S)x.push({name:Q.column_name,type:Q.data_type,nullable:Q.is_nullable==="YES",default:Q.column_default,isPrimaryKey:Q.is_primary_key,isForeignKey:Q.is_foreign_key});let v=await g.unsafe(`
188
+ SELECT
189
+ i.indexname as name,
190
+ i.indexdef,
191
+ ix.indisunique as is_unique
192
+ FROM pg_indexes i
193
+ JOIN pg_class c ON c.relname = i.indexname
194
+ JOIN pg_index ix ON ix.indexrelid = c.oid
195
+ WHERE i.tablename = $1
196
+ `,[s]);for(let Q of v){let G=Q.indexdef?.match(/\(([^)]+)\)/),Ne=(G?G[1]:"").split(",").map((Ce)=>Ce.trim());y.push({name:Q.name,columns:Ne,unique:Q.is_unique})}}else if(n(l)){let S=await g.unsafe(`
197
+ SELECT
198
+ COLUMN_NAME as column_name,
199
+ DATA_TYPE as data_type,
200
+ IS_NULLABLE as is_nullable,
201
+ COLUMN_DEFAULT as column_default,
202
+ COLUMN_KEY as column_key
203
+ FROM information_schema.COLUMNS
204
+ WHERE TABLE_NAME = ?
205
+ AND TABLE_SCHEMA = DATABASE()
206
+ ORDER BY ORDINAL_POSITION
207
+ `,[s]);for(let G of S)x.push({name:G.column_name,type:G.data_type,nullable:G.is_nullable==="YES",default:G.column_default,isPrimaryKey:G.column_key==="PRI",isForeignKey:G.column_key==="MUL"});let v=await g.unsafe(`
208
+ SHOW INDEXES FROM ${s}
209
+ `),Q=new Map;for(let G of v){let Re=G.Key_name;if(!Q.has(Re))Q.set(Re,{columns:[],unique:G.Non_unique===0});Q.get(Re).columns.push(G.Column_name)}for(let[G,Re]of Q)y.push({name:G,columns:Re.columns,unique:Re.unique})}else if(l==="sqlite"){let S=await g.unsafe(`PRAGMA table_info(${s})`);for(let Q of S)x.push({name:Q.name,type:Q.type,nullable:Q.notnull===0,default:Q.dflt_value,isPrimaryKey:Q.pk===1});let v=await g.unsafe(`PRAGMA index_list(${s})`);for(let Q of v){let G=await g.unsafe(`PRAGMA index_info(${Q.name})`);y.push({name:Q.name,columns:G.map((Re)=>Re.name),unique:Q.unique===1})}}if(d){console.log(`Table: ${s}`),console.log(`Rows: ${D.toLocaleString()}`),console.log(),console.log("Columns:"),console.log();let S=Math.max(...x.map((Ne)=>Ne.name.length),10),v=Math.max(...x.map((Ne)=>Ne.type.length),10),Q=S+2,G=v+2,Re=`${"Name".padEnd(Q)+"Type".padEnd(G)+"Nullable".padEnd(10)+"Default".padEnd(20)}Flags`;console.log(Re),console.log("-".repeat(Re.length));for(let Ne of x){let Ce=Ne.name.padEnd(Q),_e=Ne.type.padEnd(G),Ve=(Ne.nullable?"YES":"NO").padEnd(10),Oe=String(Ne.default||"").padEnd(20),We=[Ne.isPrimaryKey?"PK":"",Ne.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${Ce}${_e}${Ve}${Oe}${We}`)}if(console.log(),y.length>0){console.log("Indexes:"),console.log();for(let Ne of y){let Ce=Ne.unique?" (UNIQUE)":"";console.log(` - ${Ne.name}${Ce}: [${Ne.columns.join(", ")}]`)}console.log()}}return{tableName:s,rowCount:D,columns:x,indexes:y}}catch(g){throw console.error(`-- Failed to inspect table ${s}:`,g),g}}async function ae(s,o={}){return K(s,o)}async function oe(s,o={}){let l=await u({modelsDir:s}),d=$e(l);return console.log(JSON.stringify(d,null,2)),{models:l,schema:d}}function Xe(s){let o=s.toLowerCase();if(/^bool|boolean|tinyint\(1\)/.test(o))return"boolean";if(/int|serial|numeric|decimal|double|real|float|money/.test(o))return"number";if(/timestamp|datetime|date|time/.test(o))return"datetime";if(/json/.test(o))return"json";return"string"}function vr(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 kr(s){return s.replace(/[-_\s]+/g," ").split(" ").filter(Boolean).map((o)=>o.charAt(0).toUpperCase()+o.slice(1)).join("")}function Le(s){return kr(vr(s))}async function qn(s,o){if(o==="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((g)=>g.table_name);if(n(o))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((g)=>g.table_name??g.TABLE_NAME);return(await s.unsafe("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")).map((d)=>d.name)}async function Pr(s,o,l){if(o==="sqlite")return(await s.unsafe(`PRAGMA table_info(${l})`)).map((x)=>({name:x.name,sqlType:String(x.type||""),nullable:Number(x.notnull)===0,isPrimaryKey:Number(x.pk)>0}));if(o==="postgres")return(await s.unsafe(`SELECT c.column_name, c.data_type, c.is_nullable,
210
+ (SELECT COUNT(*) FROM information_schema.table_constraints tc
211
+ JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
212
+ WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
213
+ FROM information_schema.columns c
214
+ WHERE c.table_name = $1 AND c.table_schema = 'public'
215
+ ORDER BY c.ordinal_position`,[l])).map((x)=>({name:x.column_name,sqlType:String(x.data_type||""),nullable:String(x.is_nullable).toUpperCase()==="YES",isPrimaryKey:Number(x.is_pk)>0}));return(await s.unsafe(`SELECT column_name, data_type, is_nullable, column_key
216
+ FROM information_schema.columns
217
+ WHERE table_name = ? AND table_schema = DATABASE()
218
+ ORDER BY ordinal_position`,[l])).map((g)=>({name:g.column_name??g.COLUMN_NAME,sqlType:String(g.data_type??g.DATA_TYPE??""),nullable:String(g.is_nullable??g.IS_NULLABLE).toUpperCase()==="YES",isPrimaryKey:String(g.column_key??g.COLUMN_KEY).toUpperCase()==="PRI"}))}function Ze(s,o){let l=Le(s),d=o.find((x)=>x.isPrimaryKey)?.name??"id",g=o.map((x)=>{let y=[`type: '${Xe(x.sqlType)}'`];if(!x.nullable&&!x.isPrimaryKey)y.push("required: true");return` ${x.name}: { ${y.join(", ")} },`}).join(`
219
+ `);return`export const ${l} = defineModel({
220
+ name: '${l}',
221
+ table: '${s}',
222
+ primaryKey: '${d}',
223
+ attributes: {
224
+ ${g}
225
+ },
226
+ })
227
+ `}async function k(s={}){let o=e.dialect||"postgres",l=i(),d=s.tables?.length?s.tables:await qn(l,o),g=[];for(let x of d){let y=await Pr(l,o,x);if(!y.length)continue;g.push({table:x,modelName:Le(x),primaryKey:y.find((E)=>E.isPrimaryKey)?.name??"id",columns:y,source:Ze(x,y)})}return g}function xn(s,o,l){if(l?.enumValues&&l.enumValues.length>0)return"enum";let d=String(s||"").toLowerCase().trim(),g=d.replace(/\(.*$/,"").replace(/\s+/g," ").trim();if(n(o)&&/^tinyint\(1\)/.test(d))return"boolean";if(/^bool/.test(g))return"boolean";if(g==="int8"||g==="bigint"||g==="bigserial")return"bigint";if(/^(?:int|integer|smallint|mediumint|serial|int2|int4|tinyint)/.test(g))return"integer";if(/^(?:varchar|character varying|nvarchar|nchar|char|character|bpchar)/.test(g)){let x=d.match(/\((\d+)\)/),y=x?Number(x[1]):void 0;if(n(o))return"string";return y!==void 0&&y>255?"text":"string"}if(/text|clob/.test(g))return"text";if(g==="float8"||/^double/.test(g))return"double";if(/^(?:real|float4|float)/.test(g))return"float";if(/^(?:numeric|decimal|money)/.test(g))return"decimal";if(g==="date")return"date";if(g==="timestamptz"||/\bwith time zone\b/.test(d))return"timestamptz";if(/^(?:timestamp|datetime)/.test(g))return"datetime";if(/^time/.test(g))return"string";if(/json/.test(g))return"json";if(/^enum/.test(g))return"enum";return"string"}function Ir(s,o,l){return xn(String(o||s||""),"mysql",{enumValues:l})}function Or(s){let o=String(s||"").trim().match(/^varchar\((\d+)\)/i);if(!o)return;let l=Number(o[1]);return Number.isSafeInteger(l)&&l>0?l:void 0}function Vt(s){let o=String(s??"").toLowerCase().trim();if(o==="cascade"||o==="restrict"||o==="set null")return o;return}async function qr(s,o){let l=await s.unsafe(`PRAGMA table_info(${JSON.stringify(o)})`),d=await s.unsafe(`PRAGMA index_list(${JSON.stringify(o)})`),g=await s.unsafe(`PRAGMA foreign_key_list(${JSON.stringify(o)})`),x=await s.unsafe("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",[o]),y=String(x?.[0]?.sql??""),E=new Map;for(let Q of g)E.set(String(Q.from),{table:String(Q.table),column:String(Q.to??"id"),onDelete:Vt(Q.on_delete),onUpdate:Vt(Q.on_update)});let D=[],S=new Set;for(let Q of d){let G=String(Q.origin??""),Re=String(Q.name??"");if(G==="pk"||Re.startsWith("sqlite_autoindex_"))continue;let Ce=(await s.unsafe(`PRAGMA index_info(${JSON.stringify(Re)})`)).map((Ve)=>String(Ve.name)).filter(Boolean);if(Ce.length===0)continue;let _e=Number(Q.unique)===1;if(_e&&Ce.length===1)S.add(Ce[0]);D.push({name:Re,columns:Ce,type:_e?"unique":"index"})}let v=l.map((Q)=>{let G=String(Q.name),Re=Kr(y,G),Ne=Number(Q.pk)>0,Ce=Q.dflt_value,_e=Ce!==null&&Ce!==void 0;return{name:G,type:xn(String(Q.type??""),"sqlite",{enumValues:Re}),isPrimaryKey:Ne,isUnique:S.has(G),isNullable:Ne?!1:Number(Q.notnull)===0,hasDefault:_e,defaultValue:_e?Dn(Ce):void 0,enumValues:Re,references:E.get(G)}});return{table:o,columns:v,indexes:D}}function Kr(s,o){if(!s)return;let l=new RegExp(`(?:"${o}"|\`${o}\`|\\b${o}\\b)\\s+IN\\s*\\(([^)]*)\\)`,"i"),d=s.match(l);if(!d)return;let g=d[1].split(",").map((x)=>x.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((x)=>x.length>0);return g.length>0?g:void 0}function Dn(s){if(typeof s==="number"||typeof s==="boolean")return s;return String(s)}async function Kn(s){let o=await s.unsafe(`SELECT t.typname AS type_name, e.enumlabel AS label
228
+ FROM pg_type t
229
+ JOIN pg_enum e ON e.enumtypid = t.oid
230
+ JOIN pg_namespace n ON n.oid = t.typnamespace
231
+ WHERE n.nspname = 'public'
232
+ ORDER BY t.typname, e.enumsortorder`),l=new Map;for(let d of o){let g=String(d.type_name),x=l.get(g);if(x)x.push(String(d.label));else l.set(g,[String(d.label)])}return l}function Lr(s,o,l){let d=l.get(o),g=xn(String(s||o||""),"postgres",{enumValues:d});return d?{type:g,enumValues:d,enumTypeName:o}:{type:g}}async function Br(s,o,l){let d=l??await Kn(s),g=await s.unsafe(`SELECT c.column_name, c.data_type, c.udt_name, c.is_nullable, c.column_default, c.character_maximum_length,
233
+ (SELECT COUNT(*) FROM information_schema.table_constraints tc
234
+ JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
235
+ WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
236
+ FROM information_schema.columns c
237
+ WHERE c.table_name = $1 AND c.table_schema = 'public'
238
+ ORDER BY c.ordinal_position`,[o]),x=await s.unsafe(`SELECT i.relname AS index_name, ix.indisunique AS is_unique, ix.indisprimary AS is_primary,
239
+ a.attname AS column_name, array_position(ix.indkey, a.attnum) AS ord,
240
+ pg_get_expr(ix.indpred, ix.indrelid) AS where_clause
241
+ FROM pg_class t
242
+ JOIN pg_index ix ON t.oid = ix.indrelid
243
+ JOIN pg_class i ON i.oid = ix.indexrelid
244
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
245
+ WHERE t.relname = $1 AND t.relkind = 'r'
246
+ ORDER BY i.relname, ord`,[o]),y=await s.unsafe(`SELECT kcu.column_name, ccu.table_name AS ref_table, ccu.column_name AS ref_column,
247
+ tc.constraint_name, rc.delete_rule, rc.update_rule
248
+ FROM information_schema.table_constraints tc
249
+ JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = tc.constraint_name
250
+ JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name = tc.constraint_name
251
+ JOIN information_schema.referential_constraints rc ON rc.constraint_name = tc.constraint_name
252
+ WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = $1 AND tc.table_schema = 'public'`,[o]),E=new Map,D=new Map;for(let G of y){let Re=String(G.constraint_name);D.set(Re,(D.get(Re)??0)+1)}for(let G of y){let Re=String(G.column_name),Ne=E.get(Re),Ce=String(G.constraint_name),_e=D.get(Ce)===1?[...new Set([...Ne?.constraintNames??[],Ce])]:Ne?.constraintNames;E.set(Re,Ne?{...Ne,constraintNames:_e}:{table:String(G.ref_table),column:String(G.ref_column??"id"),onDelete:Vt(G.delete_rule),onUpdate:Vt(G.update_rule),constraintNames:_e})}let{indexes:S,uniqueColumns:v}=Ln(o,x.map((G)=>({indexName:String(G.index_name),isUnique:G.is_unique===!0||G.is_unique==="t",isPrimary:G.is_primary===!0||G.is_primary==="t",column:String(G.column_name),where:G.where_clause?String(G.where_clause):void 0}))),Q=g.map((G)=>{let Re=String(G.column_name),Ne=Number(G.is_pk)>0,Ce=G.column_default==null?null:String(G.column_default),_e=Ce!=null&&/nextval\(/i.test(Ce),Ve=Ce!=null&&!_e;return{name:Re,...Lr(String(G.data_type??""),G.udt_name==null?"":String(G.udt_name),d),isPrimaryKey:Ne,isUnique:v.has(Re),isNullable:Ne?!1:String(G.is_nullable).toUpperCase()==="YES",hasDefault:Ve,defaultValue:Ve?Dn(Ce):void 0,references:E.get(Re)}});return{table:o,columns:Q,indexes:S}}async function Ur(s,o){let l=await s.unsafe(`SELECT column_name, data_type, column_type, is_nullable, column_default, column_key
253
+ FROM information_schema.columns
254
+ WHERE table_name = ? AND table_schema = DATABASE()
255
+ ORDER BY ordinal_position`,[o]),d=await s.unsafe(`SELECT index_name, non_unique, seq_in_index, column_name
256
+ FROM information_schema.statistics
257
+ WHERE table_name = ? AND table_schema = DATABASE()
258
+ ORDER BY index_name, seq_in_index`,[o]),g=await s.unsafe(`SELECT kcu.column_name, kcu.referenced_table_name AS ref_table, kcu.referenced_column_name AS ref_column,
259
+ kcu.constraint_name, rc.delete_rule, rc.update_rule
260
+ FROM information_schema.key_column_usage kcu
261
+ JOIN information_schema.referential_constraints rc
262
+ ON rc.constraint_name = kcu.constraint_name AND rc.constraint_schema = kcu.table_schema
263
+ WHERE kcu.table_name = ? AND kcu.table_schema = DATABASE() AND kcu.referenced_table_name IS NOT NULL`,[o]),x=new Map,y=new Map;for(let v of g){let Q=String(v.constraint_name??v.CONSTRAINT_NAME);y.set(Q,(y.get(Q)??0)+1)}for(let v of g){let Q=String(v.column_name??v.COLUMN_NAME),G=x.get(Q),Re=String(v.constraint_name??v.CONSTRAINT_NAME),Ne=y.get(Re)===1?[...new Set([...G?.constraintNames??[],Re])]:G?.constraintNames;x.set(Q,G?{...G,constraintNames:Ne}:{table:String(v.ref_table??v.REF_TABLE),column:String(v.ref_column??v.REF_COLUMN??"id"),onDelete:Vt(v.delete_rule??v.DELETE_RULE),onUpdate:Vt(v.update_rule??v.UPDATE_RULE),constraintNames:Ne})}let{indexes:E,uniqueColumns:D}=Ln(o,d.map((v)=>({indexName:String(v.index_name??v.INDEX_NAME),isUnique:Number(v.non_unique??v.NON_UNIQUE)===0,isPrimary:String(v.index_name??v.INDEX_NAME).toUpperCase()==="PRIMARY",column:String(v.column_name??v.COLUMN_NAME)}))),S=l.map((v)=>{let Q=String(v.column_name??v.COLUMN_NAME),G=String(v.column_type??v.COLUMN_TYPE??""),Re=Fr(G),Ce=String(v.column_key??v.COLUMN_KEY??"").toUpperCase()==="PRI",_e=v.column_default??v.COLUMN_DEFAULT,Ve=_e!=null;return{name:Q,type:Ir(v.data_type??v.DATA_TYPE,G,Re),isPrimaryKey:Ce,isUnique:D.has(Q),isNullable:Ce?!1:String(v.is_nullable??v.IS_NULLABLE).toUpperCase()==="YES",hasDefault:Ve,defaultValue:Ve?Dn(_e):void 0,enumValues:Re,maxLength:Or(G),references:x.get(Q)}});return{table:o,columns:S,indexes:E}}function Fr(s){let o=s.match(/^enum\((.*)\)$/i);if(!o)return;return o[1].split(",").map((l)=>l.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((l)=>l.length>0)}function Ln(s,o){let l=new Map;for(let x of o){if(x.isPrimary)continue;let y=l.get(x.indexName)??{isUnique:x.isUnique,isPrimary:x.isPrimary,columns:[],where:x.where};y.columns.push(x.column),l.set(x.indexName,y)}let d=[],g=new Set;for(let[x,y]of l){if(y.columns.length===0)continue;if(y.isUnique&&y.columns.length===1)g.add(y.columns[0]);d.push({name:x,columns:y.columns,type:y.isUnique?"unique":"index",where:y.where})}return{indexes:d,uniqueColumns:g}}async function Bn(s,o={}){let l=s||e.dialect||"postgres",d=i(),x=((o.tables?.length)?o.tables:await qn(d,l)).filter((D)=>D!=="migrations"),y=l==="postgres"?await Kn(d):void 0,E=[];for(let D of x){let S;if(l==="sqlite")S=await qr(d,D);else if(l==="postgres")S=await Br(d,D,y);else S=await Ur(d,D);if(S.columns.length>0)E.push(S)}return{dialect:l,tables:E}}import{existsSync as En,mkdirSync as Vr,writeFileSync as jr}from"fs";import{dirname as Un,join as Rn}from"path";import Fn from"process";function Yr(s){let o=s;while(o!==Un(o)){if(En(Rn(o,"package.json")))return o;o=Un(o)}return Fn.cwd()}async function le(s,o={}){let l=Yr(Fn.cwd()),d=o.dir||Rn(l,"app/Models");if(!En(d))Vr(d,{recursive:!0}),console.log(`-- Created models directory: ${d}`);let g=s.charAt(0).toUpperCase()+s.slice(1),x=o.table||`${s.toLowerCase()}s`,y=`${g}.ts`,E=Rn(d,y);if(En(E))throw console.error(`-- Model already exists: ${E}`),Error(`Model already exists: ${E}`);let S=o.timestamps!==!1?` created_at: { validation: { rule: v.date() } },
264
+ updated_at: { validation: { rule: v.date() } },`:"",v=`import { v } from '@stacksjs/ts-validation'
265
+ import { defineModel } from 'bun-query-builder'
266
+
267
+ const model = defineModel({
268
+ name: '${g}',
269
+ table: '${x}',
270
+ primaryKey: 'id',
271
+ attributes: {
272
+ id: { validation: { rule: v.integer() } },
273
+ ${S}
274
+ // Add your model attributes here
275
+ // Example:
276
+ // name: { validation: { rule: v.string() } },
277
+ // email: { unique: true, validation: { rule: v.string().email() } },
278
+ // age: { default: 0, validation: { rule: v.number().min(0) } },
279
+ },
280
+ })
281
+
282
+ export default model
283
+ `;jr(E,v),console.log(`-- \u2713 Created model: ${E}`),console.log(`-- Table: ${x}`)}async function me(s,o={}){return T(s,o)}import{existsSync as Qn,readFileSync as Gr,unlinkSync as zr}from"fs";import{join as Hr}from"path";import{existsSync as Qr}from"fs";import{dirname as Vn,isAbsolute as Wr,join as Yn}from"path";import jn from"process";function Sn(s=jn.cwd()){let o=s;while(o!==Vn(o)){if(Qr(Yn(o,"package.json")))return o;o=Vn(o)}return jn.cwd()}function $t(s,o="database/migrations"){let l=o||"database/migrations";return Wr(l)?l:Yn(s??Sn(),l)}function Xr(s){let o=[],l="",d=null;for(let g=0;g<s.length;g++){let x=s[g];if(d){if(l+=x,x===d)if(s[g+1]===d)l+=s[g+1],g++;else d=null;continue}if(x==="'"||x==='"'||x==="`"){d=x,l+=x;continue}if(x==="-"&&s[g+1]==="-"){let y=s.indexOf(`
284
+ `,g);g=y===-1?s.length:y;continue}if(x==="/"&&s[g+1]==="*"){let y=s.indexOf("*/",g+2);g=y===-1?s.length:y+1;continue}if(x===";"){if(l.trim())o.push(l.trim());l="";continue}l+=x}if(l.trim())o.push(l.trim());return o}function Jr(s,o=e.dialect){let l=(x)=>n(o)?`\`${x}\``:`"${x}"`,d=[],g=[];for(let x of Xr(s)){let y;if(y=/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?/i.exec(x))d.push(`DROP TABLE IF EXISTS ${l(y[1])}`);else if(y=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+CONSTRAINT\s+["`']?(\w+)["`']?([\s\S]*)$/i.exec(x))if(o==="sqlite")g.push(x);else if(n(o)&&/\bFOREIGN\s+KEY\b/i.test(y[3]??""))d.push(`ALTER TABLE ${l(y[1])} DROP FOREIGN KEY ${l(y[2])}`);else d.push(`ALTER TABLE ${l(y[1])} DROP CONSTRAINT ${l(y[2])}`);else if(y=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+(?:COLUMN\s+["`']?(\w+)["`']?|["`'](\w+)["`']|(\w+))/i.exec(x)){let E=y[2]??y[3]??y[4];if(y[4]&&/^(?:PRIMARY|UNIQUE|INDEX|KEY|FOREIGN|CHECK|FULLTEXT|SPATIAL)$/i.test(y[4]))g.push(x);else d.push(`ALTER TABLE ${l(y[1])} DROP COLUMN ${l(E)}`)}else if(y=/^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?(?:\s+ON\s+["`']?(\w+)["`']?)?/i.exec(x))d.push(n(o)&&y[2]?`DROP INDEX ${l(y[1])} ON ${l(y[2])}`:`DROP INDEX IF EXISTS ${l(y[1])}`);else g.push(x)}return{down:d.reverse(),skipped:g}}async function he(s={}){let o=s.steps||1,l=s.reverseSchema!==!1;console.log("-- Rolling back migrations"),console.log(`-- Steps: ${o}`),console.log();try{let d=i(),g=[];try{g=await d.unsafe(`
285
+ SELECT migration, executed_at
286
+ FROM migrations
287
+ ORDER BY executed_at DESC, migration DESC
288
+ `)}catch(D){console.log("-- Migrations table not found. Nothing to rollback.",D);return}if(g.length===0){console.log("-- No migrations to rollback");return}let x=g.slice(0,o);console.log(`-- Found ${g.length} executed migrations`),console.log(`-- Rolling back ${x.length} migration(s):`),console.log();for(let D of x)console.log(` - ${D.migration}`);console.log();let y=$t(void 0,e.migrationDir),E=!1;for(let D of x)try{let S=Hr(y,D.migration);if(l&&Qn(S)){let Q=Gr(S,"utf8"),{down:G,skipped:Re}=Jr(Q);for(let Ne of G)await d.unsafe(Ne),console.log(`-- \u21A9 ${Ne}`),E=!0;if(Re.length>0)console.log(`-- \u26A0\uFE0F ${Re.length} statement(s) in ${D.migration} could not be auto-reversed (data/complex DDL) \u2014 reverse manually.`)}let v=`DELETE FROM migrations WHERE migration = ${t(1)}`;if(await d.unsafe(v,[D.migration]),console.log(`-- \u2713 Removed migration record: ${D.migration}`),s.deleteFiles&&Qn(S))zr(S),console.log(`-- \uD83D\uDDD1\uFE0F Deleted migration file: ${D.migration}`)}catch(S){throw console.error(`-- \u2717 Failed to rollback migration ${D.migration}:`,S),S}if(console.log(),l)console.log(E?"-- \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(d){throw console.error("-- Rollback failed:",d),d}}import{existsSync as Zr,readdirSync as ei}from"fs";async function F(){let s=e.dialect||"postgres",o=m(s),l=$t(void 0,e.migrationDir);if(console.log("-- Migration Status"),console.log(`-- Dialect: ${s}`),console.log(`-- SQL directory: ${l}`),console.log(),!Zr(l))return console.log("-- No SQL directory found. No migrations have been created yet."),[];let g=ei(l).filter((x)=>x.endsWith(".sql")).sort();if(g.length===0)return console.log("-- No migration files found"),[];try{let x=i(),y=[];try{y=await x.unsafe(o.getExecutedMigrationsQuery())}catch(Q){console.log("-- Migrations table not found. All migrations are pending.",Q),console.log()}let E=new Map(y.map((Q)=>[Q.migration,Q.executed_at])),D=g.map((Q)=>({file:Q,status:E.has(Q)?"executed":"pending",executedAt:E.get(Q)})),S=D.filter((Q)=>Q.status==="executed"),v=D.filter((Q)=>Q.status==="pending");if(console.log(`-- Total migrations: ${g.length}`),console.log(`-- Executed: ${S.length}`),console.log(`-- Pending: ${v.length}`),console.log(),S.length>0){console.log("\u2713 Executed Migrations:");for(let Q of S)console.log(` - ${Q.file} ${Q.executedAt?`(${new Date(Q.executedAt).toLocaleString()})`:""}`);console.log()}if(v.length>0){console.log("\u25CB Pending Migrations:");for(let Q of v)console.log(` - ${Q.file}`);console.log()}return D}catch(x){throw console.error("-- Failed to get migration status:",x),x}}async function ge(){return F()}import{readdirSync as ti}from"fs";import{extname as Mn,join as Wn}from"path";import ni from"process";async function j(s,o={}){let l=o.dir||Wn(ni.cwd(),"app/Models");try{let d=ti(l),g=d.find((v)=>v.replace(Mn(v),"").toLowerCase()===s.toLowerCase());if(!g){console.error(`Model "${s}" not found in ${l}`),console.log(`Available models: ${d.filter((v)=>[".ts",".js"].includes(Mn(v))).map((v)=>v.replace(Mn(v),"")).join(", ")}`);return}let y=await import(Wn(l,g)),E=y.default||y[Object.keys(y)[0]];if(!E||!E.name){console.error(`Invalid model file: ${g}`);return}let D={name:E.name,table:E.table||`${E.name.toLowerCase()}s`,primaryKey:E.primaryKey||"id",attributes:E.attributes||{},relations:E.relations,scopes:E.scopes,indexes:E.indexes,timestamps:E.timestamps!==!1,softDeletes:E.softDeletes===!0},S=[];if(E.beforeCreate)S.push("beforeCreate");if(E.afterCreate)S.push("afterCreate");if(E.beforeUpdate)S.push("beforeUpdate");if(E.afterUpdate)S.push("afterUpdate");if(E.beforeDelete)S.push("beforeDelete");if(E.afterDelete)S.push("afterDelete");if(S.length>0)D.hooks=S;if(o.json)return console.log(JSON.stringify(D,null,2)),D;console.log(`
289
+ \uD83D\uDCE6 Model: ${D.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: ${D.table}`),console.log(`Primary Key: ${D.primaryKey}`),console.log(`Timestamps: ${D.timestamps?"\u2713":"\u2717"}`),console.log(`Soft Deletes: ${D.softDeletes?"\u2713":"\u2717"}`),console.log(`
290
+ \uD83D\uDCCB Attributes (${Object.keys(D.attributes).length}):`);for(let[v,Q]of Object.entries(D.attributes)){let G=Q.type||"string",Re=Q.required?"(required)":"",Ne=Q.unique?"(unique)":"",Ce=Q.default!==void 0?`= ${JSON.stringify(Q.default)}`:"";console.log(` \u2022 ${v}: ${G} ${Re} ${Ne} ${Ce}`.trim())}if(D.relations&&Object.keys(D.relations).length>0){console.log(`
291
+ \uD83D\uDD17 Relations (${Object.keys(D.relations).length}):`);for(let[v,Q]of Object.entries(D.relations)){let G=Q.type||"unknown",Re=Q.model||Q.table||"unknown";console.log(` \u2022 ${v}: ${G} \u2192 ${Re}`)}}if(D.scopes&&Object.keys(D.scopes).length>0){console.log(`
292
+ \uD83D\uDD0D Scopes (${Object.keys(D.scopes).length}):`);for(let v of Object.keys(D.scopes))console.log(` \u2022 ${v}()`)}if(D.hooks&&D.hooks.length>0){console.log(`
293
+ \uD83E\uDE9D Hooks (${D.hooks.length}):`);for(let v of D.hooks)console.log(` \u2022 ${v}`)}if(D.indexes&&D.indexes.length>0){console.log(`
294
+ \uD83D\uDCC7 Indexes (${D.indexes.length}):`);for(let v of D.indexes){let Q=Array.isArray(v.columns)?v.columns.join(", "):v.columns,G=v.unique?"(unique)":"";console.log(` \u2022 ${v.name||"unnamed"}: [${Q}] ${G}`.trim())}}return console.log(),D}catch(d){throw console.error(`Error loading model "${s}":`,d.message),d}}async function pe(){let o=await i().ping();return console.log(o?"OK":"NOT READY"),o}import{readdirSync as ri,readFileSync as Gn,statSync as ii}from"fs";import{extname as zn,join as si}from"path";async function q(s,o={}){let l=[];try{let d=ii(s),g=[];if(d.isDirectory())g=ri(s).filter((D)=>zn(D)===".sql").map((D)=>si(s,D));else if(d.isFile()&&zn(s)===".sql")g=[s];else return console.error("Path must be a .sql file or directory containing .sql files"),l;if(g.length===0)return console.log("No .sql files found"),l;if(o.verbose)console.log(`Analyzing ${g.length} SQL file(s)...
295
+ `);for(let E of g)try{let D=Gn(E,"utf8").trim();if(!D){if(o.verbose)console.log(`\u2298 ${E}: empty file`);continue}if(o.verbose)console.log(`\uD83D\uDCC4 ${E}`),console.log(` Query: ${D.substring(0,60)}${D.length>60?"...":""}`);let S=await r`EXPLAIN ${r.unsafe(D)}`;if(l.push({file:E,query:D,plan:Array.isArray(S)?S:[S]}),o.verbose&&!o.json){if(console.log(" Plan:"),Array.isArray(S))for(let v of S)if(typeof v==="string")console.log(` ${v}`);else if(v["QUERY PLAN"])console.log(` ${v["QUERY PLAN"]}`);else if(v.plan)console.log(` ${JSON.stringify(v.plan)}`);else console.log(` ${JSON.stringify(v)}`);console.log()}}catch(D){if(l.push({file:E,query:Gn(E,"utf8").trim(),plan:[],error:D.message}),o.verbose)console.log(` \u2717 Error: ${D.message}
296
+ `)}let x=l.filter((E)=>!E.error).length,y=l.filter((E)=>E.error).length;if(o.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: ${x} successful, ${y} failed`);if(o.json)console.log(JSON.stringify(l,null,2));return l}catch(d){throw console.error("Error explaining queries:",d.message),d}}import{writeFileSync as ai}from"fs";import{join as oi}from"path";import li from"process";async function W(s={}){let o=s.dir||oi(li.cwd(),"app/Models"),l=s.format||"mermaid";try{let d=await u({modelsDir:o});if(!d||Object.keys(d).length===0)return console.error("No models found"),"";let g="";if(l==="mermaid")g=ui(d);else if(l==="dot")g=ci(d);else return console.error(`Unsupported format: ${l}`),"";if(s.output)ai(s.output,g,"utf8"),console.log(`\u2713 Diagram written to: ${s.output}`);else console.log(g);return g}catch(d){throw console.error("Error generating diagram:",d.message),d}}function ui(s){let o=["erDiagram"];for(let[l,d]of Object.entries(s)){let g=d.table||`${l.toLowerCase()}s`,x=d.attributes||{};o.push(` ${g} {`);for(let[y,E]of Object.entries(x)){let D=E.type||"string",S=d.primaryKey===y?"PK":"",v=E.unique?"UK":"",Q=[S,v].filter(Boolean).join(","),G=Q?` "${Q}"`:"";o.push(` ${D} ${y}${G}`)}o.push(" }")}for(let[l,d]of Object.entries(s)){let g=d.table||`${l.toLowerCase()}s`,x=d.relations||{};for(let[y,E]of Object.entries(x)){let{type:D,model:S}=E,v=s[S]?.table||`${S?.toLowerCase()}s`||"unknown",Q="";if(D==="hasOne")Q="||--||";else if(D==="hasMany")Q="||--o{";else if(D==="belongsTo")Q="}o--||";else if(D==="belongsToMany"||D==="manyToMany")Q="}o--o{";else Q="||--||";o.push(` ${g} ${Q} ${v} : "${y}"`)}}return o.join(`
297
+ `)}function ci(s){let o=["digraph schema {"," rankdir=LR;"," node [shape=record];",""];for(let[l,d]of Object.entries(s)){let g=d.table||`${l.toLowerCase()}s`,x=d.attributes||{},y=[];for(let[D,S]of Object.entries(x)){let v=S.type||"string",Q=d.primaryKey===D?" (PK)":"",G=S.unique?" (UK)":"";y.push(`${D}: ${v}${Q}${G}`)}let E=`${y.join("\\l")}\\l`;o.push(` ${g} [label="{${g}|${E}}"];`)}o.push("");for(let[l,d]of Object.entries(s)){let g=d.table||`${l.toLowerCase()}s`,x=d.relations||{};for(let[y,E]of Object.entries(x)){let{type:D,model:S}=E,v=s[S]?.table||`${S?.toLowerCase()}s`||"unknown",Q="";if(D==="hasOne")Q="arrowhead=none, arrowtail=normal";else if(D==="hasMany")Q="arrowhead=crow, arrowtail=none";else if(D==="belongsTo")Q="arrowhead=normal, arrowtail=none";else if(D==="belongsToMany"||D==="manyToMany")Q="arrowhead=crow, arrowtail=crow";o.push(` ${g} -> ${v} [label="${y}", ${Q}];`)}}return o.push("}"),o.join(`
298
+ `)}import{existsSync as Jt,mkdirSync as di,readdirSync as mi,writeFileSync as fi}from"fs";import{dirname as Hn,join as qt}from"path";import Wt from"process";function Zt(s){let o=s;while(o!==Hn(o)){if(Jt(qt(o,"package.json")))return o;o=Hn(o)}return Wt.cwd()}async function Xn(s){if(!Jt(s))return console.log(`-- Seeders directory not found: ${s}`),[];let l=mi(s).sort((g,x)=>g.localeCompare(x)).filter((g)=>(g.endsWith(".ts")||g.endsWith(".js"))&&g!=="index.ts"&&g!=="index.js"),d=[];for(let g of l){let x=qt(s,g);try{let y=await import(x),E=y.default||y[Object.keys(y)[0]];if(E&&typeof E==="function"){let D=new E;if(D&&typeof D.run==="function")d.push({name:g.replace(/\.(ts|js)$/,""),className:String(E.name||""),instance:D})}}catch(y){console.error(`-- Failed to load seeder ${g}:`,y)}}return d.sort((g,x)=>g.instance.order-x.instance.order),d}async function A(s={}){let o=Zt(Wt.cwd()),l=s.seedersDir||qt(o,"database/seeders"),d=s.verbose??!0;if(d)console.log("-- Running seeders..."),console.log(`-- Seeders directory: ${l}`);let g=await Xn(l);if(g.length===0){console.log("-- No seeders found");return}if(d)console.log(`-- Found ${g.length} seeder(s)`);let x=i();for(let{name:y,instance:E}of g)try{if(d)console.log(`-- Seeding: ${y}`);if(await E.run(x),d)console.log(`-- \u2713 Seeded: ${y}`)}catch(D){throw console.error(`-- \u2717 Failed to seed ${y}:`,D),D}if(d)console.log("-- All seeders completed successfully")}async function U(s,o={}){let l=Zt(Wt.cwd()),d=qt(l,"database/seeders"),g=o.verbose??!0;if(g)console.log(`-- Running seeder: ${s}`);let x=await Xn(d),y=x.find((D)=>D.className===s)??x.find((D)=>D.name===s);if(!y){let D=x.map((S)=>S.className||S.name).join(", ")||"none";throw console.error(`-- Seeder not found: ${s}. Available: ${D}`),Error(`Seeder not found: ${s}. Available: ${D}`)}let E=i();try{if(await y.instance.run(E),g)console.log(`-- \u2713 Seeder completed: ${s}`)}catch(D){throw console.error(`-- \u2717 Seeder failed: ${s}`,D),D}}async function ye(s){let o=Zt(Wt.cwd()),l=qt(o,"database/seeders");if(!Jt(l))di(l,{recursive:!0}),console.log(`-- Created seeders directory: ${l}`);let g=`${s.replace(/Seeder$/i,"")}Seeder`,x=`${g}.ts`,y=qt(l,x);if(Jt(y))throw console.error(`-- Seeder already exists: ${y}`),Error(`Seeder already exists: ${y}`);let E=`import type { QueryBuilder } from 'bun-query-builder'
299
+ import { Seeder } from 'bun-query-builder'
300
+ import { faker } from '@stacksjs/ts-faker'
301
+
302
+ export default class ${g} extends Seeder {
303
+ /**
304
+ * Run the database seeds.
305
+ */
306
+ async run(qb: QueryBuilder): Promise<void> {
307
+ console.log('Seeding: ${g}')
308
+
309
+ // Example: Create 10 records with faker
310
+ const records = Array.from({ length: 10 }, () => ({
311
+ name: faker.person.fullName(),
312
+ email: faker.internet.email().toLowerCase(),
313
+ age: faker.number.int({ min: 18, max: 80 }),
314
+ created_at: faker.date.past(),
315
+ updated_at: new Date(),
316
+ }))
317
+
318
+ // Option 1: Kysely-style API
319
+ await qb.insertInto('table_name').values(records).execute()
320
+
321
+ // Option 2: Laravel-style API (equivalent)
322
+ // await qb.table('table_name').insert(records).execute()
323
+
324
+ console.log(\`\u2713 Seeded \${records.length} records\`)
325
+
326
+ // For large datasets, use batch inserts:
327
+ // const batchSize = 100
328
+ // for (let i = 0; i < records.length; i += batchSize) {
329
+ // const batch = records.slice(i, i + batchSize)
330
+ // await qb.insertInto('table_name').values(batch).execute()
331
+ // // Or: await qb.table('table_name').insert(batch).execute()
332
+ // }
333
+ }
334
+
335
+ /**
336
+ * Specify the order in which this seeder should run.
337
+ * Lower numbers run first. Default is 100.
338
+ */
339
+ get order(): number {
340
+ return 100
341
+ }
342
+ }
343
+ `;fi(y,E),console.log(`-- \u2713 Created seeder: ${y}`)}async function be(s={}){let o=Zt(Wt.cwd()),l=s.modelsDir||qt(o,"app/Models"),d=s.seedersDir||qt(o,"database/seeders"),g=s.verbose??!0;try{let{resetDatabase:x,generateMigration:y,executeMigration:E}=await import("./chunk-vn93p5q6.js");if(g)console.log("-- Refreshing database...");if(await x(l),g)console.log("-- Running migrations...");if(await y(l,{full:!0}),await E(),g)console.log("-- Running seeders...");if(await A({seedersDir:d,verbose:g}),g)console.log("-- \u2713 Database refreshed successfully")}catch(x){throw console.error("-- \u2717 Database refresh failed:",x),x}}function Te(s,o,l={}){let d=u({modelsDir:s}),g=$e(d);if(e.debug)e.debug.captureText=!0;let x=i({schema:g}),y=x.selectFrom(o).limit(Number(l.limit||10)).toText?.()??"";return console.log(y||"[query]"),{sql:y,qb:x,schema:g}}async function we(s,o={}){let l=i(),d=o.params?JSON.parse(o.params):void 0,g=await l.unsafe(s,d);return console.log(JSON.stringify(g)),g}import{existsSync as pi}from"fs";import{dirname as Jn,join as Zn}from"path";import er from"process";function gi(s){let o=s;while(o!==Jn(o)){if(pi(Zn(o,"package.json")))return o;o=Jn(o)}return er.cwd()}async function V(s){if(!s)s=Zn(gi(er.cwd()),"app/Models");let o=e.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${s}`),console.log(`-- Dialect: ${o}`),console.log();let l=[];try{let d=await u({modelsDir:s}),g=H(d,{dialect:o}),x=i(),y=[];if(o==="sqlite")y=(await x.unsafe(`
344
+ SELECT name FROM sqlite_master
345
+ WHERE type = 'table'
346
+ AND name NOT LIKE 'sqlite_%'
347
+ AND name != 'migrations'
348
+ `)).map((v)=>v.name);else if(o==="postgres")y=(await x.unsafe(`
349
+ SELECT table_name
350
+ FROM information_schema.tables
351
+ WHERE table_schema = 'public'
352
+ AND table_type = 'BASE TABLE'
353
+ AND table_name != 'migrations'
354
+ `)).map((v)=>v.table_name);else if(n(o))y=(await x.unsafe(`
355
+ SELECT table_name
356
+ FROM information_schema.tables
357
+ WHERE table_schema = DATABASE()
358
+ AND table_type = 'BASE TABLE'
359
+ AND table_name != 'migrations'
360
+ `)).map((v)=>v.table_name);let E=g.tables.map((S)=>S.table);for(let S of E)if(!y.includes(S))l.push({type:"missing_table",severity:"error",table:S,message:`Table '${S}' defined in models but not found in database`});for(let S of y)if(!E.includes(S))l.push({type:"extra_table",severity:"warning",table:S,message:`Table '${S}' exists in database but not defined in models`});for(let S of g.tables){if(!y.includes(S.table))continue;let v=[];if(o==="sqlite")v=(await x.unsafe(`PRAGMA table_info(${S.table})`)).map((Ne)=>({name:Ne.name,type:Ne.type.toLowerCase()}));else if(o==="postgres")v=(await x.unsafe(`
361
+ SELECT column_name, data_type
362
+ FROM information_schema.columns
363
+ WHERE table_name = $1
364
+ `,[S.table])).map((Ne)=>({name:Ne.column_name,type:Ne.data_type.toLowerCase()}));else if(n(o))v=(await x.unsafe(`
365
+ SELECT column_name, data_type
366
+ FROM information_schema.columns
367
+ WHERE table_name = ?
368
+ AND table_schema = DATABASE()
369
+ `,[S.table])).map((Ne)=>({name:Ne.column_name,type:Ne.data_type.toLowerCase()}));let Q=v.map((Re)=>Re.name),G=S.columns.map((Re)=>Re.name);for(let Re of S.columns)if(!Q.includes(Re.name))l.push({type:"missing_column",severity:"error",table:S.table,column:Re.name,expected:Re.type,message:`Column '${S.table}.${Re.name}' defined in model but not found in database`});for(let Re of v)if(!G.includes(Re.name))l.push({type:"extra_column",severity:"warning",table:S.table,column:Re.name,actual:Re.type,message:`Column '${S.table}.${Re.name}' exists in database but not defined in model`});for(let Re of S.columns){let Ne=v.find((Ce)=>Ce.name===Re.name);if(Ne){let Ce=(Oe)=>Oe.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim(),_e=Ce(Re.type),Ve=Ce(Ne.type);if(_e!==Ve)l.push({type:"type_mismatch",severity:"warning",table:S.table,column:Re.name,expected:Re.type,actual:Ne.type,message:`Column '${S.table}.${Re.name}' type mismatch: expected '${Re.type}', found '${Ne.type}'`})}}}let D=l.filter((S)=>S.severity==="error").length===0;if(D&&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 S=l.filter((Q)=>Q.severity==="error"),v=l.filter((Q)=>Q.severity==="warning");if(S.length>0){console.log(`\u2717 Errors (${S.length}):`);for(let Q of S)console.log(` - ${Q.message}`);console.log()}if(v.length>0){console.log(`\u26A0 Warnings (${v.length}):`);for(let Q of v)console.log(` - ${Q.message}`);console.log()}if(!D)console.log("-- Recommendation: Run migrations to sync the database schema"),console.log("-- qb migrate ./app/Models --apply")}return{valid:D,issues:l}}catch(d){throw console.error("-- Schema validation failed:",d),d}}async function Se(s){return V(s)}async function De(s={}){let o=Number(s.attempts||10),l=Number(s.delay||100),d=i();try{return await d.waitForReady({attempts:o,delayMs:l}),console.log("READY"),!0}catch{throw console.error("NOT READY"),Error("Database not ready")}}class w{driver;client;tableName;indexName;entityType;keyConditions=[];filterConditions=[];projectionAttrs=[];limitValue;scanForward=!0;consistentReadValue=!1;startKey;constructor(s){this.driver=c(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,o,l){return this.keyConditions.push({attribute:s,operator:o,value:l}),this}wherePartitionKey(s,o){return this.whereKey(s,"=",o)}whereSortKey(s,o){return this.whereKey(s,"=",o)}whereSortKeyBeginsWith(s,o){return this.keyConditions.push({attribute:s,operator:"begins_with",value:o}),this}whereSortKeyBetween(s,o,l){return this.keyConditions.push({attribute:s,operator:"BETWEEN",values:[o,l]}),this}where(s,o,l){return this.filterConditions.push({attribute:s,operator:o,value:l}),this}whereEquals(s,o){return this.where(s,"=",o)}whereLessThan(s,o){return this.where(s,"<",o)}whereLessThanOrEqual(s,o){return this.where(s,"<=",o)}whereGreaterThan(s,o){return this.where(s,">",o)}whereGreaterThanOrEqual(s,o){return this.where(s,">=",o)}whereBetween(s,o,l){return this.filterConditions.push({attribute:s,operator:"BETWEEN",values:[o,l]}),this}whereBeginsWith(s,o){return this.filterConditions.push({attribute:s,operator:"begins_with",value:o}),this}whereContains(s,o){return this.where(s,"contains",o)}whereExists(s){return this.where(s,"attribute_exists")}whereNotExists(s){return this.where(s,"attribute_not_exists")}whereIn(s,o){return this.filterConditions.push({attribute:s,operator:"IN",values:o}),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(),o={TableName:s.tableName,ExpressionAttributeNames:{},ExpressionAttributeValues:{}};if(s.indexName)o.IndexName=s.indexName;let l=0;if(s.keyConditions.length>0){let d=[];for(let g of s.keyConditions){let x=`#key${l}`;if(o.ExpressionAttributeNames[x]=g.attribute,g.operator==="begins_with"){let y=`:keyval${l}`;o.ExpressionAttributeValues[y]=this.driver.marshall({v:g.value}).v,d.push(`begins_with(${x}, ${y})`)}else if(g.operator==="BETWEEN"){let y=`:keyval${l}a`,E=`:keyval${l}b`;o.ExpressionAttributeValues[y]=this.driver.marshall({v:g.values?.[0]}).v,o.ExpressionAttributeValues[E]=this.driver.marshall({v:g.values?.[1]}).v,d.push(`${x} BETWEEN ${y} AND ${E}`)}else{let y=`:keyval${l}`;o.ExpressionAttributeValues[y]=this.driver.marshall({v:g.value}).v,d.push(`${x} ${g.operator} ${y}`)}l++}o.KeyConditionExpression=d.join(" AND ")}if(s.filterConditions&&s.filterConditions.length>0){let d=[];for(let g of s.filterConditions){let x=`#flt${l}`;if(o.ExpressionAttributeNames[x]=g.attribute,g.operator==="attribute_exists")d.push(`attribute_exists(${x})`);else if(g.operator==="attribute_not_exists")d.push(`attribute_not_exists(${x})`);else if(g.operator==="begins_with"||g.operator==="contains"){let y=`:fltval${l}`;o.ExpressionAttributeValues[y]=this.driver.marshall({v:g.value}).v,d.push(`${g.operator}(${x}, ${y})`)}else if(g.operator==="BETWEEN"){let y=`:fltval${l}a`,E=`:fltval${l}b`;o.ExpressionAttributeValues[y]=this.driver.marshall({v:g.values?.[0]}).v,o.ExpressionAttributeValues[E]=this.driver.marshall({v:g.values?.[1]}).v,d.push(`${x} BETWEEN ${y} AND ${E}`)}else if(g.operator==="IN"){let y=(g.values??[]).map((E,D)=>`:fltval${l}_${D}`);g.values?.forEach((E,D)=>{o.ExpressionAttributeValues[`:fltval${l}_${D}`]=this.driver.marshall({v:E}).v}),d.push(`${x} IN (${y.join(", ")})`)}else{let y=`:fltval${l}`;o.ExpressionAttributeValues[y]=this.driver.marshall({v:g.value}).v,d.push(`${x} ${g.operator} ${y}`)}l++}o.FilterExpression=d.join(" AND ")}if(s.projectionAttributes&&s.projectionAttributes.length>0){let d=[];for(let g of s.projectionAttributes){let x=`#proj${l}`;o.ExpressionAttributeNames[x]=g,d.push(x),l++}o.ProjectionExpression=d.join(", ")}if(s.limit!==void 0)o.Limit=s.limit;if(s.scanIndexForward!==void 0)o.ScanIndexForward=s.scanIndexForward;if(s.exclusiveStartKey)o.ExclusiveStartKey=this.driver.marshall(s.exclusiveStartKey);if(s.consistentRead)o.ConsistentRead=s.consistentRead;if(Object.keys(o.ExpressionAttributeNames).length===0)delete o.ExpressionAttributeNames;if(Object.keys(o.ExpressionAttributeValues).length===0)delete o.ExpressionAttributeValues;return o}toScanRequest(){let s=this.buildScanParams(),o={TableName:s.tableName};if(s.indexName)o.IndexName=s.indexName;if(s.filterConditions&&s.filterConditions.length>0){let{expression:l,expressionAttributeNames:d,expressionAttributeValues:g}=this.driver.buildFilterExpression(s.filterConditions);o.FilterExpression=l,o.ExpressionAttributeNames=d,o.ExpressionAttributeValues=g}if(s.projectionAttributes&&s.projectionAttributes.length>0){let{expression:l,expressionAttributeNames:d}=this.driver.buildProjectionExpression(s.projectionAttributes);o.ProjectionExpression=l,o.ExpressionAttributeNames={...o.ExpressionAttributeNames,...d}}if(s.limit!==void 0)o.Limit=s.limit;if(s.exclusiveStartKey)o.ExclusiveStartKey=this.driver.marshall(s.exclusiveStartKey);if(s.consistentRead)o.ConsistentRead=s.consistentRead;return o}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(),o=await this.client.query(s);return{items:o.Items?.map((l)=>this.driver.unmarshall(l)),count:o.Count,scannedCount:o.ScannedCount,lastEvaluatedKey:o.LastEvaluatedKey?this.driver.unmarshall(o.LastEvaluatedKey):void 0,consumedCapacity:o.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(),o=await this.client.scan(s);return{items:o.Items?.map((l)=>this.driver.unmarshall(l)),count:o.Count,scannedCount:o.ScannedCount,lastEvaluatedKey:o.LastEvaluatedKey?this.driver.unmarshall(o.LastEvaluatedKey):void 0,consumedCapacity:o.ConsumedCapacity}}async getAll(){let s=[],o;do{if(o)this.startFrom(o);let l=this.keyConditions.length>0?await this.query():await this.scan();if(l.items)s.push(...l.items);o=l.lastEvaluatedKey}while(o);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 h{driver;client;tableName;itemData={};keyData={};updateExpressions={};conditionExpr;returnValuesOption="NONE";constructor(s){this.driver=c(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,o){if(!this.updateExpressions.set)this.updateExpressions.set={};return this.updateExpressions.set[s]=o,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,o){if(!this.updateExpressions.add)this.updateExpressions.add={};return this.updateExpressions.add[s]=o,this}deleteFromSet(s,o){if(!this.updateExpressions.delete)this.updateExpressions.delete={};return this.updateExpressions.delete[s]=o,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:o,expressionAttributeNames:l,expressionAttributeValues:d}=this.driver.buildUpdateExpression(this.updateExpressions);if(o)s.UpdateExpression=o,s.ExpressionAttributeNames=l,s.ExpressionAttributeValues=d;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(),o=await this.client.putItem(s);if(o.Attributes)return this.driver.unmarshall(o.Attributes);return}async update(){if(!this.client)throw Error("DynamoDB client not provided");let s=this.toUpdateRequest(),o=await this.client.updateItem(s);if(o.Attributes)return this.driver.unmarshall(o.Attributes);return}async delete(){if(!this.client)throw Error("DynamoDB client not provided");let s=this.toDeleteRequest(),o=await this.client.deleteItem(s);if(o.Attributes)return this.driver.unmarshall(o.Attributes);return}async get(){if(!this.client)throw Error("DynamoDB client not provided");let s=this.toGetRequest(),o=await this.client.getItem(s);if(o.Item)return this.driver.unmarshall(o.Item);return}}function an(s){return new w(s)}function on(s){return new h(s)}function ln(s){let o=c(s.config);return{query:()=>new w(s),item:()=>new h(s),driver:o,registerEntity:(l)=>o.registerEntity(l),buildKey:(l,d)=>o.buildPrimaryKey(l,d)}}class tt{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 o of s.entities)this.entities.set(o.name,o)}getEntity(s){return this.entities.get(s)}registerEntity(s){this.entities.set(s.name,s)}buildKey(s,o){let l=this.entities.get(s);if(!l)throw Error(`Entity not found: ${s}`);let d=this.interpolatePattern(l.pkPattern,o),g=this.interpolatePattern(l.skPattern,o);return{pk:d,sk:g}}buildGSIKey(s,o,l){let d=this.entities.get(s);if(!d)throw Error(`Entity not found: ${s}`);let g=d.indexes?.find((E)=>E.name===o);if(!g)throw Error(`GSI not found: ${o} for entity ${s}`);let x=this.interpolatePattern(g.pkPattern,l),y=g.skPattern?this.interpolatePattern(g.skPattern,l):void 0;return{pk:x,sk:y}}createItem(s,o){let{pk:l,sk:d}=this.buildKey(s,o),g=this.entities.get(s),x={[this.pkAttribute]:l,[this.skAttribute]:d,[this.typeAttribute]:s,...o};if(g.indexes)for(let y of g.indexes){let E=this.buildGSIKey(s,y.name,o),D=this.config.indexes?.find((S)=>S.name===y.name);if(D){if(x[D.pkAttribute]=E.pk,D.skAttribute&&E.sk)x[D.skAttribute]=E.sk}}return x}parseEntityType(s){if(s[this.typeAttribute])return s[this.typeAttribute];let o=s[this.pkAttribute];if(!o)return;for(let[l,d]of this.entities){let g=d.pkPattern.split("${")[0];if(o.startsWith(g))return l}return}parseItem(s){let o=this.parseEntityType(s);if(!o)return;let{[this.pkAttribute]:l,[this.skAttribute]:d,[this.typeAttribute]:g,...x}=s;return{type:o,data:x}}getEntityPrefix(s){let o=this.entities.get(s);if(!o)throw Error(`Entity not found: ${s}`);return o.pkPattern.split("${")[0]}generateTableDefinition(){let s=[{name:this.pkAttribute,type:"S"},{name:this.skAttribute,type:"S"}],o=[];if(this.config.indexes)for(let l of this.config.indexes){if(!s.find((d)=>d.name===l.pkAttribute))s.push({name:l.pkAttribute,type:"S"});if(l.skAttribute&&!s.find((d)=>d.name===l.skAttribute))s.push({name:l.skAttribute,type:"S"});o.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:o.length>0?o:void 0,billingMode:"PAY_PER_REQUEST"}}interpolatePattern(s,o){return s.replace(/\$\{(\w+)\}/g,(l,d)=>{if(!(d in o))throw Error(`Missing value for pattern key: ${d}`);return String(o[d])})}}class nt{manager;entityName;options;constructor(s,o,l){this.manager=s,this.entityName=o,this.options=l}async create(s){let o=this.manager.createItem(this.entityName,s),l=new h(this.options).table(this.options.config.tableName).item(o).ifNotExists("pk");if(this.options.client)await l.put();return s}async get(s){let{pk:o,sk:l}=this.manager.buildKey(this.entityName,s),d=new h(this.options).table(this.options.config.tableName).key({pk:o,sk:l});if(!this.options.client)throw Error("DynamoDB client not provided");let g=await d.get();if(!g)return;return this.manager.parseItem(g)?.data}async update(s,o){let{pk:l,sk:d}=this.manager.buildKey(this.entityName,s),g=new h(this.options).table(this.options.config.tableName).key({pk:l,sk:d}).setMany(o).ifExists("pk").returnNew();if(!this.options.client)throw Error("DynamoDB client not provided");let x=await g.update();if(!x)return;return this.manager.parseItem(x)?.data}async delete(s){let{pk:o,sk:l}=this.manager.buildKey(this.entityName,s),d=new h(this.options).table(this.options.config.tableName).key({pk:o,sk:l});if(!this.options.client)throw Error("DynamoDB client not provided");return await d.delete(),!0}query(){return new rt(this.manager,this.entityName,this.options)}async findAll(){let s=this.manager.typeAttribute??"_type",o=new w(this.options).table(this.options.config.tableName).whereEquals(s,this.entityName);if(!this.options.client)throw Error("DynamoDB client not provided");return(await o.getAll()).map((d)=>this.manager.parseItem(d)).filter((d)=>d!==void 0).map((d)=>d.data)}}class rt{manager;entityName;options;builder;pkValue;skConditions=[];constructor(s,o,l){this.manager=s,this.entityName=o,this.options=l,this.builder=new w(l).table(l.config.tableName)}wherePartitionKey(s){let{pk:o}=this.manager.buildKey(this.entityName,s);this.pkValue=o;let l=this.manager.pkAttribute??"pk";return this.builder.wherePartitionKey(l,o),this}whereSortKey(s){let{sk:o}=this.manager.buildKey(this.entityName,s),l=this.manager.skAttribute??"sk";return this.builder.whereSortKey(l,o),this}whereSortKeyBeginsWith(s){let o=this.manager.skAttribute??"sk";return this.builder.whereSortKeyBeginsWith(o,s),this}useIndex(s,o){let l=this.manager.buildGSIKey(this.entityName,s,o),d=this.manager.config.indexes?.find((g)=>g.name===s);if(!d)throw Error(`GSI configuration not found: ${s}`);return this.builder.index(s),this.builder.wherePartitionKey(d.pkAttribute,l.pk),this}where(s,o,l){return this.builder.where(s,o,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((o)=>this.manager.parseItem(o)).filter((o)=>o!==void 0).map((o)=>o.data)}async first(){return this.limit(1),(await this.execute())[0]}}function it(s){return new tt(s)}function st(s,o,l){return new nt(s,o,l)}var cn={simpleEntity:(s,o="id")=>({name:s,pkPattern:`${s.toUpperCase()}#\${${o}}`,skPattern:"METADATA",keyFields:[o]}),oneToMany:(s,o,l="id",d="id")=>({parent:{name:s,pkPattern:`${s.toUpperCase()}#\${${l}}`,skPattern:"METADATA",keyFields:[l]},child:{name:o,pkPattern:`${s.toUpperCase()}#\${${l}}`,skPattern:`${o.toUpperCase()}#\${${d}}`,keyFields:[l,d]}}),manyToMany:(s,o,l="id",d="relatedId")=>({entity:{name:s,pkPattern:`${s.toUpperCase()}#\${${l}}`,skPattern:"METADATA",keyFields:[l]},relation:{name:o,pkPattern:`${s.toUpperCase()}#\${${l}}`,skPattern:`${o.toUpperCase()}#\${${d}}`,keyFields:[l,d],indexes:[{name:"GSI1",pkPattern:`${s.toUpperCase()}#\${${d}}`,skPattern:`${o.toUpperCase()}#\${${l}}`}]}}),hierarchical:(s,o="rootId",l="path")=>({name:s,pkPattern:`ROOT#\${${o}}`,skPattern:`PATH#\${${l}}`,keyFields:[o,l]})};function at(s,o){let l={};for(let[d,g]of Object.entries(s))if(g)l[d]=g.replace(/\{([^}]+)\}/g,(x,y)=>o[y]!==void 0?String(o[y]):`{${y}}`);return l}async function Pt(s){return{models:new Map}}function un(s){return s}function dn(s){return s}function fn(s){return s}function mn(s){return s}class ot{config;driver;singleTableManager;models=new Map;queryBuilderOptions;constructor(s){this.config={pkAttribute:"pk",skAttribute:"sk",entityTypeAttribute:"_et",keyDelimiter:"#",...s};let o={region:s.region,endpoint:s.endpoint,credentials:s.credentials,tableName:s.tableName};this.driver=c(o);let l={tableName:s.tableName,pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,indexes:this.buildGSIConfig(),entities:[]};this.singleTableManager=it(l),this.queryBuilderOptions={config:o}}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 Pt({queryBuilder:{modelsPath:this.config.modelsPath},singleTable:{pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,delimiter:this.config.keyDelimiter}}),o=[];for(let[,l]of s.models)this.registerParsedModel(l),o.push(l);return o}registerModel(s){let o=this.parseWithTooling(s);return this.registerParsedModel(o)}registerParsedModel(s){this.models.set(s.name,s);let o=this.toSingleTableEntity(s);this.singleTableManager.registerEntity(o);let l=this.toEntityMapping(s);return this.driver.registerEntity(l),s}registerModels(s){return s.map((o)=>this.registerModel(o))}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 w(this.queryBuilderOptions).table(this.config.tableName).entity(s)}item(s){if(!this.models.get(s))throw Error(`Model not found: ${s}`);return new h(this.queryBuilderOptions).table(this.config.tableName)}buildKey(s,o){let l=this.models.get(s);if(!l)throw Error(`Model not found: ${s}`);let d=at(l.keyPatterns,o);return{pk:d.pk,sk:d.sk}}createItem(s,o){let l=this.models.get(s);if(!l)throw Error(`Model not found: ${s}`);let d=at(l.keyPatterns,o),{pk:g,sk:x}=d,y={[this.config.pkAttribute]:g,[this.config.skAttribute]:x,[this.config.entityTypeAttribute]:l.name,...o};if(l.hasTimestamps){let E=new Date().toISOString();if(!y.createdAt)y.createdAt=E;y.updatedAt=E}if(l.hasVersioning){if(!y._v)y._v=1}return y}parseItem(s){let o=s[this.config.entityTypeAttribute];if(!o)return;let{[this.config.pkAttribute]:l,[this.config.skAttribute]:d,[this.config.entityTypeAttribute]:g,...x}=s;return{type:o,data:x}}getDriver(){return this.driver}getSingleTableManager(){return this.singleTableManager}generateTableDefinition(){return this.singleTableManager.generateTableDefinition()}generateAccessPatterns(s){let o=this.models.get(s);if(!o)throw Error(`Model not found: ${s}`);return o.accessPatterns}parseWithTooling(s){let o=s.name.toUpperCase(),l=s.primaryKey??"id",d=this.config.keyDelimiter,g=this.parseAttributes(s),x=this.parseRelationships(s,l),y={pk:`${o}${d}{${l}}`,sk:`${o}${d}{${l}}`,...this.deriveGSIKeyPatterns(o,l,d,x)},E=this.deriveAccessPatterns(s.name,o,l,x);return{name:s.name,entityType:o,primaryKey:l,attributes:g,relationships:x,keyPatterns:y,accessPatterns:E,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 o=[];if(o.push({name:s.primaryKey??"id",fillable:!1,required:!0,nullable:!1,unique:!0,hidden:!1,dynamoDbType:"S"}),s.attributes)for(let[l,d]of Object.entries(s.attributes))o.push({name:l,fillable:d.fillable??!0,required:d.required??!1,nullable:d.nullable??!0,unique:d.unique??!1,hidden:d.hidden??!1,defaultValue:d.default,cast:d.cast,dynamoDbType:this.inferDynamoDBType(d)});if(s.traits?.useTimestamps)o.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)o.push({name:"deletedAt",fillable:!1,required:!1,nullable:!0,unique:!1,hidden:!1,dynamoDbType:"S"});return o}inferDynamoDBType(s){if(s.cast){let o=s.cast.toLowerCase();if(["integer","int","float","double","decimal","number"].includes(o))return"N";if(["boolean","bool"].includes(o))return"BOOL";if(["array","list"].includes(o))return"L";if(["object","json","map"].includes(o))return"M"}if(s.validation?.rule){let o=String(s.validation.rule);if(o.includes("integer")||o.includes("numeric")||o.includes("number"))return"N";if(o.includes("boolean"))return"BOOL";if(o.includes("array"))return"L";if(o.includes("object"))return"M"}return"S"}parseRelationships(s,o){let l=[];if(s.hasOne)for(let d of s.hasOne)l.push({type:"hasOne",relatedModel:d,foreignKey:`${s.name.toLowerCase()}Id`,localKey:o,requiresGsi:!0});if(s.hasMany)for(let d of s.hasMany)l.push({type:"hasMany",relatedModel:d,foreignKey:`${s.name.toLowerCase()}Id`,localKey:o,requiresGsi:!1});if(s.belongsTo)for(let d of s.belongsTo)l.push({type:"belongsTo",relatedModel:d,foreignKey:`${d.toLowerCase()}Id`,localKey:o,requiresGsi:!0});if(s.belongsToMany){let d=Array.isArray(s.belongsToMany)?s.belongsToMany:Object.values(s.belongsToMany);for(let g of d){let x=typeof g==="string"?g:g?.model;if(!x)continue;let y=[s.name,x].sort();l.push({type:"belongsToMany",relatedModel:x,foreignKey:`${s.name.toLowerCase()}Id`,localKey:o,pivotEntity:y.join(""),requiresGsi:!0})}}return l}deriveGSIKeyPatterns(s,o,l,d){let g={},x=1;for(let y of d)if(y.requiresGsi&&x<=5)g[`gsi${x}pk`]=`${y.relatedModel.toUpperCase()}${l}{${y.foreignKey}}`,g[`gsi${x}sk`]=`${s}${l}{${o}}`,y.gsiIndex=x,x++;return g}deriveAccessPatterns(s,o,l,d){let g=[];g.push({name:`Get ${s} by ID`,description:`Retrieve a single ${s} by its primary key`,entityType:o,operation:"get",index:"main",keyCondition:"pk = :pk AND sk = :sk",examplePk:`${o}#123`,exampleSk:`${o}#123`,efficient:!0}),g.push({name:`List all ${s}s`,description:`Scan all ${s} entities`,entityType:o,operation:"scan",index:"scan",keyCondition:"_et = :entityType",examplePk:o,efficient:!1});for(let x of d){if(x.type==="hasMany")g.push({name:`Get ${x.relatedModel}s for ${s}`,description:`Query ${x.relatedModel}s related to a ${s}`,entityType:o,operation:"query",index:"main",keyCondition:"pk = :pk AND begins_with(sk, :skPrefix)",examplePk:`${o}#123`,exampleSk:`${x.relatedModel.toUpperCase()}#`,efficient:!0});if(x.gsiIndex){let y=`GSI${x.gsiIndex}`;g.push({name:`Get ${s}s by ${x.relatedModel}`,description:`Query ${s}s by their related ${x.relatedModel}`,entityType:o,operation:"query",index:y,keyCondition:`gsi${x.gsiIndex}pk = :pk`,examplePk:`${x.relatedModel.toUpperCase()}#123`,efficient:!0})}}return g}toSingleTableEntity(s){let o=this.extractKeyFields(s.keyPatterns.pk);return{name:s.name,pkPattern:s.keyPatterns.pk,skPattern:s.keyPatterns.sk,keyFields:o,indexes:this.extractGSIPatterns(s.keyPatterns)}}extractKeyFields(s){let o=s.match(/\{([^}]+)\}/g);if(!o)return[];return o.map((l)=>l.slice(1,-1))}extractGSIPatterns(s){let o=[];for(let l=1;l<=5;l++){let d=`gsi${l}pk`,g=`gsi${l}sk`;if(s[d])o.push({name:`GSI${l}`,pkPattern:s[d],skPattern:s[g]})}return o.length>0?o:void 0}toEntityMapping(s){return{entityType:s.name,pkPattern:s.keyPatterns.pk,skPattern:s.keyPatterns.sk}}buildGSIConfig(){let s=this.config.gsiConfig??{},o=[];if(s.gsi1pk)o.push({name:"GSI1",pkAttribute:s.gsi1pk,skAttribute:s.gsi1sk});if(s.gsi2pk)o.push({name:"GSI2",pkAttribute:s.gsi2pk,skAttribute:s.gsi2sk});if(s.gsi3pk)o.push({name:"GSI3",pkAttribute:s.gsi3pk,skAttribute:s.gsi3sk});return o}}function hn(s){return new ot(s)}function gn(s){return s.accessPatterns}function pn(s,o="#"){let l=s.name.toUpperCase(),d=s.primaryKey??"id";return{name:s.name,pkPattern:`${l}${o}\${${d}}`,skPattern:`${l}${o}\${${d}}`}}function $e(s){let o={};for(let l of Object.keys(s)){let d=s[l],g=d.definition??d.getDefinition?.()??d,x=b(g),y=g.attributes??{},E={};for(let D of Object.keys(y))E[D]=void 0;o[x]={columns:E,primaryKey:g.primaryKey??"id"}}return o}import{readdirSync as yi}from"fs";import{basename as tr,extname as nr,isAbsolute as bi,join as rr}from"path";import hi from"process";var Ti=new Set([".ts",".mts",".cts",".js",".mjs",".cjs"]);function xi(s){let o=nr(s);if(!Ti.has(o))return!1;let l=tr(s,o);if(l.startsWith("_")||l==="index")return!1;return!l.endsWith(".d")}function Di(s){if(!s||typeof s!=="object")return!1;let o=s;return typeof o.name==="string"||typeof o.table==="string"}function ir(s){let o=[],l=yi(s,{withFileTypes:!0}).sort((d,g)=>d.name.localeCompare(g.name));for(let d of l){let g=rr(s,d.name);if(d.isDirectory()){o.push(...ir(g));continue}if(xi(d.name))o.push(g)}return o}async function u(s){let o=s.cwd??hi.cwd(),l=bi(s.modelsDir)?s.modelsDir:rr(o,s.modelsDir),d={};for(let g of ir(l)){let x=`?t=${Date.now()}-${Math.random().toString(36).slice(2)}`,y=await import(`${g}${x}`),E=y.default??y,D=E.definition??E.getDefinition?.()??E;if(!Di(D))continue;let S=D.name??tr(g,nr(g));d[S]={...D,name:S}}return d}function lt(s){let o={},l={},d={},g={},x={},y={};for(let E of Object.keys(s)){let D=s[E],S=D.definition??D.getDefinition?.()??D,v=b(S);o[E]=v,l[v]=E,d[v]=S.primaryKey??"id";let Q=[];for(let[_e,Ve]of Object.entries(S.attributes??{}))if(/^(?:datetime|timestamp|timestamptz|date)$/i.test(String(Ve?.type??"")))Q.push(_e);let G=S.traits??{};if(G.useTimestamps??G.timestampable)Q.push("created_at","updated_at");if(Q.length>0)y[v]=[...new Set(Q)];let Re=(_e)=>{if(!_e)return{};let Ve={};if(Array.isArray(_e)){for(let Oe of _e){let We=Me(Oe);if(We)Ve[We.model]=We.model}return Ve}if(typeof _e==="object"){for(let[Oe,We]of Object.entries(_e)){let ke=Me(We);if(ke)Ve[Oe]=ke.model}return Ve}return{}},Ne=(_e)=>{if(!_e)return{};if(Array.isArray(_e)){let Ve={};for(let Oe of _e)if(typeof Oe==="string")Ve[Oe]=Oe;else if(Oe&&typeof Oe==="object"&&typeof Oe.model==="string")Ve[Oe.model]=Oe;return Ve}return _e},Ce=(_e)=>{if(!_e)return{};return _e};if(g[v]={hasOne:Re(S.hasOne),hasMany:Re(S.hasMany),belongsTo:Re(S.belongsTo),belongsToMany:Ne(S.belongsToMany),hasOneThrough:Ce(S.hasOneThrough),hasManyThrough:Ce(S.hasManyThrough),morphOne:Re(S.morphOne),morphMany:Re(S.morphMany),morphTo:S.morphTo,morphToMany:Re(S.morphToMany),morphedByMany:Re(S.morphedByMany)},S.scopes&&typeof S.scopes==="object"){x[v]={};for(let _e of Object.keys(S.scopes)){let Ve=S.scopes[_e];if(typeof Ve==="function")x[v][_e]=Ve}}}return{modelToTable:o,tableToModel:l,primaryKeys:d,relations:g,scopes:x,models:s,temporalColumns:y}}import{existsSync as $n,mkdirSync as Ei,readdirSync as Ri,readFileSync as Si,writeFileSync as Mi}from"fs";import{dirname as sr,join as en}from"path";import cr from"process";function St(s){if(e.verbose)console.log(s)}function Bt(s){return s.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").toLowerCase()}function An(s){return f(e.relations?.singularizeStrategy)(s)}var zt=0,vt=0,Ut=0,tn=!0,nn=[],jt=null;function ct(){return[...nn]}function Ai(s){let o=s;while(o!==sr(o)){if($n(en(o,"package.json")))return o;o=sr(o)}return cr.cwd()}function wi(){let s=Ai(cr.cwd()),o=$t(s,e.migrationDir);if(!$n(o))Ei(o,{recursive:!0}),St(`-- Created SQL directory: ${o}`);return o}var ut="-- qb:generated";function dt(s){return s.trimStart().startsWith(ut)}function ft(s){return s.split(`
370
+ `).filter((o)=>!o.trimStart().startsWith("--")).join(`
371
+ `).replace(/\s+/g," ").trim().replace(/;+$/,"")}function Ci(s){let o=new Set,l;try{l=Ri(s).filter((d)=>d.endsWith(".sql"))}catch{return o}for(let d of l)try{o.add(ft(Si(en(s,d),"utf8")))}catch{}return o}function dr(s,o){if(!s)return!1;let l=wi();if(jt===null)jt=Ci(l);let d=ft(s);if(d.length>0&&jt.has(d))return St(`-- Migration already in the corpus, not writing it again: ${o}`),!1;zt++;let g=tn?String(zt).padStart(10,"0"):String(Math.floor(Date.now()/1000)+zt),x=`${g}-${o}.sql`;if(!tn){let E=Number(g);while($n(en(l,x)))E+=1,g=String(E),x=`${g}-${o}.sql`}let y=en(l,x);return Mi(y,`${ut}
372
+ ${s}`),St(`-- Migration file created: ${x}`),vt++,nn.push(x),jt?.add(d),!0}function Ot(s,o){return s==="integer"&&o==="bigint"||s==="string"&&o==="text"}function ar(s){if(s.endsWith("_id"))return"bigint";if(s.endsWith("_at"))return"datetime";if(s.startsWith("is_")||s.startsWith("has_"))return"boolean";return}function or(s){if(typeof s==="string"||typeof s==="number"||typeof s==="boolean"||typeof s==="bigint"||s instanceof Date)return s;return}function Ni(s){if(s&&typeof s==="object"&&"name"in s){let o=s;if(o.name==="enum"||o.getRules&&Array.isArray(o.getRules())){if(o.enumValues&&Array.isArray(o.enumValues))return o.enumValues.map((l)=>String(l));if(o._values&&Array.isArray(o._values))return o._values.map((l)=>String(l));if(o.values&&Array.isArray(o.values))return o.values.map((l)=>String(l))}}if(s&&typeof s==="object"){let o=s,l=o.allowedValues||o.enumValues||o._values||o.values;if(Array.isArray(l)&&l.length>0)return l.map((d)=>String(d))}return}function Nn(s){if(!s?.rules||!Array.isArray(s.rules))return;for(let o of s.rules)if(o?.name==="max"||o?.name==="maxLength"){if(o.params&&typeof o.params.max==="number")return o.params.max;if(Array.isArray(o.args)&&typeof o.args[0]==="number")return o.args[0];if(typeof o.value==="number")return o.value;if(typeof o.expectedValue==="number")return o.expectedValue}return}var _n=767;function _i(s){if(!s||typeof s!=="object")return;let o=s;if(o.name)switch(String(o.name).toLowerCase()){case"string":{let d=Nn(o);return d&&d>_n?"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(o.type){let l=String(o.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 $i(s){if(typeof s!=="string")return;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 H(s,o){let l=lt(s),d=[];for(let E of Object.keys(s)){let D=s[E],S=b(D),v=D.primaryKey??"id",Q=D.autoIncrement!==!1,G=D.attributes??{},Re=[],Ne=[];if(!G[v])Re.push({name:Bt(v),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});let Ce=new Map,_e=N(D.belongsTo).length>0,Ve=new Set(Object.keys(G).map((qe)=>Bt(qe))),Oe=new Set;for(let qe of Ve){if(!qe.endsWith("_type"))continue;let ze=`${qe.slice(0,-5)}_id`;if(Ve.has(ze))Oe.add(ze)}for(let qe of N(D.belongsTo)){let ze=qe.foreignKey??`${Bt(qe.model)}_id`,Je=l.modelToTable[qe.model];if(Je)Ce.set(ze,{table:Je,onDelete:qe.onDelete})}for(let qe of Object.keys(G)){let ze=G[qe],Je=Bt(qe),xt=Boolean(ze.validation?.rule?.isRequired),Mt=qe===v?!1:ze.nullable??!(ze.required??xt),Pe,Ie,He=qe===v;if(Pe=$i(ze.type)??_i(ze.validation?.rule),Pe==="string"){let yt=Nn(ze.validation?.rule);if(yt&&yt>_n)Pe="text"}if(!Pe||Pe==="enum"){let yt=Ni(ze.validation?.rule);if(yt&&yt.length>0)Pe="enum",Ie=yt}if(!Pe)Pe=ar(Je);if(!Pe){let yt=or(ze.default);if(typeof yt==="string")Pe=yt.length>255?"text":"string";else if(typeof yt==="number")Pe=Number.isInteger(yt)?"integer":"float";else if(typeof yt==="boolean")Pe="boolean";else if(typeof yt==="bigint")Pe="bigint";else if(yt instanceof Date)Pe="datetime"}if(!Pe)Pe=He?"bigint":"string";let Rt=Pe==="string"?Nn(ze.validation?.rule):void 0,kt={name:Je,type:Pe,isPrimaryKey:He,isUnique:Boolean(ze.unique),isNullable:Mt,hasDefault:typeof ze.default<"u",defaultValue:or(ze.default),enumValues:Ie,maxLength:typeof Rt==="number"&&Rt>0&&Rt<=_n?Rt:void 0};if(Je.endsWith("_id")&&ze.foreignKey!==!1&&!Oe.has(Je))if(typeof ze.foreignKey==="object"&&ze.foreignKey!==null){let yt=ze.foreignKey;if(kt.references={table:yt.table,column:yt.column??"id",onDelete:yt.onDelete,onUpdate:yt.onUpdate},yt.nullable!==void 0)kt.isNullable=yt.nullable}else{let yt=Ce.get(Je),Et=Je.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(On,Xi,Mr)=>Mr.toUpperCase()),sn=yt?.table??(_e?void 0:l.modelToTable[Et]);if(sn){let On=l.primaryKeys[sn]??"id";kt.references={table:sn,column:On,onDelete:yt?.onDelete}}}Re.push(kt)}let We=N(D.belongsTo);for(let qe of We){let ze=qe.foreignKey??`${Bt(qe.model)}_id`;if(Re.some((Mt)=>Mt.name===ze))continue;let Je=l.modelToTable[qe.model],xt=Je?l.primaryKeys[Je]??"id":void 0;Re.push({name:ze,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:Je&&xt&&!Oe.has(ze)?{table:Je,column:xt,onDelete:qe.onDelete}:void 0})}let ke=D.traits;if(ke?.useTimestamps??ke?.timestampable??!1){if(!Re.some((qe)=>qe.name==="created_at"))Re.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:p});if(!Re.some((qe)=>qe.name==="updated_at"))Re.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(ke?.useSoftDeletes??ke?.softDeletable??!1){if(!Re.some((qe)=>qe.name==="deleted_at"))Re.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(ke?.useUuid??!1){if(!Re.some((qe)=>qe.name==="uuid"))Re.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let qe of D.indexes??[])Ne.push({name:qe.name,columns:qe.columns.map((ze)=>Bt(ze)),type:qe.unique?"unique":"index",where:qe.where});for(let qe of Re)if(qe.isUnique&&!qe.isPrimaryKey)Ne.push({name:`${S}_${qe.name}_unique`,columns:[qe.name],type:"unique"});let Dt=Array.isArray(D.shardKey)?D.shardKey.map(Bt):void 0,Ye=Array.isArray(D.sortKey)?D.sortKey.map(Bt):void 0,Qe=D.tableKind;d.push({table:S,columns:Re,indexes:Ne,shardKey:Dt,sortKey:Ye,tableKind:Qe})}let g=new Set(d.map((E)=>E.table));function x(E){if(!g.has(E.table))g.add(E.table),d.push(E)}for(let E of Object.keys(s)){let D=s[E],S=D?.traits??{},v=b(D),Q=An(v);if(S.likeable){let G=typeof S.likeable==="object"?S.likeable:{},Re=G.table||`${v}_likes`,Ne=G.foreignKey||`${Q}_id`;x({table:Re,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:Ne,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:v,column:"id"}},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:p},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:`${Re}_user_target_unique`,columns:["user_id",Ne],type:"unique"}]})}if(S.taggable)x({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:p},{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"}]}),x({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:p},{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(S.categorizable)x({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:p},{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"}]}),x({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:p},{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 E of Object.keys(s)){let D=s[E],S=D?.belongsToMany;if(!S||typeof S!=="object"||Array.isArray(S))continue;let v=b(D),Q=An(v);for(let[G,Re]of Object.entries(S)){let Ne=Re;if(!Ne||typeof Ne!=="object")continue;if(Ne.through)continue;let Ce=Ne.pivot;if(!Ce||!Ce.columns&&!Ce.timestamps&&!Ce.uniques)continue;let _e=Ne.model,Oe=s[_e]?.table||`${String(_e).toLowerCase()}s`,We=An(Oe),ke=Ne.table||[Q,We].sort().join("_"),bt=Ne.foreignKey||`${Q}_id`,At=Ne.relatedKey||`${We}_id`,Tt=new Set([bt,At,...Object.keys(Ce.columns??{})]),Dt=new Set;for(let Je of Tt){if(!Je.endsWith("_type"))continue;let xt=`${Je.slice(0,-5)}_id`;if(Tt.has(xt))Dt.add(xt)}let Ye=(Je,xt)=>Dt.has(Je)?void 0:{table:xt,column:"id"},Qe=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:bt,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:Ye(bt,v)},{name:At,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:Ye(At,Oe)}];if(Ce.columns)for(let[Je,xt]of Object.entries(Ce.columns)){let Mt=xt,Pe=ar(Je)??"string";Qe.push({name:Je,type:Pe,isPrimaryKey:!1,isUnique:!1,isNullable:Mt?.nullable??!1,hasDefault:Mt?.default!==void 0,defaultValue:Mt?.default})}if(Ce.timestamps)Qe.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:p}),Qe.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1});let qe=[],ze=Ce.uniques&&Ce.uniques.length>0?Ce.uniques:[[bt,At]];for(let Je=0;Je<ze.length;Je++){let xt=ze[Je];qe.push({name:`${ke}_${xt.join("_")}_unique${Je>0?`_${Je}`:""}`,columns:[...xt],type:"unique"})}x({table:ke,columns:Qe,indexes:qe})}}let y=new Map(d.map((E)=>[E.table,E]));for(let E of d)for(let D of E.columns){if(!D.references)continue;let S=y.get(D.references.table)?.columns.find((v)=>v.name===D.references.column);if(!S||D.type===S.type)continue;D.type=S.type,D.maxLength=S.maxLength,D.enumValues=S.enumValues,D.enumTypeName=S.enumTypeName}return{dialect:o.dialect,vitessSharded:o.vitessSharded,tables:d}}function Ee(s,o={}){zt=0,vt=0,Ut=0,nn=[],jt=null,tn=!0;let l=o.dryRun?()=>!1:dr,d=[],g=m(s.dialect,{vitessSharded:s.vitessSharded}),{tables:x,deferredForeignKeys:y}=mr(s.tables,s.dialect);for(let[D,S]of x.entries()){let v={...S,columns:S.columns.map((Ce)=>y.has(Yt(S.table,Ce.name))?{...Ce,references:void 0}:Ce)},Q=[],G=new Set;for(let Ce of v.columns)if(Ce.type==="enum"&&Ce.enumValues&&Ce.enumValues.length>0){let _e=`${v.table}_${Ce.name}_type`;if(Ce.enumTypeName=_e,!G.has(_e)){let Ve=g.createEnumType(_e,Ce.enumValues);if(Ve)Q.push(Ve);G.add(_e)}}let Re=g.createTable(v);Q.push(Re);for(let Ce of v.indexes)Q.push(g.createIndex(v.table,Ce,v.columns));if(D===x.length-1)for(let Ce of x)for(let _e of Ce.columns){if(!_e.references||!y.has(Yt(Ce.table,_e.name)))continue;let Ve=g.addForeignKey(Ce.table,_e.name,_e.references.table,_e.references.column,_e.references.onDelete,_e.references.onUpdate);if(Ve)Q.push(Ve)}d.push(...Q);let Ne=Q.join(`
373
+
374
+ `);l(Ne,`create-${v.table}-table`)}if(vt+Ut===0)St("-- Nothing to migrate");else{let D=[];if(vt>0)D.push(`${vt} created`);if(Ut>0)D.push(`${Ut} updated`);St(`-- Migration files: ${D.join(", ")}`)}return d}function Yt(s,o){return`${s}\x00${o}`}function mr(s,o){if(o==="sqlite"||s.length<2)return{tables:s,deferredForeignKeys:new Set};let l=new Map(s.map((D)=>[D.table,D])),d=new Map;for(let D of s)d.set(D.table,new Set(D.columns.map((S)=>S.references?.table).filter((S)=>Boolean(S&&S!==D.table&&l.has(S)))));let g=[],x=new Set;while(g.length<s.length){let D=s.find((S)=>!x.has(S.table)&&[...d.get(S.table)??[]].every((v)=>x.has(v)));if(!D)break;g.push(D),x.add(D.table)}let y=new Set(s.filter((D)=>!x.has(D.table)).map((D)=>D.table)),E=new Set;for(let D of s){if(!y.has(D.table))continue;for(let S of D.columns)if(S.references&&y.has(S.references.table)&&S.references.table!==D.table)E.add(Yt(D.table,S.name))}return g.push(...s.filter((D)=>y.has(D.table))),{tables:g,deferredForeignKeys:E}}function yn(s){return Ee(s).join(`
375
+ `)}function bn(s,o){return _t(s,o).join(`
376
+ `)}function mt(s){let o=Ar("crypto");function l(g){if(g==null||typeof g!=="object"||g instanceof Date)return g;if(Array.isArray(g))return g.map((y)=>l(y));let x={};for(let y of Object.keys(g).sort())x[y]=l(g[y]);return x}let d=JSON.stringify(l(s));return o.createHash("sha256").update(d).digest("hex")}function lr(s){let o={};for(let l of s)o[l.table]=l;return o}function Gt(s){let o={};for(let l of s)o[l.name]=l;return o}function Ke(s,o){if(o==="sqlite"){if(s.name.endsWith("_id")&&M(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(o==="mysql"||o==="vitess"||o==="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"DECIMAL";case"date":return"DATE";case"datetime":case"timestamptz":return"DATETIME";case"json":return"JSON";case"enum":return"ENUM";default:return s.type}return s.type}var p="UTC_TIMESTAMP";function Fe(s,o){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 d=String(l).trim();if(d=d.replace(/::[\w ]+$/i,"").trim(),d.startsWith("'")&&d.endsWith("'")||d.startsWith('"')&&d.endsWith('"'))d=d.slice(1,-1);let g=d.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(g.replace(/\s+/g," ")))return p;if(o==="sqlite"&&g==="CURRENT_TIMESTAMP")return p;if(["CURRENT_TIMESTAMP","NOW()","CURRENT_DATE","CURRENT_TIME","NULL","TRUE","FALSE"].includes(g))return g==="NOW()"?"CURRENT_TIMESTAMP":g;if(s.type==="boolean"){if(/^(?:1|t|true|yes)$/i.test(d))return"1";if(/^(?:0|f|false|no)$/i.test(d))return"0"}if(/^-?\d+(?:\.\d+)?$/.test(d))return String(Number(d));return d}function vi(s,o,l){if(Ke(s,l)!==Ke(o,l))return!0;if(s.isNullable!==o.isNullable)return!0;if(s.hasDefault!==o.hasDefault)return!0;if(Fe(s,l)!==Fe(o,l))return!0;if(s.isUnique!==o.isUnique)return!0;if(s.type==="enum"&&o.type==="enum"){let d=(s.enumValues||[]).slice().sort().join(","),g=(o.enumValues||[]).slice().sort().join(",");if(d!==g)return!0}return!1}function ur(s,o){return JSON.stringify([Ke(s,o),s.isPrimaryKey,s.isUnique,s.isNullable,s.hasDefault,Fe(s,o)??null,(s.enumValues??[]).slice().sort(),s.references?[s.references.table,s.references.column,s.references.onDelete??null,s.references.onUpdate??null]:null])}function ki(s,o,l){let d=Object.keys(s).filter((v)=>!o[v]),g=Object.keys(o).filter((v)=>!s[v]),x=new Map,y=new Map;for(let v of d){let Q=ur(s[v],l),G=x.get(Q)??[];G.push(v),x.set(Q,G)}for(let v of g){let Q=ur(o[v],l),G=y.get(Q)??[];G.push(v),y.set(Q,G)}let E=[],D=new Set,S=new Set;for(let[v,Q]of x){let G=y.get(v);if(Q.length===1&&G&&G.length===1)E.push({from:Q[0],to:G[0]}),D.add(Q[0]),S.add(G[0])}return{renames:E,removed:d.filter((v)=>!D.has(v)),added:g.filter((v)=>!S.has(v))}}function Pi(s){if(!s?.references||!s.hasDefault)return!1;let o=s.defaultValue;return o!==void 0&&o!==null&&String(o).toUpperCase()!=="NULL"}function Ii(s,o){let l=s.columns.find((d)=>d.name===o);if(l&&(l.isPrimaryKey||l.isUnique||l.references))return!0;return s.indexes.some((d)=>d.columns.includes(o))}function Oi(s,o){if(Boolean(s)!==Boolean(o))return!0;if(!s||!o)return!1;if((s.constraintNames?.length??0)>1)return!0;let l=(d)=>(d??"no action").toLowerCase();return s.table!==o.table||s.column!==o.column||l(s.onDelete)!==l(o.onDelete)||l(s.onUpdate)!==l(o.onUpdate)}function fr(s,o){return`${s.type}:${Ct(o,s.name)}:${s.columns.join(",")}`}function Cn(s,o){let l={};for(let d of s)l[fr(d,o)]=d;return l}function je(s,o,l={}){if(!s||s.dialect!==o.dialect){let Oe=Ee(o,{dryRun:l.dryRun}),We=o.tables.map((ke)=>({kind:"create_table",table:ke.table,destructive:!1,sql:""}));return{statements:Oe,operations:We}}let d=l.applyRenames!==!1,g=l.preserveUnknownColumns===!0,x=l.dryRun?()=>!1:dr;zt=0,vt=0,Ut=0,nn=[],jt=null,tn=!1;let y=[],E=[],D=m(o.dialect,{vitessSharded:o.vitessSharded}),S=o.dialect,v=lr(s.tables),Q=lr(o.tables);for(let Oe of Object.keys(v))if(!Q[Oe]){let We=D.dropTable(Oe);y.push(We),E.push({kind:"drop_table",table:Oe,destructive:!0,sql:We}),x(We,`drop-${Oe}-table`),St(`-- Detected dropped table: ${Oe}`)}let G=Object.keys(Q).filter((Oe)=>!v[Oe]).map((Oe)=>Q[Oe]),{tables:Re,deferredForeignKeys:Ne}=mr(G,S);for(let[Oe,We]of Re.entries()){let ke={...We,columns:We.columns.map((Ye)=>Ne.has(Yt(We.table,Ye.name))?{...Ye,references:void 0}:Ye)},bt=[],At=new Set;for(let Ye of ke.columns)if(Ye.type==="enum"&&Ye.enumValues&&Ye.enumValues.length>0){let Qe=`${ke.table}_${Ye.name}_type`;if(Ye.enumTypeName=Qe,!At.has(Qe)){let qe=D.createEnumType(Qe,Ye.enumValues);if(qe)bt.push(qe);At.add(Qe)}}let Tt=D.createTable(ke);bt.push(Tt);for(let Ye of ke.indexes){let Qe=D.createIndex(ke.table,Ye,ke.columns);bt.push(Qe),E.push({kind:"create_index",table:ke.table,column:Ye.name,destructive:!1,sql:Qe})}for(let Ye of We.columns)if(Ye.references&&!Ne.has(Yt(We.table,Ye.name)))E.push({kind:"add_foreign_key",table:We.table,column:Ye.name,destructive:!1,sql:Tt});if(Oe===Re.length-1)for(let Ye of Re)for(let Qe of Ye.columns){if(!Qe.references||!Ne.has(Yt(Ye.table,Qe.name)))continue;let qe=D.addForeignKey(Ye.table,Qe.name,Qe.references.table,Qe.references.column,Qe.references.onDelete,Qe.references.onUpdate);if(!qe)continue;bt.push(qe),E.push({kind:"add_foreign_key",table:Ye.table,column:Qe.name,destructive:!1,sql:qe})}y.push(...bt),E.push({kind:"create_table",table:ke.table,destructive:!1,sql:Tt});let Dt=bt.join(`
377
+
378
+ `);x(Dt,`create-${ke.table}-table`)}let Ce=new Set;for(let Oe of Object.keys(Q)){let We=v[Oe],ke=Q[Oe];if(!We)continue;let bt=Gt(We.columns),At=Gt(ke.columns);for(let Tt of Object.keys(At)){let Dt=At[Tt];if(Dt.type!=="enum"||!Dt.enumValues||Dt.enumValues.length===0)continue;let Ye=`${ke.table}_${Dt.name}_type`;if(Dt.enumTypeName=Ye,bt[Tt])continue;if(!Ce.has(Ye)){let Qe=D.createEnumType(Ye,Dt.enumValues);if(Qe)y.push(Qe),E.push({kind:"create_enum",table:ke.table,column:Dt.name,destructive:!1,sql:Qe}),x(Qe,`create-${Ye}-enum`);Ce.add(Ye)}}}for(let Oe of Object.keys(Q)){let We=v[Oe],ke=Q[Oe];if(!We)continue;let bt=Gt(We.columns),At=Cn(We.indexes,We.table),Tt=Gt(ke.columns),Dt=Cn(ke.indexes,ke.table),Ye=[],Qe=Object.keys(bt).filter((Pe)=>!Tt[Pe]),qe=Object.keys(Tt).filter((Pe)=>!bt[Pe]);if(d&&!g){let Pe=ki(bt,Tt,S);Ye=Pe.renames,Qe=Pe.removed,qe=Pe.added}if(g){let Pe=Qe.map((He)=>bt[He]),Ie=We.indexes.filter((He)=>!Dt[fr(He,We.table)]);if(Pe.length>0||Ie.length>0){if(Pe.length>0)St(`-- Keeping ${Pe.length} column(s) on "${ke.table}" no model declares: ${Qe.join(", ")} \u2014 reconciled from the database, where an undeclared column is out of scope rather than removed`);if(Ie.length>0)St(`-- Keeping ${Ie.length} index(es) on "${ke.table}" no model declares: ${Ie.map((He)=>He.name).join(", ")} \u2014 reconciled from the database, where an undeclared index is out of scope rather than removed`);ke={...ke,columns:[...ke.columns,...Pe],indexes:[...ke.indexes,...Ie]},Tt=Gt(ke.columns),Dt=Cn(ke.indexes,ke.table)}Qe=[]}let ze=Object.keys(Tt).filter((Pe)=>bt[Pe]&&vi(bt[Pe],Tt[Pe],S)),Je=Object.keys(Tt).filter((Pe)=>bt[Pe]&&Oi(bt[Pe].references,Tt[Pe].references));if(S==="sqlite"){if(ze.length>0||Je.length>0||Qe.some((Ie)=>Ii(We,Ie))||qe.some((Ie)=>Pi(Tt[Ie]))){let Ie={},He=new Map(Ye.map((Et)=>[Et.to,Et.from]));for(let Et of ke.columns)if(bt[Et.name])Ie[Et.name]=Et.name;else if(He.has(Et.name))Ie[Et.name]=He.get(Et.name);let Rt=`_qb_tmp_${ke.table}`,kt=0;while((v[Rt]||Q[Rt])&&kt<100)kt+=1,Rt=`_qb_tmp_${ke.table}_${kt}`;let yt=D.rebuildTable({target:ke,tempName:Rt,columnSource:Ie});y.push(yt);let In=ze.some((Et)=>bt[Et].type!==Tt[Et].type);E.push({kind:"rebuild_table",table:ke.table,destructive:Qe.length>0||In,sql:yt});for(let Et of Ye)E.push({kind:"rename_column",table:ke.table,from:Et.from,to:Et.to,destructive:!1,confidence:"high",sql:yt});for(let Et of Qe)E.push({kind:"drop_column",table:ke.table,column:Et,destructive:!0,sql:yt});St(`-- Detected SQLite table rebuild required: ${ke.table}`),x(yt,`alter-${ke.table}-table`);continue}}let xt=[],Mt=!1;for(let Pe of Object.keys(At))if(!Dt[Pe]){let Ie=At[Pe],He=D.dropIndex(ke.table,Ie.name);xt.push(He),y.push(He),E.push({kind:"drop_index",table:ke.table,column:Ie.name,destructive:!1,sql:He}),St(`-- Detected dropped index: ${Ie.name} from ${ke.table}`),Mt=!0}for(let Pe of Ye){let Ie=D.renameColumn(ke.table,Pe.from,Pe.to);xt.push(Ie),y.push(Ie),E.push({kind:"rename_column",table:ke.table,from:Pe.from,to:Pe.to,destructive:!1,confidence:"high",sql:Ie}),St(`-- Detected renamed column: ${ke.table}.${Pe.from} -> ${Pe.to}`),Mt=!0}for(let Pe of Qe){let Ie=D.dropColumn(ke.table,Pe);xt.push(Ie),y.push(Ie),E.push({kind:"drop_column",table:ke.table,column:Pe,destructive:!0,sql:Ie}),St(`-- Detected dropped column: ${ke.table}.${Pe}`),Mt=!0}for(let Pe of ze){let Ie=bt[Pe],He=Tt[Pe],Rt=D.modifyColumn(ke.table,He);xt.push(Rt),y.push(Rt),E.push({kind:"modify_column",table:ke.table,column:Pe,destructive:Ie.type!==He.type&&!Ot(Ie.type,He.type),sql:Rt}),St(`-- Detected column change: ${ke.table}.${Pe} (${Ie.type} -> ${He.type})`),Mt=!0}for(let Pe of Je){let Ie=Tt[Pe];if(!Ie.references)continue;let He=D.addForeignKey(ke.table,Ie.name,Ie.references.table,Ie.references.column,Ie.references.onDelete,Ie.references.onUpdate,bt[Pe].references?.constraintNames);if(!He)continue;xt.push(He),y.push(He),E.push({kind:"add_foreign_key",table:ke.table,column:Pe,destructive:!1,sql:He}),St(`-- Detected foreign-key change: ${ke.table}.${Pe} -> ${Ie.references.table}(${Ie.references.column})`),Mt=!0}for(let Pe of qe){let Ie=Tt[Pe],He=D.addColumn(ke.table,Ie);if(xt.push(He),y.push(He),E.push({kind:"add_column",table:ke.table,column:Ie.name,destructive:!1,sql:He}),St(`-- Detected new column: ${ke.table}.${Ie.name}`),Mt=!0,Ie.references){let Rt=D.addForeignKey(ke.table,Ie.name,Ie.references.table,Ie.references.column,Ie.references.onDelete,Ie.references.onUpdate);if(Rt)xt.push(Rt),y.push(Rt),E.push({kind:"add_foreign_key",table:ke.table,column:Ie.name,destructive:!1,sql:Rt})}}for(let Pe of Object.keys(Dt))if(!At[Pe]){let Ie=Dt[Pe],He=D.createIndex(ke.table,Ie,ke.columns);xt.push(He),y.push(He),E.push({kind:"create_index",table:ke.table,column:Ie.name,destructive:!1,sql:He}),St(`-- Detected new index: ${Ie.name} in ${ke.table}`),Mt=!0}if(Mt){let Pe=xt.join(`
379
+
380
+ `);x(Pe,`alter-${ke.table}-table`)}}if(vt+Ut===0)St("-- Nothing to migrate");else{let Oe=[];if(vt>0)Oe.push(`${vt} created`);if(Ut>0)Oe.push(`${Ut} updated`);St(`-- Migration files: ${Oe.join(", ")}`)}return{statements:y.length===0?["-- No changes detected"]:y,operations:E}}function _t(s,o,l={}){return je(s,o,l).statements}function Tn(s){return s}class It{get order(){return 100}get description(){return}}function wn(s){return s}function ht(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 gt(s){let o=String(s??"").toLowerCase().trim();if(/^(?:bool|boolean|bit)\b/.test(o)||o==="tinyint(1)")return"boolean";if(/^(?:json|jsonb)\b/.test(o))return"json";if(/^(?:bytea|blob|binary|varbinary)\b/.test(o))return"binary";if(/^(?:date|time|timestamp|datetime)\b/.test(o))return"date";if(/(?:^|\b)(?:varchar|character varying|nvarchar|char)\b/.test(o))return"varchar";if(/^(?:text|longtext|mediumtext|tinytext|clob|citext)\b/.test(o))return"text";if(/^(?:decimal|numeric|real|double|money)\b/.test(o)||/^float\d*\b/.test(o))return"fractional";if(/^(?:integer|bigint|smallint|tinyint|serial|bigserial|smallserial|mediumint)\b/.test(o)||/^int\d*\b/.test(o))return"integer";return"other"}function pt(s,o,l){if(s===o)return!0;if(l==="sqlite"){if(s==="boolean"&&o==="integer")return!0;if((s==="date"||s==="json")&&o==="text")return!0}if(n(l)&&s==="boolean"&&o==="integer")return!0;if(s==="varchar"&&o==="text")return!0;if(s==="integer"&&o==="fractional")return!0;if(s==="other"||o==="other")return!0;return!1}async function Lt(s,o={}){let l=o.dialect??e.dialect,d=s.tables.map((S)=>S.table),g=await k({tables:d}),x=new Map(g.map((S)=>[S.table.toLowerCase(),S])),y=[],E=[],D=[];for(let S of s.tables){let v=x.get(S.table.toLowerCase());if(!v){y.push(S.table);continue}let Q=new Map(v.columns.map((G)=>[G.name.toLowerCase(),G]));for(let G of S.columns){let Re=Q.get(G.name.toLowerCase()),Ne=ht(G.type);if(!Re){E.push({table:S.table,column:G.name,expected:Ne});continue}let Ce=gt(Re.sqlType);if(!pt(Ne,Ce,l))D.push({table:S.table,column:G.name,expected:Ne,actual:Ce,actualSqlType:Re.sqlType})}}return{missingTables:y,missingColumns:E,typeMismatches:D,clean:y.length===0&&E.length===0&&D.length===0}}function Kt(s){if(s.clean)return"";let o=[];if(s.missingTables.length>0)o.push(` Missing tables: ${s.missingTables.join(", ")}`);for(let g of s.missingColumns.slice(0,10))o.push(` \u2022 ${g.table}.${g.column} is missing (models declare ${g.expected})`);for(let g of s.typeMismatches.slice(0,10))o.push(` \u2022 ${g.table}.${g.column} is ${g.actualSqlType}, models declare ${g.expected}`);let l=Math.min(s.missingColumns.length,10)+Math.min(s.typeMismatches.length,10),d=s.missingColumns.length+s.typeMismatches.length;if(d>l)o.push(` + ${d-l} more`);return["The live schema does not match the models.",...o,"","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(`
381
+ `)}async function Bi(s,o,l){if(l.length===0)return;let d=Rr(Ft());try{await Sr(s,o);for(let g of l)await rn(s,g,o),Ue(`-- \u2713 Recorded applied migration: ${g}`)}catch(g){Ue(`-- Could not record applied migrations (the schema change itself succeeded): ${g instanceof Error?g.message:String(g)}`)}}function xr(s){try{return dt(Ht(s,"utf8"))}catch{return!1}}function Ui(s){let o=s instanceof Error?s.message:String(s);return/duplicate column name/i.test(o)||/duplicate key name/i.test(o)||/duplicate foreign key constraint name/i.test(o)||/\balready exists\b/i.test(o)}function Ue(s){if(e.verbose)console.log(s)}function Dr(s){return wt(s,e.snapshotDir||".qb")}function Pn(s,o){return wt(Dr(s),`model-snapshot.${o}.json`)}function Fi(s,o){let l=Pn(s,o);if(!Nt(l))return;try{let d=Ht(l,"utf8"),g=JSON.parse(d);if(g?.plan&&Array.isArray(g.plan.tables)&&g.plan.dialect)return g.plan;if(Array.isArray(g?.tables)&&g?.dialect)return g;Ue("-- Invalid snapshot format, treating as no previous state");return}catch(d){Ue(`-- Could not load snapshot, treating as no previous state: ${d instanceof Error?d.message:String(d)}`);return}}function Er(s,o,l){let d=Pn(s,o),g=Dr(s),x=mt(l);if(Nt(d))try{let E=JSON.parse(Ht(d,"utf8"));if(E?.hash===x&&E?.dialect===o&&E?.plan){Ue("-- Model snapshot unchanged");return}}catch{}if(!Nt(g))yr(g,{recursive:!0}),Ue(`-- Created snapshot directory: ${g}`);let y={plan:l,hash:x,dialect:o,updatedAt:new Date().toISOString()};Tr(d,JSON.stringify(y,null,2)),Ue(`-- Model snapshot saved to ${d}`)}function et(s,o={}){let l=o.dialect??s.dialect;Er(o.workspaceRoot??Ft(),l,s)}function Ft(){return Sn()}function Rr(s){let o=$t(s,e.migrationDir);if(!Nt(o))yr(o,{recursive:!0}),Ue(`-- Created SQL directory: ${o}`);return o}async function T(s,o={}){if(await P(),!s)s=wt(kn.cwd(),"app/Models");let l=o.dialect||e.dialect||"postgres",d=Ft(),g=await u({modelsDir:s}),x=H(g,{dialect:l,vitessSharded:o.vitessSharded}),y,E=!1;if(!o.full)if(y=Fi(d,l),y)Ue("-- Comparing with stored model snapshot");else{let Re=wt(s,`.qb-migrations.${l}.json`),Ne=String(o.state||Re);if(Nt(Ne))try{let Ce=Ht(Ne,"utf8"),_e=JSON.parse(Ce);if(y=_e?.plan&&_e.plan.tables?_e.plan:_e?.tables?_e:void 0,y)Ue("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}if(!y||o.fromDb)try{let Ce=await Bn(l),_e=new Set(x.tables.map((Oe)=>Oe.table)),Ve=Ce.tables.filter((Oe)=>_e.has(Oe.table));if(Ve.length>0)y={dialect:Ce.dialect,tables:Ve},E=!0,Ue(`-- No snapshot; reconciling against live database (${Ve.length} matching table${Ve.length===1?"":"s"})`)}catch(Ce){Ue(`-- Could not introspect live database, treating as no previous state: ${Ce instanceof Error?Ce.message:String(Ce)}`)}if(!y)Ue("-- No previous snapshot found, generating full migration")}else Ue("-- Full migration requested, ignoring any previous state");let D=o.full?{statements:Ee(x,{dryRun:o.dryRun}),operations:x.tables.map((Re)=>({kind:"create_table",table:Re.table,destructive:!1,sql:""}))}:je(y,x,{applyRenames:o.applyRenames,dryRun:o.dryRun,preserveUnknownColumns:E}),{statements:S,operations:v}=D,Q=S.join(`
382
+ `),G=S.some((Re)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(Re));if(o.apply){let Re=qi(wt(Ki(),"qb-migrate-")),Ne=wt(Re,"migration.sql");try{if(G){Tr(Ne,Q);let Ce=i();await Ce.file(Ne),Ue("-- Migration applied"),await Bi(Ce,l,ct())}else Ue("-- No changes; nothing to apply")}catch(Ce){throw console.error("-- Migration failed:",Ce),Ce}finally{hr(Re,{recursive:!0,force:!0})}}if(!o.dryRun)Er(d,l,x);return{sql:Q,sqlStatements:S,hasChanges:G,plan:x,operations:v}}function Vi(s,o){if(s===void 0)return[Rr(o)];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((d)=>Li(d)?d:wt(o,d))}function ji(s){let o=new Map;for(let l of s){if(!Nt(l))throw Error(`Migration directory not found: ${l}`);for(let d of br(l).filter((g)=>g.endsWith(".sql"))){let g=o.get(d);if(g!==void 0)throw Error(`Duplicate migration file name across directories: "${d}" appears in both ${g} and ${wt(l,d)}. Migrations are recorded by file name, so names must be unique across every directory in a run.`);o.set(d,wt(l,d))}}return[...o].map(([l,d])=>({name:l,path:d})).sort((l,d)=>l.name<d.name?-1:l.name>d.name?1:0)}var pr="bun-query-builder:migrate",Yi=/\bCONCURRENTLY\b|^\s*VACUUM\b|^\s*BEGIN\s*(?:;|TRANSACTION\b)|^\s*PRAGMA\s+foreign_keys\b/im;function gr(s){return s==="postgres"||s==="sqlite"}async function Qi(s,o){if(s==="sqlite")return await o();let l=i(),d;try{d=await l.reserve()}catch{return await o()}let g=!1;try{return await d.advisoryLock(pr),g=!0,await o()}finally{try{if(g)await d.advisoryUnlock(pr)}finally{d.release?.()}}}async function C(s){await P();let o=Ft(),l=e.dialect||"postgres",d=ji(Vi(s,o));if(d.length===0)return Ue("-- No migration files found to execute"),!0;Ue(`-- Found ${d.length} script files to execute`);try{let g=i();return await Qi(l,async()=>{await Sr(g,l);let x=await Hi(g,l),y=d.filter((E)=>!x.includes(E.name));if(y.length===0)return Ue("-- No pending migrations to execute"),!0;Ue(`-- Executing ${y.length} migration${y.length===1?"":"s"}`);for(let{name:E,path:D}of y){Ue(`-- Executing: ${E}`);try{if(gr(l)&&!Yi.test(Ht(D,"utf-8")))await g.transaction(async(v)=>{await v.file(D),await rn(v,E,l)});else if(await g.file(D),await rn(g,E,l),!gr(l))Ue(`-- (${l} commits DDL implicitly, so ${E} was not applied atomically)`);else Ue(`-- (${E} contains a statement that cannot run in a transaction, so it was not applied atomically)`);Ue(`-- \u2713 Migration ${E} executed and recorded`)}catch(S){if(xr(D)&&Ui(S)){await rn(g,E,l),Ue(`-- \u2713 Migration ${E} was already applied; recorded it (${S instanceof Error?S.message:String(S)})`);continue}throw console.error(`-- \u2717 Migration ${E} failed:`,S),S}}return Ue("-- All migrations executed successfully"),!0})}catch(g){throw console.error("-- Migration execution failed:",g),g}return!0}async function R(s,o={}){if(await P(),!s)s=wt(kn.cwd(),"app/Models");let l=o.dialect||e.dialect||"postgres",d=m(l),g=Ft(),x=async(y)=>{let E=d.dropTable(y);await Ge(async(D)=>{if(l==="sqlite")await D.unsafe("PRAGMA foreign_keys = OFF").execute();if(l==="mysql"||l==="vitess")await D.unsafe("SET FOREIGN_KEY_CHECKS = 0").execute();try{await D.unsafe(E).execute()}finally{if(l==="sqlite")await D.unsafe("PRAGMA foreign_keys = ON").execute();if(l==="mysql"||l==="vitess")await D.unsafe("SET FOREIGN_KEY_CHECKS = 1").execute()}})};try{try{await x("migrations"),Ue("-- Dropped migrations table")}catch(D){console.error(D)}let y=[],E=[];try{let D=await u({modelsDir:s}),S=H(D,{dialect:l});y=S.tables.map((Q)=>Q.table);let v=new Set;for(let Q of S.tables)for(let G of Q.columns)if(G.type==="enum"&&G.enumValues&&G.enumValues.length>0){let Re=`${Q.table}_${G.name}_type`;v.add(Re)}E=Array.from(v)}catch(D){console.error(D),y=[],E=[]}if(y.length===0)Ue("-- No tables found to drop");else{Ue(`-- Dropping ${y.length} tables: ${y.join(", ")}`);for(let D of y.reverse())try{await x(D),Ue(`-- Dropped table: ${D}`)}catch(S){console.error(S),Ue(`-- Table ${D} may not exist, skipping drop`)}}if(E.length>0){Ue(`-- Dropping ${E.length} enum types: ${E.join(", ")}`);for(let D of E)try{let S=d.dropEnumType(D);if(S)await Ge(async(v)=>{await v.unsafe(S).execute(),Ue(`-- Dropped enum type: ${D}`)})}catch(S){console.error(S),Ue(`-- Enum type ${D} may not exist, skipping drop`)}}else Ue("-- No enum types found to drop");if(y.length>0&&!o.preserveMigrationState)try{await Wi(s,g,o)}catch(D){console.error(D),Ue("-- Could not clean up migration files")}else if(y.length===0)Ue("-- No models directory found; keeping committed migration files in place");else Ue("-- Preserving migration files and model snapshot for fresh replay");if(!o.preserveMigrationState)try{await zi(g)}catch(D){console.error(D),Ue("-- Could not clear generated directory")}return Ue("-- Database reset completed successfully"),!0}catch(y){return console.error("-- Database reset failed:",y),!1}}async function Wi(s,o,l={}){if(!s)s=wt(kn.cwd(),"app/Models");if(!o)o=Ft();let d=String(l.dialect||e.dialect||"postgres"),g=Pn(o,d);if(Nt(g))vn(g),Ue(`-- Removed model snapshot file: ${g}`);let x=wt(s,`.qb-migrations.${d}.json`),y=String(l.state||x);if(Nt(y))vn(y),Ue(`-- Removed legacy migration state file: ${y}`);Gi($t(o,e.migrationDir))}function Gi(s){if(!Nt(s))return;let o=0,l=[];for(let d of br(s).filter((g)=>g.endsWith(".sql"))){if(!xr(wt(s,d))){l.push(d);continue}vn(wt(s,d)),Ue(`-- Removed generated migration file: ${d}`),o+=1}if(Ue(`-- Cleaned up ${o} generated migration file${o===1?"":"s"} from migrations directory`),l.length>0)Ue(`-- Kept ${l.length} hand-written migration${l.length===1?"":"s"}: ${l.slice(0,5).join(", ")}${l.length>5?`, +${l.length-5} more`:""}`)}async function zi(s){if(!s)s=Ft();let o=wt(s,"generated");if(Nt(o))try{hr(o,{recursive:!0,force:!0}),Ue("-- Cleared generated directory")}catch(l){console.error("-- Failed to clear generated directory:",l)}}async function Sr(s,o){let d=m(o).createMigrationsTable();try{await s.unsafe(d).execute(),Ue("-- Migrations table ready")}catch(g){throw console.error("-- Failed to create migrations table:",g),g}}async function Hi(s,o){let l=m(o);try{return(await s.unsafe(l.getExecutedMigrationsQuery()).execute()).map((g)=>g.migration)}catch(d){return console.error("-- Failed to get executed migrations:",d),[]}}async function rn(s,o,l){let d=m(l);try{Ue(`-- Recording migration: ${o}`),await s.unsafe(d.recordMigrationQuery(),[o]).execute(),Ue(`-- Successfully recorded migration: ${o}`)}catch(g){throw console.error(`-- Failed to record migration ${o}:`,g),g}}
383
+ export{J,z,Y,X,O,Z,ee,te,ne,_,re,I,L,ie,se,K,ae,oe,Xe,Le,Ze,k,le,a,ce,ue,de,fe,m,et,T,C,R,me,he,F,ge,j,pe,q,W,A,U,ye,be,Te,we,V,Se,De,w,h,an,on,ln,tt,nt,rt,it,st,cn,at,Pt,un,dn,fn,mn,ot,hn,gn,pn,$e,u,lt,ct,ut,dt,ft,Ot,H,Ee,yn,bn,mt,Ke,p,Fe,je,_t,Tn,It,wn,ht,gt,pt,Lt,Kt};