sql-love 1.0.4 → 1.0.6

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/index.cjs CHANGED
@@ -1,16 +1,874 @@
1
- var m=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var j=(i,t)=>{for(var e in t)m(i,e,{get:t[e],enumerable:!0})},D=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of U(t))!A.call(i,s)&&s!==e&&m(i,s,{get:()=>t[s],enumerable:!(n=L(t,s))||n.enumerable});return i};var F=i=>D(m({},"__esModule",{value:!0}),i);var P={};j(P,{Parser:()=>c,SelectBuilder:()=>d,extractGrouped:()=>S,extractIndexed:()=>E,extractLookup:()=>R,getPagination:()=>g,runMysql:()=>N,runMysqlAsync:()=>$,runMysqlAsyncWithCount:()=>I,runMysqlWithCount:()=>B,runPrisma:()=>x,runPrismaWithCount:()=>q,toSafeJsonRecord:()=>T,toSafeJsonRecords:()=>C,toSafeJsonString:()=>w,toSafeJsonValue:()=>p});module.exports=F(P);var c=class{query;constructor(t){this.query=t}_stripComments(t){return t=t.replace(/\/\*[\s\S]*?\*\//g,""),t=t.replace(/--([\r\n]|\s+[^\r\n]+[\r\n])/g,""),t=t.replace(/#[^\r\n]+[\r\n]/g,""),t}_extractSubQueries(t){let e={},n=0,s=r=>{let o=`~~SUBQUERY_${n++}~~`;return e[o]=r,o};return t=t.replace(/\(\s*SELECT\s+.+\)\s+AS\s+[^\s,]+/,s),t=t.replace(/\bIF\s*\(.+\)\s+AS\s+[^\s,]+/,s),t=t.replace(/\bIN\s*\(\s*SELECT\s.+?\)/,s),{sql:t,subQueries:e}}_injectSubQueries(t){let e=s=>t[s]||s,n=s=>s.replace(/~~SUBQUERY_\d+~~/g,e);this.query._columns=this.query._columns.map(e),this.query._joins=this.query._joins.map(n),this.query._wheres=this.query._wheres.map(n),this.query._havings=this.query._havings.map(n)}_split(t){let e=/(?:^|\s)(SELECT|FROM|(?:INNER|LEFT\s+OUTER|RIGHT\s+OUTER|LEFT|RIGHT|CROSS|FULL|FULL\s+OUTER)\s+JOIN|WHERE|GROUP\s+BY|HAVING|ORDER\s+BY|LIMIT|OFFSET|FETCH\s+NEXT)\b/i;return t.split(e)}parse(t){let e=this._stripComments(t),{sql:n,subQueries:s}=this._extractSubQueries(e),r=this._split(n),o=1;for(;o<r.length;){let l=r[o++].trim().toUpperCase().replace(/\s+/g,"_"),h=r[o++].trim(),a=`_handle${l}`;this[a](h)}return this._injectSubQueries(s),!0}_handleSELECT(t){let e=t.split(/s*,s*/),n="";e.forEach((s,r)=>{if(r===0){let o=/^(SQL_CALC_FOUND_ROWS)\s+/i,u=s.match(o);u&&(this.query.option(u[1]),s=s.replace(o,""))}n.length?s.indexOf(")")>0?(n+=s,this.query.column(n.trim()),n=""):n+=s+",":s.match(/\([^)]+$/)?n=s+",":this.query.column(s.trim())})}_handleFROM(t){t.split(/\s*,\s*/).forEach(n=>this.query.table(n))}_handleINNER_JOIN(t){this.query.innerJoin(t)}_handleLEFT_JOIN(t){this.query.leftJoin(t)}_handleLEFT_OUTER_JOIN(t){this.query.leftOuterJoin(t)}_handleRIGHT_JOIN(t){this.query.rightJoin(t)}_handleRIGHT_OUTER_JOIN(t){this.query.rightOuterJoin(t)}_handleCROSS_JOIN(t){this.query.crossJoin(t)}_handleFULL_JOIN(t){this.query.fullJoin(t)}_handleFULL_OUTER_JOIN(t){this.query.fullOuterJoin(t)}_handleWHERE(t){/^(1|'1'|true)$/i.test(t)?this.query._wheres.push(t):this._handleConditions("where",t)}_handleHAVING(t){this._handleConditions("having",t)}_handleConditions(t,e){e.split(/\bAND\b/i).forEach(s=>{let r=s.split(/\bOR\b/i).map(o=>o.trim());if(r.length===1){let o=t;this.query[o](r[0])}else{let o=t==="where"?"orWhere":"orHaving";this.query[o](r.map(u=>[u]))}})}_handleGROUP_BY(t){t.split(/\s*,\s*/).forEach(n=>this.query.groupBy(n))}_handleORDER_BY(t){t.split(/\s*,\s*/).forEach(n=>this.query.orderBy(n))}_handleLIMIT(t){let e=t.match(/^(\d+|\?|:\w+)\s*,\s*(\d+|\?|:\w+)$/);e?(this.query.offset(e[1]),this.query.limit(e[2])):(t=t.replace(/ ROWS$/i,""),this.query.limit(t))}_handleOFFSET(t){t=t.replace(/^(\d+) ROWS$/i,"$1"),this.query.offset(t)}_handleFETCH_NEXT(t){t=t.replace(/^(\d+) ROWS ONLY$/i,"$1"),this.query.limit(t)}};function b(i,t){let e=0,n=i.indexOf(t);for(;n!==-1;)e+=1,n=i.indexOf(t,n+1);return e}var _=i=>i==null||i===!1||isNaN(i),y="mysql",d=class i{_bindings=[];_options=[];_tables=[];_columns=[];_joins=[];_wheres=[];_groupBys=[];_havings=[];_orderBys=[];_limit;_offset;_page;constructor(t=null,e=null){if(t){if(e){let n=Object.keys(e),s=new RegExp(`:(${n.join("|")})`,"g");t=t.replace(s,(r,o)=>(this._bindings.push(e[o]),`__BOUND_${this._bindings.length-1}__`))}new c(this).parse(t)}}static setDefaultEngine(t){return y=t,i}compile({engine:t=y,bindingIndex:e=1}={}){let n=["SELECT",this._options.length?` ${this._options.join(`
2
- `)}`:null,this._columns.length?` ${this._columns.join(`,
3
- `)}`:` *
4
- `,`FROM ${this._tables.join(", ")}`,this._joins.length?this._joins.join(`
5
- `):null,this._wheres.length?`WHERE ${this._wheres.join(`
6
- AND `)}`:null,this._groupBys.length?`GROUP BY ${this._groupBys.join(`,
7
- `)}`:null,this._havings.length?`HAVING ${this._havings.join(`
8
- AND `)}`:null,this._orderBys.length?`ORDER BY ${this._orderBys.join(`,
9
- `)}`:null];if(this._page>0){let l=(this._page-1)*this._limit;n.push(this._compileOFFSET(t,l)),n.push(this._compileLIMIT(t,this._limit))}else this._offset&&n.push(this._compileOFFSET(t,this._offset)),this._limit&&n.push(this._compileLIMIT(t,this._limit));let s=n.filter(Boolean).join(`
10
- `).trim(),r,o=[];if(t==="pg"){let l=e;r=(h,a)=>(o.push(this._bindings[a]),"$"+l++)}else r=(l,h)=>(o.push(this._bindings[h]),"?");return{sql:s.replace(/__BOUND_(\d+)__/g,r),bindings:o}}_compileLIMIT(t,e){if(t==="pg"||t==="mysql")return`LIMIT ${e}`;if(t==="mssql")return`FETCH NEXT ${e} ROWS ONLY`}_compileOFFSET(t,e){if(t==="pg"||t==="mysql")return`OFFSET ${e}`;if(t==="mssql"||t==="oracle")return`OFFSET ${e} ROWS`}compileCount({countExpr:t="*",engine:e=y,bindingIndex:n=1}={}){let s=this.getFoundRowsQuery(t),{sql:r,bindings:o}=s.compile({engine:e,bindingIndex:n});return this._havings.length===0?{sql:r,bindings:o}:{sql:`SELECT COUNT(*) AS found_rows
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __moduleCache = /* @__PURE__ */ new WeakMap;
6
+ var __toCommonJS = (from) => {
7
+ var entry = __moduleCache.get(from), desc;
8
+ if (entry)
9
+ return entry;
10
+ entry = __defProp({}, "__esModule", { value: true });
11
+ if (from && typeof from === "object" || typeof from === "function")
12
+ __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, {
13
+ get: () => from[key],
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ }));
16
+ __moduleCache.set(from, entry);
17
+ return entry;
18
+ };
19
+ var __export = (target, all) => {
20
+ for (var name in all)
21
+ __defProp(target, name, {
22
+ get: all[name],
23
+ enumerable: true,
24
+ configurable: true,
25
+ set: (newValue) => all[name] = () => newValue
26
+ });
27
+ };
28
+
29
+ // index.ts
30
+ var exports_sql_love = {};
31
+ __export(exports_sql_love, {
32
+ toSafeJsonValue: () => toSafeJsonValue,
33
+ toSafeJsonString: () => toSafeJsonString,
34
+ toSafeJsonRecords: () => toSafeJsonRecords,
35
+ toSafeJsonRecord: () => toSafeJsonRecord,
36
+ runPrismaWithCount: () => runPrismaWithCount,
37
+ runPrisma: () => runPrisma,
38
+ runMysqlWithCount: () => runMysqlWithCount,
39
+ runMysqlAsyncWithCount: () => runMysqlAsyncWithCount,
40
+ runMysqlAsync: () => runMysqlAsync,
41
+ runMysql: () => runMysql,
42
+ getPagination: () => getPagination,
43
+ extractLookup: () => extractLookup,
44
+ extractIndexed: () => extractIndexed,
45
+ extractGrouped: () => extractGrouped,
46
+ SelectBuilder: () => SelectBuilder,
47
+ Parser: () => Parser
48
+ });
49
+ module.exports = __toCommonJS(exports_sql_love);
50
+
51
+ // src/Parser/Parser.ts
52
+ class Parser {
53
+ query;
54
+ constructor(query) {
55
+ this.query = query;
56
+ }
57
+ _stripComments(sql) {
58
+ sql = sql.replace(/\/\*[\s\S]*?\*\//g, "");
59
+ sql = sql.replace(/--([\r\n]|\s+[^\r\n]+[\r\n])/g, "");
60
+ sql = sql.replace(/#[^\r\n]+[\r\n]/g, "");
61
+ return sql;
62
+ }
63
+ _extractSubQueries(sql) {
64
+ const subQueries = {};
65
+ let i = 0;
66
+ const extractor = ($0) => {
67
+ const placeholder = `~~SUBQUERY_${i++}~~`;
68
+ subQueries[placeholder] = $0;
69
+ return placeholder;
70
+ };
71
+ sql = sql.replace(/\(\s*SELECT\s+.+\)\s+AS\s+[^\s,]+/, extractor);
72
+ sql = sql.replace(/\bIF\s*\(.+\)\s+AS\s+[^\s,]+/, extractor);
73
+ sql = sql.replace(/\bIN\s*\(\s*SELECT\s.+?\)/, extractor);
74
+ return { sql, subQueries };
75
+ }
76
+ _injectSubQueries(subQueries) {
77
+ const replacer = ($0) => {
78
+ return subQueries[$0] || $0;
79
+ };
80
+ const mapper = (clause) => {
81
+ return clause.replace(/~~SUBQUERY_\d+~~/g, replacer);
82
+ };
83
+ this.query._columns = this.query._columns.map(replacer);
84
+ this.query._joins = this.query._joins.map(mapper);
85
+ this.query._wheres = this.query._wheres.map(mapper);
86
+ this.query._havings = this.query._havings.map(mapper);
87
+ }
88
+ _split(sql) {
89
+ const splitter = /(?:^|\s)(SELECT|FROM|(?:INNER|LEFT\s+OUTER|RIGHT\s+OUTER|LEFT|RIGHT|CROSS|FULL|FULL\s+OUTER)\s+JOIN|WHERE|GROUP\s+BY|HAVING|ORDER\s+BY|LIMIT|OFFSET|FETCH\s+NEXT)\b/i;
90
+ return sql.split(splitter);
91
+ }
92
+ parse(rawSql) {
93
+ const stripped = this._stripComments(rawSql);
94
+ const { sql, subQueries } = this._extractSubQueries(stripped);
95
+ const expressions = this._split(sql);
96
+ let i = 1;
97
+ while (i < expressions.length) {
98
+ const rawKeyword = expressions[i++].trim();
99
+ const keyword = rawKeyword.toUpperCase().replace(/\s+/g, "_");
100
+ const clause = expressions[i++].trim();
101
+ const handler = `_handle${keyword}`;
102
+ this[handler](clause);
103
+ }
104
+ this._injectSubQueries(subQueries);
105
+ return true;
106
+ }
107
+ _handleSELECT(clause) {
108
+ let columns = clause.split(/s*,s*/);
109
+ let buffer = "";
110
+ columns.forEach((column, i) => {
111
+ if (i === 0) {
112
+ const optionRegex = /^(SQL_CALC_FOUND_ROWS)\s+/i;
113
+ const match = column.match(optionRegex);
114
+ if (match) {
115
+ this.query.option(match[1]);
116
+ column = column.replace(optionRegex, "");
117
+ }
118
+ }
119
+ if (buffer.length) {
120
+ if (column.indexOf(")") > 0) {
121
+ buffer += column;
122
+ this.query.column(buffer.trim());
123
+ buffer = "";
124
+ } else {
125
+ buffer += column + ",";
126
+ }
127
+ } else if (column.match(/\([^)]+$/)) {
128
+ buffer = column + ",";
129
+ } else {
130
+ this.query.column(column.trim());
131
+ }
132
+ });
133
+ }
134
+ _handleFROM(clause) {
135
+ const tables = clause.split(/\s*,\s*/);
136
+ tables.forEach((table) => this.query.table(table));
137
+ }
138
+ _handleINNER_JOIN(clause) {
139
+ this.query.innerJoin(clause);
140
+ }
141
+ _handleLEFT_JOIN(clause) {
142
+ this.query.leftJoin(clause);
143
+ }
144
+ _handleLEFT_OUTER_JOIN(clause) {
145
+ this.query.leftOuterJoin(clause);
146
+ }
147
+ _handleRIGHT_JOIN(clause) {
148
+ this.query.rightJoin(clause);
149
+ }
150
+ _handleRIGHT_OUTER_JOIN(clause) {
151
+ this.query.rightOuterJoin(clause);
152
+ }
153
+ _handleCROSS_JOIN(clause) {
154
+ this.query.crossJoin(clause);
155
+ }
156
+ _handleFULL_JOIN(clause) {
157
+ this.query.fullJoin(clause);
158
+ }
159
+ _handleFULL_OUTER_JOIN(clause) {
160
+ this.query.fullOuterJoin(clause);
161
+ }
162
+ _handleWHERE(clause) {
163
+ if (/^(1|'1'|true)$/i.test(clause)) {
164
+ this.query._wheres.push(clause);
165
+ } else {
166
+ this._handleConditions("where", clause);
167
+ }
168
+ }
169
+ _handleHAVING(clause) {
170
+ this._handleConditions("having", clause);
171
+ }
172
+ _handleConditions(type, clause) {
173
+ const andGroups = clause.split(/\bAND\b/i);
174
+ andGroups.forEach((andGroup) => {
175
+ const orPieces = andGroup.split(/\bOR\b/i).map((str) => str.trim());
176
+ if (orPieces.length === 1) {
177
+ const fn = type;
178
+ this.query[fn](orPieces[0]);
179
+ } else {
180
+ const orFn = type === "where" ? "orWhere" : "orHaving";
181
+ this.query[orFn](orPieces.map((p) => [p]));
182
+ }
183
+ });
184
+ }
185
+ _handleGROUP_BY(clause) {
186
+ const columns = clause.split(/\s*,\s*/);
187
+ columns.forEach((column) => this.query.groupBy(column));
188
+ }
189
+ _handleORDER_BY(clause) {
190
+ const columns = clause.split(/\s*,\s*/);
191
+ columns.forEach((column) => this.query.orderBy(column));
192
+ }
193
+ _handleLIMIT(clause) {
194
+ const offsetLimit = clause.match(/^(\d+|\?|:\w+)\s*,\s*(\d+|\?|:\w+)$/);
195
+ if (offsetLimit) {
196
+ this.query.offset(offsetLimit[1]);
197
+ this.query.limit(offsetLimit[2]);
198
+ } else {
199
+ clause = clause.replace(/ ROWS$/i, "");
200
+ this.query.limit(clause);
201
+ }
202
+ }
203
+ _handleOFFSET(clause) {
204
+ clause = clause.replace(/^(\d+) ROWS$/i, "$1");
205
+ this.query.offset(clause);
206
+ }
207
+ _handleFETCH_NEXT(clause) {
208
+ clause = clause.replace(/^(\d+) ROWS ONLY$/i, "$1");
209
+ this.query.limit(clause);
210
+ }
211
+ }
212
+ // src/substrCount/substrCount.ts
213
+ function substrCount(haystack, needle) {
214
+ let count = 0;
215
+ let pos = haystack.indexOf(needle);
216
+ while (pos !== -1) {
217
+ count += 1;
218
+ pos = haystack.indexOf(needle, pos + 1);
219
+ }
220
+ return count;
221
+ }
222
+
223
+ // src/SelectBuilder/SelectBuilder.ts
224
+ var isNullish = (v) => v === undefined || v === null || v === false || isNaN(v);
225
+ var defaultEngine = "mysql";
226
+
227
+ class SelectBuilder {
228
+ _bindings = [];
229
+ _options = [];
230
+ _tables = [];
231
+ _columns = [];
232
+ _joins = [];
233
+ _wheres = [];
234
+ _groupBys = [];
235
+ _havings = [];
236
+ _orderBys = [];
237
+ _limit;
238
+ _offset;
239
+ _page;
240
+ constructor(sql = null, bindings = null) {
241
+ if (sql) {
242
+ if (bindings) {
243
+ const keys = Object.keys(bindings);
244
+ const regexp = new RegExp(`:(${keys.join("|")})`, "g");
245
+ sql = sql.replace(regexp, ($0, $1) => {
246
+ this._bindings.push(bindings[$1]);
247
+ return `__BOUND_${this._bindings.length - 1}__`;
248
+ });
249
+ }
250
+ new Parser(this).parse(sql);
251
+ }
252
+ }
253
+ static setDefaultEngine(engine) {
254
+ defaultEngine = engine;
255
+ return SelectBuilder;
256
+ }
257
+ compile({
258
+ engine = defaultEngine,
259
+ bindingIndex = 1
260
+ } = {}) {
261
+ const lines = [
262
+ "SELECT",
263
+ this._options.length ? ` ${this._options.join(`
264
+ `)}` : null,
265
+ this._columns.length ? ` ${this._columns.join(`,
266
+ `)}` : ` *
267
+ `,
268
+ `FROM ${this._tables.join(", ")}`,
269
+ this._joins.length ? this._joins.join(`
270
+ `) : null,
271
+ this._wheres.length ? `WHERE ${this._wheres.join(`
272
+ AND `)}` : null,
273
+ this._groupBys.length ? `GROUP BY ${this._groupBys.join(`,
274
+ `)}` : null,
275
+ this._havings.length ? `HAVING ${this._havings.join(`
276
+ AND `)}` : null,
277
+ this._orderBys.length ? `ORDER BY ${this._orderBys.join(`,
278
+ `)}` : null
279
+ ];
280
+ if (this._page > 0) {
281
+ const offset = (this._page - 1) * this._limit;
282
+ lines.push(this._compileOFFSET(engine, offset));
283
+ lines.push(this._compileLIMIT(engine, this._limit));
284
+ } else {
285
+ if (this._offset) {
286
+ lines.push(this._compileOFFSET(engine, this._offset));
287
+ }
288
+ if (this._limit) {
289
+ lines.push(this._compileLIMIT(engine, this._limit));
290
+ }
291
+ }
292
+ const pretty = lines.filter(Boolean).join(`
293
+ `).trim();
294
+ let replacer;
295
+ const bindings = [];
296
+ if (engine === "pg") {
297
+ let idx = bindingIndex;
298
+ replacer = (_, $1) => {
299
+ bindings.push(this._bindings[$1]);
300
+ return "$" + idx++;
301
+ };
302
+ } else {
303
+ replacer = (_, $1) => {
304
+ bindings.push(this._bindings[$1]);
305
+ return "?";
306
+ };
307
+ }
308
+ const sql = pretty.replace(/__BOUND_(\d+)__/g, replacer);
309
+ return { sql, bindings };
310
+ }
311
+ _compileLIMIT(engineStyle, limit) {
312
+ if (engineStyle === "pg" || engineStyle === "mysql") {
313
+ return `LIMIT ${limit}`;
314
+ } else if (engineStyle === "mssql") {
315
+ return `FETCH NEXT ${limit} ROWS ONLY`;
316
+ }
317
+ }
318
+ _compileOFFSET(engineStyle, offset) {
319
+ if (engineStyle === "pg" || engineStyle === "mysql") {
320
+ return `OFFSET ${offset}`;
321
+ } else if (engineStyle === "mssql" || engineStyle === "oracle") {
322
+ return `OFFSET ${offset} ROWS`;
323
+ }
324
+ }
325
+ compileCount({
326
+ countExpr = "*",
327
+ engine = defaultEngine,
328
+ bindingIndex = 1
329
+ } = {}) {
330
+ const query = this.getFoundRowsQuery(countExpr);
331
+ const { sql, bindings } = query.compile({ engine, bindingIndex });
332
+ if (this._havings.length === 0) {
333
+ return { sql, bindings };
334
+ } else {
335
+ const subquerySql = sql.replace(/\n/g, `
336
+ `);
337
+ return {
338
+ sql: `SELECT COUNT(*) AS found_rows
11
339
  FROM (
12
- ${r.replace(/\n/g,`
13
- `)}
14
- ) AS subquery_results`,bindings:o}}compileUnion(t,{engine:e=y,bindingIndex:n=1}={}){let s=this.compile({engine:e,bindingIndex:n}),r=t.compile({engine:e,bindingIndex:s.bindings.length+n});return{sql:`(${s.sql})
340
+ ${subquerySql}
341
+ ) AS subquery_results`,
342
+ bindings
343
+ };
344
+ }
345
+ }
346
+ compileUnion(query, {
347
+ engine = defaultEngine,
348
+ bindingIndex = 1
349
+ } = {}) {
350
+ const first = this.compile({ engine, bindingIndex });
351
+ const second = query.compile({
352
+ engine,
353
+ bindingIndex: first.bindings.length + bindingIndex
354
+ });
355
+ return {
356
+ sql: `(${first.sql})
15
357
  UNION
16
- (${r.sql})`,bindings:[...s.bindings,...r.bindings]}}reset(t=null){if(Array.isArray(t))return t.forEach(e=>this.reset(e)),this;if(t){let e=["option","column","table","where","having","groupBy","orderBy"],n="_"+t.replace(/s$/,"");e.indexOf(t)>-1&&(n+="s");let s=["limit","offset","page"].indexOf(t)>-1;this[n]=s?null:[]}else this._options=[],this._columns=[],this._tables=[],this._joins=[],this._wheres=[],this._groupBys=[],this._havings=[],this._orderBys=[],this._limit=null,this._offset=null,this._page=null,this._bindings=[];return this}getClone(){let t=new i;return t._options=[...this._options],t._columns=[...this._columns],t._tables=[...this._tables],t._joins=[...this._joins],t._wheres=[...this._wheres],t._havings=[...this._havings],t._groupBys=[...this._groupBys],t._orderBys=[...this._orderBys],t._limit=this._limit,t._offset=this._offset,t._page=this._page,t._bindings=[...this._bindings],t}getFoundRowsQuery(t="*"){if(this._havings.length===0){let e=this.getClone();return e._columns=[`COUNT(${t}) AS found_rows`],e._options=[],e._groupBys=[],e._orderBys=[],e._limit=null,e._offset=null,e._page=null,e}else{let e=this.getClone();return e._limit=null,e._offset=null,e._page=null,e}}select(t){return this._columns=this._columns.concat(t),this}columns(t){return this._columns=this._columns.concat(t),this}column(t){return this._columns.push(t),this}option(t){return this._options.push(t),this}table(t){return this._tables.push(t),this}tables(t){return this._tables.push(...t),this}from(t){return this._tables.push(t),this}_addJoin(t,e,n=[]){n.length>0&&(e=e.replace(/\?/g,()=>(this._bindings.push(n.shift()),`__BOUND_${this._bindings.length-1}__`))),this._joins.push(`${t} ${e}`)}join(t,e=[]){return this._addJoin("JOIN",t,e),this}leftJoin(t,e=[]){return this._addJoin("LEFT JOIN",t,e),this}fullJoin(t,e=[]){return this._addJoin("FULL JOIN",t,e),this}rightJoin(t,e=[]){return this._addJoin("RIGHT JOIN",t,e),this}crossJoin(t,e=[]){return this._addJoin("CROSS JOIN",t,e),this}innerJoin(t,e=[]){return this._addJoin("INNER JOIN",t,e),this}leftOuterJoin(t,e=[]){return this._addJoin("LEFT OUTER JOIN",t,e),this}fullOuterJoin(t,e=[]){return this._addJoin("FULL OUTER JOIN",t,e),this}rightOuterJoin(t,e=[]){return this._addJoin("RIGHT OUTER JOIN",t,e),this}unjoin(t){return Array.isArray(t)?(t.forEach(e=>this.unjoin(e)),this):(this._joins=this._joins.filter(e=>!new RegExp(`JOIN ${t}\\b`).test(e)),this)}_conditions(t,e){let n=e.length,[s,r,o]=e;if(typeof s=="object"){for(let l of Object.entries(s))this._conditions(t,l);return this}if(n===1)return t.push(s),this;if(n===2&&Array.isArray(r)&&r.length>0&&b(s,"?")===r.length){let l=r,h=s.replace(/\?/g,()=>(this._bindings.push(l.shift()),`__BOUND_${this._bindings.length-1}__`));return t.push(h),this}else if(n===2){o=r;let l=s.split(" ");s=l.shift(),r=l.join(" ")}(typeof r!="string"||r==="")&&(r="="),r=r.toLocaleUpperCase();let u=r.match(/^(LIKE|NOT LIKE|ILIKE|NOT ILIKE)(?: (\?|\?%|%\?|%\?%))?$/i);if(r==="NOT BETWEEN"||r==="BETWEEN"){let l=this._bindings.length,h=this._bindings.length+1;t.push(`${s} ${r} __BOUND_${l}__ AND __BOUND_${h}__`),this._bindings.push(o[0],o[1])}else if(u){let l=u[1].toUpperCase(),h=u[2]||"?";if(Array.isArray(o)){let a=[];for(let J of o)a.push(`${s} ${l} __BOUND_${this._bindings.length}__`),this._bindings.push(h.replace("?",J));let f=a.join(" OR ");t.push(`(${f})`)}else t.push(`${s} ${l} __BOUND_${this._bindings.length}__`),this._bindings.push(h.replace("?",o||""))}else if(o===null)t.push(r==="="?`${s} IS NULL`:`${s} IS NOT NULL`);else if(Array.isArray(o)){let l=[];for(let a=0;a<o.length;a++)l.push(`__BOUND_${this._bindings.length}__`),this._bindings.push(o[a]);let h=l.join(", ");t.push(r==="="||r==="IN"?`${s} IN(${h})`:`${s} NOT IN(${h})`)}else r==="IN"||r==="NOT IN"?(t.push(`${s} ${r}(__BOUND_${this._bindings.length}__)`),this._bindings.push(o)):(t.push(`${s} ${r} __BOUND_${this._bindings.length}__`),this._bindings.push(o));return this}groupBy(t){return this._groupBys.push(t),this}where(...t){return this._conditions(this._wheres,t),this}whereBetween(t,e){return!_(e[0])&&!_(e[1])?this.where(t,"BETWEEN",e):!_(e[0])&&_(e[1])?this.where(t,">=",e[0]):_(e[0])&&!_(e[1])&&this.where(t,"<=",e[1]),this}_orConditions(t){let e=[];if(Array.isArray(t))for(let s of t)Array.isArray(s)?this._conditions(e,s):this._conditions(e,[s]);else for(let[s,r]of Object.entries(t)){let o=[];this._conditions(o,[s,r]),e.push(o[0])}let n=e.join(" OR ");return n.startsWith("(")&&n.endsWith(")")?n.slice(1,-1):n}orWhere(t){let e=this._orConditions(t);return this.where(`(${e})`),this}orHaving(t){let e=this._orConditions(t);return this.having(`(${e})`),this}having(...t){return this._conditions(this._havings,t),this}orderBy(t,e=null){if(e)this._orderBys.push(`${t} ${e}`);else{let n=t.replace(/^-(.+)/,"$1 DESC");this._orderBys.push(n)}return this}sortField(t,e={}){let n="ASC";t.startsWith("-")&&(n="DESC",t=t.slice(1));let s=e[t]||t;return this.orderBy(s,n),this}_isEntirelyDigits(t){return/^(0|[1-9]\d*)$/.test(t)}_isEntirelyDigitsNoZeros(t){return/^[1-9]\d*$/.test(t)}limit(t){if(typeof t=="string")t=t.trim(),this._isEntirelyDigitsNoZeros(t)&&(this._limit=parseInt(t,10));else if(typeof t=="number"&&Number.isInteger(t)&&t>=1)this._limit=t;else throw new Error(`SelectBuilder: "limit(n)" must receive a positive integer (got "${t}")`);return this}offset(t){if(typeof t=="string"&&this._isEntirelyDigits(t.trim()))this._offset=parseInt(t,10);else if(typeof t=="number"&&Number.isInteger(t)&&t>=0)this._offset=t;else throw new Error(`SelectBuilder: "offset(n)" must receive a positive integer (got "${t}")`);return this}page(t){if(typeof t=="string"&&this._isEntirelyDigitsNoZeros(t.trim()))this._page=parseInt(t,10);else if(typeof t=="number"&&Number.isInteger(t)&&t>=1)this._page=t;else throw new Error('SelectBuilder: "page(n)" must receive a positive integer');return this}};function S(i,t){let e=0,n={};for(let s of t){if(!(i in s))throw new Error(`Column "${String(i)}" is not present in record ${e}`);n[s[i]]||(n[s[i]]=[]),n[s[i]].push(s),e++}return n}function E(i,t){let e=0,n={};for(let s of t){if(!(i in s))throw new Error(`Column "${String(i)}" is not present in record ${e}`);n[s[i]]=s,e++}return n}function R(i,t,e){let n={},s=0;for(let r of e){if(!(i in r))throw new Error(`Column "${String(i)}" is not present in record ${s}`);if(!(t in r))throw new Error(`Column "${String(t)}" is not present in record ${s}`);s++,n[String(r[i])]=r[t]}return n}function g(i,t){t=Number(t)||0;let e=Number(i._limit)||null,n=null;t===0?n=null:i._page?n=Number(i._page):i._limit&&i._offset?n=Math.floor(Number(i._offset)/Number(i._limit))+1:i._limit&&!i._offset?n=1:n=null;let s=t===0||e===null?0:Math.ceil(t/e)||0,r=n===1,o=s>0&&n===s,u=s===0?null:n-1||null,l=s>0&&n+1<=s?n+1:null;return{page:n,prevPage:u,nextPage:l,perPage:e,numPages:s,total:t,isFirst:r,isLast:o}}function O(i,t,e){return new Promise((n,s)=>{i.query(t,e,(r,o,u)=>{if(r){s(r);return}n([o,u])})})}async function N(i,t){let{sql:e,bindings:n}=t.compile({engine:"mysql"});return O(i,e,n)}async function B(i,t,{countExpr:e="*"}={}){let{sql:n,bindings:s}=t.compile({engine:"mysql"}),[r,o]=await O(i,n,s);if(r.length>0){let{sql:u,bindings:l}=t.compileCount({engine:"mysql",countExpr:e}),[h]=await O(i,u,l),a=h[0].found_rows;return{records:r,total:a,pagination:g(t,a),fields:o}}else return{records:r,total:0,pagination:g(t,0),fields:o}}async function $(i,t){let{sql:e,bindings:n}=t.compile({engine:"mysql"});return i.query(e,n)}async function I(i,t,{engine:e="mysql",countExpr:n="*"}={}){let{sql:s,bindings:r}=t.compile({engine:e}),[o,u]=await i.query(s,r);if(o.length>0){let{sql:l,bindings:h}=t.compileCount({engine:e,countExpr:n}),[a]=await i.query(l,h),f=a[0].found_rows;return{records:o,total:f,pagination:g(t,f),fields:u}}else return{records:o,total:0,pagination:g(t,0),fields:u}}function p(i){if(typeof i=="bigint"){let t=Number(i);return i==t?t:i.toString()}return i}function T(i){let t={};for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=p(i[e]));return t}function C(i){return i.map(T)}function w(i){return JSON.stringify(i,(t,e)=>p(e))}async function x(i,t,{engine:e=void 0}={}){let{sql:n,bindings:s}=t.compile({engine:e});return i.$queryRawUnsafe(n,...s)}async function q(i,t,{engine:e=void 0,countExpr:n="*"}={}){let{sql:s,bindings:r}=t.compile({engine:e}),o=await i.$queryRawUnsafe(s,...r);if(o.length>0){let{sql:u,bindings:l}=t.compileCount({engine:e,countExpr:n}),h=await i.$queryRawUnsafe(u,...l),a=p(h[0].found_rows);return{records:o,total:a,pagination:g(t,a)}}else return{records:o,total:0,pagination:g(t,0)}}0&&(module.exports={Parser,SelectBuilder,extractGrouped,extractIndexed,extractLookup,getPagination,runMysql,runMysqlAsync,runMysqlAsyncWithCount,runMysqlWithCount,runPrisma,runPrismaWithCount,toSafeJsonRecord,toSafeJsonRecords,toSafeJsonString,toSafeJsonValue});
358
+ (${second.sql})`,
359
+ bindings: [...first.bindings, ...second.bindings]
360
+ };
361
+ }
362
+ reset(fieldOrFields = null) {
363
+ if (Array.isArray(fieldOrFields)) {
364
+ fieldOrFields.forEach((name) => this.reset(name));
365
+ return this;
366
+ }
367
+ if (fieldOrFields) {
368
+ const pluralizable = [
369
+ "option",
370
+ "column",
371
+ "table",
372
+ "where",
373
+ "having",
374
+ "groupBy",
375
+ "orderBy"
376
+ ];
377
+ let prop = "_" + fieldOrFields.replace(/s$/, "");
378
+ if (pluralizable.indexOf(fieldOrFields) > -1) {
379
+ prop += "s";
380
+ }
381
+ const isScalar = ["limit", "offset", "page"].indexOf(fieldOrFields) > -1;
382
+ this[prop] = isScalar ? null : [];
383
+ } else {
384
+ this._options = [];
385
+ this._columns = [];
386
+ this._tables = [];
387
+ this._joins = [];
388
+ this._wheres = [];
389
+ this._groupBys = [];
390
+ this._havings = [];
391
+ this._orderBys = [];
392
+ this._limit = null;
393
+ this._offset = null;
394
+ this._page = null;
395
+ this._bindings = [];
396
+ }
397
+ return this;
398
+ }
399
+ getClone() {
400
+ const copy = new SelectBuilder;
401
+ copy._options = [...this._options];
402
+ copy._columns = [...this._columns];
403
+ copy._tables = [...this._tables];
404
+ copy._joins = [...this._joins];
405
+ copy._wheres = [...this._wheres];
406
+ copy._havings = [...this._havings];
407
+ copy._groupBys = [...this._groupBys];
408
+ copy._orderBys = [...this._orderBys];
409
+ copy._limit = this._limit;
410
+ copy._offset = this._offset;
411
+ copy._page = this._page;
412
+ copy._bindings = [...this._bindings];
413
+ return copy;
414
+ }
415
+ getFoundRowsQuery(countExpr = "*") {
416
+ if (this._havings.length === 0) {
417
+ const clone = this.getClone();
418
+ clone._columns = [`COUNT(${countExpr}) AS found_rows`];
419
+ clone._options = [];
420
+ clone._groupBys = [];
421
+ clone._orderBys = [];
422
+ clone._limit = null;
423
+ clone._offset = null;
424
+ clone._page = null;
425
+ return clone;
426
+ } else {
427
+ const subquery = this.getClone();
428
+ subquery._limit = null;
429
+ subquery._offset = null;
430
+ subquery._page = null;
431
+ return subquery;
432
+ }
433
+ }
434
+ select(columnNames) {
435
+ this._columns = this._columns.concat(columnNames);
436
+ return this;
437
+ }
438
+ columns(columnNames) {
439
+ this._columns = this._columns.concat(columnNames);
440
+ return this;
441
+ }
442
+ column(columnName) {
443
+ this._columns.push(columnName);
444
+ return this;
445
+ }
446
+ option(optionExpression) {
447
+ this._options.push(optionExpression);
448
+ return this;
449
+ }
450
+ table(tableName) {
451
+ this._tables.push(tableName);
452
+ return this;
453
+ }
454
+ tables(tableNames) {
455
+ this._tables.push(...tableNames);
456
+ return this;
457
+ }
458
+ from(tableName) {
459
+ this._tables.push(tableName);
460
+ return this;
461
+ }
462
+ _addJoin(joinType, expression, bindings = []) {
463
+ if (bindings.length > 0) {
464
+ expression = expression.replace(/\?/g, () => {
465
+ this._bindings.push(bindings.shift());
466
+ return `__BOUND_${this._bindings.length - 1}__`;
467
+ });
468
+ }
469
+ this._joins.push(`${joinType} ${expression}`);
470
+ }
471
+ join(expression, bindings = []) {
472
+ this._addJoin("JOIN", expression, bindings);
473
+ return this;
474
+ }
475
+ leftJoin(expression, bindings = []) {
476
+ this._addJoin("LEFT JOIN", expression, bindings);
477
+ return this;
478
+ }
479
+ fullJoin(expression, bindings = []) {
480
+ this._addJoin("FULL JOIN", expression, bindings);
481
+ return this;
482
+ }
483
+ rightJoin(expression, bindings = []) {
484
+ this._addJoin("RIGHT JOIN", expression, bindings);
485
+ return this;
486
+ }
487
+ crossJoin(expression, bindings = []) {
488
+ this._addJoin("CROSS JOIN", expression, bindings);
489
+ return this;
490
+ }
491
+ innerJoin(expression, bindings = []) {
492
+ this._addJoin("INNER JOIN", expression, bindings);
493
+ return this;
494
+ }
495
+ leftOuterJoin(expression, bindings = []) {
496
+ this._addJoin("LEFT OUTER JOIN", expression, bindings);
497
+ return this;
498
+ }
499
+ fullOuterJoin(expression, bindings = []) {
500
+ this._addJoin("FULL OUTER JOIN", expression, bindings);
501
+ return this;
502
+ }
503
+ rightOuterJoin(expression, bindings = []) {
504
+ this._addJoin("RIGHT OUTER JOIN", expression, bindings);
505
+ return this;
506
+ }
507
+ unjoin(table) {
508
+ if (Array.isArray(table)) {
509
+ table.forEach((t) => this.unjoin(t));
510
+ return this;
511
+ }
512
+ this._joins = this._joins.filter((join) => {
513
+ const regex = new RegExp(`JOIN ${table}\\b`);
514
+ return !regex.test(join);
515
+ });
516
+ return this;
517
+ }
518
+ _conditions(collection, criteria) {
519
+ const numArgs = criteria.length;
520
+ let [column, operator, value] = criteria;
521
+ if (typeof column === "object") {
522
+ for (const keyValue of Object.entries(column)) {
523
+ this._conditions(collection, keyValue);
524
+ }
525
+ return this;
526
+ }
527
+ if (numArgs === 1) {
528
+ collection.push(column);
529
+ return this;
530
+ } else if (numArgs === 2 && Array.isArray(operator) && operator.length > 0 && substrCount(column, "?") === operator.length) {
531
+ const values = operator;
532
+ const sql = column.replace(/\?/g, () => {
533
+ this._bindings.push(values.shift());
534
+ return `__BOUND_${this._bindings.length - 1}__`;
535
+ });
536
+ collection.push(sql);
537
+ return this;
538
+ } else if (numArgs === 2) {
539
+ value = operator;
540
+ const parts = column.split(" ");
541
+ column = parts.shift();
542
+ operator = parts.join(" ");
543
+ }
544
+ if (typeof operator !== "string" || operator === "") {
545
+ operator = "=";
546
+ }
547
+ operator = operator.toLocaleUpperCase();
548
+ const likeMatch = operator.match(/^(LIKE|NOT LIKE|ILIKE|NOT ILIKE)(?: (\?|\?%|%\?|%\?%))?$/i);
549
+ if (operator === "NOT BETWEEN" || operator === "BETWEEN") {
550
+ const one = this._bindings.length;
551
+ const two = this._bindings.length + 1;
552
+ collection.push(`${column} ${operator} __BOUND_${one}__ AND __BOUND_${two}__`);
553
+ this._bindings.push(value[0], value[1]);
554
+ } else if (likeMatch) {
555
+ const like = likeMatch[1].toUpperCase();
556
+ const infix = likeMatch[2] || "?";
557
+ if (Array.isArray(value)) {
558
+ const ors = [];
559
+ for (const v of value) {
560
+ ors.push(`${column} ${like} __BOUND_${this._bindings.length}__`);
561
+ this._bindings.push(infix.replace("?", v));
562
+ }
563
+ const joined = ors.join(" OR ");
564
+ collection.push(`(${joined})`);
565
+ } else {
566
+ collection.push(`${column} ${like} __BOUND_${this._bindings.length}__`);
567
+ this._bindings.push(infix.replace("?", value || ""));
568
+ }
569
+ } else if (value === null) {
570
+ collection.push(operator === "=" ? `${column} IS NULL` : `${column} IS NOT NULL`);
571
+ } else if (Array.isArray(value)) {
572
+ const inVals = [];
573
+ for (let i = 0;i < value.length; i++) {
574
+ inVals.push(`__BOUND_${this._bindings.length}__`);
575
+ this._bindings.push(value[i]);
576
+ }
577
+ const joined = inVals.join(", ");
578
+ collection.push(operator === "=" || operator === "IN" ? `${column} IN(${joined})` : `${column} NOT IN(${joined})`);
579
+ } else if (operator === "IN" || operator === "NOT IN") {
580
+ collection.push(`${column} ${operator}(__BOUND_${this._bindings.length}__)`);
581
+ this._bindings.push(value);
582
+ } else {
583
+ collection.push(`${column} ${operator} __BOUND_${this._bindings.length}__`);
584
+ this._bindings.push(value);
585
+ }
586
+ return this;
587
+ }
588
+ groupBy(column) {
589
+ this._groupBys.push(column);
590
+ return this;
591
+ }
592
+ where(...args) {
593
+ this._conditions(this._wheres, args);
594
+ return this;
595
+ }
596
+ whereBetween(column, twoValueArray) {
597
+ if (!isNullish(twoValueArray[0]) && !isNullish(twoValueArray[1])) {
598
+ this.where(column, "BETWEEN", twoValueArray);
599
+ } else if (!isNullish(twoValueArray[0]) && isNullish(twoValueArray[1])) {
600
+ this.where(column, ">=", twoValueArray[0]);
601
+ } else if (isNullish(twoValueArray[0]) && !isNullish(twoValueArray[1])) {
602
+ this.where(column, "<=", twoValueArray[1]);
603
+ } else {}
604
+ return this;
605
+ }
606
+ _orConditions(conditions) {
607
+ const items = [];
608
+ if (Array.isArray(conditions)) {
609
+ for (const condition of conditions) {
610
+ if (Array.isArray(condition)) {
611
+ this._conditions(items, condition);
612
+ } else {
613
+ this._conditions(items, [condition]);
614
+ }
615
+ }
616
+ } else {
617
+ for (const [key, value] of Object.entries(conditions)) {
618
+ const one = [];
619
+ this._conditions(one, [key, value]);
620
+ items.push(one[0]);
621
+ }
622
+ }
623
+ const joined = items.join(" OR ");
624
+ if (joined.startsWith("(") && joined.endsWith(")")) {
625
+ return joined.slice(1, -1);
626
+ } else {
627
+ return joined;
628
+ }
629
+ }
630
+ orWhere(conditions) {
631
+ const joined = this._orConditions(conditions);
632
+ this.where(`(${joined})`);
633
+ return this;
634
+ }
635
+ orHaving(conditions) {
636
+ const joined = this._orConditions(conditions);
637
+ this.having(`(${joined})`);
638
+ return this;
639
+ }
640
+ having(...args) {
641
+ this._conditions(this._havings, args);
642
+ return this;
643
+ }
644
+ orderBy(column, direction = null) {
645
+ if (direction) {
646
+ this._orderBys.push(`${column} ${direction}`);
647
+ } else {
648
+ const expression = column.replace(/^-(.+)/, "$1 DESC");
649
+ this._orderBys.push(expression);
650
+ }
651
+ return this;
652
+ }
653
+ sortField(fieldName, mapNames = {}) {
654
+ let direction = "ASC";
655
+ if (fieldName.startsWith("-")) {
656
+ direction = "DESC";
657
+ fieldName = fieldName.slice(1);
658
+ }
659
+ const column = mapNames[fieldName] || fieldName;
660
+ this.orderBy(column, direction);
661
+ return this;
662
+ }
663
+ _isEntirelyDigits(string) {
664
+ return /^(0|[1-9]\d*)$/.test(string);
665
+ }
666
+ _isEntirelyDigitsNoZeros(string) {
667
+ return /^[1-9]\d*$/.test(string);
668
+ }
669
+ limit(max) {
670
+ if (typeof max === "string") {
671
+ max = max.trim();
672
+ if (this._isEntirelyDigitsNoZeros(max)) {
673
+ this._limit = parseInt(max, 10);
674
+ }
675
+ } else if (typeof max === "number" && Number.isInteger(max) && max >= 1) {
676
+ this._limit = max;
677
+ } else {
678
+ throw new Error(`SelectBuilder: "limit(n)" must receive a positive integer (got "${max}")`);
679
+ }
680
+ return this;
681
+ }
682
+ offset(number) {
683
+ if (typeof number === "string" && this._isEntirelyDigits(number.trim())) {
684
+ this._offset = parseInt(number, 10);
685
+ } else if (typeof number === "number" && Number.isInteger(number) && number >= 0) {
686
+ this._offset = number;
687
+ } else {
688
+ throw new Error(`SelectBuilder: "offset(n)" must receive a positive integer (got "${number}")`);
689
+ }
690
+ return this;
691
+ }
692
+ page(number) {
693
+ if (typeof number === "string" && this._isEntirelyDigitsNoZeros(number.trim())) {
694
+ this._page = parseInt(number, 10);
695
+ } else if (typeof number === "number" && Number.isInteger(number) && number >= 1) {
696
+ this._page = number;
697
+ } else {
698
+ throw new Error('SelectBuilder: "page(n)" must receive a positive integer');
699
+ }
700
+ return this;
701
+ }
702
+ }
703
+ // src/extractGrouped/extractGrouped.ts
704
+ function extractGrouped(field, records) {
705
+ let idx = 0;
706
+ const grouped = {};
707
+ for (const record of records) {
708
+ if (!(field in record)) {
709
+ throw new Error(`Column "${String(field)}" is not present in record ${idx}`);
710
+ }
711
+ if (!grouped[record[field]]) {
712
+ grouped[record[field]] = [];
713
+ }
714
+ grouped[record[field]].push(record);
715
+ idx++;
716
+ }
717
+ return grouped;
718
+ }
719
+ // src/extractIndexed/extractIndexed.ts
720
+ function extractIndexed(field, records) {
721
+ let idx = 0;
722
+ const indexed = {};
723
+ for (const record of records) {
724
+ if (!(field in record)) {
725
+ throw new Error(`Column "${String(field)}" is not present in record ${idx}`);
726
+ }
727
+ indexed[record[field]] = record;
728
+ idx++;
729
+ }
730
+ return indexed;
731
+ }
732
+ // src/extractLookup/extractLookup.ts
733
+ function extractLookup(keyField, valueField, records) {
734
+ const lookup = {};
735
+ let idx = 0;
736
+ for (const record of records) {
737
+ if (!(keyField in record)) {
738
+ throw new Error(`Column "${String(keyField)}" is not present in record ${idx}`);
739
+ }
740
+ if (!(valueField in record)) {
741
+ throw new Error(`Column "${String(valueField)}" is not present in record ${idx}`);
742
+ }
743
+ idx++;
744
+ lookup[String(record[keyField])] = record[valueField];
745
+ }
746
+ return lookup;
747
+ }
748
+ // src/getPagination/getPagination.ts
749
+ function getPagination(query, total) {
750
+ total = Number(total) || 0;
751
+ const perPage = Number(query._limit) || null;
752
+ let page = null;
753
+ if (total === 0) {
754
+ page = null;
755
+ } else if (query._page) {
756
+ page = Number(query._page);
757
+ } else if (query._limit && query._offset) {
758
+ page = Math.floor(Number(query._offset) / Number(query._limit)) + 1;
759
+ } else if (query._limit && !query._offset) {
760
+ page = 1;
761
+ } else {
762
+ page = null;
763
+ }
764
+ const numPages = total === 0 || perPage === null ? 0 : Math.ceil(total / perPage) || 0;
765
+ const isFirst = page === 1;
766
+ const isLast = numPages > 0 && page === numPages;
767
+ const prevPage = numPages === 0 ? null : page - 1 || null;
768
+ const nextPage = numPages > 0 && page + 1 <= numPages ? page + 1 : null;
769
+ return {
770
+ page,
771
+ prevPage,
772
+ nextPage,
773
+ perPage,
774
+ numPages,
775
+ total,
776
+ isFirst,
777
+ isLast
778
+ };
779
+ }
780
+ // src/runMysql/runMysql.ts
781
+ function _queryToPromise(mysqlClient, sql, bindings) {
782
+ return new Promise((resolve, reject) => {
783
+ mysqlClient.query(sql, bindings, (err, rows, fields) => {
784
+ if (err) {
785
+ reject(err);
786
+ return;
787
+ }
788
+ resolve([rows, fields]);
789
+ });
790
+ });
791
+ }
792
+ async function runMysql(mysqlClient, query) {
793
+ const { sql, bindings } = query.compile({ engine: "mysql" });
794
+ return _queryToPromise(mysqlClient, sql, bindings);
795
+ }
796
+ async function runMysqlWithCount(mysqlClient, query, { countExpr = "*" } = {}) {
797
+ const { sql, bindings } = query.compile({ engine: "mysql" });
798
+ const [records, fields] = await _queryToPromise(mysqlClient, sql, bindings);
799
+ if (records.length > 0) {
800
+ const { sql: sql2, bindings: bindings2 } = query.compileCount({
801
+ engine: "mysql",
802
+ countExpr
803
+ });
804
+ const [rows] = await _queryToPromise(mysqlClient, sql2, bindings2);
805
+ const total = rows[0].found_rows;
806
+ return { records, total, pagination: getPagination(query, total), fields };
807
+ } else {
808
+ return { records, total: 0, pagination: getPagination(query, 0), fields };
809
+ }
810
+ }
811
+ async function runMysqlAsync(mysqlClient, query) {
812
+ const { sql, bindings } = query.compile({ engine: "mysql" });
813
+ return mysqlClient.query(sql, bindings);
814
+ }
815
+ async function runMysqlAsyncWithCount(mysqlClient, query, {
816
+ engine = "mysql",
817
+ countExpr = "*"
818
+ } = {}) {
819
+ const { sql, bindings } = query.compile({ engine });
820
+ const [records, fields] = await mysqlClient.query(sql, bindings);
821
+ if (records.length > 0) {
822
+ const { sql: sql2, bindings: bindings2 } = query.compileCount({ engine, countExpr });
823
+ const [rows] = await mysqlClient.query(sql2, bindings2);
824
+ const total = rows[0].found_rows;
825
+ return { records, total, pagination: getPagination(query, total), fields };
826
+ } else {
827
+ return { records, total: 0, pagination: getPagination(query, 0), fields };
828
+ }
829
+ }
830
+ // src/toSafeJson/toSafeJson.ts
831
+ function toSafeJsonValue(value) {
832
+ if (typeof value === "bigint") {
833
+ const asNumber = Number(value);
834
+ return value == asNumber ? asNumber : value.toString();
835
+ }
836
+ return value;
837
+ }
838
+ function toSafeJsonRecord(record) {
839
+ const newRecord = {};
840
+ for (const key in record) {
841
+ if (!Object.prototype.hasOwnProperty.call(record, key)) {
842
+ continue;
843
+ }
844
+ newRecord[key] = toSafeJsonValue(record[key]);
845
+ }
846
+ return newRecord;
847
+ }
848
+ function toSafeJsonRecords(records) {
849
+ return records.map(toSafeJsonRecord);
850
+ }
851
+ function toSafeJsonString(records) {
852
+ return JSON.stringify(records, (_, value) => toSafeJsonValue(value));
853
+ }
854
+
855
+ // src/runPrisma/runPrisma.ts
856
+ async function runPrisma(prisma, query, { engine = undefined } = {}) {
857
+ const { sql, bindings } = query.compile({ engine });
858
+ return prisma.$queryRawUnsafe(sql, ...bindings);
859
+ }
860
+ async function runPrismaWithCount(prisma, query, {
861
+ engine = undefined,
862
+ countExpr = "*"
863
+ } = {}) {
864
+ const { sql, bindings } = query.compile({ engine });
865
+ const records = await prisma.$queryRawUnsafe(sql, ...bindings);
866
+ if (records.length > 0) {
867
+ const { sql: sql2, bindings: bindings2 } = query.compileCount({ engine, countExpr });
868
+ const result = await prisma.$queryRawUnsafe(sql2, ...bindings2);
869
+ const total = toSafeJsonValue(result[0].found_rows);
870
+ return { records, total, pagination: getPagination(query, total) };
871
+ } else {
872
+ return { records, total: 0, pagination: getPagination(query, 0) };
873
+ }
874
+ }