bun-query-builder 0.3.3 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,384 +0,0 @@
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-axxs7680.js";import{c}from"./chunk-3xpe6b57.js";var Ar=import.meta.require;import{existsSync as Nt,mkdirSync as yr,mkdtempSync as Li,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 Bi,join as wt}from"path";import Pn 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),D=y?this.keyPartWidth(y):{bytes:0,indexableWhole:!0},E=!D.indexableWhole;return{name:x,prefixed:E,bytes:E?a.KEY_PREFIX_CHARACTERS*a.BYTES_PER_CHARACTER:D.bytes,narrowable:!D.indexableWhole||D.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,D)=>D.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 D=`${s}_${o}_fk`,E=`ALTER TABLE ${this.quoteIdentifier(s)} ADD CONSTRAINT ${this.quoteIdentifier(D)} FOREIGN KEY (${this.quoteIdentifier(o)}) REFERENCES ${this.quoteIdentifier(l)}(${this.quoteIdentifier(d)})`;if(g)E+=` ON DELETE ${g.toUpperCase()}`;if(x)E+=` 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
- ${E};`:`${E};`}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 D=`${s}_${o}_fk`,E=`ALTER TABLE ${this.quoteIdentifier(s)} ADD CONSTRAINT ${this.quoteIdentifier(D)} FOREIGN KEY (${this.quoteIdentifier(o)}) REFERENCES ${this.quoteIdentifier(l)}(${this.quoteIdentifier(d)})`;if(g)E+=` ON DELETE ${g.toUpperCase()}`;if(x)E+=` 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
- ${E};`:`${E};`}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,l){let d=this.getColumnType(o),g=this.quoteIdentifier(s),x=this.quoteIdentifier(o.name);if(l&&this.getColumnType(l)===d&&!Nr(l,o)){let E=[];if(!o.isPrimaryKey&&l.isNullable!==o.isNullable)E.push(`ALTER TABLE ${g} ALTER COLUMN ${x} ${o.isNullable?"DROP NOT NULL":"SET NOT NULL"};`);let S=this.getDefaultValue(l),v=this.getDefaultValue(o);if(S!==v)E.push(v?`ALTER TABLE ${g} ALTER COLUMN ${x} SET ${v};`:`ALTER TABLE ${g} ALTER COLUMN ${x} DROP DEFAULT;`);if(E.length)return E.join(`
17
- `)}let y=[`ALTER TABLE ${g} ALTER COLUMN ${x} DROP DEFAULT;`,`ALTER TABLE ${g} ALTER COLUMN ${x} TYPE ${d} USING ${x}::${d};`];if(!o.isPrimaryKey)y.push(`ALTER TABLE ${g} ALTER COLUMN ${x} ${o.isNullable?"DROP NOT NULL":"SET NOT NULL"};`);let D=this.getDefaultValue(o);if(D)y.push(`ALTER TABLE ${g} ALTER COLUMN ${x} SET ${D};`);return y.join(`
18
- `)}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 (
19
- id SERIAL PRIMARY KEY,
20
- migration VARCHAR(255) NOT NULL UNIQUE,
21
- executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
22
- )`}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(" ")}}function Nr(s,o){return JSON.stringify(s.enumValues??[])!==JSON.stringify(o.enumValues??[])}class ue extends a{createTable(s){let o=s.columns.map((x)=>this.renderColumn(x)).join(`,
23
- `),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(`,
24
- `);return`CREATE${this.tableKindSuffix(s.tableKind)} TABLE IF NOT EXISTS ${this.quoteIdentifier(s.table)} (
25
- ${d}
26
- );`}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 (
27
- migration VARCHAR(255) NOT NULL PRIMARY KEY,
28
- executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
29
- )`}}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(`,
30
- `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(s.table)} (
31
- ${o}
32
- );`}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(`,
33
- `),y=`CREATE TABLE ${g(l)} (
34
- ${x}
35
- );`,D=o.columns.map((S)=>S.name).filter((S)=>d[S]!==void 0),E=["PRAGMA foreign_keys=OFF;","BEGIN;",y];if(D.length>0){let S=D.map(g).join(", "),v=D.map((Q)=>g(d[Q])).join(", ");E.push(`INSERT INTO ${g(l)} (${S}) SELECT ${v} FROM ${g(o.table)};`)}E.push(`DROP TABLE ${g(o.table)};`),E.push(`ALTER TABLE ${g(l)} RENAME TO ${g(o.table)};`);for(let S of o.indexes)E.push(this.createIndex(o.table,S));return E.push("PRAGMA foreign_key_check;"),E.push("COMMIT;"),E.push("PRAGMA foreign_keys=ON;"),E.join(`
36
- `)}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 (
37
- id INTEGER PRIMARY KEY AUTOINCREMENT,
38
- migration TEXT NOT NULL UNIQUE,
39
- executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
40
- )`}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(`
41
- CREATE TABLE bench_users (
42
- id INTEGER PRIMARY KEY AUTOINCREMENT,
43
- name TEXT NOT NULL,
44
- email TEXT NOT NULL,
45
- active INTEGER DEFAULT 1,
46
- created_at TEXT
47
- )
48
- `).execute();for(let y=0;y<100;y++)await r.unsafe(`
49
- INSERT INTO bench_users (name, email, created_at)
50
- VALUES (?, ?, ?)
51
- `,[`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 D=0;D<o;D++){let E=performance.now();await d.selectFrom("bench_users").where({active:1}).limit(10).execute(),y.push(performance.now()-E)}g.push({operation:"SELECT with WHERE + LIMIT",avgTime:y.reduce((D,E)=>D+E,0)/y.length,minTime:Math.min(...y),maxTime:Math.max(...y),iterations:o})}if(l.includes("select")){let y=[];for(let D=0;D<o;D++){let E=performance.now();await d.selectFrom("bench_users").where({id:1}).first(),y.push(performance.now()-E)}g.push({operation:"SELECT by ID (first)",avgTime:y.reduce((D,E)=>D+E,0)/y.length,minTime:Math.min(...y),maxTime:Math.max(...y),iterations:o})}if(l.includes("count")){let y=[];for(let D=0;D<o;D++){let E=performance.now();await d.selectFrom("bench_users").count(),y.push(performance.now()-E)}g.push({operation:"COUNT",avgTime:y.reduce((D,E)=>D+E,0)/y.length,minTime:Math.min(...y),maxTime:Math.max(...y),iterations:o})}if(l.includes("insert")){let y=[];for(let D=0;D<o;D++){let E=performance.now();await d.insertInto("bench_users").values({name:`Bench User ${D}`,email:`bench${D}@example.com`,created_at:new Date().toISOString()}).execute(),y.push(performance.now()-E)}g.push({operation:"INSERT",avgTime:y.reduce((D,E)=>D+E,0)/y.length,minTime:Math.min(...y),maxTime:Math.max(...y),iterations:o})}if(l.includes("update")){let y=[];for(let D=0;D<o;D++){let E=performance.now();await d.updateTable("bench_users").set({active:0}).where({id:1}).execute(),y.push(performance.now()-E)}g.push({operation:"UPDATE by ID",avgTime:y.reduce((D,E)=>D+E,0)/y.length,minTime:Math.min(...y),maxTime:Math.max(...y),iterations:o})}if(l.includes("delete")){let y=[],D=[];for(let E=0;E<o;E++){let S=await d.insertInto("bench_users").values({name:"To Delete",email:`delete${E}@example.com`,created_at:new Date().toISOString()}).execute();D.push(S)}for(let E=0;E<o;E++){let S=performance.now();await d.deleteFrom("bench_users").where({id:D[E]}).execute(),y.push(performance.now()-S)}g.push({operation:"DELETE by ID",avgTime:y.reduce((E,S)=>E+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 D=y.operation.padEnd(x+2),E=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(`${D}${E}${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 _r}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=_r({input:Xt.stdin,output:Xt.stdout,prompt:"qb> "}),l="",d=!1,g=`
52
- Available Commands:
53
- .help Show this help message
54
- .exit Exit the console
55
- .tables List all tables
56
- .clear Clear the screen
57
-
58
- Query Examples:
59
- qb.selectFrom('users').where({ active: true }).limit(10).execute()
60
- qb.selectFrom('users').count()
61
- qb.insertInto('users').values({ name: 'John' }).execute()
62
- qb.selectFrom('users').where('id', '=', 1).first()
63
- qb.unsafe("SELECT * FROM users WHERE id = $1", [1]).execute()
64
-
65
- Tips:
66
- - Use 'qb' to access the query builder
67
- - Use 'await' for async operations
68
- - Multi-line input: end with \\ to continue on next line
69
- - Press Enter on an empty line to execute multi-line input
70
- `,x=async(D)=>{try{let v=await new(Object.getPrototypeOf(async()=>{})).constructor("qb",`return (${D})`)(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(E){console.error("Error:",E.message)}},y=async(D)=>{let E=D.trim();if(E.startsWith(".")){let S=E.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(`
71
- SELECT name FROM sqlite_master
72
- WHERE type = 'table'
73
- AND name NOT LIKE 'sqlite_%'
74
- ORDER BY name
75
- `);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: ${E}`),console.log("Type .help for available commands");return}if(E.endsWith("\\")){d=!0,l+=`${E.slice(0,-1)}
76
- `;return}if(d){if(E==="")await x(l),l="",d=!1;else l+=`${E}
77
- `;return}if(E)await x(E)};o.on("line",async(D)=>{await y(D),o.prompt()}),o.on("SIGINT",()=>{if(d)console.log(`
78
- -- Multi-line input cancelled`),l="",d=!1,o.prompt();else console.log(`
79
- -- Type .exit to quit`),o.prompt()}),o.on("close",()=>{console.log(`
80
- Goodbye!`),Xt.exit(0)}),o.prompt()}async function Z(){return O()}import{existsSync as $r,readFileSync as vr,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 D=await y.execute();if(console.log(`-- Retrieved ${D.length} rows`),l==="json")Qt(d,JSON.stringify(D,null,2)),console.log(`-- \u2713 Exported to JSON: ${d}`);else if(l==="csv"){if(D.length===0){Qt(d,""),console.log(`-- \u2713 Exported to CSV: ${d} (empty)`);return}let E=Object.keys(D[0]),S=[E.join(",")];for(let v of D){let Q=E.map((G)=>{let Re=v[G];if(Re===null||Re===void 0)return"";let Ne=String(Re);if(Ne.includes(",")||Ne.includes('"')||Ne.includes(`
81
- `))return`"${Ne.replace(/"/g,'""')}"`;return Ne});S.push(Q.join(","))}Qt(d,S.join(`
82
- `)),console.log(`-- \u2713 Exported to CSV: ${d}`)}else if(l==="sql"){let E=[];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,"''")}'`});E.push(`INSERT INTO ${s} (${v.join(", ")}) VALUES (${Q.join(", ")});`)}Qt(d,E.join(`
83
- `)),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=vr(o,"utf8"),D=[];if(d==="json"){if(D=JSON.parse(y),!Array.isArray(D))throw TypeError("JSON file must contain an array of objects")}else if(d==="csv"){let v=y.split(`
84
- `).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}D.push(Ne)}}if(D.length===0){console.log("-- No data to import");return}let E=100,S=0;for(let v=0;v<D.length;v+=E){let Q=D.slice(v,v+E);await x.insertInto(s).values(Q).execute(),S+=Q.length,console.log(`-- Imported ${S}/${D.length} rows...`)}console.log(`-- \u2713 Successfully imported ${D.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(`
85
- SELECT name FROM sqlite_master
86
- WHERE type = 'table'
87
- AND name NOT LIKE 'sqlite_%'
88
- ORDER BY name
89
- `)).map((E)=>E.name);else if(o==="postgres")x=(await g.unsafe(`
90
- SELECT table_name
91
- FROM information_schema.tables
92
- WHERE table_schema = 'public'
93
- AND table_type = 'BASE TABLE'
94
- ORDER BY table_name
95
- `)).map((E)=>E.table_name);else if(n(o))x=(await g.unsafe(`
96
- SELECT table_name
97
- FROM information_schema.tables
98
- WHERE table_schema = DATABASE()
99
- AND table_type = 'BASE TABLE'
100
- ORDER BY table_name
101
- `)).map((E)=>E.table_name);if(d)x=x.filter((D)=>d.includes(D));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 D of x){console.log(`-- Dumping table: ${D}`);let E=await g.selectFrom(D).execute();y.push(`-- Table: ${D}`),y.push(`-- Rows: ${E.length}`),y.push("");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,"''")}'`});y.push(`INSERT INTO ${D} (${v.join(", ")}) VALUES (${Q.join(", ")});`)}y.push("")}Qt(l,y.join(`
102
- `)),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(`
103
- SELECT table_name
104
- FROM information_schema.tables
105
- WHERE table_schema = 'public'
106
- AND table_type = 'BASE TABLE'
107
- ORDER BY table_name
108
- `)).map((D)=>D.table_name);else if(n(s))g=(await l.unsafe(`
109
- SELECT table_name
110
- FROM information_schema.tables
111
- WHERE table_schema = DATABASE()
112
- AND table_type = 'BASE TABLE'
113
- ORDER BY table_name
114
- `)).map((D)=>D.table_name);else if(s==="sqlite")g=(await l.unsafe(`
115
- SELECT name
116
- FROM sqlite_master
117
- WHERE type = 'table'
118
- AND name NOT LIKE 'sqlite_%'
119
- ORDER BY name
120
- `)).map((D)=>D.name);for(let y of g)try{let D=await l.unsafe(`SELECT COUNT(*) as count FROM ${y}`),E=Number(D[0]?.count||0),S=0,v=0;if(s==="postgres"){let Q=await l.unsafe(`
121
- SELECT COUNT(*) as count
122
- FROM information_schema.columns
123
- WHERE table_name = $1
124
- `,[y]);S=Number(Q[0]?.count||0);let G=await l.unsafe(`
125
- SELECT COUNT(*) as count
126
- FROM pg_indexes
127
- WHERE tablename = $1
128
- `,[y]);v=Number(G[0]?.count||0)}else if(n(s)){let Q=await l.unsafe(`
129
- SELECT COUNT(*) as count
130
- FROM information_schema.columns
131
- WHERE table_name = ?
132
- AND table_schema = DATABASE()
133
- `,[y]);S=Number(Q[0]?.count||0);let G=await l.unsafe(`
134
- SELECT COUNT(*) as count
135
- FROM information_schema.statistics
136
- WHERE table_name = ?
137
- AND table_schema = DATABASE()
138
- `,[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:E,columns:S,indexes:v})}catch(D){console.error(`-- Error getting info for table ${y}:`,D)}let x=d.reduce((y,D)=>y+D.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)),D=y+2,E="Table".padEnd(D)+"Rows".padStart(12)+"Columns".padStart(10)+"Indexes".padStart(10);console.log(E),console.log("-".repeat(E.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`
139
- SELECT table_name
140
- FROM information_schema.tables
141
- WHERE table_schema = ${d}
142
- `;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`
143
- SELECT tablename
144
- FROM pg_tables
145
- WHERE schemaname = 'public'
146
- `).map((g)=>g.tablename);else if(n(o)){let d=Be();l=(await r`
147
- SELECT table_name
148
- FROM information_schema.tables
149
- WHERE table_schema = ${d}
150
- `).map((x)=>x.table_name||x.TABLE_NAME)}else if(o==="sqlite")l=(await r`
151
- SELECT name
152
- FROM sqlite_master
153
- WHERE type = 'table'
154
- AND name NOT LIKE 'sqlite_%'
155
- `).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=[],D=await g.unsafe(`SELECT COUNT(*) as count FROM ${s}`),E=Number(D[0]?.count||0);if(l==="postgres"){let S=await g.unsafe(`
156
- SELECT
157
- c.column_name,
158
- c.data_type,
159
- c.is_nullable,
160
- c.column_default,
161
- CASE
162
- WHEN pk.column_name IS NOT NULL THEN true
163
- ELSE false
164
- END as is_primary_key,
165
- CASE
166
- WHEN fk.column_name IS NOT NULL THEN true
167
- ELSE false
168
- END as is_foreign_key
169
- FROM information_schema.columns c
170
- LEFT JOIN (
171
- SELECT ku.column_name
172
- FROM information_schema.table_constraints tc
173
- JOIN information_schema.key_column_usage ku
174
- ON tc.constraint_name = ku.constraint_name
175
- WHERE tc.constraint_type = 'PRIMARY KEY'
176
- AND tc.table_name = $1
177
- ) pk ON c.column_name = pk.column_name
178
- LEFT JOIN (
179
- SELECT ku.column_name
180
- FROM information_schema.table_constraints tc
181
- JOIN information_schema.key_column_usage ku
182
- ON tc.constraint_name = ku.constraint_name
183
- WHERE tc.constraint_type = 'FOREIGN KEY'
184
- AND tc.table_name = $1
185
- ) fk ON c.column_name = fk.column_name
186
- WHERE c.table_name = $1
187
- ORDER BY c.ordinal_position
188
- `,[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(`
189
- SELECT
190
- i.indexname as name,
191
- i.indexdef,
192
- ix.indisunique as is_unique
193
- FROM pg_indexes i
194
- JOIN pg_class c ON c.relname = i.indexname
195
- JOIN pg_index ix ON ix.indexrelid = c.oid
196
- WHERE i.tablename = $1
197
- `,[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(`
198
- SELECT
199
- COLUMN_NAME as column_name,
200
- DATA_TYPE as data_type,
201
- IS_NULLABLE as is_nullable,
202
- COLUMN_DEFAULT as column_default,
203
- COLUMN_KEY as column_key
204
- FROM information_schema.COLUMNS
205
- WHERE TABLE_NAME = ?
206
- AND TABLE_SCHEMA = DATABASE()
207
- ORDER BY ORDINAL_POSITION
208
- `,[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(`
209
- SHOW INDEXES FROM ${s}
210
- `),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: ${E.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:E,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 Pr(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(Pr(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 Ir(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,
211
- (SELECT COUNT(*) FROM information_schema.table_constraints tc
212
- JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
213
- WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
214
- FROM information_schema.columns c
215
- WHERE c.table_name = $1 AND c.table_schema = 'public'
216
- 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
217
- FROM information_schema.columns
218
- WHERE table_name = ? AND table_schema = DATABASE()
219
- 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(`
220
- `);return`export const ${l} = defineModel({
221
- name: '${l}',
222
- table: '${s}',
223
- primaryKey: '${d}',
224
- attributes: {
225
- ${g}
226
- },
227
- })
228
- `}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 Ir(l,o,x);if(!y.length)continue;g.push({table:x,modelName:Le(x),primaryKey:y.find((D)=>D.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 Or(s,o,l){return xn(String(o||s||""),"mysql",{enumValues:l})}function qr(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 Lr(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??""),D=new Map;for(let Q of g)D.set(String(Q.from),{table:String(Q.table),column:String(Q.to??"id"),onDelete:Vt(Q.on_delete),onUpdate:Vt(Q.on_update)});let E=[],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]);E.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?En(Ce):void 0,enumValues:Re,references:D.get(G)}});return{table:o,columns:v,indexes:E}}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 En(s){if(typeof s==="number"||typeof s==="boolean")return s;return String(s)}async function Ln(s){let o=await s.unsafe(`SELECT t.typname AS type_name, e.enumlabel AS label
229
- FROM pg_type t
230
- JOIN pg_enum e ON e.enumtypid = t.oid
231
- JOIN pg_namespace n ON n.oid = t.typnamespace
232
- WHERE n.nspname = 'public'
233
- 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 Br(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 Ur(s,o,l){let d=l??await Ln(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,
234
- (SELECT COUNT(*) FROM information_schema.table_constraints tc
235
- JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
236
- WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
237
- FROM information_schema.columns c
238
- WHERE c.table_name = $1 AND c.table_schema = 'public'
239
- 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,
240
- a.attname AS column_name, array_position(ix.indkey, a.attnum) AS ord,
241
- pg_get_expr(ix.indpred, ix.indrelid) AS where_clause
242
- FROM pg_class t
243
- JOIN pg_index ix ON t.oid = ix.indrelid
244
- JOIN pg_class i ON i.oid = ix.indexrelid
245
- JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
246
- WHERE t.relname = $1 AND t.relkind = 'r'
247
- 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,
248
- tc.constraint_name, rc.delete_rule, rc.update_rule
249
- FROM information_schema.table_constraints tc
250
- JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = tc.constraint_name
251
- JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name = tc.constraint_name
252
- JOIN information_schema.referential_constraints rc ON rc.constraint_name = tc.constraint_name
253
- WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = $1 AND tc.table_schema = 'public'`,[o]),D=new Map,E=new Map;for(let G of y){let Re=String(G.constraint_name);E.set(Re,(E.get(Re)??0)+1)}for(let G of y){let Re=String(G.column_name),Ne=D.get(Re),Ce=String(G.constraint_name),_e=E.get(Ce)===1?[...new Set([...Ne?.constraintNames??[],Ce])]:Ne?.constraintNames;D.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}=Kn(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,...Br(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?En(Ce):void 0,references:D.get(Re)}});return{table:o,columns:Q,indexes:S}}async function Fr(s,o){let l=await s.unsafe(`SELECT column_name, data_type, column_type, is_nullable, column_default, column_key
254
- FROM information_schema.columns
255
- WHERE table_name = ? AND table_schema = DATABASE()
256
- ORDER BY ordinal_position`,[o]),d=await s.unsafe(`SELECT index_name, non_unique, seq_in_index, column_name
257
- FROM information_schema.statistics
258
- WHERE table_name = ? AND table_schema = DATABASE()
259
- 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,
260
- kcu.constraint_name, rc.delete_rule, rc.update_rule
261
- FROM information_schema.key_column_usage kcu
262
- JOIN information_schema.referential_constraints rc
263
- ON rc.constraint_name = kcu.constraint_name AND rc.constraint_schema = kcu.table_schema
264
- 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:D,uniqueColumns:E}=Kn(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=Vr(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:Or(v.data_type??v.DATA_TYPE,G,Re),isPrimaryKey:Ce,isUnique:E.has(Q),isNullable:Ce?!1:String(v.is_nullable??v.IS_NULLABLE).toUpperCase()==="YES",hasDefault:Ve,defaultValue:Ve?En(_e):void 0,enumValues:Re,maxLength:qr(G),references:x.get(Q)}});return{table:o,columns:S,indexes:D}}function Vr(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 Kn(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((E)=>E!=="migrations"),y=l==="postgres"?await Ln(d):void 0,D=[];for(let E of x){let S;if(l==="sqlite")S=await Lr(d,E);else if(l==="postgres")S=await Ur(d,E,y);else S=await Fr(d,E);if(S.columns.length>0)D.push(S)}return{dialect:l,tables:D}}import{existsSync as Dn,mkdirSync as jr,writeFileSync as Yr}from"fs";import{dirname as Un,join as Rn}from"path";import Fn from"process";function Qr(s){let o=s;while(o!==Un(o)){if(Dn(Rn(o,"package.json")))return o;o=Un(o)}return Fn.cwd()}async function le(s,o={}){let l=Qr(Fn.cwd()),d=o.dir||Rn(l,"app/Models");if(!Dn(d))jr(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`,D=Rn(d,y);if(Dn(D))throw console.error(`-- Model already exists: ${D}`),Error(`Model already exists: ${D}`);let S=o.timestamps!==!1?` created_at: { validation: { rule: v.date() } },
265
- updated_at: { validation: { rule: v.date() } },`:"",v=`import { v } from '@stacksjs/ts-validation'
266
- import { defineModel } from 'bun-query-builder'
267
-
268
- const model = defineModel({
269
- name: '${g}',
270
- table: '${x}',
271
- primaryKey: 'id',
272
- attributes: {
273
- id: { validation: { rule: v.integer() } },
274
- ${S}
275
- // Add your model attributes here
276
- // Example:
277
- // name: { validation: { rule: v.string() } },
278
- // email: { unique: true, validation: { rule: v.string().email() } },
279
- // age: { default: 0, validation: { rule: v.number().min(0) } },
280
- },
281
- })
282
-
283
- export default model
284
- `;Yr(D,v),console.log(`-- \u2713 Created model: ${D}`),console.log(`-- Table: ${x}`)}async function me(s,o={}){return T(s,o)}import{existsSync as Qn,readFileSync as zr,unlinkSync as Hr}from"fs";import{join as Xr}from"path";import{existsSync as Wr}from"fs";import{dirname as Vn,isAbsolute as Gr,join as Yn}from"path";import jn from"process";function Sn(s=jn.cwd()){let o=s;while(o!==Vn(o)){if(Wr(Yn(o,"package.json")))return o;o=Vn(o)}return jn.cwd()}function $t(s,o="database/migrations"){let l=o||"database/migrations";return Gr(l)?l:Yn(s??Sn(),l)}function Jr(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(`
285
- `,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 Zr(s,o=e.dialect){let l=(x)=>n(o)?`\`${x}\``:`"${x}"`,d=[],g=[];for(let x of Jr(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 D=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(D)}`)}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(`
286
- SELECT migration, executed_at
287
- FROM migrations
288
- ORDER BY executed_at DESC, migration DESC
289
- `)}catch(E){console.log("-- Migrations table not found. Nothing to rollback.",E);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 E of x)console.log(` - ${E.migration}`);console.log();let y=$t(void 0,e.migrationDir),D=!1;for(let E of x)try{let S=Xr(y,E.migration);if(l&&Qn(S)){let Q=zr(S,"utf8"),{down:G,skipped:Re}=Zr(Q);for(let Ne of G)await d.unsafe(Ne),console.log(`-- \u21A9 ${Ne}`),D=!0;if(Re.length>0)console.log(`-- \u26A0\uFE0F ${Re.length} statement(s) in ${E.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,[E.migration]),console.log(`-- \u2713 Removed migration record: ${E.migration}`),s.deleteFiles&&Qn(S))Hr(S),console.log(`-- \uD83D\uDDD1\uFE0F Deleted migration file: ${E.migration}`)}catch(S){throw console.error(`-- \u2717 Failed to rollback migration ${E.migration}:`,S),S}if(console.log(),l)console.log(D?"-- \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 ei,readdirSync as ti}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(),!ei(l))return console.log("-- No SQL directory found. No migrations have been created yet."),[];let g=ti(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 D=new Map(y.map((Q)=>[Q.migration,Q.executed_at])),E=g.map((Q)=>({file:Q,status:D.has(Q)?"executed":"pending",executedAt:D.get(Q)})),S=E.filter((Q)=>Q.status==="executed"),v=E.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 E}catch(x){throw console.error("-- Failed to get migration status:",x),x}}async function ge(){return F()}import{readdirSync as ni}from"fs";import{extname as Mn,join as Wn}from"path";import ri from"process";async function j(s,o={}){let l=o.dir||Wn(ri.cwd(),"app/Models");try{let d=ni(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)),D=y.default||y[Object.keys(y)[0]];if(!D||!D.name){console.error(`Invalid model file: ${g}`);return}let E={name:D.name,table:D.table||`${D.name.toLowerCase()}s`,primaryKey:D.primaryKey||"id",attributes:D.attributes||{},relations:D.relations,scopes:D.scopes,indexes:D.indexes,timestamps:D.timestamps!==!1,softDeletes:D.softDeletes===!0},S=[];if(D.beforeCreate)S.push("beforeCreate");if(D.afterCreate)S.push("afterCreate");if(D.beforeUpdate)S.push("beforeUpdate");if(D.afterUpdate)S.push("afterUpdate");if(D.beforeDelete)S.push("beforeDelete");if(D.afterDelete)S.push("afterDelete");if(S.length>0)E.hooks=S;if(o.json)return console.log(JSON.stringify(E,null,2)),E;console.log(`
290
- \uD83D\uDCE6 Model: ${E.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: ${E.table}`),console.log(`Primary Key: ${E.primaryKey}`),console.log(`Timestamps: ${E.timestamps?"\u2713":"\u2717"}`),console.log(`Soft Deletes: ${E.softDeletes?"\u2713":"\u2717"}`),console.log(`
291
- \uD83D\uDCCB Attributes (${Object.keys(E.attributes).length}):`);for(let[v,Q]of Object.entries(E.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(E.relations&&Object.keys(E.relations).length>0){console.log(`
292
- \uD83D\uDD17 Relations (${Object.keys(E.relations).length}):`);for(let[v,Q]of Object.entries(E.relations)){let G=Q.type||"unknown",Re=Q.model||Q.table||"unknown";console.log(` \u2022 ${v}: ${G} \u2192 ${Re}`)}}if(E.scopes&&Object.keys(E.scopes).length>0){console.log(`
293
- \uD83D\uDD0D Scopes (${Object.keys(E.scopes).length}):`);for(let v of Object.keys(E.scopes))console.log(` \u2022 ${v}()`)}if(E.hooks&&E.hooks.length>0){console.log(`
294
- \uD83E\uDE9D Hooks (${E.hooks.length}):`);for(let v of E.hooks)console.log(` \u2022 ${v}`)}if(E.indexes&&E.indexes.length>0){console.log(`
295
- \uD83D\uDCC7 Indexes (${E.indexes.length}):`);for(let v of E.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(),E}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 ii,readFileSync as Gn,statSync as si}from"fs";import{extname as zn,join as ai}from"path";async function q(s,o={}){let l=[];try{let d=si(s),g=[];if(d.isDirectory())g=ii(s).filter((E)=>zn(E)===".sql").map((E)=>ai(s,E));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)...
296
- `);for(let D of g)try{let E=Gn(D,"utf8").trim();if(!E){if(o.verbose)console.log(`\u2298 ${D}: empty file`);continue}if(o.verbose)console.log(`\uD83D\uDCC4 ${D}`),console.log(` Query: ${E.substring(0,60)}${E.length>60?"...":""}`);let S=await r`EXPLAIN ${r.unsafe(E)}`;if(l.push({file:D,query:E,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(E){if(l.push({file:D,query:Gn(D,"utf8").trim(),plan:[],error:E.message}),o.verbose)console.log(` \u2717 Error: ${E.message}
297
- `)}let x=l.filter((D)=>!D.error).length,y=l.filter((D)=>D.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 oi}from"fs";import{join as li}from"path";import ui from"process";async function W(s={}){let o=s.dir||li(ui.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=ci(d);else if(l==="dot")g=di(d);else return console.error(`Unsupported format: ${l}`),"";if(s.output)oi(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 ci(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,D]of Object.entries(x)){let E=D.type||"string",S=d.primaryKey===y?"PK":"",v=D.unique?"UK":"",Q=[S,v].filter(Boolean).join(","),G=Q?` "${Q}"`:"";o.push(` ${E} ${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,D]of Object.entries(x)){let{type:E,model:S}=D,v=s[S]?.table||`${S?.toLowerCase()}s`||"unknown",Q="";if(E==="hasOne")Q="||--||";else if(E==="hasMany")Q="||--o{";else if(E==="belongsTo")Q="}o--||";else if(E==="belongsToMany"||E==="manyToMany")Q="}o--o{";else Q="||--||";o.push(` ${g} ${Q} ${v} : "${y}"`)}}return o.join(`
298
- `)}function di(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[E,S]of Object.entries(x)){let v=S.type||"string",Q=d.primaryKey===E?" (PK)":"",G=S.unique?" (UK)":"";y.push(`${E}: ${v}${Q}${G}`)}let D=`${y.join("\\l")}\\l`;o.push(` ${g} [label="{${g}|${D}}"];`)}o.push("");for(let[l,d]of Object.entries(s)){let g=d.table||`${l.toLowerCase()}s`,x=d.relations||{};for(let[y,D]of Object.entries(x)){let{type:E,model:S}=D,v=s[S]?.table||`${S?.toLowerCase()}s`||"unknown",Q="";if(E==="hasOne")Q="arrowhead=none, arrowtail=normal";else if(E==="hasMany")Q="arrowhead=crow, arrowtail=none";else if(E==="belongsTo")Q="arrowhead=normal, arrowtail=none";else if(E==="belongsToMany"||E==="manyToMany")Q="arrowhead=crow, arrowtail=crow";o.push(` ${g} -> ${v} [label="${y}", ${Q}];`)}}return o.push("}"),o.join(`
299
- `)}import{existsSync as Jt,mkdirSync as mi,readdirSync as fi,writeFileSync as pi}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=fi(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),D=y.default||y[Object.keys(y)[0]];if(D&&typeof D==="function"){let E=new D;if(E&&typeof E.run==="function")d.push({name:g.replace(/\.(ts|js)$/,""),className:String(D.name||""),instance:E})}}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:D}of g)try{if(d)console.log(`-- Seeding: ${y}`);if(await D.run(x),d)console.log(`-- \u2713 Seeded: ${y}`)}catch(E){throw console.error(`-- \u2717 Failed to seed ${y}:`,E),E}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((E)=>E.className===s)??x.find((E)=>E.name===s);if(!y){let E=x.map((S)=>S.className||S.name).join(", ")||"none";throw console.error(`-- Seeder not found: ${s}. Available: ${E}`),Error(`Seeder not found: ${s}. Available: ${E}`)}let D=i();try{if(await y.instance.run(D),g)console.log(`-- \u2713 Seeder completed: ${s}`)}catch(E){throw console.error(`-- \u2717 Seeder failed: ${s}`,E),E}}async function ye(s){let o=Zt(Wt.cwd()),l=qt(o,"database/seeders");if(!Jt(l))mi(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 D=`import type { QueryBuilder } from 'bun-query-builder'
300
- import { Seeder } from 'bun-query-builder'
301
- import { faker } from '@stacksjs/ts-faker'
302
-
303
- export default class ${g} extends Seeder {
304
- /**
305
- * Run the database seeds.
306
- */
307
- async run(qb: QueryBuilder): Promise<void> {
308
- console.log('Seeding: ${g}')
309
-
310
- // Example: Create 10 records with faker
311
- const records = Array.from({ length: 10 }, () => ({
312
- name: faker.person.fullName(),
313
- email: faker.internet.email().toLowerCase(),
314
- age: faker.number.int({ min: 18, max: 80 }),
315
- created_at: faker.date.past(),
316
- updated_at: new Date(),
317
- }))
318
-
319
- // Option 1: Kysely-style API
320
- await qb.insertInto('table_name').values(records).execute()
321
-
322
- // Option 2: Laravel-style API (equivalent)
323
- // await qb.table('table_name').insert(records).execute()
324
-
325
- console.log(\`\u2713 Seeded \${records.length} records\`)
326
-
327
- // For large datasets, use batch inserts:
328
- // const batchSize = 100
329
- // for (let i = 0; i < records.length; i += batchSize) {
330
- // const batch = records.slice(i, i + batchSize)
331
- // await qb.insertInto('table_name').values(batch).execute()
332
- // // Or: await qb.table('table_name').insert(batch).execute()
333
- // }
334
- }
335
-
336
- /**
337
- * Specify the order in which this seeder should run.
338
- * Lower numbers run first. Default is 100.
339
- */
340
- get order(): number {
341
- return 100
342
- }
343
- }
344
- `;pi(y,D),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:D}=await import("./chunk-zbjamkgf.js");if(g)console.log("-- Refreshing database...");if(await x(l),g)console.log("-- Running migrations...");if(await y(l,{full:!0}),await D(),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 gi}from"fs";import{dirname as Jn,join as Zn}from"path";import er from"process";function yi(s){let o=s;while(o!==Jn(o)){if(gi(Zn(o,"package.json")))return o;o=Jn(o)}return er.cwd()}async function V(s){if(!s)s=Zn(yi(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(`
345
- SELECT name FROM sqlite_master
346
- WHERE type = 'table'
347
- AND name NOT LIKE 'sqlite_%'
348
- AND name != 'migrations'
349
- `)).map((v)=>v.name);else if(o==="postgres")y=(await x.unsafe(`
350
- SELECT table_name
351
- FROM information_schema.tables
352
- WHERE table_schema = 'public'
353
- AND table_type = 'BASE TABLE'
354
- AND table_name != 'migrations'
355
- `)).map((v)=>v.table_name);else if(n(o))y=(await x.unsafe(`
356
- SELECT table_name
357
- FROM information_schema.tables
358
- WHERE table_schema = DATABASE()
359
- AND table_type = 'BASE TABLE'
360
- AND table_name != 'migrations'
361
- `)).map((v)=>v.table_name);let D=g.tables.map((S)=>S.table);for(let S of D)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(!D.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(`
362
- SELECT column_name, data_type
363
- FROM information_schema.columns
364
- WHERE table_name = $1
365
- `,[S.table])).map((Ne)=>({name:Ne.column_name,type:Ne.data_type.toLowerCase()}));else if(n(o))v=(await x.unsafe(`
366
- SELECT column_name, data_type
367
- FROM information_schema.columns
368
- WHERE table_name = ?
369
- AND table_schema = DATABASE()
370
- `,[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 E=l.filter((S)=>S.severity==="error").length===0;if(E&&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(!E)console.log("-- Recommendation: Run migrations to sync the database schema"),console.log("-- qb migrate ./app/Models --apply")}return{valid:E,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`,D=`:keyval${l}b`;o.ExpressionAttributeValues[y]=this.driver.marshall({v:g.values?.[0]}).v,o.ExpressionAttributeValues[D]=this.driver.marshall({v:g.values?.[1]}).v,d.push(`${x} BETWEEN ${y} AND ${D}`)}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`,D=`:fltval${l}b`;o.ExpressionAttributeValues[y]=this.driver.marshall({v:g.values?.[0]}).v,o.ExpressionAttributeValues[D]=this.driver.marshall({v:g.values?.[1]}).v,d.push(`${x} BETWEEN ${y} AND ${D}`)}else if(g.operator==="IN"){let y=(g.values??[]).map((D,E)=>`:fltval${l}_${E}`);g.values?.forEach((D,E)=>{o.ExpressionAttributeValues[`:fltval${l}_${E}`]=this.driver.marshall({v:D}).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((D)=>D.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 D=this.buildGSIKey(s,y.name,o),E=this.config.indexes?.find((S)=>S.name===y.name);if(E){if(x[E.pkAttribute]=D.pk,E.skAttribute&&D.sk)x[E.skAttribute]=D.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 D=new Date().toISOString();if(!y.createdAt)y.createdAt=D;y.updatedAt=D}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)},D=this.deriveAccessPatterns(s.name,o,l,x);return{name:s.name,entityType:o,primaryKey:l,attributes:g,relationships:x,keyPatterns:y,accessPatterns:D,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??{},D={};for(let E of Object.keys(y))D[E]=void 0;o[x]={columns:D,primaryKey:g.primaryKey??"id"}}return o}import{readdirSync as bi}from"fs";import{basename as tr,extname as nr,isAbsolute as hi,join as rr}from"path";import Ti from"process";var xi=new Set([".ts",".mts",".cts",".js",".mjs",".cjs"]);function Ei(s){let o=nr(s);if(!xi.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=bi(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(Ei(d.name))o.push(g)}return o}async function u(s){let o=s.cwd??Ti.cwd(),l=hi(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}`),D=y.default??y,E=D.definition??D.getDefinition?.()??D;if(!Di(E))continue;let S=E.name??tr(g,nr(g));d[S]={...E,name:S}}return d}function lt(s){let o={},l={},d={},g={},x={},y={};for(let D of Object.keys(s)){let E=s[D],S=E.definition??E.getDefinition?.()??E,v=b(S);o[D]=v,l[v]=D,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 Pe=Me(We);if(Pe)Ve[Oe]=Pe.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 Ri,readdirSync as Si,readFileSync as Mi,writeFileSync as Ai}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 wi(s){let o=s;while(o!==sr(o)){if($n(en(o,"package.json")))return o;o=sr(o)}return cr.cwd()}function Ci(){let s=wi(cr.cwd()),o=$t(s,e.migrationDir);if(!$n(o))Ri(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(`
371
- `).filter((o)=>!o.trimStart().startsWith("--")).join(`
372
- `).replace(/\s+/g," ").trim().replace(/;+$/,"")}function Ni(s){let o=new Set,l;try{l=Si(s).filter((d)=>d.endsWith(".sql"))}catch{return o}for(let d of l)try{o.add(ft(Mi(en(s,d),"utf8")))}catch{}return o}function dr(s,o){if(!s)return!1;let l=Ci();if(jt===null)jt=Ni(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 D=Number(g);while($n(en(l,x)))D+=1,g=String(D),x=`${g}-${o}.sql`}let y=en(l,x);return Ai(y,`${ut}
373
- ${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 _i(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 vi(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 D of Object.keys(s)){let E=s[D],S=b(E),v=E.primaryKey??"id",Q=E.autoIncrement!==!1,G=E.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(E.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(E.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),ke,Ie,He=qe===v;if(ke=vi(ze.type)??$i(ze.validation?.rule),ke==="string"){let yt=Nn(ze.validation?.rule);if(yt&&yt>_n)ke="text"}if(!ke||ke==="enum"){let yt=_i(ze.validation?.rule);if(yt&&yt.length>0)ke="enum",Ie=yt}if(!ke)ke=ar(Je);if(!ke){let yt=or(ze.default);if(typeof yt==="string")ke=yt.length>255?"text":"string";else if(typeof yt==="number")ke=Number.isInteger(yt)?"integer":"float";else if(typeof yt==="boolean")ke="boolean";else if(typeof yt==="bigint")ke="bigint";else if(yt instanceof Date)ke="datetime"}if(!ke)ke=He?"bigint":"string";let Rt=ke==="string"?Nn(ze.validation?.rule):void 0,kt={name:Je,type:ke,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),Dt=Je.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(On,Ji,Mr)=>Mr.toUpperCase()),sn=yt?.table??(_e?void 0:l.modelToTable[Dt]);if(sn){let On=l.primaryKeys[sn]??"id";kt.references={table:sn,column:On,onDelete:yt?.onDelete}}}Re.push(kt)}let We=N(E.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 Pe=E.traits;if(Pe?.useTimestamps??Pe?.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(Pe?.useSoftDeletes??Pe?.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(Pe?.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 E.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 Et=Array.isArray(E.shardKey)?E.shardKey.map(Bt):void 0,Ye=Array.isArray(E.sortKey)?E.sortKey.map(Bt):void 0,Qe=E.tableKind;d.push({table:S,columns:Re,indexes:Ne,shardKey:Et,sortKey:Ye,tableKind:Qe})}let g=new Set(d.map((D)=>D.table));function x(D){if(!g.has(D.table))g.add(D.table),d.push(D)}for(let D of Object.keys(s)){let E=s[D],S=E?.traits??{},v=b(E),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 D of Object.keys(s)){let E=s[D],S=E?.belongsToMany;if(!S||typeof S!=="object"||Array.isArray(S))continue;let v=b(E),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),Pe=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??{})]),Et=new Set;for(let Je of Tt){if(!Je.endsWith("_type"))continue;let xt=`${Je.slice(0,-5)}_id`;if(Tt.has(xt))Et.add(xt)}let Ye=(Je,xt)=>Et.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,ke=ar(Je)??"string";Qe.push({name:Je,type:ke,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:`${Pe}_${xt.join("_")}_unique${Je>0?`_${Je}`:""}`,columns:[...xt],type:"unique"})}x({table:Pe,columns:Qe,indexes:qe})}}let y=new Map(d.map((D)=>[D.table,D]));for(let D of d)for(let E of D.columns){if(!E.references)continue;let S=y.get(E.references.table)?.columns.find((v)=>v.name===E.references.column);if(!S||E.type===S.type)continue;E.type=S.type,E.maxLength=S.maxLength,E.enumValues=S.enumValues,E.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[E,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(E===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(`
374
-
375
- `);l(Ne,`create-${v.table}-table`)}if(vt+Ut===0)St("-- Nothing to migrate");else{let E=[];if(vt>0)E.push(`${vt} created`);if(Ut>0)E.push(`${Ut} updated`);St(`-- Migration files: ${E.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((E)=>[E.table,E])),d=new Map;for(let E of s)d.set(E.table,new Set(E.columns.map((S)=>S.references?.table).filter((S)=>Boolean(S&&S!==E.table&&l.has(S)))));let g=[],x=new Set;while(g.length<s.length){let E=s.find((S)=>!x.has(S.table)&&[...d.get(S.table)??[]].every((v)=>x.has(v)));if(!E)break;g.push(E),x.add(E.table)}let y=new Set(s.filter((E)=>!x.has(E.table)).map((E)=>E.table)),D=new Set;for(let E of s){if(!y.has(E.table))continue;for(let S of E.columns)if(S.references&&y.has(S.references.table)&&S.references.table!==E.table)D.add(Yt(E.table,S.name))}return g.push(...s.filter((E)=>y.has(E.table))),{tables:g,deferredForeignKeys:D}}function yn(s){return Ee(s).join(`
376
- `)}function bn(s,o){return _t(s,o).join(`
377
- `)}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 Pi(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 D=[],E=new Set,S=new Set;for(let[v,Q]of x){let G=y.get(v);if(Q.length===1&&G&&G.length===1)D.push({from:Q[0],to:G[0]}),E.add(Q[0]),S.add(G[0])}return{renames:D,removed:d.filter((v)=>!E.has(v)),added:g.filter((v)=>!S.has(v))}}function Ii(s){if(!s?.references||!s.hasDefault)return!1;let o=s.defaultValue;return o!==void 0&&o!==null&&String(o).toUpperCase()!=="NULL"}function Oi(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 qi(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((Pe)=>({kind:"create_table",table:Pe.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=[],D=[],E=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=E.dropTable(Oe);y.push(We),D.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 Pe={...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 Pe.columns)if(Ye.type==="enum"&&Ye.enumValues&&Ye.enumValues.length>0){let Qe=`${Pe.table}_${Ye.name}_type`;if(Ye.enumTypeName=Qe,!At.has(Qe)){let qe=E.createEnumType(Qe,Ye.enumValues);if(qe)bt.push(qe);At.add(Qe)}}let Tt=E.createTable(Pe);bt.push(Tt);for(let Ye of Pe.indexes){let Qe=E.createIndex(Pe.table,Ye,Pe.columns);bt.push(Qe),D.push({kind:"create_index",table:Pe.table,column:Ye.name,destructive:!1,sql:Qe})}for(let Ye of We.columns)if(Ye.references&&!Ne.has(Yt(We.table,Ye.name)))D.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=E.addForeignKey(Ye.table,Qe.name,Qe.references.table,Qe.references.column,Qe.references.onDelete,Qe.references.onUpdate);if(!qe)continue;bt.push(qe),D.push({kind:"add_foreign_key",table:Ye.table,column:Qe.name,destructive:!1,sql:qe})}y.push(...bt),D.push({kind:"create_table",table:Pe.table,destructive:!1,sql:Tt});let Et=bt.join(`
378
-
379
- `);x(Et,`create-${Pe.table}-table`)}let Ce=new Set;for(let Oe of Object.keys(Q)){let We=v[Oe],Pe=Q[Oe];if(!We)continue;let bt=Gt(We.columns),At=Gt(Pe.columns);for(let Tt of Object.keys(At)){let Et=At[Tt];if(Et.type!=="enum"||!Et.enumValues||Et.enumValues.length===0)continue;let Ye=`${Pe.table}_${Et.name}_type`;if(Et.enumTypeName=Ye,bt[Tt])continue;if(!Ce.has(Ye)){let Qe=E.createEnumType(Ye,Et.enumValues);if(Qe)y.push(Qe),D.push({kind:"create_enum",table:Pe.table,column:Et.name,destructive:!1,sql:Qe}),x(Qe,`create-${Ye}-enum`);Ce.add(Ye)}}}for(let Oe of Object.keys(Q)){let We=v[Oe],Pe=Q[Oe];if(!We)continue;let bt=Gt(We.columns),At=Cn(We.indexes,We.table),Tt=Gt(Pe.columns),Et=Cn(Pe.indexes,Pe.table),Ye=[],Qe=Object.keys(bt).filter((ke)=>!Tt[ke]),qe=Object.keys(Tt).filter((ke)=>!bt[ke]);if(d&&!g){let ke=ki(bt,Tt,S);Ye=ke.renames,Qe=ke.removed,qe=ke.added}if(g){let ke=Qe.map((He)=>bt[He]),Ie=We.indexes.filter((He)=>!Et[fr(He,We.table)]);if(ke.length>0||Ie.length>0){if(ke.length>0)St(`-- Keeping ${ke.length} column(s) on "${Pe.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 "${Pe.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`);Pe={...Pe,columns:[...Pe.columns,...ke],indexes:[...Pe.indexes,...Ie]},Tt=Gt(Pe.columns),Et=Cn(Pe.indexes,Pe.table)}Qe=[]}let ze=Object.keys(Tt).filter((ke)=>bt[ke]&&Pi(bt[ke],Tt[ke],S)),Je=Object.keys(Tt).filter((ke)=>bt[ke]&&qi(bt[ke].references,Tt[ke].references));if(S==="sqlite"){if(ze.length>0||Je.length>0||Qe.some((Ie)=>Oi(We,Ie))||qe.some((Ie)=>Ii(Tt[Ie]))){let Ie={},He=new Map(Ye.map((Dt)=>[Dt.to,Dt.from]));for(let Dt of Pe.columns)if(bt[Dt.name])Ie[Dt.name]=Dt.name;else if(He.has(Dt.name))Ie[Dt.name]=He.get(Dt.name);let Rt=`_qb_tmp_${Pe.table}`,kt=0;while((v[Rt]||Q[Rt])&&kt<100)kt+=1,Rt=`_qb_tmp_${Pe.table}_${kt}`;let yt=E.rebuildTable({target:Pe,tempName:Rt,columnSource:Ie});y.push(yt);let In=ze.some((Dt)=>bt[Dt].type!==Tt[Dt].type);D.push({kind:"rebuild_table",table:Pe.table,destructive:Qe.length>0||In,sql:yt});for(let Dt of Ye)D.push({kind:"rename_column",table:Pe.table,from:Dt.from,to:Dt.to,destructive:!1,confidence:"high",sql:yt});for(let Dt of Qe)D.push({kind:"drop_column",table:Pe.table,column:Dt,destructive:!0,sql:yt});St(`-- Detected SQLite table rebuild required: ${Pe.table}`),x(yt,`alter-${Pe.table}-table`);continue}}let xt=[],Mt=!1;for(let ke of Object.keys(At))if(!Et[ke]){let Ie=At[ke],He=E.dropIndex(Pe.table,Ie.name);xt.push(He),y.push(He),D.push({kind:"drop_index",table:Pe.table,column:Ie.name,destructive:!1,sql:He}),St(`-- Detected dropped index: ${Ie.name} from ${Pe.table}`),Mt=!0}for(let ke of Ye){let Ie=E.renameColumn(Pe.table,ke.from,ke.to);xt.push(Ie),y.push(Ie),D.push({kind:"rename_column",table:Pe.table,from:ke.from,to:ke.to,destructive:!1,confidence:"high",sql:Ie}),St(`-- Detected renamed column: ${Pe.table}.${ke.from} -> ${ke.to}`),Mt=!0}for(let ke of Qe){let Ie=E.dropColumn(Pe.table,ke);xt.push(Ie),y.push(Ie),D.push({kind:"drop_column",table:Pe.table,column:ke,destructive:!0,sql:Ie}),St(`-- Detected dropped column: ${Pe.table}.${ke}`),Mt=!0}for(let ke of ze){let Ie=bt[ke],He=Tt[ke],Rt=E.modifyColumn(Pe.table,He,Ie);xt.push(Rt),y.push(Rt),D.push({kind:"modify_column",table:Pe.table,column:ke,destructive:Ie.type!==He.type&&!Ot(Ie.type,He.type),sql:Rt}),St(`-- Detected column change: ${Pe.table}.${ke} (${Ie.type} -> ${He.type})`),Mt=!0}for(let ke of Je){let Ie=Tt[ke];if(!Ie.references)continue;let He=E.addForeignKey(Pe.table,Ie.name,Ie.references.table,Ie.references.column,Ie.references.onDelete,Ie.references.onUpdate,bt[ke].references?.constraintNames);if(!He)continue;xt.push(He),y.push(He),D.push({kind:"add_foreign_key",table:Pe.table,column:ke,destructive:!1,sql:He}),St(`-- Detected foreign-key change: ${Pe.table}.${ke} -> ${Ie.references.table}(${Ie.references.column})`),Mt=!0}for(let ke of qe){let Ie=Tt[ke],He=E.addColumn(Pe.table,Ie);if(xt.push(He),y.push(He),D.push({kind:"add_column",table:Pe.table,column:Ie.name,destructive:!1,sql:He}),St(`-- Detected new column: ${Pe.table}.${Ie.name}`),Mt=!0,Ie.references){let Rt=E.addForeignKey(Pe.table,Ie.name,Ie.references.table,Ie.references.column,Ie.references.onDelete,Ie.references.onUpdate);if(Rt)xt.push(Rt),y.push(Rt),D.push({kind:"add_foreign_key",table:Pe.table,column:Ie.name,destructive:!1,sql:Rt})}}for(let ke of Object.keys(Et))if(!At[ke]){let Ie=Et[ke],He=E.createIndex(Pe.table,Ie,Pe.columns);xt.push(He),y.push(He),D.push({kind:"create_index",table:Pe.table,column:Ie.name,destructive:!1,sql:He}),St(`-- Detected new index: ${Ie.name} in ${Pe.table}`),Mt=!0}if(Mt){let ke=xt.join(`
380
-
381
- `);x(ke,`alter-${Pe.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:D}}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=[],D=[],E=[];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){D.push({table:S.table,column:G.name,expected:Ne});continue}let Ce=gt(Re.sqlType);if(!pt(Ne,Ce,l))E.push({table:S.table,column:G.name,expected:Ne,actual:Ce,actualSqlType:Re.sqlType})}}return{missingTables:y,missingColumns:D,typeMismatches:E,clean:y.length===0&&D.length===0&&E.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(`
382
- `)}async function Ui(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 Fi(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 Er(s){return wt(s,e.snapshotDir||".qb")}function kn(s,o){return wt(Er(s),`model-snapshot.${o}.json`)}function Vi(s,o){let l=kn(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 Dr(s,o,l){let d=kn(s,o),g=Er(s),x=mt(l);if(Nt(d))try{let D=JSON.parse(Ht(d,"utf8"));if(D?.hash===x&&D?.dialect===o&&D?.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;Dr(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(Pn.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,D=!1;if(!o.full)if(y=Vi(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},D=!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 E=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:D}),{statements:S,operations:v}=E,Q=S.join(`
383
- `),G=S.some((Re)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(Re));if(o.apply){let Re=Li(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 Ui(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)Dr(d,l,x);return{sql:Q,sqlStatements:S,hasChanges:G,plan:x,operations:v}}function ji(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)=>Bi(d)?d:wt(o,d))}function Yi(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",Qi=/\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 Wi(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=Yi(ji(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 Wi(l,async()=>{await Sr(g,l);let x=await Xi(g,l),y=d.filter((D)=>!x.includes(D.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:D,path:E}of y){Ue(`-- Executing: ${D}`);try{if(gr(l)&&!Qi.test(Ht(E,"utf-8")))await g.transaction(async(v)=>{await v.file(E),await rn(v,D,l)});else if(await g.file(E),await rn(g,D,l),!gr(l))Ue(`-- (${l} commits DDL implicitly, so ${D} was not applied atomically)`);else Ue(`-- (${D} contains a statement that cannot run in a transaction, so it was not applied atomically)`);Ue(`-- \u2713 Migration ${D} executed and recorded`)}catch(S){if(xr(E)&&Fi(S)){await rn(g,D,l),Ue(`-- \u2713 Migration ${D} was already applied; recorded it (${S instanceof Error?S.message:String(S)})`);continue}throw console.error(`-- \u2717 Migration ${D} 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(Pn.cwd(),"app/Models");let l=o.dialect||e.dialect||"postgres",d=m(l),g=Ft(),x=async(y)=>{let D=d.dropTable(y);await Ge(async(E)=>{if(l==="sqlite")await E.unsafe("PRAGMA foreign_keys = OFF").execute();if(l==="mysql"||l==="vitess")await E.unsafe("SET FOREIGN_KEY_CHECKS = 0").execute();try{await E.unsafe(D).execute()}finally{if(l==="sqlite")await E.unsafe("PRAGMA foreign_keys = ON").execute();if(l==="mysql"||l==="vitess")await E.unsafe("SET FOREIGN_KEY_CHECKS = 1").execute()}})};try{try{await x("migrations"),Ue("-- Dropped migrations table")}catch(E){console.error(E)}let y=[],D=[];try{let E=await u({modelsDir:s}),S=H(E,{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)}D=Array.from(v)}catch(E){console.error(E),y=[],D=[]}if(y.length===0)Ue("-- No tables found to drop");else{Ue(`-- Dropping ${y.length} tables: ${y.join(", ")}`);for(let E of y.reverse())try{await x(E),Ue(`-- Dropped table: ${E}`)}catch(S){console.error(S),Ue(`-- Table ${E} may not exist, skipping drop`)}}if(D.length>0){Ue(`-- Dropping ${D.length} enum types: ${D.join(", ")}`);for(let E of D)try{let S=d.dropEnumType(E);if(S)await Ge(async(v)=>{await v.unsafe(S).execute(),Ue(`-- Dropped enum type: ${E}`)})}catch(S){console.error(S),Ue(`-- Enum type ${E} may not exist, skipping drop`)}}else Ue("-- No enum types found to drop");if(y.length>0&&!o.preserveMigrationState)try{await Gi(s,g,o)}catch(E){console.error(E),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 Hi(g)}catch(E){console.error(E),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 Gi(s,o,l={}){if(!s)s=wt(Pn.cwd(),"app/Models");if(!o)o=Ft();let d=String(l.dialect||e.dialect||"postgres"),g=kn(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}`);zi($t(o,e.migrationDir))}function zi(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 Hi(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 Xi(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}}
384
- 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};