@starbemtech/star-db-query-builder 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintrc.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "env": {
3
+ "es2021": true,
4
+ "node": true
5
+ },
6
+ "extends": [
7
+ "eslint:recommended",
8
+ "prettier",
9
+ "plugin:@typescript-eslint/recommended"
10
+ ],
11
+ "parser": "@typescript-eslint/parser",
12
+ "parserOptions": {
13
+ "ecmaVersion": "latest",
14
+ "sourceType": "module"
15
+ },
16
+ "plugins": [
17
+ "@typescript-eslint",
18
+ "prettier"
19
+ ],
20
+ "rules": {
21
+ "prettier/prettier": "error",
22
+ "@typescript-eslint/explicit-function-return-type": "off",
23
+ "@typescript-eslint/no-explicit-any": "off",
24
+ "@typescript-eslint/explicit-module-boundary-types": "off",
25
+ "@typescript-eslint/no-require-imports": "off",
26
+ "import/prefer-default-export": "off",
27
+ "no-param-reassign": "off",
28
+ "no-console": "off",
29
+ "no-return-assign": "off",
30
+ "array-callback-return": "off"
31
+ }
32
+ }
@@ -1,6 +1,6 @@
1
1
  <?xml version="1.0" encoding="UTF-8"?>
2
- <coverage generated="1711563334484" clover="3.2.0">
3
- <project timestamp="1711563334484" name="All files">
2
+ <coverage generated="1711588190593" clover="3.2.0">
3
+ <project timestamp="1711588190593" name="All files">
4
4
  <metrics statements="0" coveredstatements="0" conditionals="0" coveredconditionals="0" methods="0" coveredmethods="0" elements="0" coveredelements="0" complexity="0" loc="0" ncloc="0" packages="0" files="0" classes="0"/>
5
5
  </project>
6
6
  </coverage>
@@ -86,7 +86,7 @@
86
86
  <div class='footer quiet pad2 space-top1 center small'>
87
87
  Code coverage generated by
88
88
  <a href="https://istanbul.js.org/" target="_blank" rel="noopener noreferrer">istanbul</a>
89
- at 2024-03-27T18:15:34.481Z
89
+ at 2024-03-28T01:09:50.588Z
90
90
  </div>
91
91
  <script src="prettify.js"></script>
92
92
  <script>
@@ -0,0 +1,32 @@
1
+ {
2
+ "env": {
3
+ "es2021": true,
4
+ "node": true
5
+ },
6
+ "extends": [
7
+ "eslint:recommended",
8
+ "prettier",
9
+ "plugin:@typescript-eslint/recommended"
10
+ ],
11
+ "parser": "@typescript-eslint/parser",
12
+ "parserOptions": {
13
+ "ecmaVersion": "latest",
14
+ "sourceType": "module"
15
+ },
16
+ "plugins": [
17
+ "@typescript-eslint",
18
+ "prettier"
19
+ ],
20
+ "rules": {
21
+ "prettier/prettier": "error",
22
+ "@typescript-eslint/explicit-function-return-type": "off",
23
+ "@typescript-eslint/no-explicit-any": "off",
24
+ "@typescript-eslint/explicit-module-boundary-types": "off",
25
+ "@typescript-eslint/no-require-imports": "off",
26
+ "import/prefer-default-export": "off",
27
+ "no-param-reassign": "off",
28
+ "no-console": "off",
29
+ "no-return-assign": "off",
30
+ "array-callback-return": "off"
31
+ }
32
+ }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- import { PoolConfig } from 'pg';
2
- import { PoolOptions } from 'mysql2';
1
+ import { PoolConfig as PgPoolConfig } from 'pg';
2
+ import { PoolOptions as MySqlPoolOptions } from 'mysql2';
3
3
  export * from './src/db/initDb';
4
4
  export * from './src/default/genericRepository';
