@zuzjs/orm 0.3.10 → 0.3.11
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.cjs +1 -1
- package/dist/bin.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/bin.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
'use strict';var chunkNTG6OYMF_cjs=require('./chunk-NTG6OYMF.cjs'),commander=require('commander'),l=require('fs'),t=require('path'),i=require('picocolors');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var l__default=/*#__PURE__*/_interopDefault(l);var t__default=/*#__PURE__*/_interopDefault(t);var i__default=/*#__PURE__*/_interopDefault(i);/* ZuzJS ORM (ZORM) */
|
|
3
|
-
var d=chunkNTG6OYMF_cjs.a((D,f)=>{f.exports={name:"@zuzjs/orm",version:"0.3.
|
|
3
|
+
var d=chunkNTG6OYMF_cjs.a((D,f)=>{f.exports={name:"@zuzjs/orm",version:"0.3.10",description:"ZuzJS ORM Library",keywords:["orm","zuz","zuz.js","zuz orm","zuzjs"],homepage:"https://orm.zuz.com.pk",bugs:{url:"https://github.com/zuzpk/zorm/issues"},repository:{type:"git",url:"git+https://github.com/zuzpk/zorm.git"},author:"Zuz.js Team <support@zuz.com.pk>",license:"MIT",type:"module",main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",bin:{zorm:"./dist/bin.cjs"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"}},files:["dist"],scripts:{"dev:js":"tsup --watch",dev:"npm-run-all -p dev:*",build:"rm -rf dist && tsup",publish:"npm run build && node publish-pre.js && npm publish && node publish-post.js"},engines:{node:">=18.17.0"},sideEffects:["reflect-metadata"],dependencies:{"@types/md5":"^2.3.6",commander:"14.0.3",md5:"^2.3.0",mysql2:"3.17.1",nanoid:"5.1.6",picocolors:"^1.1.1","reflect-metadata":"^0.2.2",typeorm:"^0.3.28"},devDependencies:{husky:"^9.1.7",tsup:"^8.5.1",typescript:"^5.8.3"},peerDependencies:{"reflect-metadata":"^0.2.2",typeorm:"^0.3.28"}};});var z=(e,s)=>{s=s||t__default.default.join("src","zorm");let o=chunkNTG6OYMF_cjs.b(t__default.default.join(process.cwd(),s),true);o.access||(console.log(i__default.default.red(`\u25CB ${o.message}`)),process.exit(1)),e.startsWith("mysql")?new chunkNTG6OYMF_cjs.g(decodeURIComponent(e),s).generate():(console.log("\u25CB Only MySQL is supported for now"),process.exit(1));},c=()=>{let e=t__default.default.join(process.cwd(),".env");if(!l.existsSync(e)){console.log(i__default.default.red('\u25CB ".env" not exists. Create .env and add DATABASE_URL="connection_string"'));return}let s=l__default.default.readFileSync(e,"utf8").split(`
|
|
4
4
|
`).filter(o=>o.startsWith("DATABASE_URL"));if(s.length==0){console.log(i__default.default.red('\u25CB DATABASE_URL not found in ".env". Add DATABASE_URL="connection_string"'));return}z(s[0].trim().replace(/DATABASE_URL=|"|"/g,""));};commander.program.name("zorm").description("ZuzORM is a lightweight ORM wrapper around TypeORM with support for MySQL.");commander.program.option("-v, --version").description("Displays current version of ZuzORM").action(()=>{let e=d();console.log(i__default.default.cyan(`ZuzORM v${e.version}`)),process.exit(1);});commander.program.command("pull").description("Pull using DATABASE_URL from .env in project directory").action(c);commander.program.parse();
|
package/dist/bin.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a,b,g}from'./chunk-674L2AWT.js';import {program}from'commander';import a$1,{existsSync}from'fs';import t from'path';import i from'picocolors';var d=a((S,g)=>{g.exports={name:"@zuzjs/orm",version:"0.3.
|
|
2
|
+
import {a,b,g}from'./chunk-674L2AWT.js';import {program}from'commander';import a$1,{existsSync}from'fs';import t from'path';import i from'picocolors';var d=a((S,g)=>{g.exports={name:"@zuzjs/orm",version:"0.3.10",description:"ZuzJS ORM Library",keywords:["orm","zuz","zuz.js","zuz orm","zuzjs"],homepage:"https://orm.zuz.com.pk",bugs:{url:"https://github.com/zuzpk/zorm/issues"},repository:{type:"git",url:"git+https://github.com/zuzpk/zorm.git"},author:"Zuz.js Team <support@zuz.com.pk>",license:"MIT",type:"module",main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",bin:{zorm:"./dist/bin.cjs"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"}},files:["dist"],scripts:{"dev:js":"tsup --watch",dev:"npm-run-all -p dev:*",build:"rm -rf dist && tsup",publish:"npm run build && node publish-pre.js && npm publish && node publish-post.js"},engines:{node:">=18.17.0"},sideEffects:["reflect-metadata"],dependencies:{"@types/md5":"^2.3.6",commander:"14.0.3",md5:"^2.3.0",mysql2:"3.17.1",nanoid:"5.1.6",picocolors:"^1.1.1","reflect-metadata":"^0.2.2",typeorm:"^0.3.28"},devDependencies:{husky:"^9.1.7",tsup:"^8.5.1",typescript:"^5.8.3"},peerDependencies:{"reflect-metadata":"^0.2.2",typeorm:"^0.3.28"}};});var f=(e,s)=>{s=s||t.join("src","zorm");let o=b(t.join(process.cwd(),s),true);o.access||(console.log(i.red(`\u25CB ${o.message}`)),process.exit(1)),e.startsWith("mysql")?new g(decodeURIComponent(e),s).generate():(console.log("\u25CB Only MySQL is supported for now"),process.exit(1));},c=()=>{let e=t.join(process.cwd(),".env");if(!existsSync(e)){console.log(i.red('\u25CB ".env" not exists. Create .env and add DATABASE_URL="connection_string"'));return}let s=a$1.readFileSync(e,"utf8").split(`
|
|
3
3
|
`).filter(o=>o.startsWith("DATABASE_URL"));if(s.length==0){console.log(i.red('\u25CB DATABASE_URL not found in ".env". Add DATABASE_URL="connection_string"'));return}f(s[0].trim().replace(/DATABASE_URL=|"|"/g,""));};program.name("zorm").description("ZuzORM is a lightweight ORM wrapper around TypeORM with support for MySQL.");program.option("-v, --version").description("Displays current version of ZuzORM").action(()=>{let e=d();console.log(i.cyan(`ZuzORM v${e.version}`)),process.exit(1);});program.command("pull").description("Pull using DATABASE_URL from .env in project directory").action(c);program.parse();
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var chunkNTG6OYMF_cjs=require('./chunk-NTG6OYMF.cjs'),x=require('path'),f=require('picocolors');require('reflect-metadata');var typeorm=require('typeorm');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var x__default=/*#__PURE__*/_interopDefault(x);var f__default=/*#__PURE__*/_interopDefault(f);/* ZuzJS ORM (ZORM) */
|
|
2
|
-
var m=class c{_parts=[];_params={};_paramIdx=0;_alias;static globalParamIdx=0;constructor(e,t){this._alias=e?`${e}.`:"",this._paramIdx=t?t.idx:0,this._params=t?t.params:{};}field(e){return this._parts.push(`${this._alias}${String(e)}`),this}equals(e){let t=`p${this._paramIdx++}`;return this.append(` = :${t}`),this._params[t]=e,this}append(e){if(this._parts.length===0)throw new Error("Cannot append to empty expression");return this._parts[this._parts.length-1]+=e,this}wrap(e){if(this._parts.length===0)throw new Error("Cannot wrap empty expression");return this._parts[this._parts.length-1]=e(this._parts[this._parts.length-1]),this}exists(e){let t=new c(void 0,{params:this._params,idx:this._paramIdx});return e(t),this._parts.push(`EXISTS (${t.buildExpression()})`),this._paramIdx=t._paramIdx,this}select(e){return this._parts.push(`SELECT ${e}`),this}from(e,t){return this._parts.push(`FROM ${e} ${t}`),this._alias=t,this}where(e){let t=[];for(let[r,i]of Object.entries(e)){let s=`p${this._paramIdx++}`;t.push(`${r} = :${s}`),this._params[s]=i;}return this._parts.push(`WHERE ${t.join(" AND ")}`),this}or(){return this._parts.push("OR"),this}group(){return this.wrap(e=>`(${e})`)}fromUnixTime(){return this.wrap(e=>`FROM_UNIXTIME(${e})`),this}date(){return this.wrap(e=>`DATE(${e})`),this}substring(e,t,r){return this._parts=[`SUBSTRING_INDEX(${this._alias}${String(e)}, '${t}', ${r})`],this}toExpression(){return {expression:this._parts.join(" "),param:this._params}}buildExpression(){return this.toExpression().expression}buildParams(){return this.toExpression().param}},b=m;var T=class c extends Promise{repository;queryBuilder;entityAlias;action;queryValues=null;usePromise;whereCount=0;isActiveRecord=false;activeRecord;joinedAliases={};constructor(e,t,r){super(()=>{}),this.repository=e,this.entityAlias=e.metadata.tableName,this.queryBuilder=e.createQueryBuilder(this.entityAlias),this.action=t,this.usePromise=r||false,this.activeRecord=null;}_create(){if(this.queryValues)this.queryBuilder=this.queryBuilder.insert().into(this.entityAlias).values(this.queryValues);else throw chunkNTG6OYMF_cjs.c("\u25CB Values are missing. You forgot to call .with({ key: value })");return this}upsert(){if(this.queryValues)this.queryBuilder=this.repository.createQueryBuilder(this.entityAlias).insert().into(this.entityAlias).values(this.queryValues).orUpdate(Object.keys(this.queryValues));else throw chunkNTG6OYMF_cjs.c("\u25CB Values are missing. You forgot to call .with({ key: value })");return this}_update(){if(this.queryValues)if(this.whereCount>0)this.queryBuilder=this.queryBuilder.update().set(this.queryValues);else throw chunkNTG6OYMF_cjs.c("\u25CB Update must have at least one WHERE condition. You forgot to call .where({ condition: value })");else throw chunkNTG6OYMF_cjs.c("\u25CB Values are missing. You forgot to call .with({ key: value })");return this}_delete(){if(this.whereCount>0)this.queryBuilder=this.queryBuilder.delete();else throw chunkNTG6OYMF_cjs.c("\u25CB Delete must have at least one WHERE condition. You forgot to call .where({ condition: value })");return this}_getRawQuery(){return this.queryBuilder.getQueryAndParameters()}active(){return this.isActiveRecord=true,this}async _saveActiveRecord(e){return this.repository.save(e)}clone(){let e=new c(this.repository,this.action,this.usePromise);return e.queryBuilder=this.queryBuilder.clone(),e.entityAlias=this.entityAlias,e.queryValues=this.queryValues?structuredClone(this.queryValues):null,e.whereCount=this.whereCount,e.isActiveRecord=this.isActiveRecord,e.activeRecord=this.activeRecord,e}with(e){return this.queryValues=e,this}withData(e){return this.queryValues=e,this}select(e){return this.queryBuilder.select(e.map(t=>`${this.entityAlias}.${String(t)}`)),this}applyCondition(e,t,r){Object.entries(t).forEach(([i,s],u)=>{let a=`${i}Param${u}_${this.whereCount}`,l="=";if(typeof s=="string"){let n=s.match(/^(!=|>=|<=|>|<|=)\s*(.+)$/);if(n){let[,o,h]=n;l=o;let y=isNaN(Number(h))?h.trim():Number(h);e[r](`${e.alias}.${i} ${l} :${a}`,{[a]:y});return}}else if(typeof s=="object"&&s!==null){let n={gt:">",gte:">=",lt:"<",lte:"<=",ne:"!=",eq:"="};Object.entries(s).forEach(([o,h])=>{if(n[o]){let y=`${i}Param_${o}_${this.whereCount++}`;e[r](`${e.alias}.${i} ${n[o]} :${y}`,{[y]:h});}});return}e[r](`${this.entityAlias}.${i} = :${a}`,{[a]:s}),this.whereCount++;});}expression(e,t=true){let r=this.queryBuilder,i=e(new b(this.entityAlias)),s=i.buildExpression();return r.andWhere(t?`(${s})`:s,i.buildParams()),this.whereCount++,this}where(e){let t=this.queryBuilder;return this.applyCondition(t,e,"andWhere"),this}or(e){let t=this.queryBuilder;return this.applyCondition(t,e,"orWhere"),this}orderBy(e,t="ASC"){return this.queryBuilder.orderBy(`${this.entityAlias}.${String(e)}`,t),this}limit(e){return this.queryBuilder.limit(e),this}offset(e){return this.queryBuilder.offset(e),this}withRelation(e,...t){return [e,...t].forEach(r=>this.queryBuilder.leftJoinAndSelect(`${this.entityAlias}.${r}`,r)),this}innerJoin(e,t,r){return r?this.queryBuilder.innerJoin(`${this.entityAlias}.${e}`,t,r):this.queryBuilder.innerJoin(`${this.entityAlias}.${e}`,t),this.joinedAliases[t]=e,this}leftJoin(e,t,r){return r?this.queryBuilder.leftJoin(`${this.entityAlias}.${e}`,t,r):this.queryBuilder.leftJoin(`${this.entityAlias}.${e}`,t),this.joinedAliases[t]=e,this}groupBy(e){return this.queryBuilder.groupBy(`${this.entityAlias}.${String(e)}`),this}having(e){return this.queryBuilder.having(e),this}in(e,t){return this.queryBuilder.andWhere(`${this.entityAlias}.${String(e)} IN (:...values)`,{values:t}),this.whereCount++,this}like(e,t){if(!e||Object.keys(e).length===0)return this;let r=this.queryBuilder,i=[],s={};return Object.entries(e).forEach(([u,a])=>{let l=Array.isArray(a)?a:[a],n=[];l.forEach((o,h)=>{let y=`${u}LikeParam${h}_${this.whereCount}`;n.push(`${this.entityAlias}.${String(u)} LIKE :${y}`);let p=o;switch(t||"contains"){case "startsWith":p=`${o}%`;break;case "endsWith":p=`%${o}`;break;case "exact":p=`${o}`;break;default:p=`%${o}%`;}s[y]=p;}),n.length>0&&i.push(`(${n.join(" OR ")})`);}),i.length>0&&(r.andWhere(`(${i.join(" OR ")})`,s),this.whereCount++),this}distinct(){return this.queryBuilder.distinct(true),this}async count(e){return e&&this.queryBuilder.select(`COUNT(${e})`),await this.queryBuilder.getCount()}async sum(e){return (await this.queryBuilder.select(`SUM(${this.entityAlias}.${String(e)})`,"sum").getRawOne()).sum||0}async avg(e){return (await this.queryBuilder.select(`AVG(${this.entityAlias}.${String(e)})`,"avg").getRawOne()).avg||0}async min(e){return (await this.queryBuilder.select(`MIN(${this.entityAlias}.${String(e)})`,"min").getRawOne()).min||0}async max(e){return (await this.queryBuilder.select(`MAX(${this.entityAlias}.${String(e)})`,"max").getRawOne()).max||0}async rawQuery(e,t){return await this.repository.query(e,t)}async execute(){let e={};Object.keys(Object.prototype).forEach(t=>{Object.prototype.hasOwnProperty.call(Object.prototype,t)&&(e[t]=Object.prototype[t],delete Object.prototype[t]);});try{switch(this.action){case "upsert":case "create":this._create();let t=await this.queryBuilder.execute();return {created:!0,id:t.raw.insertId,record:t.generatedMaps[0],records:t.generatedMaps.length>1?t.generatedMaps:null};case "update":this._update();let r=this.queryBuilder,i=await r.execute(),s=r.getQuery().split("WHERE")[1]?.trim(),a=await this.repository.createQueryBuilder(this.entityAlias).where(s,r.getParameters()).getMany();return {updated:i.affected?i.affected>0:!1,record:a[0],records:a.length>1?a:[]};case "delete":this._delete();let l=await this.queryBuilder.execute();return {deleted:l.affected?l.affected>0:!1,count:l.affected||0};default:let n=await this.queryBuilder.getMany(),o={hasRows:n.length>0,count:n.length,row:n.length>0?n[0]:null,rows:n.length==1?[n[0]]:n};return this.isActiveRecord&&(o.save=()=>this._saveActiveRecord(n[0])),o}}catch(t){let r=t,i={code:chunkNTG6OYMF_cjs.f[r.code]||r.code,message:r.message,query:r.query,values:r.parameters};switch(this.action){case "upsert":case "create":let s={created:false,id:0,error:i};return this.usePromise?Promise.reject(s):s;case "update":let u={updated:false,error:i};return this.usePromise?Promise.reject(u):u;case "delete":let a={deleted:false,error:i};return this.usePromise?Promise.reject(a):a;default:let l={hasRows:false,count:0,row:null,rows:[],error:i};return this.usePromise?Promise.reject(l):l}}finally{Object.entries(e).forEach(([t,r])=>{Object.prototype[t]=r;});}}then(e,t){return this.execute().then(e,t)}},$=T;var Q=class c{static instance;dataSource;initialized=false;usePromise=false;_init;constructor(e,t,r,i){let s=r||x__default.default.join("src","zorm"),u=x__default.default.join(process.cwd(),s),a=chunkNTG6OYMF_cjs.b(u,false);if(this.usePromise=i||false,!a.access){console.log(f__default.default.red(`\u25CB ${a.message}`));return}if(e.startsWith("mysql")){let n=new chunkNTG6OYMF_cjs.g(decodeURIComponent(e)).connection();this.dataSource=new typeorm.DataSource({type:"mysql",username:n.user,password:n.password,host:n.host,port:Number(n.port),database:n.database,entities:t||[]}),this._init=this.dataSource.initialize.bind(this.dataSource);}else console.log("Only MySQL is supported for now"),process.exit(1);}static get(e,t,r,i){return c.instance||(c.instance=new c(e,t,r,i)),c.instance}async connect(e){if(!this.initialized)try{e&&!this.dataSource.options.entities?.length&&this.dataSource.setOptions({entities:e}),await this._init(),this.initialized=!0,console.log(f__default.default.green("\u25CB Zorm is connected"));}catch(t){console.log(f__default.default.red("\u25CB Error while connecting to your MySQL Server with following error:"),t);}}whenReady(){if(this.initialized)return this;let e={get:(t,r)=>{if(r==="then")return;let i=t[r];return typeof i=="function"?(...s)=>{let u=i.apply(t,s);if(u&&u.constructor.name==="ZormQueryBuilder")return this.wrapQueryBuilder(u);this._init().then(()=>u);}:i}};return new Proxy(this,e)}wrapQueryBuilder(e){let t={get:(r,i)=>{if(i==="then")return;let s=r[i];return typeof s=="function"?(...u)=>{let a=s.apply(r,u);return a&&a.constructor.name==="ZormQueryBuilder"?this.wrapQueryBuilder(a):this._init().then(()=>a)}:s}};return new Proxy(e,t)}getQueryBuilder(e,t){let r=this.getRepository(e);switch(this.dataSource.options.type){case "mysql":case "mariadb":case "postgres":case "sqlite":case "mssql":case "oracle":return new $(r,t,this.usePromise);case "mongodb":throw new Error("MongoDB does not support QueryBuilder. Use repository methods instead.");default:throw new Error(`Unsupported database type: ${this.dataSource.options.type}`)}}getRepository(e){return this.dataSource.getRepository(e)}create(e){return this.getQueryBuilder(e,"create")}find(e){return this.getQueryBuilder(e,"select")}update(e){return this.getQueryBuilder(e,"update")}delete(e){return this.getQueryBuilder(e,"delete")}},ue=Q;Object.defineProperty(exports,"BigIntTransformer",{enumerable:true,get:function(){return chunkNTG6OYMF_cjs.e}});Object.defineProperty(exports,"BooleanTransformer",{enumerable:true,get:function(){return chunkNTG6OYMF_cjs.d}});Object.defineProperty(exports,"BaseEntity",{enumerable:true,get:function(){return typeorm.BaseEntity}});Object.defineProperty(exports,"Column",{enumerable:true,get:function(){return typeorm.Column}});Object.defineProperty(exports,"Entity",{enumerable:true,get:function(){return typeorm.Entity}});Object.defineProperty(exports,"JoinColumn",{enumerable:true,get:function(){return typeorm.JoinColumn}});Object.defineProperty(exports,"ManyToMany",{enumerable:true,get:function(){return typeorm.ManyToMany}});Object.defineProperty(exports,"ManyToOne",{enumerable:true,get:function(){return typeorm.ManyToOne}});Object.defineProperty(exports,"OneToMany",{enumerable:true,get:function(){return typeorm.OneToMany}});Object.defineProperty(exports,"OneToOne",{enumerable:true,get:function(){return typeorm.OneToOne}});Object.defineProperty(exports,"PrimaryColumn",{enumerable:true,get:function(){return typeorm.PrimaryColumn}});Object.defineProperty(exports,"PrimaryGeneratedColumn",{enumerable:true,get:function(){return typeorm.PrimaryGeneratedColumn}});exports.default=ue;
|
|
2
|
+
var m=class h{_parts=[];_params={};_paramIdx=0;_alias;static globalParamIdx=0;constructor(e,t){this._alias=e?`${e}.`:"",this._paramIdx=t?t.idx:0,this._params=t?t.params:{};}field(e){return this._parts.push(`${this._alias}${String(e)}`),this}equals(e){let t=`p${this._paramIdx++}`;return this.append(` = :${t}`),this._params[t]=e,this}append(e){if(this._parts.length===0)throw new Error("Cannot append to empty expression");return this._parts[this._parts.length-1]+=e,this}wrap(e){if(this._parts.length===0)throw new Error("Cannot wrap empty expression");return this._parts[this._parts.length-1]=e(this._parts[this._parts.length-1]),this}exists(e){let t=new h(void 0,{params:this._params,idx:this._paramIdx});return e(t),this._parts.push(`EXISTS (${t.buildExpression()})`),this._paramIdx=t._paramIdx,this}select(e){return this._parts.push(`SELECT ${e}`),this}from(e,t){return this._parts.push(`FROM ${e} ${t}`),this._alias=t,this}where(e){let t=[];for(let[r,i]of Object.entries(e)){let s=`p${this._paramIdx++}`;t.push(`${r} = :${s}`),this._params[s]=i;}return this._parts.push(`WHERE ${t.join(" AND ")}`),this}or(){return this._parts.push("OR"),this}and(){return this._parts.push("AND"),this}group(){return this.wrap(e=>`(${e})`)}fromUnixTime(){return this.wrap(e=>`FROM_UNIXTIME(${e})`),this}date(){return this.wrap(e=>`DATE(${e})`),this}substring(e,t,r){return this._parts=[`SUBSTRING_INDEX(${this._alias}${String(e)}, '${t}', ${r})`],this}toExpression(){return {expression:this._parts.join(" "),param:this._params}}buildExpression(){return this.toExpression().expression}buildParams(){return this.toExpression().param}},b=m;var T=class h extends Promise{repository;queryBuilder;entityAlias;action;queryValues=null;usePromise;whereCount=0;isActiveRecord=false;activeRecord;joinedAliases={};constructor(e,t,r){super(()=>{}),this.repository=e,this.entityAlias=e.metadata.tableName,this.queryBuilder=e.createQueryBuilder(this.entityAlias),this.action=t,this.usePromise=r||false,this.activeRecord=null;}_create(){if(this.queryValues)this.queryBuilder=this.queryBuilder.insert().into(this.entityAlias).values(this.queryValues);else throw chunkNTG6OYMF_cjs.c("\u25CB Values are missing. You forgot to call .with({ key: value })");return this}upsert(){if(this.queryValues)this.queryBuilder=this.repository.createQueryBuilder(this.entityAlias).insert().into(this.entityAlias).values(this.queryValues).orUpdate(Object.keys(this.queryValues));else throw chunkNTG6OYMF_cjs.c("\u25CB Values are missing. You forgot to call .with({ key: value })");return this}_update(){if(this.queryValues)if(this.whereCount>0)this.queryBuilder=this.queryBuilder.update().set(this.queryValues);else throw chunkNTG6OYMF_cjs.c("\u25CB Update must have at least one WHERE condition. You forgot to call .where({ condition: value })");else throw chunkNTG6OYMF_cjs.c("\u25CB Values are missing. You forgot to call .with({ key: value })");return this}_delete(){if(this.whereCount>0)this.queryBuilder=this.queryBuilder.delete();else throw chunkNTG6OYMF_cjs.c("\u25CB Delete must have at least one WHERE condition. You forgot to call .where({ condition: value })");return this}_getRawQuery(){return this.queryBuilder.getQueryAndParameters()}active(){return this.isActiveRecord=true,this}async _saveActiveRecord(e){return this.repository.save(e)}clone(){let e=new h(this.repository,this.action,this.usePromise);return e.queryBuilder=this.queryBuilder.clone(),e.entityAlias=this.entityAlias,e.queryValues=this.queryValues?structuredClone(this.queryValues):null,e.whereCount=this.whereCount,e.isActiveRecord=this.isActiveRecord,e.activeRecord=this.activeRecord,e}with(e){return this.queryValues=e,this}withData(e){return this.queryValues=e,this}select(e){return this.queryBuilder.select(e.map(t=>`${this.entityAlias}.${String(t)}`)),this}applyCondition(e,t,r){Object.entries(t).forEach(([i,s],u)=>{let a=`${i}Param${u}_${this.whereCount}`,l="=";if(typeof s=="string"){let n=s.match(/^(!=|>=|<=|>|<|=)\s*(.+)$/);if(n){let[,o,c]=n;l=o;let y=isNaN(Number(c))?c.trim():Number(c);e[r](`${e.alias}.${i} ${l} :${a}`,{[a]:y});return}}else if(typeof s=="object"&&s!==null){let n={gt:">",gte:">=",lt:"<",lte:"<=",ne:"!=",eq:"="};Object.entries(s).forEach(([o,c])=>{if(n[o]){let y=`${i}Param_${o}_${this.whereCount++}`;e[r](`${e.alias}.${i} ${n[o]} :${y}`,{[y]:c});}});return}e[r](`${this.entityAlias}.${i} = :${a}`,{[a]:s}),this.whereCount++;});}expression(e,t=true){let r=this.queryBuilder,i=e(new b(this.entityAlias)),s=i.buildExpression();return r.andWhere(t?`(${s})`:s,i.buildParams()),this.whereCount++,this}where(e){let t=this.queryBuilder;return this.applyCondition(t,e,"andWhere"),this}or(e){let t=this.queryBuilder;return this.applyCondition(t,e,"orWhere"),this}orderBy(e,t="ASC"){return this.queryBuilder.orderBy(`${this.entityAlias}.${String(e)}`,t),this}limit(e){return this.queryBuilder.limit(e),this}offset(e){return this.queryBuilder.offset(e),this}withRelation(e,...t){return [e,...t].forEach(r=>this.queryBuilder.leftJoinAndSelect(`${this.entityAlias}.${r}`,r)),this}innerJoin(e,t,r){return r?this.queryBuilder.innerJoin(`${this.entityAlias}.${e}`,t,r):this.queryBuilder.innerJoin(`${this.entityAlias}.${e}`,t),this.joinedAliases[t]=e,this}leftJoin(e,t,r){return r?this.queryBuilder.leftJoin(`${this.entityAlias}.${e}`,t,r):this.queryBuilder.leftJoin(`${this.entityAlias}.${e}`,t),this.joinedAliases[t]=e,this}groupBy(e){return this.queryBuilder.groupBy(`${this.entityAlias}.${String(e)}`),this}having(e){return this.queryBuilder.having(e),this}in(e,t){return this.queryBuilder.andWhere(`${this.entityAlias}.${String(e)} IN (:...values)`,{values:t}),this.whereCount++,this}like(e,t){if(!e||Object.keys(e).length===0)return this;let r=this.queryBuilder,i=[],s={};return Object.entries(e).forEach(([u,a])=>{let l=Array.isArray(a)?a:[a],n=[];l.forEach((o,c)=>{let y=`${u}LikeParam${c}_${this.whereCount}`;n.push(`${this.entityAlias}.${String(u)} LIKE :${y}`);let p=o;switch(t||"contains"){case "startsWith":p=`${o}%`;break;case "endsWith":p=`%${o}`;break;case "exact":p=`${o}`;break;default:p=`%${o}%`;}s[y]=p;}),n.length>0&&i.push(`(${n.join(" OR ")})`);}),i.length>0&&(r.andWhere(`(${i.join(" OR ")})`,s),this.whereCount++),this}distinct(){return this.queryBuilder.distinct(true),this}async count(e){return e&&this.queryBuilder.select(`COUNT(${e})`),await this.queryBuilder.getCount()}async sum(e){return (await this.queryBuilder.select(`SUM(${this.entityAlias}.${String(e)})`,"sum").getRawOne()).sum||0}async avg(e){return (await this.queryBuilder.select(`AVG(${this.entityAlias}.${String(e)})`,"avg").getRawOne()).avg||0}async min(e){return (await this.queryBuilder.select(`MIN(${this.entityAlias}.${String(e)})`,"min").getRawOne()).min||0}async max(e){return (await this.queryBuilder.select(`MAX(${this.entityAlias}.${String(e)})`,"max").getRawOne()).max||0}async rawQuery(e,t){return await this.repository.query(e,t)}async execute(){let e={};Object.keys(Object.prototype).forEach(t=>{Object.prototype.hasOwnProperty.call(Object.prototype,t)&&(e[t]=Object.prototype[t],delete Object.prototype[t]);});try{switch(this.action){case "upsert":case "create":this._create();let t=await this.queryBuilder.execute();return {created:!0,id:t.raw.insertId,record:t.generatedMaps[0],records:t.generatedMaps.length>1?t.generatedMaps:null};case "update":this._update();let r=this.queryBuilder,i=await r.execute(),s=r.getQuery().split("WHERE")[1]?.trim(),a=await this.repository.createQueryBuilder(this.entityAlias).where(s,r.getParameters()).getMany();return {updated:i.affected?i.affected>0:!1,record:a[0],records:a.length>1?a:[]};case "delete":this._delete();let l=await this.queryBuilder.execute();return {deleted:l.affected?l.affected>0:!1,count:l.affected||0};default:let n=await this.queryBuilder.getMany(),o={hasRows:n.length>0,count:n.length,row:n.length>0?n[0]:null,rows:n.length==1?[n[0]]:n};return this.isActiveRecord&&(o.save=()=>this._saveActiveRecord(n[0])),o}}catch(t){let r=t,i={code:chunkNTG6OYMF_cjs.f[r.code]||r.code,message:r.message,query:r.query,values:r.parameters};switch(this.action){case "upsert":case "create":let s={created:false,id:0,error:i};return this.usePromise?Promise.reject(s):s;case "update":let u={updated:false,error:i};return this.usePromise?Promise.reject(u):u;case "delete":let a={deleted:false,error:i};return this.usePromise?Promise.reject(a):a;default:let l={hasRows:false,count:0,row:null,rows:[],error:i};return this.usePromise?Promise.reject(l):l}}finally{Object.entries(e).forEach(([t,r])=>{Object.prototype[t]=r;});}}then(e,t){return this.execute().then(e,t)}},$=T;var Q=class h{static instance;dataSource;initialized=false;usePromise=false;_init;constructor(e,t,r,i){let s=r||x__default.default.join("src","zorm"),u=x__default.default.join(process.cwd(),s),a=chunkNTG6OYMF_cjs.b(u,false);if(this.usePromise=i||false,!a.access){console.log(f__default.default.red(`\u25CB ${a.message}`));return}if(e.startsWith("mysql")){let n=new chunkNTG6OYMF_cjs.g(decodeURIComponent(e)).connection();this.dataSource=new typeorm.DataSource({type:"mysql",username:n.user,password:n.password,host:n.host,port:Number(n.port),database:n.database,entities:t||[]}),this._init=this.dataSource.initialize.bind(this.dataSource);}else console.log("Only MySQL is supported for now"),process.exit(1);}static get(e,t,r,i){return h.instance||(h.instance=new h(e,t,r,i)),h.instance}async connect(e){if(!this.initialized)try{e&&!this.dataSource.options.entities?.length&&this.dataSource.setOptions({entities:e}),await this._init(),this.initialized=!0,console.log(f__default.default.green("\u25CB Zorm is connected"));}catch(t){console.log(f__default.default.red("\u25CB Error while connecting to your MySQL Server with following error:"),t);}}whenReady(){if(this.initialized)return this;let e={get:(t,r)=>{if(r==="then")return;let i=t[r];return typeof i=="function"?(...s)=>{let u=i.apply(t,s);if(u&&u.constructor.name==="ZormQueryBuilder")return this.wrapQueryBuilder(u);this._init().then(()=>u);}:i}};return new Proxy(this,e)}wrapQueryBuilder(e){let t={get:(r,i)=>{if(i==="then")return;let s=r[i];return typeof s=="function"?(...u)=>{let a=s.apply(r,u);return a&&a.constructor.name==="ZormQueryBuilder"?this.wrapQueryBuilder(a):this._init().then(()=>a)}:s}};return new Proxy(e,t)}getQueryBuilder(e,t){let r=this.getRepository(e);switch(this.dataSource.options.type){case "mysql":case "mariadb":case "postgres":case "sqlite":case "mssql":case "oracle":return new $(r,t,this.usePromise);case "mongodb":throw new Error("MongoDB does not support QueryBuilder. Use repository methods instead.");default:throw new Error(`Unsupported database type: ${this.dataSource.options.type}`)}}getRepository(e){return this.dataSource.getRepository(e)}create(e){return this.getQueryBuilder(e,"create")}find(e){return this.getQueryBuilder(e,"select")}update(e){return this.getQueryBuilder(e,"update")}delete(e){return this.getQueryBuilder(e,"delete")}},ue=Q;Object.defineProperty(exports,"BigIntTransformer",{enumerable:true,get:function(){return chunkNTG6OYMF_cjs.e}});Object.defineProperty(exports,"BooleanTransformer",{enumerable:true,get:function(){return chunkNTG6OYMF_cjs.d}});Object.defineProperty(exports,"BaseEntity",{enumerable:true,get:function(){return typeorm.BaseEntity}});Object.defineProperty(exports,"Column",{enumerable:true,get:function(){return typeorm.Column}});Object.defineProperty(exports,"Entity",{enumerable:true,get:function(){return typeorm.Entity}});Object.defineProperty(exports,"JoinColumn",{enumerable:true,get:function(){return typeorm.JoinColumn}});Object.defineProperty(exports,"ManyToMany",{enumerable:true,get:function(){return typeorm.ManyToMany}});Object.defineProperty(exports,"ManyToOne",{enumerable:true,get:function(){return typeorm.ManyToOne}});Object.defineProperty(exports,"OneToMany",{enumerable:true,get:function(){return typeorm.OneToMany}});Object.defineProperty(exports,"OneToOne",{enumerable:true,get:function(){return typeorm.OneToOne}});Object.defineProperty(exports,"PrimaryColumn",{enumerable:true,get:function(){return typeorm.PrimaryColumn}});Object.defineProperty(exports,"PrimaryGeneratedColumn",{enumerable:true,get:function(){return typeorm.PrimaryGeneratedColumn}});exports.default=ue;
|
package/dist/index.d.cts
CHANGED
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b,g,c,f as f$1}from'./chunk-674L2AWT.js';export{e as BigIntTransformer,d as BooleanTransformer}from'./chunk-674L2AWT.js';import S from'path';import Q from'picocolors';import'reflect-metadata';import {DataSource}from'typeorm';export{BaseEntity,Column,Entity,JoinColumn,ManyToMany,ManyToOne,OneToMany,OneToOne,PrimaryColumn,PrimaryGeneratedColumn}from'typeorm';var m=class c{_parts=[];_params={};_paramIdx=0;_alias;static globalParamIdx=0;constructor(e,t){this._alias=e?`${e}.`:"",this._paramIdx=t?t.idx:0,this._params=t?t.params:{};}field(e){return this._parts.push(`${this._alias}${String(e)}`),this}equals(e){let t=`p${this._paramIdx++}`;return this.append(` = :${t}`),this._params[t]=e,this}append(e){if(this._parts.length===0)throw new Error("Cannot append to empty expression");return this._parts[this._parts.length-1]+=e,this}wrap(e){if(this._parts.length===0)throw new Error("Cannot wrap empty expression");return this._parts[this._parts.length-1]=e(this._parts[this._parts.length-1]),this}exists(e){let t=new c(void 0,{params:this._params,idx:this._paramIdx});return e(t),this._parts.push(`EXISTS (${t.buildExpression()})`),this._paramIdx=t._paramIdx,this}select(e){return this._parts.push(`SELECT ${e}`),this}from(e,t){return this._parts.push(`FROM ${e} ${t}`),this._alias=t,this}where(e){let t=[];for(let[r,i]of Object.entries(e)){let s=`p${this._paramIdx++}`;t.push(`${r} = :${s}`),this._params[s]=i;}return this._parts.push(`WHERE ${t.join(" AND ")}`),this}or(){return this._parts.push("OR"),this}group(){return this.wrap(e=>`(${e})`)}fromUnixTime(){return this.wrap(e=>`FROM_UNIXTIME(${e})`),this}date(){return this.wrap(e=>`DATE(${e})`),this}substring(e,t,r){return this._parts=[`SUBSTRING_INDEX(${this._alias}${String(e)}, '${t}', ${r})`],this}toExpression(){return {expression:this._parts.join(" "),param:this._params}}buildExpression(){return this.toExpression().expression}buildParams(){return this.toExpression().param}},$=m;var f=class c$1 extends Promise{repository;queryBuilder;entityAlias;action;queryValues=null;usePromise;whereCount=0;isActiveRecord=false;activeRecord;joinedAliases={};constructor(e,t,r){super(()=>{}),this.repository=e,this.entityAlias=e.metadata.tableName,this.queryBuilder=e.createQueryBuilder(this.entityAlias),this.action=t,this.usePromise=r||false,this.activeRecord=null;}_create(){if(this.queryValues)this.queryBuilder=this.queryBuilder.insert().into(this.entityAlias).values(this.queryValues);else throw c("\u25CB Values are missing. You forgot to call .with({ key: value })");return this}upsert(){if(this.queryValues)this.queryBuilder=this.repository.createQueryBuilder(this.entityAlias).insert().into(this.entityAlias).values(this.queryValues).orUpdate(Object.keys(this.queryValues));else throw c("\u25CB Values are missing. You forgot to call .with({ key: value })");return this}_update(){if(this.queryValues)if(this.whereCount>0)this.queryBuilder=this.queryBuilder.update().set(this.queryValues);else throw c("\u25CB Update must have at least one WHERE condition. You forgot to call .where({ condition: value })");else throw c("\u25CB Values are missing. You forgot to call .with({ key: value })");return this}_delete(){if(this.whereCount>0)this.queryBuilder=this.queryBuilder.delete();else throw c("\u25CB Delete must have at least one WHERE condition. You forgot to call .where({ condition: value })");return this}_getRawQuery(){return this.queryBuilder.getQueryAndParameters()}active(){return this.isActiveRecord=true,this}async _saveActiveRecord(e){return this.repository.save(e)}clone(){let e=new c$1(this.repository,this.action,this.usePromise);return e.queryBuilder=this.queryBuilder.clone(),e.entityAlias=this.entityAlias,e.queryValues=this.queryValues?structuredClone(this.queryValues):null,e.whereCount=this.whereCount,e.isActiveRecord=this.isActiveRecord,e.activeRecord=this.activeRecord,e}with(e){return this.queryValues=e,this}withData(e){return this.queryValues=e,this}select(e){return this.queryBuilder.select(e.map(t=>`${this.entityAlias}.${String(t)}`)),this}applyCondition(e,t,r){Object.entries(t).forEach(([i,s],u)=>{let a=`${i}Param${u}_${this.whereCount}`,l="=";if(typeof s=="string"){let n=s.match(/^(!=|>=|<=|>|<|=)\s*(.+)$/);if(n){let[,o,h]=n;l=o;let y=isNaN(Number(h))?h.trim():Number(h);e[r](`${e.alias}.${i} ${l} :${a}`,{[a]:y});return}}else if(typeof s=="object"&&s!==null){let n={gt:">",gte:">=",lt:"<",lte:"<=",ne:"!=",eq:"="};Object.entries(s).forEach(([o,h])=>{if(n[o]){let y=`${i}Param_${o}_${this.whereCount++}`;e[r](`${e.alias}.${i} ${n[o]} :${y}`,{[y]:h});}});return}e[r](`${this.entityAlias}.${i} = :${a}`,{[a]:s}),this.whereCount++;});}expression(e,t=true){let r=this.queryBuilder,i=e(new $(this.entityAlias)),s=i.buildExpression();return r.andWhere(t?`(${s})`:s,i.buildParams()),this.whereCount++,this}where(e){let t=this.queryBuilder;return this.applyCondition(t,e,"andWhere"),this}or(e){let t=this.queryBuilder;return this.applyCondition(t,e,"orWhere"),this}orderBy(e,t="ASC"){return this.queryBuilder.orderBy(`${this.entityAlias}.${String(e)}`,t),this}limit(e){return this.queryBuilder.limit(e),this}offset(e){return this.queryBuilder.offset(e),this}withRelation(e,...t){return [e,...t].forEach(r=>this.queryBuilder.leftJoinAndSelect(`${this.entityAlias}.${r}`,r)),this}innerJoin(e,t,r){return r?this.queryBuilder.innerJoin(`${this.entityAlias}.${e}`,t,r):this.queryBuilder.innerJoin(`${this.entityAlias}.${e}`,t),this.joinedAliases[t]=e,this}leftJoin(e,t,r){return r?this.queryBuilder.leftJoin(`${this.entityAlias}.${e}`,t,r):this.queryBuilder.leftJoin(`${this.entityAlias}.${e}`,t),this.joinedAliases[t]=e,this}groupBy(e){return this.queryBuilder.groupBy(`${this.entityAlias}.${String(e)}`),this}having(e){return this.queryBuilder.having(e),this}in(e,t){return this.queryBuilder.andWhere(`${this.entityAlias}.${String(e)} IN (:...values)`,{values:t}),this.whereCount++,this}like(e,t){if(!e||Object.keys(e).length===0)return this;let r=this.queryBuilder,i=[],s={};return Object.entries(e).forEach(([u,a])=>{let l=Array.isArray(a)?a:[a],n=[];l.forEach((o,h)=>{let y=`${u}LikeParam${h}_${this.whereCount}`;n.push(`${this.entityAlias}.${String(u)} LIKE :${y}`);let p=o;switch(t||"contains"){case "startsWith":p=`${o}%`;break;case "endsWith":p=`%${o}`;break;case "exact":p=`${o}`;break;default:p=`%${o}%`;}s[y]=p;}),n.length>0&&i.push(`(${n.join(" OR ")})`);}),i.length>0&&(r.andWhere(`(${i.join(" OR ")})`,s),this.whereCount++),this}distinct(){return this.queryBuilder.distinct(true),this}async count(e){return e&&this.queryBuilder.select(`COUNT(${e})`),await this.queryBuilder.getCount()}async sum(e){return (await this.queryBuilder.select(`SUM(${this.entityAlias}.${String(e)})`,"sum").getRawOne()).sum||0}async avg(e){return (await this.queryBuilder.select(`AVG(${this.entityAlias}.${String(e)})`,"avg").getRawOne()).avg||0}async min(e){return (await this.queryBuilder.select(`MIN(${this.entityAlias}.${String(e)})`,"min").getRawOne()).min||0}async max(e){return (await this.queryBuilder.select(`MAX(${this.entityAlias}.${String(e)})`,"max").getRawOne()).max||0}async rawQuery(e,t){return await this.repository.query(e,t)}async execute(){let e={};Object.keys(Object.prototype).forEach(t=>{Object.prototype.hasOwnProperty.call(Object.prototype,t)&&(e[t]=Object.prototype[t],delete Object.prototype[t]);});try{switch(this.action){case "upsert":case "create":this._create();let t=await this.queryBuilder.execute();return {created:!0,id:t.raw.insertId,record:t.generatedMaps[0],records:t.generatedMaps.length>1?t.generatedMaps:null};case "update":this._update();let r=this.queryBuilder,i=await r.execute(),s=r.getQuery().split("WHERE")[1]?.trim(),a=await this.repository.createQueryBuilder(this.entityAlias).where(s,r.getParameters()).getMany();return {updated:i.affected?i.affected>0:!1,record:a[0],records:a.length>1?a:[]};case "delete":this._delete();let l=await this.queryBuilder.execute();return {deleted:l.affected?l.affected>0:!1,count:l.affected||0};default:let n=await this.queryBuilder.getMany(),o={hasRows:n.length>0,count:n.length,row:n.length>0?n[0]:null,rows:n.length==1?[n[0]]:n};return this.isActiveRecord&&(o.save=()=>this._saveActiveRecord(n[0])),o}}catch(t){let r=t,i={code:f$1[r.code]||r.code,message:r.message,query:r.query,values:r.parameters};switch(this.action){case "upsert":case "create":let s={created:false,id:0,error:i};return this.usePromise?Promise.reject(s):s;case "update":let u={updated:false,error:i};return this.usePromise?Promise.reject(u):u;case "delete":let a={deleted:false,error:i};return this.usePromise?Promise.reject(a):a;default:let l={hasRows:false,count:0,row:null,rows:[],error:i};return this.usePromise?Promise.reject(l):l}}finally{Object.entries(e).forEach(([t,r])=>{Object.prototype[t]=r;});}}then(e,t){return this.execute().then(e,t)}},x=f;var B=class c{static instance;dataSource;initialized=false;usePromise=false;_init;constructor(e,t,r,i){let s=r||S.join("src","zorm"),u=S.join(process.cwd(),s),a=b(u,false);if(this.usePromise=i||false,!a.access){console.log(Q.red(`\u25CB ${a.message}`));return}if(e.startsWith("mysql")){let n=new g(decodeURIComponent(e)).connection();this.dataSource=new DataSource({type:"mysql",username:n.user,password:n.password,host:n.host,port:Number(n.port),database:n.database,entities:t||[]}),this._init=this.dataSource.initialize.bind(this.dataSource);}else console.log("Only MySQL is supported for now"),process.exit(1);}static get(e,t,r,i){return c.instance||(c.instance=new c(e,t,r,i)),c.instance}async connect(e){if(!this.initialized)try{e&&!this.dataSource.options.entities?.length&&this.dataSource.setOptions({entities:e}),await this._init(),this.initialized=!0,console.log(Q.green("\u25CB Zorm is connected"));}catch(t){console.log(Q.red("\u25CB Error while connecting to your MySQL Server with following error:"),t);}}whenReady(){if(this.initialized)return this;let e={get:(t,r)=>{if(r==="then")return;let i=t[r];return typeof i=="function"?(...s)=>{let u=i.apply(t,s);if(u&&u.constructor.name==="ZormQueryBuilder")return this.wrapQueryBuilder(u);this._init().then(()=>u);}:i}};return new Proxy(this,e)}wrapQueryBuilder(e){let t={get:(r,i)=>{if(i==="then")return;let s=r[i];return typeof s=="function"?(...u)=>{let a=s.apply(r,u);return a&&a.constructor.name==="ZormQueryBuilder"?this.wrapQueryBuilder(a):this._init().then(()=>a)}:s}};return new Proxy(e,t)}getQueryBuilder(e,t){let r=this.getRepository(e);switch(this.dataSource.options.type){case "mysql":case "mariadb":case "postgres":case "sqlite":case "mssql":case "oracle":return new x(r,t,this.usePromise);case "mongodb":throw new Error("MongoDB does not support QueryBuilder. Use repository methods instead.");default:throw new Error(`Unsupported database type: ${this.dataSource.options.type}`)}}getRepository(e){return this.dataSource.getRepository(e)}create(e){return this.getQueryBuilder(e,"create")}find(e){return this.getQueryBuilder(e,"select")}update(e){return this.getQueryBuilder(e,"update")}delete(e){return this.getQueryBuilder(e,"delete")}},oe=B;export{oe as default};
|
|
1
|
+
import {b,g,c,f as f$1}from'./chunk-674L2AWT.js';export{e as BigIntTransformer,d as BooleanTransformer}from'./chunk-674L2AWT.js';import S from'path';import Q from'picocolors';import'reflect-metadata';import {DataSource}from'typeorm';export{BaseEntity,Column,Entity,JoinColumn,ManyToMany,ManyToOne,OneToMany,OneToOne,PrimaryColumn,PrimaryGeneratedColumn}from'typeorm';var m=class h{_parts=[];_params={};_paramIdx=0;_alias;static globalParamIdx=0;constructor(e,t){this._alias=e?`${e}.`:"",this._paramIdx=t?t.idx:0,this._params=t?t.params:{};}field(e){return this._parts.push(`${this._alias}${String(e)}`),this}equals(e){let t=`p${this._paramIdx++}`;return this.append(` = :${t}`),this._params[t]=e,this}append(e){if(this._parts.length===0)throw new Error("Cannot append to empty expression");return this._parts[this._parts.length-1]+=e,this}wrap(e){if(this._parts.length===0)throw new Error("Cannot wrap empty expression");return this._parts[this._parts.length-1]=e(this._parts[this._parts.length-1]),this}exists(e){let t=new h(void 0,{params:this._params,idx:this._paramIdx});return e(t),this._parts.push(`EXISTS (${t.buildExpression()})`),this._paramIdx=t._paramIdx,this}select(e){return this._parts.push(`SELECT ${e}`),this}from(e,t){return this._parts.push(`FROM ${e} ${t}`),this._alias=t,this}where(e){let t=[];for(let[r,i]of Object.entries(e)){let s=`p${this._paramIdx++}`;t.push(`${r} = :${s}`),this._params[s]=i;}return this._parts.push(`WHERE ${t.join(" AND ")}`),this}or(){return this._parts.push("OR"),this}and(){return this._parts.push("AND"),this}group(){return this.wrap(e=>`(${e})`)}fromUnixTime(){return this.wrap(e=>`FROM_UNIXTIME(${e})`),this}date(){return this.wrap(e=>`DATE(${e})`),this}substring(e,t,r){return this._parts=[`SUBSTRING_INDEX(${this._alias}${String(e)}, '${t}', ${r})`],this}toExpression(){return {expression:this._parts.join(" "),param:this._params}}buildExpression(){return this.toExpression().expression}buildParams(){return this.toExpression().param}},$=m;var f=class h extends Promise{repository;queryBuilder;entityAlias;action;queryValues=null;usePromise;whereCount=0;isActiveRecord=false;activeRecord;joinedAliases={};constructor(e,t,r){super(()=>{}),this.repository=e,this.entityAlias=e.metadata.tableName,this.queryBuilder=e.createQueryBuilder(this.entityAlias),this.action=t,this.usePromise=r||false,this.activeRecord=null;}_create(){if(this.queryValues)this.queryBuilder=this.queryBuilder.insert().into(this.entityAlias).values(this.queryValues);else throw c("\u25CB Values are missing. You forgot to call .with({ key: value })");return this}upsert(){if(this.queryValues)this.queryBuilder=this.repository.createQueryBuilder(this.entityAlias).insert().into(this.entityAlias).values(this.queryValues).orUpdate(Object.keys(this.queryValues));else throw c("\u25CB Values are missing. You forgot to call .with({ key: value })");return this}_update(){if(this.queryValues)if(this.whereCount>0)this.queryBuilder=this.queryBuilder.update().set(this.queryValues);else throw c("\u25CB Update must have at least one WHERE condition. You forgot to call .where({ condition: value })");else throw c("\u25CB Values are missing. You forgot to call .with({ key: value })");return this}_delete(){if(this.whereCount>0)this.queryBuilder=this.queryBuilder.delete();else throw c("\u25CB Delete must have at least one WHERE condition. You forgot to call .where({ condition: value })");return this}_getRawQuery(){return this.queryBuilder.getQueryAndParameters()}active(){return this.isActiveRecord=true,this}async _saveActiveRecord(e){return this.repository.save(e)}clone(){let e=new h(this.repository,this.action,this.usePromise);return e.queryBuilder=this.queryBuilder.clone(),e.entityAlias=this.entityAlias,e.queryValues=this.queryValues?structuredClone(this.queryValues):null,e.whereCount=this.whereCount,e.isActiveRecord=this.isActiveRecord,e.activeRecord=this.activeRecord,e}with(e){return this.queryValues=e,this}withData(e){return this.queryValues=e,this}select(e){return this.queryBuilder.select(e.map(t=>`${this.entityAlias}.${String(t)}`)),this}applyCondition(e,t,r){Object.entries(t).forEach(([i,s],u)=>{let a=`${i}Param${u}_${this.whereCount}`,l="=";if(typeof s=="string"){let n=s.match(/^(!=|>=|<=|>|<|=)\s*(.+)$/);if(n){let[,o,c]=n;l=o;let y=isNaN(Number(c))?c.trim():Number(c);e[r](`${e.alias}.${i} ${l} :${a}`,{[a]:y});return}}else if(typeof s=="object"&&s!==null){let n={gt:">",gte:">=",lt:"<",lte:"<=",ne:"!=",eq:"="};Object.entries(s).forEach(([o,c])=>{if(n[o]){let y=`${i}Param_${o}_${this.whereCount++}`;e[r](`${e.alias}.${i} ${n[o]} :${y}`,{[y]:c});}});return}e[r](`${this.entityAlias}.${i} = :${a}`,{[a]:s}),this.whereCount++;});}expression(e,t=true){let r=this.queryBuilder,i=e(new $(this.entityAlias)),s=i.buildExpression();return r.andWhere(t?`(${s})`:s,i.buildParams()),this.whereCount++,this}where(e){let t=this.queryBuilder;return this.applyCondition(t,e,"andWhere"),this}or(e){let t=this.queryBuilder;return this.applyCondition(t,e,"orWhere"),this}orderBy(e,t="ASC"){return this.queryBuilder.orderBy(`${this.entityAlias}.${String(e)}`,t),this}limit(e){return this.queryBuilder.limit(e),this}offset(e){return this.queryBuilder.offset(e),this}withRelation(e,...t){return [e,...t].forEach(r=>this.queryBuilder.leftJoinAndSelect(`${this.entityAlias}.${r}`,r)),this}innerJoin(e,t,r){return r?this.queryBuilder.innerJoin(`${this.entityAlias}.${e}`,t,r):this.queryBuilder.innerJoin(`${this.entityAlias}.${e}`,t),this.joinedAliases[t]=e,this}leftJoin(e,t,r){return r?this.queryBuilder.leftJoin(`${this.entityAlias}.${e}`,t,r):this.queryBuilder.leftJoin(`${this.entityAlias}.${e}`,t),this.joinedAliases[t]=e,this}groupBy(e){return this.queryBuilder.groupBy(`${this.entityAlias}.${String(e)}`),this}having(e){return this.queryBuilder.having(e),this}in(e,t){return this.queryBuilder.andWhere(`${this.entityAlias}.${String(e)} IN (:...values)`,{values:t}),this.whereCount++,this}like(e,t){if(!e||Object.keys(e).length===0)return this;let r=this.queryBuilder,i=[],s={};return Object.entries(e).forEach(([u,a])=>{let l=Array.isArray(a)?a:[a],n=[];l.forEach((o,c)=>{let y=`${u}LikeParam${c}_${this.whereCount}`;n.push(`${this.entityAlias}.${String(u)} LIKE :${y}`);let p=o;switch(t||"contains"){case "startsWith":p=`${o}%`;break;case "endsWith":p=`%${o}`;break;case "exact":p=`${o}`;break;default:p=`%${o}%`;}s[y]=p;}),n.length>0&&i.push(`(${n.join(" OR ")})`);}),i.length>0&&(r.andWhere(`(${i.join(" OR ")})`,s),this.whereCount++),this}distinct(){return this.queryBuilder.distinct(true),this}async count(e){return e&&this.queryBuilder.select(`COUNT(${e})`),await this.queryBuilder.getCount()}async sum(e){return (await this.queryBuilder.select(`SUM(${this.entityAlias}.${String(e)})`,"sum").getRawOne()).sum||0}async avg(e){return (await this.queryBuilder.select(`AVG(${this.entityAlias}.${String(e)})`,"avg").getRawOne()).avg||0}async min(e){return (await this.queryBuilder.select(`MIN(${this.entityAlias}.${String(e)})`,"min").getRawOne()).min||0}async max(e){return (await this.queryBuilder.select(`MAX(${this.entityAlias}.${String(e)})`,"max").getRawOne()).max||0}async rawQuery(e,t){return await this.repository.query(e,t)}async execute(){let e={};Object.keys(Object.prototype).forEach(t=>{Object.prototype.hasOwnProperty.call(Object.prototype,t)&&(e[t]=Object.prototype[t],delete Object.prototype[t]);});try{switch(this.action){case "upsert":case "create":this._create();let t=await this.queryBuilder.execute();return {created:!0,id:t.raw.insertId,record:t.generatedMaps[0],records:t.generatedMaps.length>1?t.generatedMaps:null};case "update":this._update();let r=this.queryBuilder,i=await r.execute(),s=r.getQuery().split("WHERE")[1]?.trim(),a=await this.repository.createQueryBuilder(this.entityAlias).where(s,r.getParameters()).getMany();return {updated:i.affected?i.affected>0:!1,record:a[0],records:a.length>1?a:[]};case "delete":this._delete();let l=await this.queryBuilder.execute();return {deleted:l.affected?l.affected>0:!1,count:l.affected||0};default:let n=await this.queryBuilder.getMany(),o={hasRows:n.length>0,count:n.length,row:n.length>0?n[0]:null,rows:n.length==1?[n[0]]:n};return this.isActiveRecord&&(o.save=()=>this._saveActiveRecord(n[0])),o}}catch(t){let r=t,i={code:f$1[r.code]||r.code,message:r.message,query:r.query,values:r.parameters};switch(this.action){case "upsert":case "create":let s={created:false,id:0,error:i};return this.usePromise?Promise.reject(s):s;case "update":let u={updated:false,error:i};return this.usePromise?Promise.reject(u):u;case "delete":let a={deleted:false,error:i};return this.usePromise?Promise.reject(a):a;default:let l={hasRows:false,count:0,row:null,rows:[],error:i};return this.usePromise?Promise.reject(l):l}}finally{Object.entries(e).forEach(([t,r])=>{Object.prototype[t]=r;});}}then(e,t){return this.execute().then(e,t)}},x=f;var B=class h{static instance;dataSource;initialized=false;usePromise=false;_init;constructor(e,t,r,i){let s=r||S.join("src","zorm"),u=S.join(process.cwd(),s),a=b(u,false);if(this.usePromise=i||false,!a.access){console.log(Q.red(`\u25CB ${a.message}`));return}if(e.startsWith("mysql")){let n=new g(decodeURIComponent(e)).connection();this.dataSource=new DataSource({type:"mysql",username:n.user,password:n.password,host:n.host,port:Number(n.port),database:n.database,entities:t||[]}),this._init=this.dataSource.initialize.bind(this.dataSource);}else console.log("Only MySQL is supported for now"),process.exit(1);}static get(e,t,r,i){return h.instance||(h.instance=new h(e,t,r,i)),h.instance}async connect(e){if(!this.initialized)try{e&&!this.dataSource.options.entities?.length&&this.dataSource.setOptions({entities:e}),await this._init(),this.initialized=!0,console.log(Q.green("\u25CB Zorm is connected"));}catch(t){console.log(Q.red("\u25CB Error while connecting to your MySQL Server with following error:"),t);}}whenReady(){if(this.initialized)return this;let e={get:(t,r)=>{if(r==="then")return;let i=t[r];return typeof i=="function"?(...s)=>{let u=i.apply(t,s);if(u&&u.constructor.name==="ZormQueryBuilder")return this.wrapQueryBuilder(u);this._init().then(()=>u);}:i}};return new Proxy(this,e)}wrapQueryBuilder(e){let t={get:(r,i)=>{if(i==="then")return;let s=r[i];return typeof s=="function"?(...u)=>{let a=s.apply(r,u);return a&&a.constructor.name==="ZormQueryBuilder"?this.wrapQueryBuilder(a):this._init().then(()=>a)}:s}};return new Proxy(e,t)}getQueryBuilder(e,t){let r=this.getRepository(e);switch(this.dataSource.options.type){case "mysql":case "mariadb":case "postgres":case "sqlite":case "mssql":case "oracle":return new x(r,t,this.usePromise);case "mongodb":throw new Error("MongoDB does not support QueryBuilder. Use repository methods instead.");default:throw new Error(`Unsupported database type: ${this.dataSource.options.type}`)}}getRepository(e){return this.dataSource.getRepository(e)}create(e){return this.getQueryBuilder(e,"create")}find(e){return this.getQueryBuilder(e,"select")}update(e){return this.getQueryBuilder(e,"update")}delete(e){return this.getQueryBuilder(e,"delete")}},oe=B;export{oe as default};
|