@zuzjs/orm 0.3.6 → 0.3.8
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 +4 -0
- package/dist/bin.d.cts +1 -0
- package/dist/bin.d.ts +0 -1
- package/dist/bin.js +2 -25
- package/dist/chunk-3TCXY5YG.js +16 -0
- package/dist/chunk-ZWZYE56D.cjs +17 -0
- package/dist/index.cjs +2 -0
- package/dist/index.d.cts +386 -0
- package/dist/index.d.ts +303 -8
- package/dist/index.js +1 -183
- package/package.json +56 -48
- package/dist/core/cli.d.ts +0 -5
- package/dist/core/cli.js +0 -78
- package/dist/core/index.d.ts +0 -8
- package/dist/core/index.js +0 -72
- package/dist/drivers/expressionBuilder.d.ts +0 -32
- package/dist/drivers/expressionBuilder.js +0 -100
- package/dist/drivers/mysql/index.d.ts +0 -39
- package/dist/drivers/mysql/index.js +0 -336
- package/dist/drivers/queryBuilder.d.ts +0 -162
- package/dist/drivers/queryBuilder.js +0 -518
- package/dist/types.d.ts +0 -104
- package/dist/types.js +0 -14
package/dist/bin.cjs
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';var chunkZWZYE56D_cjs=require('./chunk-ZWZYE56D.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=chunkZWZYE56D_cjs.a((D,f)=>{f.exports={name:"@zuzjs/orm",version:"0.3.7",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=chunkZWZYE56D_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 chunkZWZYE56D_cjs.e(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
|
+
`).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.d.cts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
package/dist/bin.d.ts
CHANGED
package/dist/bin.js
CHANGED
|
@@ -1,26 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"
|
|
3
|
-
|
|
4
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
5
|
-
};
|
|
6
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
-
const commander_1 = require("commander");
|
|
8
|
-
const cli_js_1 = require("./core/cli.js");
|
|
9
|
-
const picocolors_1 = __importDefault(require("picocolors"));
|
|
10
|
-
commander_1.program
|
|
11
|
-
.name("zorm")
|
|
12
|
-
.description("ZuzORM is a lightweight ORM wrapper around TypeORM with support for MySQL.");
|
|
13
|
-
/**Version */
|
|
14
|
-
commander_1.program
|
|
15
|
-
.option(`-v, --version`)
|
|
16
|
-
.description("Displays current version of ZuzORM")
|
|
17
|
-
.action(() => {
|
|
18
|
-
const packageJson = require("../package.json");
|
|
19
|
-
console.log(picocolors_1.default.cyan(`ZuzORM v${packageJson.version}`));
|
|
20
|
-
process.exit(1);
|
|
21
|
-
});
|
|
22
|
-
commander_1.program
|
|
23
|
-
.command(`pull`)
|
|
24
|
-
.description(`Pull using DATABASE_URL from .env in project directory`)
|
|
25
|
-
.action(cli_js_1.Pull);
|
|
26
|
-
commander_1.program.parse();
|
|
2
|
+
import {a,b,e}from'./chunk-3TCXY5YG.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.7",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$1,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$1.startsWith("mysql")?new e(decodeURIComponent(e$1),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
|
+
`).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,16 @@
|
|
|
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};
|
|
@@ -0,0 +1,17 @@
|
|
|
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;
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var chunkZWZYE56D_cjs=require('./chunk-ZWZYE56D.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 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;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import { ObjectLiteral, Repository, MixedList, EntitySchema, EntityTarget } from 'typeorm';
|
|
2
|
+
export { BaseEntity, Column, Entity, JoinColumn, ManyToMany, ManyToOne, OneToMany, OneToOne, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
|
|
3
|
+
import { QueryResult as QueryResult$1 } from 'mysql2';
|
|
4
|
+
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
|
|
5
|
+
|
|
6
|
+
type dynamicObject = {
|
|
7
|
+
[x: string]: any;
|
|
8
|
+
};
|
|
9
|
+
interface ModelGenerator {
|
|
10
|
+
generate: () => void;
|
|
11
|
+
connection: () => ConnectionDetails;
|
|
12
|
+
mapColumns: (sqlType: string) => void;
|
|
13
|
+
}
|
|
14
|
+
type ConnectionDetails = {
|
|
15
|
+
host: string;
|
|
16
|
+
port: string | number;
|
|
17
|
+
user: string;
|
|
18
|
+
password: string;
|
|
19
|
+
database: string;
|
|
20
|
+
params: dynamicObject;
|
|
21
|
+
};
|
|
22
|
+
type QueryAction = "create" | "upsert" | "select" | "update" | "delete";
|
|
23
|
+
type QueryResult = InsertQueryResult | SelectQueryResult | UpdateQueryResult | DeleteQueryResult;
|
|
24
|
+
/**
|
|
25
|
+
* Defines supported comparison operators for filtering queries.
|
|
26
|
+
* Enables IntelliSense support in `.where()` conditions.
|
|
27
|
+
*
|
|
28
|
+
* @template T The type of the value being compared (e.g., number, string, Date).
|
|
29
|
+
*/
|
|
30
|
+
type WhereOperators<T> = {
|
|
31
|
+
/**
|
|
32
|
+
* Greater than (`>`) operator.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* query.where({ age: { gt: 18 } }) // WHERE age > 18
|
|
36
|
+
*/
|
|
37
|
+
gt?: T;
|
|
38
|
+
/**
|
|
39
|
+
* Greater than or equal to (`>=`) operator.
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* query.where({ price: { gte: 100 } }) // WHERE price >= 100
|
|
43
|
+
*/
|
|
44
|
+
gte?: T;
|
|
45
|
+
/**
|
|
46
|
+
* Less than (`<`) operator.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* query.where({ age: { lt: 30 } }) // WHERE age < 30
|
|
50
|
+
*/
|
|
51
|
+
lt?: T;
|
|
52
|
+
/**
|
|
53
|
+
* Less than or equal to (`<=`) operator.
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* query.where({ date: { lte: '2024-01-01' } }) // WHERE date <= '2024-01-01'
|
|
57
|
+
*/
|
|
58
|
+
lte?: T;
|
|
59
|
+
/**
|
|
60
|
+
* Not equal (`!=`) operator.
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* query.where({ status: { ne: 'inactive' } }) // WHERE status != 'inactive'
|
|
64
|
+
*/
|
|
65
|
+
ne?: T;
|
|
66
|
+
/**
|
|
67
|
+
* Equal (`=`) operator.
|
|
68
|
+
* This is typically unnecessary since `.where({ key: value })` already handles equality.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* query.where({ id: { eq: 1 } }) // WHERE id = 1
|
|
72
|
+
*/
|
|
73
|
+
eq?: T;
|
|
74
|
+
};
|
|
75
|
+
type PartialConditions<T> = Partial<Record<keyof T, string | number | boolean | WhereOperators<any>>>;
|
|
76
|
+
type QueryError = {
|
|
77
|
+
code: number | string;
|
|
78
|
+
message: string;
|
|
79
|
+
query: string;
|
|
80
|
+
values: string[];
|
|
81
|
+
};
|
|
82
|
+
type InsertQueryResult = {
|
|
83
|
+
created: boolean;
|
|
84
|
+
id?: number;
|
|
85
|
+
record?: ObjectLiteral;
|
|
86
|
+
records?: ObjectLiteral[];
|
|
87
|
+
error?: QueryError;
|
|
88
|
+
};
|
|
89
|
+
type SelectQueryResult = {
|
|
90
|
+
hasRows: boolean;
|
|
91
|
+
count?: number;
|
|
92
|
+
row?: any;
|
|
93
|
+
rows?: any[];
|
|
94
|
+
error?: QueryError;
|
|
95
|
+
save?: () => void;
|
|
96
|
+
};
|
|
97
|
+
type UpdateQueryResult = {
|
|
98
|
+
updated: boolean;
|
|
99
|
+
record?: ObjectLiteral;
|
|
100
|
+
records?: ObjectLiteral[];
|
|
101
|
+
error?: QueryError;
|
|
102
|
+
};
|
|
103
|
+
type DeleteQueryResult = {
|
|
104
|
+
deleted: boolean;
|
|
105
|
+
count: number;
|
|
106
|
+
error?: QueryError;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
declare class ZormExprBuilder<T extends ObjectLiteral> {
|
|
110
|
+
private _parts;
|
|
111
|
+
private _params;
|
|
112
|
+
private _paramIdx;
|
|
113
|
+
private _alias;
|
|
114
|
+
private static globalParamIdx;
|
|
115
|
+
constructor(alias?: string, parent?: {
|
|
116
|
+
params: Record<string, any>;
|
|
117
|
+
idx: number;
|
|
118
|
+
});
|
|
119
|
+
field(col: keyof T | string): this;
|
|
120
|
+
equals(value: any): this;
|
|
121
|
+
append(extra: string): this;
|
|
122
|
+
wrap(wrapper: (expr: string) => string): this;
|
|
123
|
+
exists(sub: (q: ZormExprBuilder<T>) => ZormExprBuilder<T>): this;
|
|
124
|
+
select(expr: string): this;
|
|
125
|
+
from(table: string, alias: string): this;
|
|
126
|
+
where(cond: Record<string, any>): this;
|
|
127
|
+
or(): this;
|
|
128
|
+
group(): this;
|
|
129
|
+
fromUnixTime(): this;
|
|
130
|
+
date(): this;
|
|
131
|
+
substring(column: keyof T | string, delimiter: string, index: number): this;
|
|
132
|
+
toExpression(): {
|
|
133
|
+
expression: string;
|
|
134
|
+
param: Record<string, any>;
|
|
135
|
+
};
|
|
136
|
+
buildExpression(): string;
|
|
137
|
+
buildParams(): Record<string, any>;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
declare class ZormQueryBuilder<T extends ObjectLiteral, R = QueryResult$1> extends Promise<R> {
|
|
141
|
+
private repository;
|
|
142
|
+
private queryBuilder;
|
|
143
|
+
private entityAlias;
|
|
144
|
+
private action;
|
|
145
|
+
private queryValues;
|
|
146
|
+
private usePromise;
|
|
147
|
+
private whereCount;
|
|
148
|
+
private isActiveRecord;
|
|
149
|
+
private activeRecord;
|
|
150
|
+
private joinedAliases;
|
|
151
|
+
constructor(repository: Repository<T>, _action: QueryAction, _usePromise?: boolean);
|
|
152
|
+
_create(): this;
|
|
153
|
+
upsert(): this;
|
|
154
|
+
_update(): this;
|
|
155
|
+
_delete(): this;
|
|
156
|
+
_getRawQuery(): [string, any[]];
|
|
157
|
+
active(): this;
|
|
158
|
+
_saveActiveRecord(activeRecord: T): Promise<T | null>;
|
|
159
|
+
clone(): ZormQueryBuilder<T, R>;
|
|
160
|
+
/**
|
|
161
|
+
* Sets the values for an insert or update query.
|
|
162
|
+
* @param data - The data to be inserted or updated.
|
|
163
|
+
* @returns The current instance of ZormQueryBuilder.
|
|
164
|
+
*/
|
|
165
|
+
with(data: QueryDeepPartialEntity<T> | QueryDeepPartialEntity<T[]>): this;
|
|
166
|
+
/**
|
|
167
|
+
* Sets the values for an insert or update query.
|
|
168
|
+
* @param data - The data to be inserted or updated.
|
|
169
|
+
* @returns The current instance of ZormQueryBuilder.
|
|
170
|
+
*/
|
|
171
|
+
withData(data: QueryDeepPartialEntity<T> | QueryDeepPartialEntity<T[]>): this;
|
|
172
|
+
/**
|
|
173
|
+
* Specifies the fields to be selected in a select query.
|
|
174
|
+
* @param fields - The fields to be selected.
|
|
175
|
+
* @returns The current instance of ZormQueryBuilder.
|
|
176
|
+
*/
|
|
177
|
+
select(fields: (keyof T)[]): this;
|
|
178
|
+
private applyCondition;
|
|
179
|
+
/**
|
|
180
|
+
* Adds a custom expression-based WHERE clause using a fluent builder.
|
|
181
|
+
* @param fn - A callback that receives a ZormExprBuilder and returns an expression + param.
|
|
182
|
+
*/
|
|
183
|
+
expression(exprFn: (q: ZormExprBuilder<T>) => ZormExprBuilder<T>,
|
|
184
|
+
/** Add parentheses group to built expression */
|
|
185
|
+
group?: boolean): this;
|
|
186
|
+
/**
|
|
187
|
+
* Adds a WHERE condition to the query.
|
|
188
|
+
* @param condition - The condition to be added.
|
|
189
|
+
* @returns The current instance of ZormQueryBuilder.
|
|
190
|
+
*/
|
|
191
|
+
where(condition: PartialConditions<T>): this;
|
|
192
|
+
/**
|
|
193
|
+
* Adds an OR condition to the query.
|
|
194
|
+
* @param condition - The condition to be added.
|
|
195
|
+
* @returns The current instance of ZormQueryBuilder.
|
|
196
|
+
*/
|
|
197
|
+
or(condition: PartialConditions<T>): this;
|
|
198
|
+
/**
|
|
199
|
+
* Adds an ORDER BY clause to the query.
|
|
200
|
+
* @param field - The field to order by.
|
|
201
|
+
* @param direction - The direction of the order (ASC or DESC).
|
|
202
|
+
* @returns The current instance of ZormQueryBuilder.
|
|
203
|
+
*/
|
|
204
|
+
orderBy(field: keyof T, direction?: "ASC" | "DESC"): this;
|
|
205
|
+
/**
|
|
206
|
+
* Adds a LIMIT clause to the query.
|
|
207
|
+
* @param n - The maximum number of records to return.
|
|
208
|
+
* @returns The current instance of ZormQueryBuilder.
|
|
209
|
+
*/
|
|
210
|
+
limit(n: number): this;
|
|
211
|
+
/**
|
|
212
|
+
* Adds an OFFSET clause to the query.
|
|
213
|
+
* @param n - The number of records to skip.
|
|
214
|
+
* @returns The current instance of ZormQueryBuilder.
|
|
215
|
+
*/
|
|
216
|
+
offset(n: number): this;
|
|
217
|
+
/**
|
|
218
|
+
* Adds relations to be included in the query.
|
|
219
|
+
* @param relations - The relations to be included.
|
|
220
|
+
* @returns The current instance of ZormQueryBuilder.
|
|
221
|
+
*/
|
|
222
|
+
withRelation(rel: string, ...more: string[]): this;
|
|
223
|
+
/**
|
|
224
|
+
* Adds an INNER JOIN clause to the query.
|
|
225
|
+
* @param relation - The relation to join.
|
|
226
|
+
* @param alias - The alias for the joined relation.
|
|
227
|
+
* @param condition - Optional condition for the join.
|
|
228
|
+
* @returns The current instance of ZormQueryBuilder.
|
|
229
|
+
*/
|
|
230
|
+
innerJoin(relation: string, alias: string, condition?: string): this;
|
|
231
|
+
/**
|
|
232
|
+
* Adds a LEFT JOIN clause to the query.
|
|
233
|
+
* @param relation - The relation to join.
|
|
234
|
+
* @param alias - The alias for the joined relation.
|
|
235
|
+
* @param condition - Optional condition for the join.
|
|
236
|
+
* @returns The current instance of ZormQueryBuilder.
|
|
237
|
+
*/
|
|
238
|
+
leftJoin(relation: string, alias: string, condition?: string): this;
|
|
239
|
+
/**
|
|
240
|
+
* Adds a GROUP BY clause to the query.
|
|
241
|
+
* @param field - The field to group by.
|
|
242
|
+
* @returns The current instance of ZormQueryBuilder.
|
|
243
|
+
*/
|
|
244
|
+
groupBy(field: keyof T): this;
|
|
245
|
+
/**
|
|
246
|
+
* Adds a HAVING clause to the query.
|
|
247
|
+
* @param condition - The condition for the HAVING clause.
|
|
248
|
+
* @returns The current instance of ZormQueryBuilder.
|
|
249
|
+
*/
|
|
250
|
+
having(condition: string): this;
|
|
251
|
+
/**
|
|
252
|
+
* Adds an IN clause to the query.
|
|
253
|
+
* @param field - The field to check.
|
|
254
|
+
* @param values - The values for the IN clause.
|
|
255
|
+
* @returns The current instance of ZormQueryBuilder.
|
|
256
|
+
*/
|
|
257
|
+
in(field: keyof T, values: any[]): this;
|
|
258
|
+
/**
|
|
259
|
+
* Adds a LIKE condition to the query, supporting both single and multiple values.
|
|
260
|
+
* If an array is provided, it uses OR conditions between them.
|
|
261
|
+
* @param field - The field to apply the LIKE condition on.
|
|
262
|
+
* @param value - A string or an array of strings to match.
|
|
263
|
+
* @returns The current instance of ZormQueryBuilder.
|
|
264
|
+
*/
|
|
265
|
+
like(conditions: Partial<Record<keyof T, string | string[]>>, mode: "contains" | "startsWith" | "endsWith" | "exact"): this;
|
|
266
|
+
/**
|
|
267
|
+
* Adds a DISTINCT clause to the query.
|
|
268
|
+
* @returns The current instance of ZormQueryBuilder.
|
|
269
|
+
*/
|
|
270
|
+
distinct(): this;
|
|
271
|
+
count(field?: keyof T): Promise<number>;
|
|
272
|
+
sum(field: keyof T): Promise<number>;
|
|
273
|
+
avg(field: keyof T): Promise<number>;
|
|
274
|
+
min(field: keyof T): Promise<number>;
|
|
275
|
+
max(field: keyof T): Promise<number>;
|
|
276
|
+
/**
|
|
277
|
+
* Executes a raw SQL query.
|
|
278
|
+
* @param sql - The raw SQL query.
|
|
279
|
+
* @param params - Optional parameters for the query.
|
|
280
|
+
* @returns A promise that resolves with the query result.
|
|
281
|
+
*/
|
|
282
|
+
rawQuery(sql: string, params?: any): Promise<any>;
|
|
283
|
+
/**
|
|
284
|
+
* Executes the query and returns the result.
|
|
285
|
+
* @returns A promise that resolves with the query result.
|
|
286
|
+
*/
|
|
287
|
+
execute(): Promise<R>;
|
|
288
|
+
/**
|
|
289
|
+
* Handles the fulfillment and rejection of the promise.
|
|
290
|
+
* @param onfulfilled - The callback to execute when the promise is fulfilled.
|
|
291
|
+
* @param onrejected - The callback to execute when the promise is rejected.
|
|
292
|
+
* @returns A promise that resolves with the result of the callback.
|
|
293
|
+
*/
|
|
294
|
+
then<TResult1 = R, TResult2 = never>(onfulfilled?: ((value: R) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Zorm is a lightweight ORM wrapper around TypeORM with support for MySQL.
|
|
299
|
+
*/
|
|
300
|
+
declare class Zorm {
|
|
301
|
+
/**
|
|
302
|
+
* Singleton instance of Zorm.
|
|
303
|
+
* @private
|
|
304
|
+
*/
|
|
305
|
+
private static instance;
|
|
306
|
+
/**
|
|
307
|
+
* TypeORM DataSource instance.
|
|
308
|
+
* @private
|
|
309
|
+
*/
|
|
310
|
+
private dataSource;
|
|
311
|
+
/**
|
|
312
|
+
* Flag to track if the connection is initialized.
|
|
313
|
+
* @private
|
|
314
|
+
*/
|
|
315
|
+
private initialized;
|
|
316
|
+
/**
|
|
317
|
+
* Determines whether to use Promises for queries.
|
|
318
|
+
* @private
|
|
319
|
+
*/
|
|
320
|
+
private usePromise;
|
|
321
|
+
private _init;
|
|
322
|
+
/**
|
|
323
|
+
* Private constructor to enforce singleton pattern.
|
|
324
|
+
* @param {string} connectionString - The database connection string.
|
|
325
|
+
* @param {string | null} [entitiesPath] - Path to the entities directory.
|
|
326
|
+
* @param {boolean} [usePromise] - Whether to use Promises for queries.
|
|
327
|
+
* @private
|
|
328
|
+
*/
|
|
329
|
+
private constructor();
|
|
330
|
+
/**
|
|
331
|
+
* Returns the singleton instance of Zorm.
|
|
332
|
+
* @param {string} connectionString - The database connection string.
|
|
333
|
+
* @param {string | null} [entitiesPath] - Path to the entities directory.
|
|
334
|
+
* @param {boolean} [usePromise] - Whether to use Promises for queries.
|
|
335
|
+
* @returns {Zorm} The singleton instance of Zorm.
|
|
336
|
+
*/
|
|
337
|
+
static get(connectionString: string, entities?: MixedList<string | Function | EntitySchema<any>>, entitiesPath?: string | null, usePromise?: boolean): Zorm;
|
|
338
|
+
/**
|
|
339
|
+
* Connects to the database and initializes entities.
|
|
340
|
+
* @param {MixedList<string | Function | EntitySchema<any>>} entities - List of entity schemas.
|
|
341
|
+
* @returns {Promise<void>} Resolves when the connection is initialized.
|
|
342
|
+
*/
|
|
343
|
+
connect(entities?: MixedList<string | Function | EntitySchema<any>>): Promise<void>;
|
|
344
|
+
whenReady<T = this>(): T;
|
|
345
|
+
private wrapQueryBuilder;
|
|
346
|
+
/**
|
|
347
|
+
* Returns the appropriate QueryBuilder based on the database type.
|
|
348
|
+
* @param {EntityTarget<T>} entity - The entity target.
|
|
349
|
+
* @param {QueryAction} action - The query action type.
|
|
350
|
+
* @returns {ZormQueryBuilder<T, R>} Query builder instance.
|
|
351
|
+
* @private
|
|
352
|
+
*/
|
|
353
|
+
private getQueryBuilder;
|
|
354
|
+
/**
|
|
355
|
+
* Retrieves the repository for a given entity.
|
|
356
|
+
* @param {EntityTarget<T>} entity - The entity target.
|
|
357
|
+
* @returns {Repository<T>} The repository instance.
|
|
358
|
+
*/
|
|
359
|
+
getRepository<T extends ObjectLiteral>(entity: EntityTarget<T>): Repository<T>;
|
|
360
|
+
/**
|
|
361
|
+
* Creates a new record in the database.
|
|
362
|
+
* @param {EntityTarget<T>} entity - The entity target.
|
|
363
|
+
* @returns {ZormQueryBuilder<T, InsertQueryResult>} The query builder instance.
|
|
364
|
+
*/
|
|
365
|
+
create<T extends ObjectLiteral>(entity: EntityTarget<T>): ZormQueryBuilder<T, InsertQueryResult>;
|
|
366
|
+
/**
|
|
367
|
+
* Finds records in the database.
|
|
368
|
+
* @param {EntityTarget<T>} entity - The entity target.
|
|
369
|
+
* @returns {ZormQueryBuilder<T, SelectQueryResult>} The query builder instance.
|
|
370
|
+
*/
|
|
371
|
+
find<T extends ObjectLiteral>(entity: EntityTarget<T>): ZormQueryBuilder<T, SelectQueryResult>;
|
|
372
|
+
/**
|
|
373
|
+
* Updates records in the database.
|
|
374
|
+
* @param {EntityTarget<T>} entity - The entity target.
|
|
375
|
+
* @returns {ZormQueryBuilder<T, UpdateQueryResult>} The query builder instance.
|
|
376
|
+
*/
|
|
377
|
+
update<T extends ObjectLiteral>(entity: EntityTarget<T>): ZormQueryBuilder<T, UpdateQueryResult>;
|
|
378
|
+
/**
|
|
379
|
+
* Deletes records from the database.
|
|
380
|
+
* @param {EntityTarget<T>} entity - The entity target.
|
|
381
|
+
* @returns {ZormQueryBuilder<T, DeleteQueryResult>} The query builder instance.
|
|
382
|
+
*/
|
|
383
|
+
delete<T extends ObjectLiteral>(entity: EntityTarget<T>): ZormQueryBuilder<T, DeleteQueryResult>;
|
|
384
|
+
}
|
|
385
|
+
|
|
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 dynamicObject };
|