5
- export type PgPoolConfig = PoolConfig;
6
- export type MySqlPoolOptions = PoolOptions;
5
+ export type { PgPoolConfig, MySqlPoolOptions };
@@ -0,0 +1,5 @@
1
+ import { DBClients } from '../default/types';
2
+ export type IDatabaseClient = {
3
+ clientType: DBClients;
4
+ query: <T>(sql: string, params?: any[]) => Promise<T>;
5
+ };
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=IDatabaseClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IDatabaseClient.js","sourceRoot":"","sources":["../../../src/db/IDatabaseClient.ts"],"names":[],"mappings":""}
@@ -0,0 +1,7 @@
1
+ import { IDatabaseClient } from './IDatabaseClient';
2
+ import { DBClients } from '../default/types';
3
+ export declare const initDb: <T>(config: {
4
+ type: DBClients;
5
+ options: T;
6
+ }) => void;
7
+ export declare const getDbClient: () => IDatabaseClient;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getDbClient = exports.initDb = void 0;
4
+ const pg_1 = require("pg");
5
+ const promise_1 = require("mysql2/promise");
6
+ const pgClient_1 = require("./pgClient");
7
+ const mysqlClient_1 = require("./mysqlClient");
8
+ let dbClient = null;
9
+ const initDb = (config) => {
10
+ if (!config.type)
11
+ throw new Error('Type is required. Accept values: pg | mysql');
12
+ if (!config.options)
13
+ throw new Error('Connection options is required');
14
+ if (config.type === 'pg') {
15
+ const pool = new pg_1.Pool(config.options);
16
+ dbClient = (0, pgClient_1.createPgClient)(pool);
17
+ console.log(`@starbemtech/star-db-query-builder: Postgres db client created success`);
18
+ }
19
+ else if (config.type === 'mysql') {
20
+ const pool = (0, promise_1.createPool)(config.options);
21
+ dbClient = (0, mysqlClient_1.createMysqlClient)(pool);
22
+ console.info(`@starbemtech/star-db-query-builder: MySQL db client created success.`);
23
+ }
24
+ else {
25
+ throw new Error('Unsupported database type');
26
+ }
27
+ };
28
+ exports.initDb = initDb;
29
+ const getDbClient = () => {
30
+ if (!dbClient) {
31
+ throw new Error('Database client is not initialized');
32
+ }
33
+ return dbClient;
34
+ };
35
+ exports.getDbClient = getDbClient;
36
+ //# sourceMappingURL=initDb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initDb.js","sourceRoot":"","sources":["../../../src/db/initDb.ts"],"names":[],"mappings":";;;AAAA,2BAAmC;AACnC,4CAA8D;AAC9D,yCAA2C;AAC3C,+CAAiD;AAIjD,IAAI,QAAQ,GAA2B,IAAI,CAAA;AAEpC,MAAM,MAAM,GAAG,CAAI,MAAuC,EAAQ,EAAE;IACzE,IAAI,CAAC,MAAM,CAAC,IAAI;QACd,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAA;IAEhE,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAA;IAEtE,IAAI,MAAM,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;QACzB,MAAM,IAAI,GAAG,IAAI,SAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;QACvC,QAAQ,GAAG,IAAA,yBAAc,EAAC,IAAI,CAAC,CAAA;QAE/B,OAAO,CAAC,GAAG,CACT,wEAAwE,CACzE,CAAA;IACH,CAAC;SAAM,IAAI,MAAM,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;QACnC,MAAM,IAAI,GAAG,IAAA,oBAAe,EAAC,MAAM,CAAC,OAAO,CAAC,CAAA;QAC5C,QAAQ,GAAG,IAAA,+BAAiB,EAAC,IAAI,CAAC,CAAA;QAElC,OAAO,CAAC,IAAI,CACV,sEAAsE,CACvE,CAAA;IACH,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAA;IAC9C,CAAC;AACH,CAAC,CAAA;AAvBY,QAAA,MAAM,UAuBlB;AAEM,MAAM,WAAW,GAAG,GAAoB,EAAE;IAC/C,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAA;IACvD,CAAC;IAED,OAAO,QAAQ,CAAA;AACjB,CAAC,CAAA;AANY,QAAA,WAAW,eAMvB"}
@@ -0,0 +1,3 @@
1
+ import { Pool } from 'mysql2/promise';
2
+ import { IDatabaseClient } from './IDatabaseClient';
3
+ export declare const createMysqlClient: (pool: Pool) => IDatabaseClient;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createMysqlClient = void 0;
4
+ const createMysqlClient = (pool) => ({
5
+ clientType: 'mysql',
6
+ query: async (sql, params) => {
7
+ const [rows] = await pool.execute(sql, params);
8
+ return rows;
9
+ },
10
+ });
11
+ exports.createMysqlClient = createMysqlClient;
12
+ //# sourceMappingURL=mysqlClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mysqlClient.js","sourceRoot":"","sources":["../../../src/db/mysqlClient.ts"],"names":[],"mappings":";;;AAGO,MAAM,iBAAiB,GAAG,CAAC,IAAU,EAAmB,EAAE,CAAC,CAAC;IACjE,UAAU,EAAE,OAAO;IACnB,KAAK,EAAE,KAAK,EAAK,GAAW,EAAE,MAAc,EAAc,EAAE;QAC1D,MAAM,CAAC,IAAI,CAAC,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;QAC9C,OAAO,IAAoB,CAAA;IAC7B,CAAC;CACF,CAAC,CAAA;AANW,QAAA,iBAAiB,qBAM5B"}
@@ -0,0 +1,3 @@
1
+ import { Pool } from 'pg';
2
+ import { IDatabaseClient } from './IDatabaseClient';
3
+ export declare const createPgClient: (pool: Pool) => IDatabaseClient;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPgClient = void 0;
4
+ const createPgClient = (pool) => ({
5
+ clientType: 'pg',
6
+ query: async (sql, params) => {
7
+ const { rows } = await pool.query(sql, params);
8
+ return rows;
9
+ },
10
+ });
11
+ exports.createPgClient = createPgClient;
12
+ //# sourceMappingURL=pgClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pgClient.js","sourceRoot":"","sources":["../../../src/db/pgClient.ts"],"names":[],"mappings":";;;AAGO,MAAM,cAAc,GAAG,CAAC,IAAU,EAAmB,EAAE,CAAC,CAAC;IAC9D,UAAU,EAAE,IAAI;IAChB,KAAK,EAAE,KAAK,EAAK,GAAW,EAAE,MAAc,EAAc,EAAE;QAC1D,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;QAC9C,OAAO,IAAoB,CAAA;IAC7B,CAAC;CACF,CAAC,CAAA;AANW,QAAA,cAAc,kBAMzB"}
@@ -0,0 +1,14 @@
1
+ import { QueryParams } from './types';
2
+ export declare const findFirst: <T>({ tableName, dbClient, select, where, groupBy, orderBy, }: QueryParams) => Promise<T>;
3
+ export declare const findMany: <T>({ tableName, dbClient, select, where, groupBy, orderBy, limit, }: QueryParams) => Promise<T[]>;
4
+ export declare const insert: <T>({ tableName, dbClient, data, returning, }: QueryParams & {
5
+ data: T;
6
+ returning?: string[] | undefined;
7
+ }) => Promise<T | void>;
8
+ export declare const update: <T>({ tableName, dbClient, id, data, returning, }: QueryParams & {
9
+ data: T;
10
+ returning?: string[] | undefined;
11
+ }) => Promise<T | void>;
12
+ export declare const deleteOne: ({ tableName, dbClient, id, permanently, }: QueryParams & {
13
+ permanently?: boolean | undefined;
14
+ }) => Promise<void>;
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deleteOne = exports.update = exports.insert = exports.findMany = exports.findFirst = void 0;
4
+ const uuid_1 = require("uuid");
5
+ const utils_1 = require("./utils");
6
+ const findFirst = async ({ tableName, dbClient, select, where, groupBy, orderBy, }) => {
7
+ if (!tableName)
8
+ throw new Error('Table name is required');
9
+ if (!dbClient)
10
+ throw new Error('DB client is required');
11
+ const fields = (0, utils_1.createSelectFields)(select, dbClient.clientType);
12
+ const [whereClause, params] = (0, utils_1.createWhereClause)(where, 1, dbClient.clientType);
13
+ const orderByClause = (0, utils_1.createOrderByClause)(orderBy);
14
+ const groupByClause = (0, utils_1.createGroupByClause)(groupBy);
15
+ const rows = await dbClient.query(`SELECT ${fields} FROM ${tableName}
16
+ ${whereClause.length > 7 ? whereClause : ''}
17
+ ${groupByClause}
18
+ ${orderByClause}
19
+ `, params);
20
+ return rows[0] || null;
21
+ };
22
+ exports.findFirst = findFirst;
23
+ const findMany = async ({ tableName, dbClient, select, where, groupBy, orderBy, limit, }) => {
24
+ if (!tableName)
25
+ throw new Error('Table name is required');
26
+ if (!dbClient)
27
+ throw new Error('DB client is required');
28
+ const fields = (0, utils_1.createSelectFields)(select, dbClient.clientType);
29
+ const [whereClause, params] = (0, utils_1.createWhereClause)(where, 1, dbClient.clientType);
30
+ const orderByClause = (0, utils_1.createOrderByClause)(orderBy);
31
+ const groupByClause = (0, utils_1.createGroupByClause)(groupBy);
32
+ const limitClause = (0, utils_1.createLimitClause)(limit);
33
+ const rows = await dbClient.query(`SELECT ${fields} FROM ${tableName}
34
+ ${whereClause.length > 7 ? whereClause : ''}
35
+ ${groupByClause}
36
+ ${orderByClause}
37
+ ${limitClause}
38
+ `, params);
39
+ return rows || [];
40
+ };
41
+ exports.findMany = findMany;
42
+ const insert = async ({ tableName, dbClient, data, returning, }) => {
43
+ if (!tableName)
44
+ throw new Error('Table name is required');
45
+ if (!dbClient)
46
+ throw new Error('DB client is required');
47
+ if (!data)
48
+ throw new Error('Data object is required');
49
+ const keys = Object.keys(data);
50
+ const values = Object.values(data);
51
+ keys.unshift('id');
52
+ const generatedUUID = (0, uuid_1.v4)();
53
+ values.unshift(generatedUUID);
54
+ keys.push('updated_at');
55
+ values.push(new Date());
56
+ const placeholders = (0, utils_1.generatePlaceholders)(keys, dbClient.clientType);
57
+ let query = `INSERT INTO ${tableName} (${keys.join(', ')}) VALUES (${placeholders})`;
58
+ if (dbClient.clientType === 'pg') {
59
+ if (returning && returning.length > 0) {
60
+ query += ` RETURNING ${(0, utils_1.createSelectFields)(returning, dbClient.clientType)}`;
61
+ }
62
+ }
63
+ const inserted = await dbClient.query(query, values);
64
+ if (dbClient.clientType === 'mysql') {
65
+ const rows = await dbClient.query(`SELECT ${returning && returning.length > 0
66
+ ? (0, utils_1.createSelectFields)(returning, dbClient.clientType)
67
+ : '*'} FROM ${tableName}
68
+ WHERE
69
+ id = ?
70
+ `, [generatedUUID]);
71
+ return rows[0];
72
+ }
73
+ return inserted[0];
74
+ };
75
+ exports.insert = insert;
76
+ const update = async ({ tableName, dbClient, id, data, returning, }) => {
77
+ if (!tableName)
78
+ throw new Error('Table name is required');
79
+ if (!dbClient)
80
+ throw new Error('DB client is required');
81
+ if (!id)
82
+ throw new Error('ID is required');
83
+ if (!data)
84
+ throw new Error('Data object is required');
85
+ const keys = Object.keys(data);
86
+ const values = Object.values(data);
87
+ const setClause = (0, utils_1.generateSetClause)(keys, dbClient.clientType);
88
+ let query = `UPDATE ${tableName} SET ${setClause} WHERE ${id}`;
89
+ if (dbClient.clientType === 'pg') {
90
+ if (returning && returning.length > 0) {
91
+ query += ` RETURNIN ${(0, utils_1.createSelectFields)(returning, dbClient.clientType)}`;
92
+ }
93
+ }
94
+ const updated = await dbClient.query(query, values);
95
+ if (dbClient.clientType === 'mysql') {
96
+ const rows = await dbClient.query(`SELECT ${returning && returning.length > 0
97
+ ? (0, utils_1.createSelectFields)(returning, dbClient.clientType)
98
+ : '*'} FROM ${tableName}
99
+ WHERE
100
+ id = ?
101
+ `, [id]);
102
+ return rows[0];
103
+ }
104
+ return updated[0];
105
+ };
106
+ exports.update = update;
107
+ const deleteOne = async ({ tableName, dbClient, id, permanently = false, }) => {
108
+ if (!tableName)
109
+ throw new Error('Table name is required');
110
+ if (!dbClient)
111
+ throw new Error('DB client is required');
112
+ if (!id)
113
+ throw new Error('ID is required');
114
+ await dbClient.query(permanently
115
+ ? `DELETE FROM ${tableName} WHERE id = ${dbClient.clientType === 'pg' ? '$1' : '?'}`
116
+ : `UPDATE ${tableName} SET status = 'deleted' WHERE id = ${dbClient.clientType === 'pg' ? '$1' : '?'}`, [id]);
117
+ };
118
+ exports.deleteOne = deleteOne;
119
+ //# sourceMappingURL=genericRepository.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"genericRepository.js","sourceRoot":"","sources":["../../../src/default/genericRepository.ts"],"names":[],"mappings":";;;AAAA,+BAAiC;AAEjC,mCAQgB;AAET,MAAM,SAAS,GAAG,KAAK,EAAK,EACjC,SAAS,EACT,QAAQ,EACR,MAAM,EACN,K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,CAAC;IAED,OAAO,OAAO,CAAC,CAAC,CAAC,CAAA;AACnB,CAAC,CAAA;AA3CY,QAAA,MAAM,UA2ClB;AAEM,MAAM,SAAS,GAAG,KAAK,EAAE,EAC9B,SAAS,EACT,QAAQ,EACR,EAAE,EACF,WAAW,GAAG,KAAK,GACqB,EAAiB,EAAE;IAC3D,IAAI,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAA;IACzD,IAAI,CAAC,QAAQ;QAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAA;IACvD,IAAI,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC,CAAA;IAE1C,MAAM,QAAQ,CAAC,KAAK,CAClB,WAAW;QACT,CAAC,CAAC,eAAe,SAAS,eACtB,QAAQ,CAAC,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GACxC,EAAE;QACJ,CAAC,CAAC,UAAU,SAAS,sCACjB,QAAQ,CAAC,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GACxC,EAAE,EACN,CAAC,EAAE,CAAC,CACL,CAAA;AACH,CAAC,CAAA;AApBY,QAAA,SAAS,aAoBrB"}
@@ -0,0 +1,35 @@
1
+ import { IDatabaseClient } from '../db/IDatabaseClient';
2
+ export interface QueryExec {
3
+ text: string;
4
+ values?: any[];
5
+ }
6
+ type SimpleValue = string | number | boolean | Date;
7
+ type ConditionOperator = 'AND' | 'OR';
8
+ interface OperatorCondition {
9
+ operator: 'LIKE' | '=' | '>' | '<' | 'IN' | 'BETWEEN' | '!=' | '<=' | '>=' | 'NOT IN' | 'LIKE' | 'NOT LIKE';
10
+ value: SimpleValue | SimpleValue[];
11
+ }
12
+ export type DBClients = 'pg' | 'mysql';
13
+ export interface CompositeCondition {
14
+ type: ConditionOperator;
15
+ conditions: Condition[];
16
+ }
17
+ export type Condition = SimpleValue | OperatorCondition | CompositeCondition;
18
+ export interface Conditions {
19
+ [key: string]: Condition;
20
+ }
21
+ export type OrderBy = {
22
+ field: string;
23
+ direction: 'ASC' | 'DESC';
24
+ }[];
25
+ export interface QueryParams {
26
+ tableName: string;
27
+ dbClient: IDatabaseClient;
28
+ id?: string;
29
+ select?: string[];
30
+ where?: Conditions;
31
+ orderBy?: OrderBy;
32
+ groupBy?: string[];
33
+ limit?: number;
34
+ }
35
+ export {};
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/default/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,8 @@
1
+ import { Conditions, OrderBy, DBClients } from './types';
2
+ export declare const createSelectFields: (fields: string[] | undefined, clientType: DBClients) => string;
3
+ export declare const generatePlaceholders: (keys: any[], clientType: DBClients) => string;
4
+ export declare const generateSetClause: (keys: any[], clientType: DBClients) => string;
5
+ export declare const createWhereClause: (conditions: Conditions | undefined, startIndex: number | undefined, clientType: DBClients) => [string, any[], number];
6
+ export declare const createOrderByClause: (orderBy?: OrderBy) => string;
7
+ export declare const createGroupByClause: (groupBy?: string[]) => string;
8
+ export declare const createLimitClause: (limit?: number) => string;
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createLimitClause = exports.createGroupByClause = exports.createOrderByClause = exports.createWhereClause = exports.generateSetClause = exports.generatePlaceholders = exports.createSelectFields = void 0;
4
+ const arrayToStringWithQuotes = (items, clientType) => {
5
+ const itemsWithQuotes = items.map((item) => clientType === 'pg' ? `"${item}"` : `${item}`);
6
+ return itemsWithQuotes.join(', ');
7
+ };
8
+ const pgPlaceholderGenerator = (index) => `$${index}`;
9
+ const mysqlPlaceholderGenerator = () => `?`;
10
+ const createSelectFields = (fields = [], clientType) => {
11
+ return fields && fields.length > 0
12
+ ? arrayToStringWithQuotes(fields, clientType)
13
+ : '*';
14
+ };
15
+ exports.createSelectFields = createSelectFields;
16
+ const generatePlaceholders = (keys, clientType) => {
17
+ return keys
18
+ .map((_, index) => (clientType === 'pg' ? `$${index + 1}` : '?'))
19
+ .join(', ');
20
+ };
21
+ exports.generatePlaceholders = generatePlaceholders;
22
+ const generateSetClause = (keys, clientType) => {
23
+ return keys
24
+ .map((key, index) => clientType === 'pg' ? `${key} = $${index + 1}` : `${key} = ?`)
25
+ .join(', ');
26
+ };
27
+ exports.generateSetClause = generateSetClause;
28
+ const createWhereClause = (conditions = {}, startIndex = 1, clientType) => {
29
+ let index = startIndex;
30
+ const whereParts = [];
31
+ const values = [];
32
+ const processCondition = (key, condition) => {
33
+ if (typeof condition === 'object' && condition !== null) {
34
+ if ('operator' in condition && 'value' in condition) {
35
+ const { operator, value } = condition;
36
+ if (Array.isArray(value)) {
37
+ const placeholders = value
38
+ .map(() => clientType === 'pg'
39
+ ? pgPlaceholderGenerator(index++)
40
+ : mysqlPlaceholderGenerator())
41
+ .join(', ');
42
+ if (operator === 'BETWEEN') {
43
+ whereParts.push(clientType === 'pg'
44
+ ? `"${key}" ${operator} ${placeholders.replace(', ', ' AND ')}`
45
+ : `${key} ${operator} ${placeholders.replace(', ', ' AND ')}`);
46
+ }
47
+ else {
48
+ whereParts.push(clientType === 'pg'
49
+ ? `"${key}" ${operator} (${placeholders})`
50
+ : `${key} ${operator} ${placeholders}`);
51
+ }
52
+ values.push(...value);
53
+ }
54
+ else {
55
+ whereParts.push(clientType === 'pg'
56
+ ? `"${key}" ${operator} ${pgPlaceholderGenerator(index++)}`
57
+ : `${key} ${operator} ${mysqlPlaceholderGenerator()}`);
58
+ values.push(value);
59
+ }
60
+ }
61
+ else if ('type' in condition && 'conditions' in condition) {
62
+ const compositeCondition = condition;
63
+ const subWhereParts = [];
64
+ compositeCondition.conditions.forEach((subCondition) => {
65
+ // Recurso: criar uma chave fictícia, pois as condições compostas não necessitam de chave
66
+ index = processCondition('', subCondition);
67
+ });
68
+ whereParts.push(`(${subWhereParts.join(` ${compositeCondition.type} `)})`);
69
+ }
70
+ }
71
+ else if (key) {
72
+ // Condição simples
73
+ whereParts.push(clientType === 'pg' ? `"${key}" = $${index}` : `${key} = ?`);
74
+ values.push(condition);
75
+ index++;
76
+ }
77
+ return index;
78
+ };
79
+ Object.entries(conditions).forEach(([key, value]) => {
80
+ index = processCondition(key, value);
81
+ });
82
+ const whereClause = whereParts.length > 0 ? ` WHERE ${whereParts.join(' AND ')}` : '';
83
+ return [whereClause, values, index];
84
+ };
85
+ exports.createWhereClause = createWhereClause;
86
+ const createOrderByClause = (orderBy) => {
87
+ if (!orderBy || orderBy.length === 0)
88
+ return '';
89
+ const clause = orderBy.map((o) => `${o.field} ${o.direction}`).join(', ');
90
+ return ` ORDER BY ${clause}`;
91
+ };
92
+ exports.createOrderByClause = createOrderByClause;
93
+ const createGroupByClause = (groupBy) => {
94
+ if (!groupBy || groupBy.length === 0)
95
+ return '';
96
+ return ` GROUP BY ${groupBy.join(', ')}`;
97
+ };
98
+ exports.createGroupByClause = createGroupByClause;
99
+ const createLimitClause = (limit) => {
100
+ if (!limit)
101
+ return '';
102
+ return ` LIMIT ${limit}`;
103
+ };
104
+ exports.createLimitClause = createLimitClause;
105
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/default/utils.ts"],"names":[],"mappings":";;;AAQA,MAAM,uBAAuB,GAAG,CAC9B,KAAe,EACf,UAAqB,EACb,EAAE;IACV,MAAM,eAAe,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACzC,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,IAAI,EAAE,CAC9C,CAAA;IACD,OAAO,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AACnC,CAAC,CAAA;A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AW,GACf,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;IACnE,OAAO,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;AACrC,CAAC,CAAA;AAxEY,QAAA,iBAAiB,qBAwE7B;AAEM,MAAM,mBAAmB,GAAG,CAAC,OAAiB,EAAE,EAAE;IACvD,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAA;IAC/C,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IACzE,OAAO,aAAa,MAAM,EAAE,CAAA;AAC9B,CAAC,CAAA;AAJY,QAAA,mBAAmB,uBAI/B;AAEM,MAAM,mBAAmB,GAAG,CAAC,OAAkB,EAAE,EAAE;IACxD,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAA;IAC/C,OAAO,aAAa,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAA;AAC1C,CAAC,CAAA;AAHY,QAAA,mBAAmB,uBAG/B;AAEM,MAAM,iBAAiB,GAAG,CAAC,KAAc,EAAE,EAAE;IAClD,IAAI,CAAC,KAAK;QAAE,OAAO,EAAE,CAAA;IACrB,OAAO,UAAU,KAAK,EAAE,CAAA;AAC1B,CAAC,CAAA;AAHY,QAAA,iBAAiB,qBAG7B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@starbemtech/star-db-query-builder",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "A query builder to be used with mysql or postgres",
5
5
  "author": "Julio Sousa <julio.sousa@starbem.app>",
