@zuzjs/orm 0.3.8 → 0.3.9
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 +2 -2
- package/dist/bin.js +1 -1
- package/dist/chunk-PCRKWOPW.cjs +17 -0
- package/dist/chunk-W6M2RAX7.js +16 -0
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +13 -4
- package/dist/index.d.ts +13 -4
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-3TCXY5YG.js +0 -16
- package/dist/chunk-ZWZYE56D.cjs +0 -17
package/dist/bin.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';var
|
|
3
|
-
var d=
|
|
2
|
+
'use strict';var chunkPCRKWOPW_cjs=require('./chunk-PCRKWOPW.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=chunkPCRKWOPW_cjs.a((D,f)=>{f.exports={name:"@zuzjs/orm",version:"0.3.8",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=chunkPCRKWOPW_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 chunkPCRKWOPW_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,
|
|
2
|
+
import {a,b,g}from'./chunk-W6M2RAX7.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.8",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();
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
'use strict';var A=require('fs'),H=require('mysql2/promise'),P=require('path'),f=require('picocolors');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var A__default=/*#__PURE__*/_interopDefault(A);var H__default=/*#__PURE__*/_interopDefault(H);var P__default=/*#__PURE__*/_interopDefault(P);var f__default=/*#__PURE__*/_interopDefault(f);/* ZuzJS ORM (ZORM) */
|
|
2
|
+
var V=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports);var p=r=>r.replace(/(^\w|_\w)/g,t=>t.replace("_","").toUpperCase());var v=(r,t)=>{try{if(!A__default.default.existsSync(r))if(t)A__default.default.mkdirSync(r,{recursive:!0});else return {access:!1,message:`${r} does not exist.
|
|
3
|
+
Run \`zorm -c [DATABASE_CONNECTION_STRING]\``};if(!A__default.default.statSync(r).isDirectory())return {access:!1,message:`${r} is not a folder.`};try{A__default.default.accessSync(r,A__default.default.constants.W_OK);}catch{return {access:!1,message:`${r} has no write permission.`}}return {access:!0}}catch{return {access:false,message:"Destination folder is not accessible"}}},J=(r,...t)=>{let c=[new Error([r,...t].join(" ")).message];return Error(c.join(`
|
|
4
|
+
`))},F=r=>/^[+-]?\d+(\.\d+)?$/.test(r);var B=class{to(t){return t==null?null:t?1:0}from(t){return t==null?null:t===1}},W=class{to(t){return t!=null?String(t):null}from(t){return t!=null?String(t):null}},it={ER_DUP_ENTRY:"DuplicateEntry",ER_NO_REFERENCED_ROW:"ForeignKeyConstraintFails",ER_NO_REFERENCED_ROW_2:"ForeignKeyConstraintFails",ER_BAD_NULL_ERROR:"NullValueNotAllowed",ER_PARSE_ERROR:"SQLSyntaxError",ER_ACCESS_DENIED_ERROR:"AccessDenied",ER_TABLE_EXISTS_ERROR:"TableAlreadyExists",ER_NO_SUCH_TABLE:"TableNotFound",ER_LOCK_WAIT_TIMEOUT:"LockWaitTimeout",ER_LOCK_DEADLOCK:"DeadlockDetected",ER_DATA_TOO_LONG:"DataTooLong",ER_TRUNCATED_WRONG_VALUE:"InvalidDataFormat",ER_WRONG_VALUE_COUNT_ON_ROW:"WrongValueCount",ER_CANT_CREATE_TABLE:"TableCreationFailed",ER_CANT_DROP_FIELD_OR_KEY:"CannotDropKey",ER_ROW_IS_REFERENCED:"RowReferenced",ER_ROW_IS_REFERENCED_2:"RowReferenced",ER_PRIMARY_CANT_HAVE_NULL:"PrimaryKeyCannotBeNull",ER_KEY_COLUMN_DOES_NOT_EXITS:"KeyColumnNotFound",ER_UNKNOWN_COLUMN:"UnknownColumn",ER_WRONG_DB_NAME:"InvalidDatabaseName",ER_WRONG_TABLE_NAME:"InvalidTableName",ER_UNKNOWN_PROCEDURE:"ProcedureNotFound",ER_DUP_UNIQUE:"UniqueConstraintViolation",ER_SP_DOES_NOT_EXIST:"StoredProcedureNotFound",ER_BAD_FIELD_ERROR:"InvalidColumn"},j=class{pool;conn;dist;constructor(t,E){this.pool=null,this.dist=E||null,this.conn=this.parseConnectionString(t);}connection(){return this.conn}parseConnectionString=t=>{let E=/mysql:\/\/(?<user>[^:]+):(?<password>[^@]+)@(?<host>[^:/]+)(?::(?<port>\d+))?\/(?<database>[^?]+)(?:\?(?<params>.+))?/,c=t.match(E);if(!c||!c.groups)throw new Error("Invalid MySQL connection string");let{user:u,password:g,host:T,port:y,database:h,params:n}=c.groups,m=n?Object.fromEntries(new URLSearchParams(n)):{};return {user:u,password:g,host:T,port:y?Number(y):3306,database:h,params:m}};createPool(){if(!this.pool)try{this.pool=H__default.default.createPool({user:this.conn.user,password:this.conn.password,host:this.conn.host,port:this.conn.port,database:this.conn.database,...this.conn.params}),this.pool.getConnection().then(t=>{console.log(f__default.default.green("\u2713 MySQL Connected...")),t.release();}).catch(t=>{console.error(f__default.default.red("\u25CB Error while connecting to your MySQL Server with following error:"),t),process.exit(1);});}catch(t){console.error(f__default.default.red("\u25CB Error while connecting to your MySQL Server with following error:"),t),process.exit(1);}}mapColumns(t){let E={int:{tsType:"number",columnType:"int"},tinyint:{tsType:"boolean",columnType:"tinyint",transformer:"BooleanTransformer"},smallint:{tsType:"number",columnType:"smallint"},mediumint:{tsType:"number",columnType:"mediumint"},bigint:{tsType:"string",columnType:"bigint",transformer:"BigIntTransformer"},decimal:{tsType:"number",columnType:"decimal"},float:{tsType:"number",columnType:"float"},double:{tsType:"number",columnType:"double"},varchar:{tsType:"string",columnType:"varchar",length:255},char:{tsType:"string",columnType:"char",length:1},tinytext:{tsType:"string",columnType:"tinytext"},text:{tsType:"string",columnType:"text"},mediumtext:{tsType:"string",columnType:"mediumtext"},longtext:{tsType:"string",columnType:"longtext"},datetime:{tsType:"Date",columnType:"datetime"},timestamp:{tsType:"Date",columnType:"timestamp"},date:{tsType:"Date",columnType:"date"},time:{tsType:"string",columnType:"time"},json:{tsType:"any",columnType:"json"}},c=t.match(/^enum\((.*)\)$/i);if(c){let h=c[1].split(",").map(n=>n.trim().replace(/^'|'$/g,""));return {tsType:`"${h.join('" | "')}"`,columnType:"enum",enumValues:h}}let u=t.match(/^(\w+)(?:\((\d+)\))?/);if(!u)return {tsType:"any",columnType:"text"};let g=u[1].toLowerCase(),T=u[2]?parseInt(u[2],10):void 0,y=E[g]||{tsType:"any",columnType:g};return {...y,length:g.includes("char")?T||y.length:void 0}}formatDefault(t,E){return E==="number"?Number(t):E==="boolean"?t==="1"?"true":"false":`"${t}"`}async generate(){let t=this;t.createPool();console.log(f__default.default.cyan("\u25CB Extract Tables..."));let[c]=await t.pool.execute("SHOW TABLES");console.log(f__default.default.cyan(`\u25CB ${c.length} Tables Found.`));let u=c.map(n=>Object.values(n)[0]);console.log(f__default.default.yellow("\u25CB Generating Models..."));let g={};for(let n of u){let[m]=await this.pool.execute(`SELECT COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
|
|
5
|
+
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
|
|
6
|
+
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,[this.conn.database,n]);g[n]=m;}let T={};for(let[n,m]of Object.entries(g))for(let l of m){let e=l.REFERENCED_TABLE_NAME,d=l.COLUMN_NAME,s=`fk${p(e)}`;T[e]||(T[e]=[]),T[e].push({fkColumn:d,fkPropName:s,targetTable:n,targetEntity:p(n)});}let y={};for(let n of u){let[m]=await this.pool.execute(`SELECT COLUMN_NAME, COLUMN_KEY, EXTRA FROM INFORMATION_SCHEMA.COLUMNS
|
|
7
|
+
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?`,[this.conn.database,n]),l=g[String(n)]||[];if(l.length!==2||m.length!==2||m.filter($=>$.COLUMN_KEY!=="PRI").length>0)continue;let[e,d]=l,[s,C]=[e.REFERENCED_TABLE_NAME,d.REFERENCED_TABLE_NAME].sort(),M=`${s}_${C}`;y[M]||(y[M]={left:s,right:C,leftCol:e.COLUMN_NAME,rightCol:d.COLUMN_NAME});}for(let n of u){let m=[],l=[],e=["Entity","BaseEntity"],[d]=await this.pool.execute("SELECT COLUMN_NAME as `Field`, COLUMN_TYPE as `Type`, COLUMN_KEY as `Key`, IS_NULLABLE as `Null`, COLUMN_DEFAULT as `Default`, EXTRA as `Extra`, COLUMN_COMMENT as `Comment`\n FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION ASC",[this.conn.database,n]),s=[],C=false;for(let o of d){let{Field:i,Type:_,Key:R,Null:b,Default:L,Extra:K,Comment:S}=o,{tsType:D,columnType:U,length:w,enumValues:x,transformer:N}=this.mapColumns(_),O=null;if(U==="enum"&&x&&(O=p(i),m.push(`export enum ${O} { ${x.map(a=>`${F(a)?`val${a}`:p(a)} = "${a}"`).join(", ")} }`)),R==="PRI"){let a=K.includes("auto_increment")?"PrimaryGeneratedColumn":"PrimaryColumn";e.includes(a)||e.push(a),N?(e.includes(N)||e.push(N),s.push(` @${a}({ transformer: new ${N}() })`)):s.push(` @${a}()`),C=true;}else {e.includes("Column")||e.push("Column");let a=[`type: "${U}"`];w&&a.push(`length: ${w}`),b==="YES"&&a.push("nullable: true"),O&&a.push(`enum: ${O}`),L!==null&&a.push(`default: ${this.formatDefault(L,D)}`),N&&(e.includes(N)||e.push(N),a.push(`transformer: new ${N}()`)),s.push(` @Column({ ${a.join(", ")} })`);}S&&S.length>0&&s.push(` /** @comment ${S} */`);let G=O||D;s.push(` ${i}!: ${G};
|
|
8
|
+
`);}if(g[n])for(let o of g[n]||[]){let i=p(o.REFERENCED_TABLE_NAME);l.includes(`import { ${i} } from "./${o.REFERENCED_TABLE_NAME}";`)===false&&(s.push(` @OneToOne(() => ${i})`),s.push(` @JoinColumn({ name: "${o.COLUMN_NAME}" })`),s.push(` fk${i}!: ${i};
|
|
9
|
+
`),l.push(`import { ${i} } from "./${o.REFERENCED_TABLE_NAME}";`),e.includes("OneToOne")||e.push("OneToOne"),e.includes("JoinColumn")||e.push("JoinColumn"));}let M=T[String(n)]||[];for(let o of M){let i=o.targetTable.endsWith("s")?o.targetTable:`${o.targetTable}s`;if(s.some(R=>R.includes(` ${i}!:`)))continue;let _=`import { ${o.targetEntity} } from "./${o.targetTable}";`;l.includes(_)||l.push(_),e.includes("OneToMany")||e.push("OneToMany"),s.push(` @OneToMany(() => ${o.targetEntity}, r => r.${o.fkPropName})`),s.push(` fk${p(i)}!: ${o.targetEntity}[];
|
|
10
|
+
`);}let $=Object.values(y).filter(o=>o.left===n||o.right===n);for(let o of $){let i=o.left===n?o.right:o.left,_=p(i),R=i.endsWith("s")?i:`${i}s`;if(s.some(L=>L.includes(`@${R}`)))continue;let b=`import { ${_} } from "./${i}";`;l.includes(b)||l.push(b),e.includes("ManyToMany")||e.push("ManyToMany"),e.includes("JoinTable")||e.push("JoinTable"),s.push(` @ManyToMany(() => ${_})`),s.push(" @JoinTable()"),s.push(` om${R}!: ${_}[];
|
|
11
|
+
`);}let k=["/**","* AutoGenerated by @zuzjs/orm.",`* @ ${new Date().toString().split(" GMT")[0].trim()}`,"*/",`import { ${e.join(", ")} } from "@zuzjs/orm";`,l.length>0?l.join(`
|
|
12
|
+
`):"",m.length>0?m.join(`
|
|
13
|
+
`):"",`${m.length>0||l.length>0?`
|
|
14
|
+
`:""}@Entity({ name: "${n}" })`,`export class ${p(n)} extends BaseEntity {
|
|
15
|
+
`,...s,"}"];C||console.log(f__default.default.bgRed(f__default.default.whiteBright(" WARNING ")),f__default.default.yellow(`\u25CB "${n}" does not have a primary column. Primary column is required.`)),A__default.default.writeFileSync(P__default.default.join(this.dist,`${n}.ts`),k.join(`
|
|
16
|
+
`));}let h=u.map(n=>`import { ${p(n)} } from "./${n}";`);h.push('import Zorm from "@zuzjs/orm";','import de from "dotenv";',"de.config()",`const zormEntities = [${u.map(n=>p(n)).join(", ")}];`,"const zorm = Zorm.get("," process.env.DATABASE_URL!,"," zormEntities",");","zorm.connect(zormEntities);","export default zorm",`export { ${u.map(n=>p(n)).join(", ")} }`),A__default.default.writeFileSync(P__default.default.join(this.dist,"index.ts"),h.join(`
|
|
17
|
+
`)),await t.pool.end(),console.log(f__default.default.green(`\u2713 ${c.length} Tables Processed.`));}};exports.a=V;exports.b=v;exports.c=J;exports.d=B;exports.e=W;exports.f=it;exports.g=j;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import A from'fs';import V from'mysql2/promise';import P from'path';import f from'picocolors';var Y=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports);var p=r=>r.replace(/(^\w|_\w)/g,t=>t.replace("_","").toUpperCase());var J=(r,t)=>{try{if(!A.existsSync(r))if(t)A.mkdirSync(r,{recursive:!0});else return {access:!1,message:`${r} does not exist.
|
|
2
|
+
Run \`zorm -c [DATABASE_CONNECTION_STRING]\``};if(!A.statSync(r).isDirectory())return {access:!1,message:`${r} is not a folder.`};try{A.accessSync(r,A.constants.W_OK);}catch{return {access:!1,message:`${r} has no write permission.`}}return {access:!0}}catch{return {access:false,message:"Destination folder is not accessible"}}},X=(r,...t)=>{let c=[new Error([r,...t].join(" ")).message];return Error(c.join(`
|
|
3
|
+
`))},F=r=>/^[+-]?\d+(\.\d+)?$/.test(r);var B=class{to(t){return t==null?null:t?1:0}from(t){return t==null?null:t===1}},W=class{to(t){return t!=null?String(t):null}from(t){return t!=null?String(t):null}},at={ER_DUP_ENTRY:"DuplicateEntry",ER_NO_REFERENCED_ROW:"ForeignKeyConstraintFails",ER_NO_REFERENCED_ROW_2:"ForeignKeyConstraintFails",ER_BAD_NULL_ERROR:"NullValueNotAllowed",ER_PARSE_ERROR:"SQLSyntaxError",ER_ACCESS_DENIED_ERROR:"AccessDenied",ER_TABLE_EXISTS_ERROR:"TableAlreadyExists",ER_NO_SUCH_TABLE:"TableNotFound",ER_LOCK_WAIT_TIMEOUT:"LockWaitTimeout",ER_LOCK_DEADLOCK:"DeadlockDetected",ER_DATA_TOO_LONG:"DataTooLong",ER_TRUNCATED_WRONG_VALUE:"InvalidDataFormat",ER_WRONG_VALUE_COUNT_ON_ROW:"WrongValueCount",ER_CANT_CREATE_TABLE:"TableCreationFailed",ER_CANT_DROP_FIELD_OR_KEY:"CannotDropKey",ER_ROW_IS_REFERENCED:"RowReferenced",ER_ROW_IS_REFERENCED_2:"RowReferenced",ER_PRIMARY_CANT_HAVE_NULL:"PrimaryKeyCannotBeNull",ER_KEY_COLUMN_DOES_NOT_EXITS:"KeyColumnNotFound",ER_UNKNOWN_COLUMN:"UnknownColumn",ER_WRONG_DB_NAME:"InvalidDatabaseName",ER_WRONG_TABLE_NAME:"InvalidTableName",ER_UNKNOWN_PROCEDURE:"ProcedureNotFound",ER_DUP_UNIQUE:"UniqueConstraintViolation",ER_SP_DOES_NOT_EXIST:"StoredProcedureNotFound",ER_BAD_FIELD_ERROR:"InvalidColumn"},j=class{pool;conn;dist;constructor(t,E){this.pool=null,this.dist=E||null,this.conn=this.parseConnectionString(t);}connection(){return this.conn}parseConnectionString=t=>{let E=/mysql:\/\/(?<user>[^:]+):(?<password>[^@]+)@(?<host>[^:/]+)(?::(?<port>\d+))?\/(?<database>[^?]+)(?:\?(?<params>.+))?/,c=t.match(E);if(!c||!c.groups)throw new Error("Invalid MySQL connection string");let{user:u,password:g,host:T,port:y,database:h,params:n}=c.groups,m=n?Object.fromEntries(new URLSearchParams(n)):{};return {user:u,password:g,host:T,port:y?Number(y):3306,database:h,params:m}};createPool(){if(!this.pool)try{this.pool=V.createPool({user:this.conn.user,password:this.conn.password,host:this.conn.host,port:this.conn.port,database:this.conn.database,...this.conn.params}),this.pool.getConnection().then(t=>{console.log(f.green("\u2713 MySQL Connected...")),t.release();}).catch(t=>{console.error(f.red("\u25CB Error while connecting to your MySQL Server with following error:"),t),process.exit(1);});}catch(t){console.error(f.red("\u25CB Error while connecting to your MySQL Server with following error:"),t),process.exit(1);}}mapColumns(t){let E={int:{tsType:"number",columnType:"int"},tinyint:{tsType:"boolean",columnType:"tinyint",transformer:"BooleanTransformer"},smallint:{tsType:"number",columnType:"smallint"},mediumint:{tsType:"number",columnType:"mediumint"},bigint:{tsType:"string",columnType:"bigint",transformer:"BigIntTransformer"},decimal:{tsType:"number",columnType:"decimal"},float:{tsType:"number",columnType:"float"},double:{tsType:"number",columnType:"double"},varchar:{tsType:"string",columnType:"varchar",length:255},char:{tsType:"string",columnType:"char",length:1},tinytext:{tsType:"string",columnType:"tinytext"},text:{tsType:"string",columnType:"text"},mediumtext:{tsType:"string",columnType:"mediumtext"},longtext:{tsType:"string",columnType:"longtext"},datetime:{tsType:"Date",columnType:"datetime"},timestamp:{tsType:"Date",columnType:"timestamp"},date:{tsType:"Date",columnType:"date"},time:{tsType:"string",columnType:"time"},json:{tsType:"any",columnType:"json"}},c=t.match(/^enum\((.*)\)$/i);if(c){let h=c[1].split(",").map(n=>n.trim().replace(/^'|'$/g,""));return {tsType:`"${h.join('" | "')}"`,columnType:"enum",enumValues:h}}let u=t.match(/^(\w+)(?:\((\d+)\))?/);if(!u)return {tsType:"any",columnType:"text"};let g=u[1].toLowerCase(),T=u[2]?parseInt(u[2],10):void 0,y=E[g]||{tsType:"any",columnType:g};return {...y,length:g.includes("char")?T||y.length:void 0}}formatDefault(t,E){return E==="number"?Number(t):E==="boolean"?t==="1"?"true":"false":`"${t}"`}async generate(){let t=this;t.createPool();console.log(f.cyan("\u25CB Extract Tables..."));let[c]=await t.pool.execute("SHOW TABLES");console.log(f.cyan(`\u25CB ${c.length} Tables Found.`));let u=c.map(n=>Object.values(n)[0]);console.log(f.yellow("\u25CB Generating Models..."));let g={};for(let n of u){let[m]=await this.pool.execute(`SELECT COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
|
|
4
|
+
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
|
|
5
|
+
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,[this.conn.database,n]);g[n]=m;}let T={};for(let[n,m]of Object.entries(g))for(let l of m){let e=l.REFERENCED_TABLE_NAME,d=l.COLUMN_NAME,s=`fk${p(e)}`;T[e]||(T[e]=[]),T[e].push({fkColumn:d,fkPropName:s,targetTable:n,targetEntity:p(n)});}let y={};for(let n of u){let[m]=await this.pool.execute(`SELECT COLUMN_NAME, COLUMN_KEY, EXTRA FROM INFORMATION_SCHEMA.COLUMNS
|
|
6
|
+
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?`,[this.conn.database,n]),l=g[String(n)]||[];if(l.length!==2||m.length!==2||m.filter($=>$.COLUMN_KEY!=="PRI").length>0)continue;let[e,d]=l,[s,C]=[e.REFERENCED_TABLE_NAME,d.REFERENCED_TABLE_NAME].sort(),M=`${s}_${C}`;y[M]||(y[M]={left:s,right:C,leftCol:e.COLUMN_NAME,rightCol:d.COLUMN_NAME});}for(let n of u){let m=[],l=[],e=["Entity","BaseEntity"],[d]=await this.pool.execute("SELECT COLUMN_NAME as `Field`, COLUMN_TYPE as `Type`, COLUMN_KEY as `Key`, IS_NULLABLE as `Null`, COLUMN_DEFAULT as `Default`, EXTRA as `Extra`, COLUMN_COMMENT as `Comment`\n FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION ASC",[this.conn.database,n]),s=[],C=false;for(let o of d){let{Field:i,Type:_,Key:R,Null:b,Default:L,Extra:K,Comment:S}=o,{tsType:D,columnType:U,length:w,enumValues:x,transformer:N}=this.mapColumns(_),O=null;if(U==="enum"&&x&&(O=p(i),m.push(`export enum ${O} { ${x.map(a=>`${F(a)?`val${a}`:p(a)} = "${a}"`).join(", ")} }`)),R==="PRI"){let a=K.includes("auto_increment")?"PrimaryGeneratedColumn":"PrimaryColumn";e.includes(a)||e.push(a),N?(e.includes(N)||e.push(N),s.push(` @${a}({ transformer: new ${N}() })`)):s.push(` @${a}()`),C=true;}else {e.includes("Column")||e.push("Column");let a=[`type: "${U}"`];w&&a.push(`length: ${w}`),b==="YES"&&a.push("nullable: true"),O&&a.push(`enum: ${O}`),L!==null&&a.push(`default: ${this.formatDefault(L,D)}`),N&&(e.includes(N)||e.push(N),a.push(`transformer: new ${N}()`)),s.push(` @Column({ ${a.join(", ")} })`);}S&&S.length>0&&s.push(` /** @comment ${S} */`);let G=O||D;s.push(` ${i}!: ${G};
|
|
7
|
+
`);}if(g[n])for(let o of g[n]||[]){let i=p(o.REFERENCED_TABLE_NAME);l.includes(`import { ${i} } from "./${o.REFERENCED_TABLE_NAME}";`)===false&&(s.push(` @OneToOne(() => ${i})`),s.push(` @JoinColumn({ name: "${o.COLUMN_NAME}" })`),s.push(` fk${i}!: ${i};
|
|
8
|
+
`),l.push(`import { ${i} } from "./${o.REFERENCED_TABLE_NAME}";`),e.includes("OneToOne")||e.push("OneToOne"),e.includes("JoinColumn")||e.push("JoinColumn"));}let M=T[String(n)]||[];for(let o of M){let i=o.targetTable.endsWith("s")?o.targetTable:`${o.targetTable}s`;if(s.some(R=>R.includes(` ${i}!:`)))continue;let _=`import { ${o.targetEntity} } from "./${o.targetTable}";`;l.includes(_)||l.push(_),e.includes("OneToMany")||e.push("OneToMany"),s.push(` @OneToMany(() => ${o.targetEntity}, r => r.${o.fkPropName})`),s.push(` fk${p(i)}!: ${o.targetEntity}[];
|
|
9
|
+
`);}let $=Object.values(y).filter(o=>o.left===n||o.right===n);for(let o of $){let i=o.left===n?o.right:o.left,_=p(i),R=i.endsWith("s")?i:`${i}s`;if(s.some(L=>L.includes(`@${R}`)))continue;let b=`import { ${_} } from "./${i}";`;l.includes(b)||l.push(b),e.includes("ManyToMany")||e.push("ManyToMany"),e.includes("JoinTable")||e.push("JoinTable"),s.push(` @ManyToMany(() => ${_})`),s.push(" @JoinTable()"),s.push(` om${R}!: ${_}[];
|
|
10
|
+
`);}let k=["/**","* AutoGenerated by @zuzjs/orm.",`* @ ${new Date().toString().split(" GMT")[0].trim()}`,"*/",`import { ${e.join(", ")} } from "@zuzjs/orm";`,l.length>0?l.join(`
|
|
11
|
+
`):"",m.length>0?m.join(`
|
|
12
|
+
`):"",`${m.length>0||l.length>0?`
|
|
13
|
+
`:""}@Entity({ name: "${n}" })`,`export class ${p(n)} extends BaseEntity {
|
|
14
|
+
`,...s,"}"];C||console.log(f.bgRed(f.whiteBright(" WARNING ")),f.yellow(`\u25CB "${n}" does not have a primary column. Primary column is required.`)),A.writeFileSync(P.join(this.dist,`${n}.ts`),k.join(`
|
|
15
|
+
`));}let h=u.map(n=>`import { ${p(n)} } from "./${n}";`);h.push('import Zorm from "@zuzjs/orm";','import de from "dotenv";',"de.config()",`const zormEntities = [${u.map(n=>p(n)).join(", ")}];`,"const zorm = Zorm.get("," process.env.DATABASE_URL!,"," zormEntities",");","zorm.connect(zormEntities);","export default zorm",`export { ${u.map(n=>p(n)).join(", ")} }`),A.writeFileSync(P.join(this.dist,"index.ts"),h.join(`
|
|
16
|
+
`)),await t.pool.end(),console.log(f.green(`\u2713 ${c.length} Tables Processed.`));}};export{Y as a,J as b,X as c,B as d,W as e,at as f,j as g};
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var
|
|
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 chunkZWZYE56D_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 chunkZWZYE56D_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 chunkZWZYE56D_cjs.c("\u25CB Update must have at least one WHERE condition. You forgot to call .where({ condition: value })");else throw chunkZWZYE56D_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 chunkZWZYE56D_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:chunkZWZYE56D_cjs.d[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=chunkZWZYE56D_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 chunkZWZYE56D_cjs.e(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")}},ne=Q;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=ne;
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var chunkPCRKWOPW_cjs=require('./chunk-PCRKWOPW.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 chunkPCRKWOPW_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 chunkPCRKWOPW_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 chunkPCRKWOPW_cjs.c("\u25CB Update must have at least one WHERE condition. You forgot to call .where({ condition: value })");else throw chunkPCRKWOPW_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 chunkPCRKWOPW_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:chunkPCRKWOPW_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=chunkPCRKWOPW_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 chunkPCRKWOPW_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 chunkPCRKWOPW_cjs.e}});Object.defineProperty(exports,"BooleanTransformer",{enumerable:true,get:function(){return chunkPCRKWOPW_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
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { ObjectLiteral, Repository, MixedList, EntitySchema, EntityTarget } from 'typeorm';
|
|
1
|
+
import { ObjectLiteral, Repository, ValueTransformer, MixedList, EntitySchema, EntityTarget } from 'typeorm';
|
|
2
2
|
export { BaseEntity, Column, Entity, JoinColumn, ManyToMany, ManyToOne, OneToMany, OneToOne, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
|
|
3
3
|
import { QueryResult as QueryResult$1 } from 'mysql2';
|
|
4
4
|
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
|
|
5
5
|
|
|
6
|
-
type
|
|
6
|
+
type dynamic = {
|
|
7
7
|
[x: string]: any;
|
|
8
8
|
};
|
|
9
9
|
interface ModelGenerator {
|
|
@@ -17,7 +17,7 @@ type ConnectionDetails = {
|
|
|
17
17
|
user: string;
|
|
18
18
|
password: string;
|
|
19
19
|
database: string;
|
|
20
|
-
params:
|
|
20
|
+
params: dynamic;
|
|
21
21
|
};
|
|
22
22
|
type QueryAction = "create" | "upsert" | "select" | "update" | "delete";
|
|
23
23
|
type QueryResult = InsertQueryResult | SelectQueryResult | UpdateQueryResult | DeleteQueryResult;
|
|
@@ -294,6 +294,15 @@ declare class ZormQueryBuilder<T extends ObjectLiteral, R = QueryResult$1> exten
|
|
|
294
294
|
then<TResult1 = R, TResult2 = never>(onfulfilled?: ((value: R) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
|
|
295
295
|
}
|
|
296
296
|
|
|
297
|
+
declare class BooleanTransformer implements ValueTransformer {
|
|
298
|
+
to(value: boolean | null): number | null;
|
|
299
|
+
from(value: number | null): boolean | null;
|
|
300
|
+
}
|
|
301
|
+
declare class BigIntTransformer implements ValueTransformer {
|
|
302
|
+
to(value: string | bigint | null): string | null;
|
|
303
|
+
from(value: string | number | null): string | null;
|
|
304
|
+
}
|
|
305
|
+
|
|
297
306
|
/**
|
|
298
307
|
* Zorm is a lightweight ORM wrapper around TypeORM with support for MySQL.
|
|
299
308
|
*/
|
|
@@ -383,4 +392,4 @@ declare class Zorm {
|
|
|
383
392
|
delete<T extends ObjectLiteral>(entity: EntityTarget<T>): ZormQueryBuilder<T, DeleteQueryResult>;
|
|
384
393
|
}
|
|
385
394
|
|
|
386
|
-
export { type ConnectionDetails, type DeleteQueryResult, type InsertQueryResult, type ModelGenerator, type PartialConditions, type QueryAction, type QueryError, type QueryResult, type SelectQueryResult, type UpdateQueryResult, type WhereOperators, Zorm as default, type
|
|
395
|
+
export { BigIntTransformer, BooleanTransformer, type ConnectionDetails, type DeleteQueryResult, type InsertQueryResult, type ModelGenerator, type PartialConditions, type QueryAction, type QueryError, type QueryResult, type SelectQueryResult, type UpdateQueryResult, type WhereOperators, Zorm as default, type dynamic };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { ObjectLiteral, Repository, MixedList, EntitySchema, EntityTarget } from 'typeorm';
|
|
1
|
+
import { ObjectLiteral, Repository, ValueTransformer, MixedList, EntitySchema, EntityTarget } from 'typeorm';
|
|
2
2
|
export { BaseEntity, Column, Entity, JoinColumn, ManyToMany, ManyToOne, OneToMany, OneToOne, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
|
|
3
3
|
import { QueryResult as QueryResult$1 } from 'mysql2';
|
|
4
4
|
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
|
|
5
5
|
|
|
6
|
-
type
|
|
6
|
+
type dynamic = {
|
|
7
7
|
[x: string]: any;
|
|
8
8
|
};
|
|
9
9
|
interface ModelGenerator {
|
|
@@ -17,7 +17,7 @@ type ConnectionDetails = {
|
|
|
17
17
|
user: string;
|
|
18
18
|
password: string;
|
|
19
19
|
database: string;
|
|
20
|
-
params:
|
|
20
|
+
params: dynamic;
|
|
21
21
|
};
|
|
22
22
|
type QueryAction = "create" | "upsert" | "select" | "update" | "delete";
|
|
23
23
|
type QueryResult = InsertQueryResult | SelectQueryResult | UpdateQueryResult | DeleteQueryResult;
|
|
@@ -294,6 +294,15 @@ declare class ZormQueryBuilder<T extends ObjectLiteral, R = QueryResult$1> exten
|
|
|
294
294
|
then<TResult1 = R, TResult2 = never>(onfulfilled?: ((value: R) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
|
|
295
295
|
}
|
|
296
296
|
|
|
297
|
+
declare class BooleanTransformer implements ValueTransformer {
|
|
298
|
+
to(value: boolean | null): number | null;
|
|
299
|
+
from(value: number | null): boolean | null;
|
|
300
|
+
}
|
|
301
|
+
declare class BigIntTransformer implements ValueTransformer {
|
|
302
|
+
to(value: string | bigint | null): string | null;
|
|
303
|
+
from(value: string | number | null): string | null;
|
|
304
|
+
}
|
|
305
|
+
|
|
297
306
|
/**
|
|
298
307
|
* Zorm is a lightweight ORM wrapper around TypeORM with support for MySQL.
|
|
299
308
|
*/
|
|
@@ -383,4 +392,4 @@ declare class Zorm {
|
|
|
383
392
|
delete<T extends ObjectLiteral>(entity: EntityTarget<T>): ZormQueryBuilder<T, DeleteQueryResult>;
|
|
384
393
|
}
|
|
385
394
|
|
|
386
|
-
export { type ConnectionDetails, type DeleteQueryResult, type InsertQueryResult, type ModelGenerator, type PartialConditions, type QueryAction, type QueryError, type QueryResult, type SelectQueryResult, type UpdateQueryResult, type WhereOperators, Zorm as default, type
|
|
395
|
+
export { BigIntTransformer, BooleanTransformer, type ConnectionDetails, type DeleteQueryResult, type InsertQueryResult, type ModelGenerator, type PartialConditions, type QueryAction, type QueryError, type QueryResult, type SelectQueryResult, type UpdateQueryResult, type WhereOperators, Zorm as default, type dynamic };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b,e,c,d}from'./chunk-3TCXY5YG.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:d[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$1,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$1.startsWith("mysql")){let n=new e(decodeURIComponent(e$1)).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")}},ae=B;export{ae as default};
|
|
1
|
+
import {b,g,c,f as f$1}from'./chunk-W6M2RAX7.js';export{e as BigIntTransformer,d as BooleanTransformer}from'./chunk-W6M2RAX7.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};
|
package/package.json
CHANGED
package/dist/chunk-3TCXY5YG.js
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import O from'fs';import v from'mysql2/promise';import I from'path';import y from'picocolors';var G=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var g=i=>i.replace(/(^\w|_\w)/g,e=>e.replace("_","").toUpperCase());var Y=(i,e)=>{try{if(!O.existsSync(i))if(e)O.mkdirSync(i,{recursive:!0});else return {access:!1,message:`${i} does not exist.
|
|
2
|
-
Run \`zorm -c [DATABASE_CONNECTION_STRING]\``};if(!O.statSync(i).isDirectory())return {access:!1,message:`${i} is not a folder.`};try{O.accessSync(i,O.constants.W_OK);}catch{return {access:!1,message:`${i} has no write permission.`}}return {access:!0}}catch{return {access:false,message:"Destination folder is not accessible"}}},V=(i,...e)=>{let m=[new Error([i,...e].join(" ")).message];return Error(m.join(`
|
|
3
|
-
`))},x=i=>/^[+-]?\d+(\.\d+)?$/.test(i);var st={ER_DUP_ENTRY:"DuplicateEntry",ER_NO_REFERENCED_ROW:"ForeignKeyConstraintFails",ER_NO_REFERENCED_ROW_2:"ForeignKeyConstraintFails",ER_BAD_NULL_ERROR:"NullValueNotAllowed",ER_PARSE_ERROR:"SQLSyntaxError",ER_ACCESS_DENIED_ERROR:"AccessDenied",ER_TABLE_EXISTS_ERROR:"TableAlreadyExists",ER_NO_SUCH_TABLE:"TableNotFound",ER_LOCK_WAIT_TIMEOUT:"LockWaitTimeout",ER_LOCK_DEADLOCK:"DeadlockDetected",ER_DATA_TOO_LONG:"DataTooLong",ER_TRUNCATED_WRONG_VALUE:"InvalidDataFormat",ER_WRONG_VALUE_COUNT_ON_ROW:"WrongValueCount",ER_CANT_CREATE_TABLE:"TableCreationFailed",ER_CANT_DROP_FIELD_OR_KEY:"CannotDropKey",ER_ROW_IS_REFERENCED:"RowReferenced",ER_ROW_IS_REFERENCED_2:"RowReferenced",ER_PRIMARY_CANT_HAVE_NULL:"PrimaryKeyCannotBeNull",ER_KEY_COLUMN_DOES_NOT_EXITS:"KeyColumnNotFound",ER_UNKNOWN_COLUMN:"UnknownColumn",ER_WRONG_DB_NAME:"InvalidDatabaseName",ER_WRONG_TABLE_NAME:"InvalidTableName",ER_UNKNOWN_PROCEDURE:"ProcedureNotFound",ER_DUP_UNIQUE:"UniqueConstraintViolation",ER_SP_DOES_NOT_EXIST:"StoredProcedureNotFound",ER_BAD_FIELD_ERROR:"InvalidColumn"},P=class{pool;conn;dist;constructor(e,l){this.pool=null,this.dist=l||null,this.conn=this.parseConnectionString(e);}connection(){return this.conn}parseConnectionString=e=>{let l=/mysql:\/\/(?<user>[^:]+):(?<password>[^@]+)@(?<host>[^:/]+)(?::(?<port>\d+))?\/(?<database>[^?]+)(?:\?(?<params>.+))?/,m=e.match(l);if(!m||!m.groups)throw new Error("Invalid MySQL connection string");let{user:u,password:p,host:_,port:T,database:f,params:t}=m.groups,E=t?Object.fromEntries(new URLSearchParams(t)):{};return {user:u,password:p,host:_,port:T?Number(T):3306,database:f,params:E}};createPool(){if(!this.pool)try{this.pool=v.createPool({user:this.conn.user,password:this.conn.password,host:this.conn.host,port:this.conn.port,database:this.conn.database,...this.conn.params}),this.pool.getConnection().then(e=>{console.log(y.green("\u2713 MySQL Connected...")),e.release();}).catch(e=>{console.error(y.red("\u25CB Error while connecting to your MySQL Server with following error:"),e),process.exit(1);});}catch(e){console.error(y.red("\u25CB Error while connecting to your MySQL Server with following error:"),e),process.exit(1);}}mapColumns(e){let l={int:{tsType:"number",columnType:"int"},tinyint:{tsType:"boolean",columnType:"tinyint"},smallint:{tsType:"number",columnType:"smallint"},mediumint:{tsType:"number",columnType:"mediumint"},bigint:{tsType:"string",columnType:"bigint"},decimal:{tsType:"number",columnType:"decimal"},float:{tsType:"number",columnType:"float"},double:{tsType:"number",columnType:"double"},varchar:{tsType:"string",columnType:"varchar",length:255},char:{tsType:"string",columnType:"char",length:1},tinytext:{tsType:"string",columnType:"tinytext"},text:{tsType:"string",columnType:"text"},mediumtext:{tsType:"string",columnType:"mediumtext"},longtext:{tsType:"string",columnType:"longtext"},datetime:{tsType:"Date",columnType:"datetime"},timestamp:{tsType:"Date",columnType:"timestamp"},date:{tsType:"Date",columnType:"date"},time:{tsType:"string",columnType:"time"},json:{tsType:"any",columnType:"json"}},m=e.match(/^enum\((.*)\)$/i);if(m){let T=m[1].split(",").map(f=>f.trim().replace(/^'|'$/g,""));return {tsType:`"${T.join('" | "')}"`,columnType:"enum",enumValues:T}}let u=e.match(/^(\w+)(?:\((\d+)\))?/);if(!u)return {tsType:"any",columnType:"varchar",length:255};let p=u[1].toLowerCase(),_=u[2]?parseInt(u[2],10):void 0;return l[p]?{...l[p],length:_||l[p].length}:{tsType:"any",columnType:p||"varchar"}}formatDefault(e,l){return l==="number"?Number(e):l==="boolean"?e==="1"?"true":"false":`"${e}"`}async generate(){let e=this;e.createPool();console.log(y.cyan("\u25CB Extract Tables..."));let[m]=await e.pool.execute("SHOW TABLES");console.log(y.cyan(`\u25CB ${m.length} Tables Found.`));let u=m.map(t=>Object.values(t)[0]);console.log(y.yellow("\u25CB Generating Models..."));let p={};for(let t of u){let[E]=await this.pool.execute(`SELECT COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
|
|
4
|
-
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
|
|
5
|
-
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,[this.conn.database,t]);p[t]=E;}let _={};for(let[t,E]of Object.entries(p))for(let a of E){let n=a.REFERENCED_TABLE_NAME,h=a.COLUMN_NAME,s=`fk${g(n)}`;_[n]||(_[n]=[]),_[n].push({fkColumn:h,fkPropName:s,targetTable:t,targetEntity:g(t)});}let T={};for(let t of u){let[E]=await this.pool.execute(`SELECT COLUMN_NAME, COLUMN_KEY, EXTRA FROM INFORMATION_SCHEMA.COLUMNS
|
|
6
|
-
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?`,[this.conn.database,t]),a=p[String(t)]||[];if(a.length!==2||E.length!==2||E.filter(b=>b.COLUMN_KEY!=="PRI").length>0)continue;let[n,h]=a,[s,d]=[n.REFERENCED_TABLE_NAME,h.REFERENCED_TABLE_NAME].sort(),A=`${s}_${d}`;T[A]||(T[A]={left:s,right:d,leftCol:n.COLUMN_NAME,rightCol:h.COLUMN_NAME});}for(let t of u){let E=[],a=[],n=["Entity","BaseEntity"],[h]=await this.pool.execute("SELECT COLUMN_NAME as `Field`, COLUMN_TYPE as `Type`, COLUMN_KEY as `Key`, IS_NULLABLE as `Null`, COLUMN_DEFAULT as `Default`, EXTRA as `Extra`, COLUMN_COMMENT as `Comment`\n FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION ASC",[this.conn.database,t]),s=[],d=false;for(let o of h){let{Field:r,Type:N,Key:R,Null:M,Default:L,Extra:W,Comment:D}=o,{tsType:S,columnType:$,length:U,enumValues:w}=this.mapColumns(N),C=null;if($==="enum"&&w&&(C=g(r),E.push(`export enum ${C} { ${w.map(c=>`${x(c)?`val${c}`:g(c)} = "${c}"`).join(", ")} }`)),R==="PRI"){let c=W.includes("auto_increment")?"PrimaryGeneratedColumn":"PrimaryColumn";n.includes(c)||n.push(c),s.push(` @${c}()`),d=true;}else {let c=` @Column({ type: "${$}"`;n.includes("Column")||n.push("Column"),U&&(c+=`, length: ${U}`),M==="YES"&&(c+=", nullable: true"),C&&(c+=`, enum: ${C}`),L!==null&&(c+=`, default: ${this.formatDefault(L,S)}`),c+=" })",s.push(c);}D&&D.length>0&&s.push(` /** @comment ${D} */`);let j=C||S;s.push(` ${r}!: ${j};
|
|
7
|
-
`);}if(p[t])for(let o of p[t]||[]){let r=g(o.REFERENCED_TABLE_NAME);a.includes(`import { ${r} } from "./${o.REFERENCED_TABLE_NAME}";`)===false&&(s.push(` @OneToOne(() => ${r})`),s.push(` @JoinColumn({ name: "${o.COLUMN_NAME}" })`),s.push(` fk${r}!: ${r};
|
|
8
|
-
`),a.push(`import { ${r} } from "./${o.REFERENCED_TABLE_NAME}";`),n.includes("OneToOne")||n.push("OneToOne"),n.includes("JoinColumn")||n.push("JoinColumn"));}let A=_[String(t)]||[];for(let o of A){let r=o.targetTable.endsWith("s")?o.targetTable:`${o.targetTable}s`;if(s.some(R=>R.includes(` ${r}!:`)))continue;let N=`import { ${o.targetEntity} } from "./${o.targetTable}";`;a.includes(N)||a.push(N),n.includes("OneToMany")||n.push("OneToMany"),s.push(` @OneToMany(() => ${o.targetEntity}, r => r.${o.fkPropName})`),s.push(` fk${g(r)}!: ${o.targetEntity}[];
|
|
9
|
-
`);}let b=Object.values(T).filter(o=>o.left===t||o.right===t);for(let o of b){let r=o.left===t?o.right:o.left,N=g(r),R=r.endsWith("s")?r:`${r}s`;if(s.some(L=>L.includes(`@${R}`)))continue;let M=`import { ${N} } from "./${r}";`;a.includes(M)||a.push(M),n.includes("ManyToMany")||n.push("ManyToMany"),n.includes("JoinTable")||n.push("JoinTable"),s.push(` @ManyToMany(() => ${N})`),s.push(" @JoinTable()"),s.push(` om${R}!: ${N}[];
|
|
10
|
-
`);}let B=["/**","* AutoGenerated by @zuzjs/orm.",`* @ ${new Date().toString().split(" GMT")[0].trim()}`,"*/",`import { ${n.join(", ")} } from "@zuzjs/orm";`,a.length>0?a.join(`
|
|
11
|
-
`):"",E.length>0?E.join(`
|
|
12
|
-
`):"",`${E.length>0||a.length>0?`
|
|
13
|
-
`:""}@Entity({ name: "${t}" })`,`export class ${g(t)} extends BaseEntity {
|
|
14
|
-
`,...s,"}"];d||console.log(y.bgRed(y.whiteBright(" WARNING ")),y.yellow(`\u25CB "${t}" does not have a primary column. Primary column is required.`)),O.writeFileSync(I.join(this.dist,`${t}.ts`),B.join(`
|
|
15
|
-
`));}let f=u.map(t=>`import { ${g(t)} } from "./${t}";`);f.push('import Zorm from "@zuzjs/orm";','import de from "dotenv";',"de.config()",`const zormEntities = [${u.map(t=>g(t)).join(", ")}];`,"const zorm = Zorm.get("," process.env.DATABASE_URL!,"," zormEntities",");","zorm.connect(zormEntities);","export default zorm",`export { ${u.map(t=>g(t)).join(", ")} }`),O.writeFileSync(I.join(this.dist,"index.ts"),f.join(`
|
|
16
|
-
`)),await e.pool.end(),console.log(y.green(`\u2713 ${m.length} Tables Processed.`));}};export{G as a,Y as b,V as c,st as d,P as e};
|
package/dist/chunk-ZWZYE56D.cjs
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
'use strict';var O=require('fs'),K=require('mysql2/promise'),I=require('path'),y=require('picocolors');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var O__default=/*#__PURE__*/_interopDefault(O);var K__default=/*#__PURE__*/_interopDefault(K);var I__default=/*#__PURE__*/_interopDefault(I);var y__default=/*#__PURE__*/_interopDefault(y);/* ZuzJS ORM (ZORM) */
|
|
2
|
-
var v=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var g=i=>i.replace(/(^\w|_\w)/g,e=>e.replace("_","").toUpperCase());var H=(i,e)=>{try{if(!O__default.default.existsSync(i))if(e)O__default.default.mkdirSync(i,{recursive:!0});else return {access:!1,message:`${i} does not exist.
|
|
3
|
-
Run \`zorm -c [DATABASE_CONNECTION_STRING]\``};if(!O__default.default.statSync(i).isDirectory())return {access:!1,message:`${i} is not a folder.`};try{O__default.default.accessSync(i,O__default.default.constants.W_OK);}catch{return {access:!1,message:`${i} has no write permission.`}}return {access:!0}}catch{return {access:false,message:"Destination folder is not accessible"}}},Y=(i,...e)=>{let m=[new Error([i,...e].join(" ")).message];return Error(m.join(`
|
|
4
|
-
`))},x=i=>/^[+-]?\d+(\.\d+)?$/.test(i);var ot={ER_DUP_ENTRY:"DuplicateEntry",ER_NO_REFERENCED_ROW:"ForeignKeyConstraintFails",ER_NO_REFERENCED_ROW_2:"ForeignKeyConstraintFails",ER_BAD_NULL_ERROR:"NullValueNotAllowed",ER_PARSE_ERROR:"SQLSyntaxError",ER_ACCESS_DENIED_ERROR:"AccessDenied",ER_TABLE_EXISTS_ERROR:"TableAlreadyExists",ER_NO_SUCH_TABLE:"TableNotFound",ER_LOCK_WAIT_TIMEOUT:"LockWaitTimeout",ER_LOCK_DEADLOCK:"DeadlockDetected",ER_DATA_TOO_LONG:"DataTooLong",ER_TRUNCATED_WRONG_VALUE:"InvalidDataFormat",ER_WRONG_VALUE_COUNT_ON_ROW:"WrongValueCount",ER_CANT_CREATE_TABLE:"TableCreationFailed",ER_CANT_DROP_FIELD_OR_KEY:"CannotDropKey",ER_ROW_IS_REFERENCED:"RowReferenced",ER_ROW_IS_REFERENCED_2:"RowReferenced",ER_PRIMARY_CANT_HAVE_NULL:"PrimaryKeyCannotBeNull",ER_KEY_COLUMN_DOES_NOT_EXITS:"KeyColumnNotFound",ER_UNKNOWN_COLUMN:"UnknownColumn",ER_WRONG_DB_NAME:"InvalidDatabaseName",ER_WRONG_TABLE_NAME:"InvalidTableName",ER_UNKNOWN_PROCEDURE:"ProcedureNotFound",ER_DUP_UNIQUE:"UniqueConstraintViolation",ER_SP_DOES_NOT_EXIST:"StoredProcedureNotFound",ER_BAD_FIELD_ERROR:"InvalidColumn"},P=class{pool;conn;dist;constructor(e,l){this.pool=null,this.dist=l||null,this.conn=this.parseConnectionString(e);}connection(){return this.conn}parseConnectionString=e=>{let l=/mysql:\/\/(?<user>[^:]+):(?<password>[^@]+)@(?<host>[^:/]+)(?::(?<port>\d+))?\/(?<database>[^?]+)(?:\?(?<params>.+))?/,m=e.match(l);if(!m||!m.groups)throw new Error("Invalid MySQL connection string");let{user:u,password:p,host:_,port:T,database:f,params:t}=m.groups,E=t?Object.fromEntries(new URLSearchParams(t)):{};return {user:u,password:p,host:_,port:T?Number(T):3306,database:f,params:E}};createPool(){if(!this.pool)try{this.pool=K__default.default.createPool({user:this.conn.user,password:this.conn.password,host:this.conn.host,port:this.conn.port,database:this.conn.database,...this.conn.params}),this.pool.getConnection().then(e=>{console.log(y__default.default.green("\u2713 MySQL Connected...")),e.release();}).catch(e=>{console.error(y__default.default.red("\u25CB Error while connecting to your MySQL Server with following error:"),e),process.exit(1);});}catch(e){console.error(y__default.default.red("\u25CB Error while connecting to your MySQL Server with following error:"),e),process.exit(1);}}mapColumns(e){let l={int:{tsType:"number",columnType:"int"},tinyint:{tsType:"boolean",columnType:"tinyint"},smallint:{tsType:"number",columnType:"smallint"},mediumint:{tsType:"number",columnType:"mediumint"},bigint:{tsType:"string",columnType:"bigint"},decimal:{tsType:"number",columnType:"decimal"},float:{tsType:"number",columnType:"float"},double:{tsType:"number",columnType:"double"},varchar:{tsType:"string",columnType:"varchar",length:255},char:{tsType:"string",columnType:"char",length:1},tinytext:{tsType:"string",columnType:"tinytext"},text:{tsType:"string",columnType:"text"},mediumtext:{tsType:"string",columnType:"mediumtext"},longtext:{tsType:"string",columnType:"longtext"},datetime:{tsType:"Date",columnType:"datetime"},timestamp:{tsType:"Date",columnType:"timestamp"},date:{tsType:"Date",columnType:"date"},time:{tsType:"string",columnType:"time"},json:{tsType:"any",columnType:"json"}},m=e.match(/^enum\((.*)\)$/i);if(m){let T=m[1].split(",").map(f=>f.trim().replace(/^'|'$/g,""));return {tsType:`"${T.join('" | "')}"`,columnType:"enum",enumValues:T}}let u=e.match(/^(\w+)(?:\((\d+)\))?/);if(!u)return {tsType:"any",columnType:"varchar",length:255};let p=u[1].toLowerCase(),_=u[2]?parseInt(u[2],10):void 0;return l[p]?{...l[p],length:_||l[p].length}:{tsType:"any",columnType:p||"varchar"}}formatDefault(e,l){return l==="number"?Number(e):l==="boolean"?e==="1"?"true":"false":`"${e}"`}async generate(){let e=this;e.createPool();console.log(y__default.default.cyan("\u25CB Extract Tables..."));let[m]=await e.pool.execute("SHOW TABLES");console.log(y__default.default.cyan(`\u25CB ${m.length} Tables Found.`));let u=m.map(t=>Object.values(t)[0]);console.log(y__default.default.yellow("\u25CB Generating Models..."));let p={};for(let t of u){let[E]=await this.pool.execute(`SELECT COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
|
|
5
|
-
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
|
|
6
|
-
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,[this.conn.database,t]);p[t]=E;}let _={};for(let[t,E]of Object.entries(p))for(let a of E){let n=a.REFERENCED_TABLE_NAME,h=a.COLUMN_NAME,s=`fk${g(n)}`;_[n]||(_[n]=[]),_[n].push({fkColumn:h,fkPropName:s,targetTable:t,targetEntity:g(t)});}let T={};for(let t of u){let[E]=await this.pool.execute(`SELECT COLUMN_NAME, COLUMN_KEY, EXTRA FROM INFORMATION_SCHEMA.COLUMNS
|
|
7
|
-
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?`,[this.conn.database,t]),a=p[String(t)]||[];if(a.length!==2||E.length!==2||E.filter(b=>b.COLUMN_KEY!=="PRI").length>0)continue;let[n,h]=a,[s,d]=[n.REFERENCED_TABLE_NAME,h.REFERENCED_TABLE_NAME].sort(),A=`${s}_${d}`;T[A]||(T[A]={left:s,right:d,leftCol:n.COLUMN_NAME,rightCol:h.COLUMN_NAME});}for(let t of u){let E=[],a=[],n=["Entity","BaseEntity"],[h]=await this.pool.execute("SELECT COLUMN_NAME as `Field`, COLUMN_TYPE as `Type`, COLUMN_KEY as `Key`, IS_NULLABLE as `Null`, COLUMN_DEFAULT as `Default`, EXTRA as `Extra`, COLUMN_COMMENT as `Comment`\n FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION ASC",[this.conn.database,t]),s=[],d=false;for(let o of h){let{Field:r,Type:N,Key:R,Null:M,Default:L,Extra:W,Comment:D}=o,{tsType:S,columnType:$,length:U,enumValues:w}=this.mapColumns(N),C=null;if($==="enum"&&w&&(C=g(r),E.push(`export enum ${C} { ${w.map(c=>`${x(c)?`val${c}`:g(c)} = "${c}"`).join(", ")} }`)),R==="PRI"){let c=W.includes("auto_increment")?"PrimaryGeneratedColumn":"PrimaryColumn";n.includes(c)||n.push(c),s.push(` @${c}()`),d=true;}else {let c=` @Column({ type: "${$}"`;n.includes("Column")||n.push("Column"),U&&(c+=`, length: ${U}`),M==="YES"&&(c+=", nullable: true"),C&&(c+=`, enum: ${C}`),L!==null&&(c+=`, default: ${this.formatDefault(L,S)}`),c+=" })",s.push(c);}D&&D.length>0&&s.push(` /** @comment ${D} */`);let j=C||S;s.push(` ${r}!: ${j};
|
|
8
|
-
`);}if(p[t])for(let o of p[t]||[]){let r=g(o.REFERENCED_TABLE_NAME);a.includes(`import { ${r} } from "./${o.REFERENCED_TABLE_NAME}";`)===false&&(s.push(` @OneToOne(() => ${r})`),s.push(` @JoinColumn({ name: "${o.COLUMN_NAME}" })`),s.push(` fk${r}!: ${r};
|
|
9
|
-
`),a.push(`import { ${r} } from "./${o.REFERENCED_TABLE_NAME}";`),n.includes("OneToOne")||n.push("OneToOne"),n.includes("JoinColumn")||n.push("JoinColumn"));}let A=_[String(t)]||[];for(let o of A){let r=o.targetTable.endsWith("s")?o.targetTable:`${o.targetTable}s`;if(s.some(R=>R.includes(` ${r}!:`)))continue;let N=`import { ${o.targetEntity} } from "./${o.targetTable}";`;a.includes(N)||a.push(N),n.includes("OneToMany")||n.push("OneToMany"),s.push(` @OneToMany(() => ${o.targetEntity}, r => r.${o.fkPropName})`),s.push(` fk${g(r)}!: ${o.targetEntity}[];
|
|
10
|
-
`);}let b=Object.values(T).filter(o=>o.left===t||o.right===t);for(let o of b){let r=o.left===t?o.right:o.left,N=g(r),R=r.endsWith("s")?r:`${r}s`;if(s.some(L=>L.includes(`@${R}`)))continue;let M=`import { ${N} } from "./${r}";`;a.includes(M)||a.push(M),n.includes("ManyToMany")||n.push("ManyToMany"),n.includes("JoinTable")||n.push("JoinTable"),s.push(` @ManyToMany(() => ${N})`),s.push(" @JoinTable()"),s.push(` om${R}!: ${N}[];
|
|
11
|
-
`);}let B=["/**","* AutoGenerated by @zuzjs/orm.",`* @ ${new Date().toString().split(" GMT")[0].trim()}`,"*/",`import { ${n.join(", ")} } from "@zuzjs/orm";`,a.length>0?a.join(`
|
|
12
|
-
`):"",E.length>0?E.join(`
|
|
13
|
-
`):"",`${E.length>0||a.length>0?`
|
|
14
|
-
`:""}@Entity({ name: "${t}" })`,`export class ${g(t)} extends BaseEntity {
|
|
15
|
-
`,...s,"}"];d||console.log(y__default.default.bgRed(y__default.default.whiteBright(" WARNING ")),y__default.default.yellow(`\u25CB "${t}" does not have a primary column. Primary column is required.`)),O__default.default.writeFileSync(I__default.default.join(this.dist,`${t}.ts`),B.join(`
|
|
16
|
-
`));}let f=u.map(t=>`import { ${g(t)} } from "./${t}";`);f.push('import Zorm from "@zuzjs/orm";','import de from "dotenv";',"de.config()",`const zormEntities = [${u.map(t=>g(t)).join(", ")}];`,"const zorm = Zorm.get("," process.env.DATABASE_URL!,"," zormEntities",");","zorm.connect(zormEntities);","export default zorm",`export { ${u.map(t=>g(t)).join(", ")} }`),O__default.default.writeFileSync(I__default.default.join(this.dist,"index.ts"),f.join(`
|
|
17
|
-
`)),await e.pool.end(),console.log(y__default.default.green(`\u2713 ${m.length} Tables Processed.`));}};exports.a=v;exports.b=H;exports.c=Y;exports.d=ot;exports.e=P;
|