bun-query-builder 0.3.2 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +6 -6
- package/dist/chunk-afbb8bx3.js +384 -0
- package/dist/chunk-cwf5anrk.js +2 -0
- package/dist/{chunk-4cs1xx1d.js → chunk-jwwbnv83.js} +2 -2
- package/dist/{chunk-3xpe6b57.js → chunk-mbt007va.js} +3 -3
- package/dist/chunk-ne1tyjpr.js +2 -0
- package/dist/{chunk-hjgcemhy.js → chunk-qa7wq5xr.js} +14 -14
- package/dist/chunk-wq450xdk.js +3 -0
- package/dist/chunk-yr0kc2zt.js +3 -0
- package/dist/orm.d.ts +40 -6
- package/dist/src/browser.js +1 -1
- package/dist/src/dynamodb/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/runtime.js +1 -1
- package/dist/type-inference.d.ts +2 -0
- package/package.json +5 -5
- package/dist/chunk-66eeqvc5.js +0 -2
- package/dist/chunk-c7m701dd.js +0 -3
- package/dist/chunk-eghdwdz9.js +0 -3
- package/dist/chunk-p4nmh8jd.js +0 -2
- package/dist/chunk-w4pttgsy.js +0 -384
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{n,e,B,t,P,Pe,Je,r,b,f}from"./chunk-qa7wq5xr.js";import{i,ve,ke}from"./chunk-yr0kc2zt.js";import{M,Me,Ne,N}from"./chunk-wq450xdk.js";import{c}from"./chunk-mbt007va.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 ue{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 de 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 fe 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 me{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 Me(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 ue;case"mysql":return new a;case"singlestore":return new de;case"vitess":return new fe(o.vitessSharded??e.vitess?.sharded??!0);case"sqlite":return new me;default:throw Error(`Unsupported dialect: ${s}`)}}async function z(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 Y(){console.log("-- Clearing query cache..."),ve(),console.log("-- \u2713 Query cache cleared")}async function X(){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 Z(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");ke(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 ee(){return O()}import{existsSync as $r,readFileSync as vr,writeFileSync as Qt}from"fs";async function te(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 J=v[G];if(J===null||J===void 0)return"";let Ae=String(J);if(Ae.includes(",")||Ae.includes('"')||Ae.includes(`
|
|
81
|
+
`))return`"${Ae.replace(/"/g,'""')}"`;return Ae});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 J=S[G];if(J===null||J===void 0)return"NULL";if(typeof J==="number")return String(J);return`'${String(J).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 ne(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 J=v[G].split(",").map((Re)=>Re.trim()),Ae={};for(let Re=0;Re<Q.length;Re++){let Ce=J[Re];if(Ce.startsWith('"')&&Ce.endsWith('"'))Ce=Ce.slice(1,-1).replace(/""/g,'"');if(Ce==="")Ce=null;else if(!Number.isNaN(Number(Ce)))Ce=Number(Ce);Ae[Q[Re]]=Ce}D.push(Ae)}}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 re(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 J=S[G];if(J===null||J===void 0)return"NULL";if(typeof J==="number")return String(J);return`'${String(J).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),J=(S.indexes||0).toString().padStart(10);console.log(`${v}${Q}${G}${J}`)}}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 ie(){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=Pe(),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=Pe();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 se(s){let d=await(i().raw([s]).simple()?.execute?.()??Promise.resolve([]));return console.log(JSON.stringify(d,null,2)),d}async function ae(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(/\(([^)]+)\)/),Ae=(G?G[1]:"").split(",").map((Re)=>Re.trim());y.push({name:Q.name,columns:Ae,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 J=G.Key_name;if(!Q.has(J))Q.set(J,{columns:[],unique:G.Non_unique===0});Q.get(J).columns.push(G.Column_name)}for(let[G,J]of Q)y.push({name:G,columns:J.columns,unique:J.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((J)=>J.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((Ae)=>Ae.name.length),10),v=Math.max(...x.map((Ae)=>Ae.type.length),10),Q=S+2,G=v+2,J=`${"Name".padEnd(Q)+"Type".padEnd(G)+"Nullable".padEnd(10)+"Default".padEnd(20)}Flags`;console.log(J),console.log("-".repeat(J.length));for(let Ae of x){let Re=Ae.name.padEnd(Q),Ce=Ae.type.padEnd(G),Ve=(Ae.nullable?"YES":"NO").padEnd(10),Le=String(Ae.default||"").padEnd(20),We=[Ae.isPrimaryKey?"PK":"",Ae.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${Re}${Ce}${Ve}${Le}${We}`)}if(console.log(),y.length>0){console.log("Indexes:"),console.log();for(let Ae of y){let Re=Ae.unique?" (UNIQUE)":"";console.log(` - ${Ae.name}${Re}: [${Ae.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 oe(s,o={}){return K(s,o)}async function le(s,o={}){let l=await u({modelsDir:s}),d=Ee(l);return console.log(JSON.stringify(d,null,2)),{models:l,schema:d}}function Ze(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 Ke(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 et(s,o){let l=Ke(s),d=o.find((x)=>x.isPrimaryKey)?.name??"id",g=o.map((x)=>{let y=[`type: '${Ze(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:Ke(x),primaryKey:y.find((D)=>D.isPrimaryKey)?.name??"id",columns:y,source:et(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??""),J=String(Q.name??"");if(G==="pk"||J.startsWith("sqlite_autoindex_"))continue;let Re=(await s.unsafe(`PRAGMA index_info(${JSON.stringify(J)})`)).map((Ve)=>String(Ve.name)).filter(Boolean);if(Re.length===0)continue;let Ce=Number(Q.unique)===1;if(Ce&&Re.length===1)S.add(Re[0]);E.push({name:J,columns:Re,type:Ce?"unique":"index"})}let v=l.map((Q)=>{let G=String(Q.name),J=Kr(y,G),Ae=Number(Q.pk)>0,Re=Q.dflt_value,Ce=Re!==null&&Re!==void 0;return{name:G,type:xn(String(Q.type??""),"sqlite",{enumValues:J}),isPrimaryKey:Ae,isUnique:S.has(G),isNullable:Ae?!1:Number(Q.notnull)===0,hasDefault:Ce,defaultValue:Ce?En(Re):void 0,enumValues:J,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 J=String(G.constraint_name);E.set(J,(E.get(J)??0)+1)}for(let G of y){let J=String(G.column_name),Ae=D.get(J),Re=String(G.constraint_name),Ce=E.get(Re)===1?[...new Set([...Ae?.constraintNames??[],Re])]:Ae?.constraintNames;D.set(J,Ae?{...Ae,constraintNames:Ce}:{table:String(G.ref_table),column:String(G.ref_column??"id"),onDelete:Vt(G.delete_rule),onUpdate:Vt(G.update_rule),constraintNames:Ce})}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 J=String(G.column_name),Ae=Number(G.is_pk)>0,Re=G.column_default==null?null:String(G.column_default),Ce=Re!=null&&/nextval\(/i.test(Re),Ve=Re!=null&&!Ce;return{name:J,...Br(String(G.data_type??""),G.udt_name==null?"":String(G.udt_name),d),isPrimaryKey:Ae,isUnique:v.has(J),isNullable:Ae?!1:String(G.is_nullable).toUpperCase()==="YES",hasDefault:Ve,defaultValue:Ve?En(Re):void 0,references:D.get(J)}});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),J=String(v.constraint_name??v.CONSTRAINT_NAME),Ae=y.get(J)===1?[...new Set([...G?.constraintNames??[],J])]:G?.constraintNames;x.set(Q,G?{...G,constraintNames:Ae}:{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:Ae})}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??""),J=Vr(G),Re=String(v.column_key??v.COLUMN_KEY??"").toUpperCase()==="PRI",Ce=v.column_default??v.COLUMN_DEFAULT,Ve=Ce!=null;return{name:Q,type:Or(v.data_type??v.DATA_TYPE,G,J),isPrimaryKey:Re,isUnique:E.has(Q),isNullable:Re?!1:String(v.is_nullable??v.IS_NULLABLE).toUpperCase()==="YES",hasDefault:Ve,defaultValue:Ve?En(Ce):void 0,enumValues:J,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 ce(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 he(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 ge(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:J}=Zr(Q);for(let Ae of G)await d.unsafe(Ae),console.log(`-- \u21A9 ${Ae}`),D=!0;if(J.length>0)console.log(`-- \u26A0\uFE0F ${J.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 pe(){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",J=Q.required?"(required)":"",Ae=Q.unique?"(unique)":"",Re=Q.default!==void 0?`= ${JSON.stringify(Q.default)}`:"";console.log(` \u2022 ${v}: ${G} ${J} ${Ae} ${Re}`.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",J=Q.model||Q.table||"unknown";console.log(` \u2022 ${v}: ${G} \u2192 ${J}`)}}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 ye(){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 be(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 Te(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-cwf5anrk.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 we(s,o,l={}){let d=u({modelsDir:s}),g=Ee(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 Se(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((Ae)=>({name:Ae.name,type:Ae.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((Ae)=>({name:Ae.column_name,type:Ae.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((Ae)=>({name:Ae.column_name,type:Ae.data_type.toLowerCase()}));let Q=v.map((J)=>J.name),G=S.columns.map((J)=>J.name);for(let J of S.columns)if(!Q.includes(J.name))l.push({type:"missing_column",severity:"error",table:S.table,column:J.name,expected:J.type,message:`Column '${S.table}.${J.name}' defined in model but not found in database`});for(let J of v)if(!G.includes(J.name))l.push({type:"extra_column",severity:"warning",table:S.table,column:J.name,actual:J.type,message:`Column '${S.table}.${J.name}' exists in database but not defined in model`});for(let J of S.columns){let Ae=v.find((Re)=>Re.name===J.name);if(Ae){let Re=(Le)=>Le.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim(),Ce=Re(J.type),Ve=Re(Ae.type);if(Ce!==Ve)l.push({type:"type_mismatch",severity:"warning",table:S.table,column:J.name,expected:J.type,actual:Ae.type,message:`Column '${S.table}.${J.name}' type mismatch: expected '${J.type}', found '${Ae.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 De(s){return V(s)}async function $e(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 nt{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 rt{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 it(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 it{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 st(s){return new nt(s)}function at(s,o,l){return new rt(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 ot(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 lt{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=st(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 at(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=ot(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=ot(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 lt(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 Ee(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 ct(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[Ce,Ve]of Object.entries(S.attributes??{}))if(/^(?:datetime|timestamp|timestamptz|date)$/i.test(String(Ve?.type??"")))Q.push(Ce);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 J=(Ce)=>{if(!Ce)return{};let Ve={};if(Array.isArray(Ce)){for(let Le of Ce){let We=Ne(Le);if(We)Ve[We.model]=We.model}return Ve}if(typeof Ce==="object"){for(let[Le,We]of Object.entries(Ce)){let _e=Ne(We);if(_e)Ve[Le]=_e.model}return Ve}return{}},Ae=(Ce)=>{if(!Ce)return{};if(Array.isArray(Ce)){let Ve={};for(let Le of Ce)if(typeof Le==="string")Ve[Le]=Le;else if(Le&&typeof Le==="object"&&typeof Le.model==="string")Ve[Le.model]=Le;return Ve}return Ce},Re=(Ce)=>{if(!Ce)return{};return Ce};if(g[v]={hasOne:J(S.hasOne),hasMany:J(S.hasMany),belongsTo:J(S.belongsTo),belongsToMany:Ae(S.belongsToMany),hasOneThrough:Re(S.hasOneThrough),hasManyThrough:Re(S.hasManyThrough),morphOne:J(S.morphOne),morphMany:J(S.morphMany),morphTo:S.morphTo,morphToMany:J(S.morphToMany),morphedByMany:J(S.morphedByMany)},S.scopes&&typeof S.scopes==="object"){x[v]={};for(let Ce of Object.keys(S.scopes)){let Ve=S.scopes[Ce];if(typeof Ve==="function")x[v][Ce]=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 ut(){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 dt="-- qb:generated";function ft(s){return s.trimStart().startsWith(dt)}function mt(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(mt(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=mt(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,`${dt}
|
|
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=ct(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??{},J=[],Ae=[];if(!G[v])J.push({name:Bt(v),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});let Re=new Map,Ce=N(E.belongsTo).length>0,Ve=new Set(Object.keys(G).map((Be)=>Bt(Be))),Le=new Set;for(let Be of Ve){if(!Be.endsWith("_type"))continue;let Ge=`${Be.slice(0,-5)}_id`;if(Ve.has(Ge))Le.add(Ge)}for(let Be of N(E.belongsTo)){let Ge=Be.foreignKey??`${Bt(Be.model)}_id`,He=l.modelToTable[Be.model];if(He)Re.set(Ge,{table:He,onDelete:Be.onDelete})}for(let Be of Object.keys(G)){let Ge=G[Be],He=Bt(Be),xt=Boolean(Ge.validation?.rule?.isRequired),Mt=Be===v?!1:Ge.nullable??!(Ge.required??xt),Ie,Oe,ze=Be===v;if(Ie=vi(Ge.type)??$i(Ge.validation?.rule),Ie==="string"){let Xe=Nn(Ge.validation?.rule);if(Xe&&Xe>_n)Ie="text"}if(!Ie||Ie==="enum"){let Xe=_i(Ge.validation?.rule);if(Xe&&Xe.length>0)Ie="enum",Oe=Xe}if(!Ie)Ie=ar(He);if(!Ie){let Xe=or(Ge.default);if(typeof Xe==="string")Ie=Xe.length>255?"text":"string";else if(typeof Xe==="number")Ie=Number.isInteger(Xe)?"integer":"float";else if(typeof Xe==="boolean")Ie="boolean";else if(typeof Xe==="bigint")Ie="bigint";else if(Xe instanceof Date)Ie="datetime"}if(!Ie)Ie=ze?"bigint":"string";let Rt=Ie==="string"?Nn(Ge.validation?.rule):void 0,kt={name:He,type:Ie,isPrimaryKey:ze,isUnique:Boolean(Ge.unique),isNullable:Mt,hasDefault:typeof Ge.default<"u",defaultValue:or(Ge.default),enumValues:Oe,maxLength:typeof Rt==="number"&&Rt>0&&Rt<=_n?Rt:void 0};if(He.endsWith("_id")&&Ge.foreignKey!==!1&&!Le.has(He))if(typeof Ge.foreignKey==="object"&&Ge.foreignKey!==null){let Xe=Ge.foreignKey;if(kt.references={table:Xe.table,column:Xe.column??"id",onDelete:Xe.onDelete,onUpdate:Xe.onUpdate},Xe.nullable!==void 0)kt.isNullable=Xe.nullable}else{let Xe=Re.get(He),Dt=He.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(On,Ji,Mr)=>Mr.toUpperCase()),sn=Xe?.table??(Ce?void 0:l.modelToTable[Dt]);if(sn){let On=l.primaryKeys[sn]??"id";kt.references={table:sn,column:On,onDelete:Xe?.onDelete}}}J.push(kt)}let We=N(E.belongsTo);for(let Be of We){let Ge=Be.foreignKey??`${Bt(Be.model)}_id`;if(J.some((Mt)=>Mt.name===Ge))continue;let He=l.modelToTable[Be.model],xt=He?l.primaryKeys[He]??"id":void 0;J.push({name:Ge,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:He&&xt&&!Le.has(Ge)?{table:He,column:xt,onDelete:Be.onDelete}:void 0})}let _e=E.traits;if(_e?.useTimestamps??_e?.timestampable??!1){if(!J.some((Be)=>Be.name==="created_at"))J.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:p});if(!J.some((Be)=>Be.name==="updated_at"))J.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(_e?.useSoftDeletes??_e?.softDeletable??!1){if(!J.some((Be)=>Be.name==="deleted_at"))J.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(_e?.useUuid??!1){if(!J.some((Be)=>Be.name==="uuid"))J.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let Be of E.indexes??[])Ae.push({name:Be.name,columns:Be.columns.map((Ge)=>Bt(Ge)),type:Be.unique?"unique":"index",where:Be.where});for(let Be of J)if(Be.isUnique&&!Be.isPrimaryKey)Ae.push({name:`${S}_${Be.name}_unique`,columns:[Be.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:J,indexes:Ae,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:{},J=G.table||`${v}_likes`,Ae=G.foreignKey||`${Q}_id`;x({table:J,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:Ae,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:`${J}_user_target_unique`,columns:["user_id",Ae],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,J]of Object.entries(S)){let Ae=J;if(!Ae||typeof Ae!=="object")continue;if(Ae.through)continue;let Re=Ae.pivot;if(!Re||!Re.columns&&!Re.timestamps&&!Re.uniques)continue;let Ce=Ae.model,Le=s[Ce]?.table||`${String(Ce).toLowerCase()}s`,We=An(Le),_e=Ae.table||[Q,We].sort().join("_"),bt=Ae.foreignKey||`${Q}_id`,At=Ae.relatedKey||`${We}_id`,Tt=new Set([bt,At,...Object.keys(Re.columns??{})]),Et=new Set;for(let He of Tt){if(!He.endsWith("_type"))continue;let xt=`${He.slice(0,-5)}_id`;if(Tt.has(xt))Et.add(xt)}let Ye=(He,xt)=>Et.has(He)?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,Le)}];if(Re.columns)for(let[He,xt]of Object.entries(Re.columns)){let Mt=xt,Ie=ar(He)??"string";Qe.push({name:He,type:Ie,isPrimaryKey:!1,isUnique:!1,isNullable:Mt?.nullable??!1,hasDefault:Mt?.default!==void 0,defaultValue:Mt?.default})}if(Re.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 Be=[],Ge=Re.uniques&&Re.uniques.length>0?Re.uniques:[[bt,At]];for(let He=0;He<Ge.length;He++){let xt=Ge[He];Be.push({name:`${_e}_${xt.join("_")}_unique${He>0?`_${He}`:""}`,columns:[...xt],type:"unique"})}x({table:_e,columns:Qe,indexes:Be})}}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 xe(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((Re)=>y.has(Yt(S.table,Re.name))?{...Re,references:void 0}:Re)},Q=[],G=new Set;for(let Re of v.columns)if(Re.type==="enum"&&Re.enumValues&&Re.enumValues.length>0){let Ce=`${v.table}_${Re.name}_type`;if(Re.enumTypeName=Ce,!G.has(Ce)){let Ve=g.createEnumType(Ce,Re.enumValues);if(Ve)Q.push(Ve);G.add(Ce)}}let J=g.createTable(v);Q.push(J);for(let Re of v.indexes)Q.push(g.createIndex(v.table,Re,v.columns));if(E===x.length-1)for(let Re of x)for(let Ce of Re.columns){if(!Ce.references||!y.has(Yt(Re.table,Ce.name)))continue;let Ve=g.addForeignKey(Re.table,Ce.name,Ce.references.table,Ce.references.column,Ce.references.onDelete,Ce.references.onUpdate);if(Ve)Q.push(Ve)}d.push(...Q);let Ae=Q.join(`
|
|
374
|
+
|
|
375
|
+
`);l(Ae,`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 xe(s).join(`
|
|
376
|
+
`)}function bn(s,o){return _t(s,o).join(`
|
|
377
|
+
`)}function ht(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 Fe(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 je(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(Fe(s,l)!==Fe(o,l))return!0;if(s.isNullable!==o.isNullable)return!0;if(s.hasDefault!==o.hasDefault)return!0;if(je(s,l)!==je(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([Fe(s,o),s.isPrimaryKey,s.isUnique,s.isNullable,s.hasDefault,je(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 qe(s,o,l={}){if(!s||s.dialect!==o.dialect){let Le=xe(o,{dryRun:l.dryRun}),We=o.tables.map((_e)=>({kind:"create_table",table:_e.table,destructive:!1,sql:""}));return{statements:Le,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 Le of Object.keys(v))if(!Q[Le]){let We=E.dropTable(Le);y.push(We),D.push({kind:"drop_table",table:Le,destructive:!0,sql:We}),x(We,`drop-${Le}-table`),St(`-- Detected dropped table: ${Le}`)}let G=Object.keys(Q).filter((Le)=>!v[Le]).map((Le)=>Q[Le]),{tables:J,deferredForeignKeys:Ae}=mr(G,S);for(let[Le,We]of J.entries()){let _e={...We,columns:We.columns.map((Ye)=>Ae.has(Yt(We.table,Ye.name))?{...Ye,references:void 0}:Ye)},bt=[],At=new Set;for(let Ye of _e.columns)if(Ye.type==="enum"&&Ye.enumValues&&Ye.enumValues.length>0){let Qe=`${_e.table}_${Ye.name}_type`;if(Ye.enumTypeName=Qe,!At.has(Qe)){let Be=E.createEnumType(Qe,Ye.enumValues);if(Be)bt.push(Be);At.add(Qe)}}let Tt=E.createTable(_e);bt.push(Tt);for(let Ye of _e.indexes){let Qe=E.createIndex(_e.table,Ye,_e.columns);bt.push(Qe),D.push({kind:"create_index",table:_e.table,column:Ye.name,destructive:!1,sql:Qe})}for(let Ye of We.columns)if(Ye.references&&!Ae.has(Yt(We.table,Ye.name)))D.push({kind:"add_foreign_key",table:We.table,column:Ye.name,destructive:!1,sql:Tt});if(Le===J.length-1)for(let Ye of J)for(let Qe of Ye.columns){if(!Qe.references||!Ae.has(Yt(Ye.table,Qe.name)))continue;let Be=E.addForeignKey(Ye.table,Qe.name,Qe.references.table,Qe.references.column,Qe.references.onDelete,Qe.references.onUpdate);if(!Be)continue;bt.push(Be),D.push({kind:"add_foreign_key",table:Ye.table,column:Qe.name,destructive:!1,sql:Be})}y.push(...bt),D.push({kind:"create_table",table:_e.table,destructive:!1,sql:Tt});let Et=bt.join(`
|
|
378
|
+
|
|
379
|
+
`);x(Et,`create-${_e.table}-table`)}let Re=new Set;for(let Le of Object.keys(Q)){let We=v[Le],_e=Q[Le];if(!We)continue;let bt=Gt(We.columns),At=Gt(_e.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=`${_e.table}_${Et.name}_type`;if(Et.enumTypeName=Ye,bt[Tt])continue;if(!Re.has(Ye)){let Qe=E.createEnumType(Ye,Et.enumValues);if(Qe)y.push(Qe),D.push({kind:"create_enum",table:_e.table,column:Et.name,destructive:!1,sql:Qe}),x(Qe,`create-${Ye}-enum`);Re.add(Ye)}}}for(let Le of Object.keys(Q)){let We=v[Le],_e=Q[Le];if(!We)continue;let bt=Gt(We.columns),At=Cn(We.indexes,We.table),Tt=Gt(_e.columns),Et=Cn(_e.indexes,_e.table),Ye=[],Qe=Object.keys(bt).filter((Ie)=>!Tt[Ie]),Be=Object.keys(Tt).filter((Ie)=>!bt[Ie]);if(d&&!g){let Ie=ki(bt,Tt,S);Ye=Ie.renames,Qe=Ie.removed,Be=Ie.added}if(g){let Ie=Qe.map((ze)=>bt[ze]),Oe=We.indexes.filter((ze)=>!Et[fr(ze,We.table)]);if(Ie.length>0||Oe.length>0){if(Ie.length>0)St(`-- Keeping ${Ie.length} column(s) on "${_e.table}" no model declares: ${Qe.join(", ")} \u2014 reconciled from the database, where an undeclared column is out of scope rather than removed`);if(Oe.length>0)St(`-- Keeping ${Oe.length} index(es) on "${_e.table}" no model declares: ${Oe.map((ze)=>ze.name).join(", ")} \u2014 reconciled from the database, where an undeclared index is out of scope rather than removed`);_e={..._e,columns:[..._e.columns,...Ie],indexes:[..._e.indexes,...Oe]},Tt=Gt(_e.columns),Et=Cn(_e.indexes,_e.table)}Qe=[]}let Ge=Object.keys(Tt).filter((Ie)=>bt[Ie]&&Pi(bt[Ie],Tt[Ie],S)),He=Object.keys(Tt).filter((Ie)=>bt[Ie]&&qi(bt[Ie].references,Tt[Ie].references));if(S==="sqlite"){if(Ge.length>0||He.length>0||Qe.some((Oe)=>Oi(We,Oe))||Be.some((Oe)=>Ii(Tt[Oe]))){let Oe={},ze=new Map(Ye.map((Dt)=>[Dt.to,Dt.from]));for(let Dt of _e.columns)if(bt[Dt.name])Oe[Dt.name]=Dt.name;else if(ze.has(Dt.name))Oe[Dt.name]=ze.get(Dt.name);let Rt=`_qb_tmp_${_e.table}`,kt=0;while((v[Rt]||Q[Rt])&&kt<100)kt+=1,Rt=`_qb_tmp_${_e.table}_${kt}`;let Xe=E.rebuildTable({target:_e,tempName:Rt,columnSource:Oe});y.push(Xe);let In=Ge.some((Dt)=>bt[Dt].type!==Tt[Dt].type);D.push({kind:"rebuild_table",table:_e.table,destructive:Qe.length>0||In,sql:Xe});for(let Dt of Ye)D.push({kind:"rename_column",table:_e.table,from:Dt.from,to:Dt.to,destructive:!1,confidence:"high",sql:Xe});for(let Dt of Qe)D.push({kind:"drop_column",table:_e.table,column:Dt,destructive:!0,sql:Xe});St(`-- Detected SQLite table rebuild required: ${_e.table}`),x(Xe,`alter-${_e.table}-table`);continue}}let xt=[],Mt=!1;for(let Ie of Object.keys(At))if(!Et[Ie]){let Oe=At[Ie],ze=E.dropIndex(_e.table,Oe.name);xt.push(ze),y.push(ze),D.push({kind:"drop_index",table:_e.table,column:Oe.name,destructive:!1,sql:ze}),St(`-- Detected dropped index: ${Oe.name} from ${_e.table}`),Mt=!0}for(let Ie of Ye){let Oe=E.renameColumn(_e.table,Ie.from,Ie.to);xt.push(Oe),y.push(Oe),D.push({kind:"rename_column",table:_e.table,from:Ie.from,to:Ie.to,destructive:!1,confidence:"high",sql:Oe}),St(`-- Detected renamed column: ${_e.table}.${Ie.from} -> ${Ie.to}`),Mt=!0}for(let Ie of Qe){let Oe=E.dropColumn(_e.table,Ie);xt.push(Oe),y.push(Oe),D.push({kind:"drop_column",table:_e.table,column:Ie,destructive:!0,sql:Oe}),St(`-- Detected dropped column: ${_e.table}.${Ie}`),Mt=!0}for(let Ie of Ge){let Oe=bt[Ie],ze=Tt[Ie],Rt=E.modifyColumn(_e.table,ze,Oe);xt.push(Rt),y.push(Rt),D.push({kind:"modify_column",table:_e.table,column:Ie,destructive:Oe.type!==ze.type&&!Ot(Oe.type,ze.type),sql:Rt}),St(`-- Detected column change: ${_e.table}.${Ie} (${Oe.type} -> ${ze.type})`),Mt=!0}for(let Ie of He){let Oe=Tt[Ie];if(!Oe.references)continue;let ze=E.addForeignKey(_e.table,Oe.name,Oe.references.table,Oe.references.column,Oe.references.onDelete,Oe.references.onUpdate,bt[Ie].references?.constraintNames);if(!ze)continue;xt.push(ze),y.push(ze),D.push({kind:"add_foreign_key",table:_e.table,column:Ie,destructive:!1,sql:ze}),St(`-- Detected foreign-key change: ${_e.table}.${Ie} -> ${Oe.references.table}(${Oe.references.column})`),Mt=!0}for(let Ie of Be){let Oe=Tt[Ie],ze=E.addColumn(_e.table,Oe);if(xt.push(ze),y.push(ze),D.push({kind:"add_column",table:_e.table,column:Oe.name,destructive:!1,sql:ze}),St(`-- Detected new column: ${_e.table}.${Oe.name}`),Mt=!0,Oe.references){let Rt=E.addForeignKey(_e.table,Oe.name,Oe.references.table,Oe.references.column,Oe.references.onDelete,Oe.references.onUpdate);if(Rt)xt.push(Rt),y.push(Rt),D.push({kind:"add_foreign_key",table:_e.table,column:Oe.name,destructive:!1,sql:Rt})}}for(let Ie of Object.keys(Et))if(!At[Ie]){let Oe=Et[Ie],ze=E.createIndex(_e.table,Oe,_e.columns);xt.push(ze),y.push(ze),D.push({kind:"create_index",table:_e.table,column:Oe.name,destructive:!1,sql:ze}),St(`-- Detected new index: ${Oe.name} in ${_e.table}`),Mt=!0}if(Mt){let Ie=xt.join(`
|
|
380
|
+
|
|
381
|
+
`);x(Ie,`alter-${_e.table}-table`)}}if(vt+Ut===0)St("-- Nothing to migrate");else{let Le=[];if(vt>0)Le.push(`${vt} created`);if(Ut>0)Le.push(`${Ut} updated`);St(`-- Migration files: ${Le.join(", ")}`)}return{statements:y.length===0?["-- No changes detected"]:y,operations:D}}function _t(s,o,l={}){return qe(s,o,l).statements}function Tn(s){return s}class It{get order(){return 100}get description(){return}}function wn(s){return s}function gt(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 pt(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 yt(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 J=Q.get(G.name.toLowerCase()),Ae=gt(G.type);if(!J){D.push({table:S.table,column:G.name,expected:Ae});continue}let Re=pt(J.sqlType);if(!yt(Ae,Re,l))E.push({table:S.table,column:G.name,expected:Ae,actual:Re,actualSqlType:J.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 ft(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=ht(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 tt(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 J=wt(s,`.qb-migrations.${l}.json`),Ae=String(o.state||J);if(Nt(Ae))try{let Re=Ht(Ae,"utf8"),Ce=JSON.parse(Re);if(y=Ce?.plan&&Ce.plan.tables?Ce.plan:Ce?.tables?Ce:void 0,y)Ue("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}if(!y||o.fromDb)try{let Re=await Bn(l),Ce=new Set(x.tables.map((Le)=>Le.table)),Ve=Re.tables.filter((Le)=>Ce.has(Le.table));if(Ve.length>0)y={dialect:Re.dialect,tables:Ve},D=!0,Ue(`-- No snapshot; reconciling against live database (${Ve.length} matching table${Ve.length===1?"":"s"})`)}catch(Re){Ue(`-- Could not introspect live database, treating as no previous state: ${Re instanceof Error?Re.message:String(Re)}`)}if(!y)Ue("-- No previous snapshot found, generating full migration")}else Ue("-- Full migration requested, ignoring any previous state");let E=o.full?{statements:xe(x,{dryRun:o.dryRun}),operations:x.tables.map((J)=>({kind:"create_table",table:J.table,destructive:!1,sql:""}))}:qe(y,x,{applyRenames:o.applyRenames,dryRun:o.dryRun,preserveUnknownColumns:D}),{statements:S,operations:v}=E,Q=S.join(`
|
|
383
|
+
`),G=S.some((J)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(J));if(o.apply){let J=Li(wt(Ki(),"qb-migrate-")),Ae=wt(J,"migration.sql");try{if(G){Tr(Ae,Q);let Re=i();await Re.file(Ae),Ue("-- Migration applied"),await Ui(Re,l,ut())}else Ue("-- No changes; nothing to apply")}catch(Re){throw console.error("-- Migration failed:",Re),Re}finally{hr(J,{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 Je(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 J=`${Q.table}_${G.name}_type`;v.add(J)}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 Je(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{z,Y,X,Z,O,ee,te,ne,re,_,ie,I,L,se,ae,K,oe,le,Ze,Ke,et,k,ce,a,ue,de,fe,me,m,tt,T,C,R,he,ge,F,pe,j,ye,q,W,A,U,be,Te,we,Se,V,De,$e,w,h,an,on,ln,nt,rt,it,st,at,cn,ot,Pt,un,dn,fn,mn,lt,hn,gn,pn,Ee,u,ct,ut,dt,ft,mt,Ot,H,xe,yn,bn,ht,Fe,p,je,qe,_t,Tn,It,wn,gt,pt,yt,Lt,Kt};
|