6
6
  "main": "./dist/index.js",
@@ -35,6 +35,7 @@
35
35
  "@types/mysql": "^2.15.26",
36
36
  "@types/node": "^20.11.30",
37
37
  "@types/pg": "^8.11.4",
38
+ "@types/uuid": "^9.0.8",
38
39
  "@typescript-eslint/eslint-plugin": "^7.4.0",
39
40
  "@typescript-eslint/parser": "^7.4.0",
40
41
  "eslint": "^8.57.0",
@@ -51,7 +52,8 @@
51
52
  },
52
53
  "dependencies": {
53
54
  "mysql2": "^3.9.3",
54
- "pg": "^8.11.3"
55
+ "pg": "^8.11.3",
56
+ "uuid": "^9.0.1"
55
57
  },
56
58
  "lint-staged": {
57
59
  "*.{ts}": [
@@ -0,0 +1,6 @@
1
+ import { DBClients } from '../default/types'
2
+
3
+ export type IDatabaseClient = {
4
+ clientType: DBClients
5
+ query: <T>(sql: string, params?: any[]) => Promise<T>
6
+ }
@@ -0,0 +1,41 @@
1
+ import { Pool as PgPool } from 'pg'
2
+ import { createPool as createMySqlPool } from 'mysql2/promise'
3
+ import { createPgClient } from './pgClient'
4
+ import { createMysqlClient } from './mysqlClient'
5
+ import { IDatabaseClient } from './IDatabaseClient'
6
+ import { DBClients } from '../default/types'
7
+
8
+ let dbClient: IDatabaseClient | null = null
9
+
10
+ export const initDb = <T>(config: { type: DBClients; options: T }): void => {
11
+ if (!config.type)
12
+ throw new Error('Type is required. Accept values: pg | mysql')
13
+
14
+ if (!config.options) throw new Error('Connection options is required')
15
+
16
+ if (config.type === 'pg') {
17
+ const pool = new PgPool(config.options)
18
+ dbClient = createPgClient(pool)
19
+
20
+ console.log(
21
+ `@starbemtech/star-db-query-builder: Postgres db client created success`
22
+ )
23
+ } else if (config.type === 'mysql') {
24
+ const pool = createMySqlPool(config.options)
25
+ dbClient = createMysqlClient(pool)
26
+
27
+ console.info(
28
+ `@starbemtech/star-db-query-builder: MySQL db client created success.`
29
+ )
30
+ } else {
31
+ throw new Error('Unsupported database type')
32
+ }
33
+ }
34
+
35
+ export const getDbClient = (): IDatabaseClient => {
36
+ if (!dbClient) {
37
+ throw new Error('Database client is not initialized')
38
+ }
39
+
40
+ return dbClient
41
+ }
@@ -0,0 +1,10 @@
1
+ import { Pool } from 'mysql2/promise'
2
+ import { IDatabaseClient } from './IDatabaseClient'
3
+
4
+ export const createMysqlClient = (pool: Pool): IDatabaseClient => ({
5
+ clientType: 'mysql',
6
+ query: async <T>(sql: string, params?: any[]): Promise<T> => {
7
+ const [rows] = await pool.execute(sql, params)
8
+ return rows as unknown as T
9
+ },
10
+ })
@@ -0,0 +1,10 @@
1
+ import { Pool } from 'pg'
2
+ import { IDatabaseClient } from './IDatabaseClient'
3
+
4
+ export const createPgClient = (pool: Pool): IDatabaseClient => ({
5
+ clientType: 'pg',
6
+ query: async <T>(sql: string, params?: any[]): Promise<T> => {
7
+ const { rows } = await pool.query(sql, params)
8
+ return rows as unknown as T
9
+ },
10
+ })
@@ -0,0 +1,202 @@
1
+ import { v4 as uuid } from 'uuid'
2
+ import { QueryParams } from './types'
3
+ import {
4
+ createGroupByClause,
5
+ createLimitClause,
6
+ createOrderByClause,
7
+ generatePlaceholders,
8
+ createSelectFields,
9
+ createWhereClause,
10
+ generateSetClause,
11
+ } from './utils'
12
+
13
+ export const findFirst = async <T>({
14
+ tableName,
15
+ dbClient,
16
+ select,
17
+ where,
18
+ groupBy,
19
+ orderBy,
20
+ }: QueryParams<T>): Promise<T | null> => {
21
+ if (!tableName) throw new Error('Table name is required')
22
+ if (!dbClient) throw new Error('DB client is required')
23
+
24
+ const fields = createSelectFields(select, dbClient.clientType)
25
+ const [whereClause, params] = createWhereClause<T>(
26
+ where,
27
+ 1,
28
+ dbClient.clientType
29
+ )
30
+ console.log(whereClause, 'WHERE')
31
+ console.log(params)
32
+ const orderByClause = createOrderByClause(orderBy)
33
+ const groupByClause = createGroupByClause(groupBy)
34
+ try {
35
+ const rows = await dbClient.query<T>(
36
+ `SELECT ${fields} FROM ${tableName}
37
+ ${whereClause.length > 7 ? whereClause : ''}
38
+ ${groupByClause}
39
+ ${orderByClause}
40
+ `,
41
+ params
42
+ )
43
+
44
+ return rows[0] || null
45
+ } catch (error) {
46
+ console.log(error, 'ERROR QUERY')
47
+ return null
48
+ }
49
+ }
50
+
51
+ export const findMany = async <T>({
52
+ tableName,
53
+ dbClient,
54
+ select,
55
+ where,
56
+ groupBy,
57
+ orderBy,
58
+ limit,
59
+ }: QueryParams<T>): Promise<T[]> => {
60
+ if (!tableName) throw new Error('Table name is required')
61
+ if (!dbClient) throw new Error('DB client is required')
62
+
63
+ const fields = createSelectFields(select, dbClient.clientType)
64
+ const [whereClause, params] = createWhereClause(where, 1, dbClient.clientType)
65
+ const orderByClause = createOrderByClause(orderBy)
66
+ const groupByClause = createGroupByClause(groupBy)
67
+ const limitClause = createLimitClause(limit)
68
+
69
+ const rows = await dbClient.query<T[]>(
70
+ `SELECT ${fields} FROM ${tableName}
71
+ ${whereClause.length > 7 ? whereClause : ''}
72
+ ${groupByClause}
73
+ ${orderByClause}
74
+ ${limitClause}
75
+ `,
76
+ params
77
+ )
78
+
79
+ return rows || []
80
+ }
81
+
82
+ export const insert = async <T>({
83
+ tableName,
84
+ dbClient,
85
+ data,
86
+ returning,
87
+ }: QueryParams<T> & { data: any; returning?: string[] }): Promise<T> => {
88
+ if (!tableName) throw new Error('Table name is required')
89
+ if (!dbClient) throw new Error('DB client is required')
90
+ if (!data) throw new Error('Data object is required')
91
+
92
+ const keys = Object.keys(data)
93
+ const values = Object.values(data)
94
+
95
+ keys.unshift('id')
96
+ const generatedUUID: string = uuid()
97
+ values.unshift(generatedUUID)
98
+
99
+ keys.push('updated_at')
100
+ values.push(new Date())
101
+
102
+ const placeholders = generatePlaceholders(keys, dbClient.clientType)
103
+ let query = `INSERT INTO ${tableName} (${keys.join(
104
+ ', '
105
+ )}) VALUES (${placeholders})`
106
+
107
+ if (dbClient.clientType === 'pg') {
108
+ if (returning && returning.length > 0) {
109
+ query += ` RETURNING ${createSelectFields(
110
+ returning,
111
+ dbClient.clientType
112
+ )}`
113
+ }
114
+ }
115
+
116
+ const inserted = await dbClient.query<T[]>(query, values)
117
+
118
+ if (dbClient.clientType === 'mysql') {
119
+ const rows = await dbClient.query<T>(
120
+ `SELECT ${
121
+ returning && returning.length > 0
122
+ ? createSelectFields(returning, dbClient.clientType)
123
+ : '*'
124
+ } FROM ${tableName}
125
+ WHERE
126
+ id = ?
127
+ `,
128
+ [generatedUUID]
129
+ )
130
+
131
+ return rows[0]
132
+ }
133
+
134
+ return inserted[0]
135
+ }
136
+
137
+ export const update = async <T>({
138
+ tableName,
139
+ dbClient,
140
+ id,
141
+ data,
142
+ returning,
143
+ }: QueryParams<T> & { data: T; returning?: string[] }): Promise<T | void> => {
144
+ if (!tableName) throw new Error('Table name is required')
145
+ if (!dbClient) throw new Error('DB client is required')
146
+ if (!id) throw new Error('ID is required')
147
+ if (!data) throw new Error('Data object is required')
148
+
149
+ const keys = Object.keys(data)
150
+ const values: any[] = Object.values(data)
151
+
152
+ const setClause = generateSetClause(keys, dbClient.clientType)
153
+ let query = `UPDATE ${tableName} SET ${setClause} WHERE ${id}`
154
+
155
+ if (dbClient.clientType === 'pg') {
156
+ if (returning && returning.length > 0) {
157
+ query += ` RETURNIN ${createSelectFields(returning, dbClient.clientType)}`
158
+ }
159
+ }
160
+
161
+ const updated = await dbClient.query<T[]>(query, values)
162
+
163
+ if (dbClient.clientType === 'mysql') {
164
+ const rows = await dbClient.query<T>(
165
+ `SELECT ${
166
+ returning && returning.length > 0
167
+ ? createSelectFields(returning, dbClient.clientType)
168
+ : '*'
169
+ } FROM ${tableName}
170
+ WHERE
171
+ id = ?
172
+ `,
173
+ [id]
174
+ )
175
+
176
+ return rows[0]
177
+ }
178
+
179
+ return updated[0]
180
+ }
181
+
182
+ export const deleteOne = async <T>({
183
+ tableName,
184
+ dbClient,
185
+ id,
186
+ permanently = false,
187
+ }: QueryParams<T> & { permanently?: boolean }): Promise<void> => {
188
+ if (!tableName) throw new Error('Table name is required')
189
+ if (!dbClient) throw new Error('DB client is required')
190
+ if (!id) throw new Error('ID is required')
191
+
192
+ await dbClient.query(
193
+ permanently
194
+ ? `DELETE FROM ${tableName} WHERE id = ${
195
+ dbClient.clientType === 'pg' ? '$1' : '?'
196
+ }`
197
+ : `UPDATE ${tableName} SET status = 'deleted' WHERE id = ${
198
+ dbClient.clientType === 'pg' ? '$1' : '?'
199
+ }`,
200
+ [id]
201
+ )
202
+ }
@@ -0,0 +1,53 @@
1
+ import { IDatabaseClient } from '../db/IDatabaseClient'
2
+
3
+ export interface QueryExec {
4
+ text: string
5
+ values?: any[]
6
+ }
7
+
8
+ type SimpleValue = string | number | boolean | Date
9
+
10
+ export interface OperatorCondition {
11
+ operator:
12
+ | 'LIKE'
13
+ | '='
14
+ | '>'
15
+ | '<'
16
+ | 'IN'
17
+ | 'BETWEEN'
18
+ | '!='
19
+ | '<='
20
+ | '>='
21
+ | 'NOT IN'
22
+ | 'LIKE'
23
+ | 'NOT LIKE'
24
+ value: SimpleValue | SimpleValue[]
25
+ }
26
+
27
+ export type LogicalOperator = 'OR' | 'AND'
28
+
29
+ export type Condition<T> = OperatorCondition | LogicalCondition<T>
30
+
31
+ interface LogicalCondition<T> {
32
+ OR?: Conditions<T>[]
33
+ AND?: Conditions<T>[]
34
+ }
35
+
36
+ export type Conditions<T> = {
37
+ [P in keyof T]?: Condition<T[P]>
38
+ } & LogicalCondition<T>
39
+
40
+ export type DBClients = 'pg' | 'mysql'
41
+
42
+ export type OrderBy = { field: string; direction: 'ASC' | 'DESC' }[]
43
+
44
+ export interface QueryParams<T> {
45
+ tableName: string
46
+ dbClient: IDatabaseClient
47
+ id?: string
48
+ select?: string[]
49
+ where?: Conditions<T>
50
+ orderBy?: OrderBy
51
+ groupBy?: string[]
52
+ limit?: number
53
+ }
@@ -0,0 +1,150 @@
1
+ import { Conditions, Condition, OrderBy, DBClients } from './types'
2
+
3
+ const arrayToStringWithQuotes = (
4
+ items: string[],
5
+ clientType: DBClients
6
+ ): string => {
7
+ const itemsWithQuotes = items.map((item) =>
8
+ clientType === 'pg' ? `"${item}"` : `${item}`
9
+ )
10
+ return itemsWithQuotes.join(', ')
11
+ }
12
+
13
+ const pgPlaceholderGenerator = (index: number) => `$${index}`
14
+ const mysqlPlaceholderGenerator = () => `?`
15
+
16
+ export const createSelectFields = (
17
+ fields: string[] = [],
18
+ clientType: DBClients
19
+ ): string => {
20
+ return fields && fields.length > 0
21
+ ? arrayToStringWithQuotes(fields, clientType)
22
+ : '*'
23
+ }
24
+
25
+ export const generatePlaceholders = (
26
+ keys: any[],
27
+ clientType: DBClients
28
+ ): string => {
29
+ return keys
30
+ .map((_, index) => (clientType === 'pg' ? `$${index + 1}` : '?'))
31
+ .join(', ')
32
+ }
33
+
34
+ export const generateSetClause = (
35
+ keys: any[],
36
+ clientType: DBClients
37
+ ): string => {
38
+ return keys
39
+ .map((key, index) =>
40
+ clientType === 'pg' ? `${key} = $${index + 1}` : `${key} = ?`
41
+ )
42
+ .join(', ')
43
+ }
44
+
45
+ export const createWhereClause = <T>(
46
+ conditions: Conditions<T> = {},
47
+ startIndex = 1,
48
+ clientType: DBClients
49
+ ): [string, any[], number] => {
50
+ let index = startIndex
51
+ const whereParts: string[] = []
52
+ const values: any[] = []
53
+
54
+ const processCondition = (key: string, condition: Condition<T>) => {
55
+ if (typeof condition === 'object' && condition !== null) {
56
+ if ('operator' in condition && 'value' in condition) {
57
+ const { operator, value } = condition
58
+ if (Array.isArray(value)) {
59
+ const placeholders = value
60
+ .map(() =>
61
+ clientType === 'pg'
62
+ ? pgPlaceholderGenerator(index++)
63
+ : mysqlPlaceholderGenerator()
64
+ )
65
+ .join(', ')
66
+ if (operator === 'BETWEEN') {
67
+ whereParts.push(
68
+ clientType === 'pg'
69
+ ? `"${key}" ${operator} ${placeholders.replace(', ', ' AND ')}`
70
+ : `${key} ${operator} ${placeholders.replace(', ', ' AND ')}`
71
+ )
72
+ } else {
73
+ whereParts.push(
74
+ clientType === 'pg'
75
+ ? `"${key}" ${operator} (${placeholders})`
76
+ : `${key} ${operator} ${placeholders}`
77
+ )
78
+ }
79
+ values.push(...value)
80
+ } else {
81
+ whereParts.push(
82
+ clientType === 'pg'
83
+ ? `"${key}" ${operator} ${pgPlaceholderGenerator(index++)}`
84
+ : `${key} ${operator} ${mysqlPlaceholderGenerator()}`
85
+ )
86
+ values.push(value)
87
+ }
88
+ } else {
89
+ console.error('Unsupported condition format: ', condition)
90
+ }
91
+ }
92
+ }
93
+
94
+ if ('OR' in conditions || 'AND' in conditions) {
95
+ const logicalOperator = conditions.OR ? 'OR' : 'AND'
96
+ const compositeConditions = conditions.OR || conditions.AND
97
+
98
+ if (Array.isArray(compositeConditions)) {
99
+ const subWhereParts = compositeConditions
100
+ .map((subCondition) => {
101
+ if (
102
+ typeof subCondition === 'object' &&
103
+ !Array.isArray(subCondition) &&
104
+ subCondition !== null
105
+ ) {
106
+ const key = Object.keys(subCondition)[0]
107
+ const condition = subCondition[key]
108
+ processCondition(key, condition)
109
+ return whereParts.pop()
110
+ }
111
+
112
+ return ''
113
+ })
114
+ .filter((part) => part)
115
+
116
+ whereParts.push(
117
+ clientType === 'pg'
118
+ ? `(${subWhereParts.join(` ${logicalOperator} `)})`
119
+ : `${subWhereParts.join(` ${logicalOperator} `)}`
120
+ )
121
+ }
122
+ } else {
123
+ Object.entries(conditions).forEach(([key, value]) => {
124
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
125
+ // @ts-expect-error
126
+ processCondition(key, value)
127
+ })
128
+ }
129
+
130
+ const whereClause =
131
+ whereParts.length > 0 ? ` WHERE ${whereParts.join(' AND ')}` : ''
132
+
133
+ return [whereClause, values, index]
134
+ }
135
+
136
+ export const createOrderByClause = (orderBy?: OrderBy) => {
137
+ if (!orderBy || orderBy.length === 0) return ''
138
+ const clause = orderBy.map((o) => `${o.field} ${o.direction}`).join(', ')
139
+ return ` ORDER BY ${clause}`
140
+ }
141
+
142
+ export const createGroupByClause = (groupBy?: string[]) => {
143
+ if (!groupBy || groupBy.length === 0) return ''
144
+ return ` GROUP BY ${groupBy.join(', ')}`
145
+ }
146
+
147
+ export const createLimitClause = (limit?: number) => {
148
+ if (!limit) return ''
149
+ return ` LIMIT ${limit}`
150
+ }