@iamkirbki/database-handler-core 2.0.0

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.
@@ -0,0 +1,409 @@
1
+ /**
2
+ * QueryStatementBuilder - Utility class for building SQL query strings
3
+ *
4
+ * Provides static methods to construct SQL statements in a consistent, safe manner.
5
+ * All methods use named parameters (@fieldName syntax) for better-sqlite3 compatibility.
6
+ *
7
+ * Features:
8
+ * - Consistent query building pattern using array concatenation
9
+ * - Support for SELECT, INSERT, UPDATE, DELETE, and COUNT operations
10
+ * - JOIN support with nested join capabilities
11
+ * - WHERE clause building with AND conditions
12
+ * - Query options (ORDER BY, LIMIT, OFFSET)
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * // Build a SELECT query
17
+ * const query = QueryStatementBuilder.BuildSelect(usersTable, {
18
+ * select: 'id, name, email',
19
+ * where: { status: 'active' },
20
+ * orderBy: 'created_at DESC',
21
+ * limit: 10
22
+ * });
23
+ * // Result: "SELECT id, name, email FROM users WHERE status = @status ORDER BY created_at DESC LIMIT 10"
24
+ *
25
+ * // Build an INSERT query
26
+ * const insertQuery = QueryStatementBuilder.BuildInsert(usersTable, {
27
+ * name: 'John',
28
+ * email: 'john@example.com'
29
+ * });
30
+ * // Result: "INSERT INTO users (name, email) VALUES (@name, @email)"
31
+ * ```
32
+ */
33
+ export default class QueryStatementBuilder {
34
+ /**
35
+ * Build a SELECT SQL statement with optional filtering, ordering, and pagination
36
+ *
37
+ * @param table - The table to select from
38
+ * @param options - Query options including select columns, where conditions, orderBy, limit, offset
39
+ * @returns Complete SELECT SQL statement string
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * // Select all columns
44
+ * const query = QueryStatementBuilder.BuildSelect(usersTable);
45
+ * // "SELECT * FROM users"
46
+ *
47
+ * // Select specific columns with filtering
48
+ * const query = QueryStatementBuilder.BuildSelect(usersTable, {
49
+ * select: 'id, name, email',
50
+ * where: { status: 'active', age: 25 },
51
+ * orderBy: 'created_at DESC',
52
+ * limit: 10,
53
+ * offset: 20
54
+ * });
55
+ * // "SELECT id, name, email FROM users WHERE status = @status AND age = @age ORDER BY created_at DESC LIMIT 10 OFFSET 20"
56
+ * ```
57
+ */
58
+ static BuildSelect(table, options) {
59
+ var _a;
60
+ const queryParts = [];
61
+ queryParts.push(`SELECT ${(_a = options === null || options === void 0 ? void 0 : options.select) !== null && _a !== void 0 ? _a : "*"}`);
62
+ queryParts.push(`FROM "${table.Name}"`);
63
+ queryParts.push(this.BuildWhere(options === null || options === void 0 ? void 0 : options.where));
64
+ queryParts.push(this.BuildQueryOptions(options !== null && options !== void 0 ? options : {}));
65
+ return queryParts.join(" ");
66
+ }
67
+ /**
68
+ * Build an INSERT SQL statement with named parameter placeholders
69
+ *
70
+ * @param table - The table to insert into
71
+ * @param record - Object containing column names and their placeholder values
72
+ * @returns Complete INSERT SQL statement string with @fieldName placeholders
73
+ *
74
+ * @example
75
+ * ```typescript
76
+ * const query = QueryStatementBuilder.BuildInsert(usersTable, {
77
+ * name: 'John',
78
+ * email: 'john@example.com',
79
+ * age: 30
80
+ * });
81
+ * // "INSERT INTO users (name, email, age) VALUES (@name, @email, @age)"
82
+ *
83
+ * // Note: The actual values will be bound separately using the Parameters object
84
+ * ```
85
+ */
86
+ static BuildInsert(table, record) {
87
+ const queryParts = [];
88
+ const columns = Object.keys(record);
89
+ const placeholders = columns.map(col => `@${col}`);
90
+ queryParts.push(`INSERT INTO "${table.Name}"`);
91
+ queryParts.push(`(${columns.join(", ")})`);
92
+ queryParts.push(`VALUES (${placeholders.join(", ")})`);
93
+ return queryParts.join(" ");
94
+ }
95
+ /**
96
+ * Build an UPDATE SQL statement with SET clause and WHERE conditions
97
+ *
98
+ * @param table - The table to update
99
+ * @param record - Object containing columns to update with their placeholder values
100
+ * @param where - Object containing WHERE conditions for targeting specific rows
101
+ * @returns Complete UPDATE SQL statement string with @fieldName placeholders
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * const query = QueryStatementBuilder.BuildUpdate(
106
+ * usersTable,
107
+ * { name: 'John Doe', age: 31 },
108
+ * { id: 1 }
109
+ * );
110
+ * // "UPDATE users SET name = @name, age = @age WHERE id = @id"
111
+ *
112
+ * // Multiple WHERE conditions
113
+ * const query = QueryStatementBuilder.BuildUpdate(
114
+ * usersTable,
115
+ * { status: 'inactive' },
116
+ * { status: 'active', last_login: '2023-01-01' }
117
+ * );
118
+ * // "UPDATE users SET status = @status WHERE status = @status AND last_login = @last_login"
119
+ * ```
120
+ */
121
+ static BuildUpdate(table, record, where) {
122
+ const queryParts = [];
123
+ const setClauses = Object.keys(record).map(col => `${col} = @${col}`);
124
+ queryParts.push(`UPDATE "${table.Name}"`);
125
+ queryParts.push(`SET ${setClauses.join(", ")}`);
126
+ queryParts.push(this.BuildWhere(where));
127
+ return queryParts.join(" ");
128
+ }
129
+ /**
130
+ * Build a DELETE SQL statement with WHERE conditions
131
+ *
132
+ * @param table - The table to delete from
133
+ * @param where - Object containing WHERE conditions for targeting specific rows to delete
134
+ * @returns Complete DELETE SQL statement string with @fieldName placeholders
135
+ *
136
+ * @example
137
+ * ```typescript
138
+ * const query = QueryStatementBuilder.BuildDelete(usersTable, { id: 1 });
139
+ * // "DELETE FROM users WHERE id = @id"
140
+ *
141
+ * // Multiple WHERE conditions
142
+ * const query = QueryStatementBuilder.BuildDelete(usersTable, {
143
+ * status: 'deleted',
144
+ * last_login: '2020-01-01'
145
+ * });
146
+ * // "DELETE FROM users WHERE status = @status AND last_login = @last_login"
147
+ * ```
148
+ */
149
+ static BuildDelete(table, where) {
150
+ const queryParts = [];
151
+ queryParts.push(`DELETE FROM "${table.Name}"`);
152
+ queryParts.push(this.BuildWhere(where));
153
+ return queryParts.join(" ");
154
+ }
155
+ /**
156
+ * Build a COUNT SQL statement to count rows, optionally with WHERE conditions
157
+ *
158
+ * @param table - The table to count rows from
159
+ * @param where - Optional object containing WHERE conditions to filter counted rows
160
+ * @returns Complete COUNT SQL statement string with @fieldName placeholders
161
+ *
162
+ * @example
163
+ * ```typescript
164
+ * // Count all rows
165
+ * const query = QueryStatementBuilder.BuildCount(usersTable);
166
+ * // "SELECT COUNT(*) as count FROM users"
167
+ *
168
+ * // Count with conditions
169
+ * const query = QueryStatementBuilder.BuildCount(usersTable, {
170
+ * status: 'active',
171
+ * age: 25
172
+ * });
173
+ * // "SELECT COUNT(*) as count FROM users WHERE status = @status AND age = @age"
174
+ * ```
175
+ */
176
+ static BuildCount(table, where) {
177
+ const queryParts = [];
178
+ queryParts.push(`SELECT COUNT(*) as count FROM "${table.Name}"`);
179
+ queryParts.push(this.BuildWhere(where));
180
+ return queryParts.join(" ");
181
+ }
182
+ /**
183
+ * Build a WHERE clause from parameter conditions (helper method)
184
+ *
185
+ * Joins multiple conditions with AND operator.
186
+ * Returns empty string if no conditions are provided.
187
+ *
188
+ * @param where - Optional object containing WHERE conditions
189
+ * @returns WHERE clause string with @fieldName placeholders, or empty string if no conditions
190
+ *
191
+ * @example
192
+ * ```typescript
193
+ * // Single condition
194
+ * const whereClause = QueryStatementBuilder.BuildWhere({ id: 1 });
195
+ * // "WHERE id = @id"
196
+ *
197
+ * // Multiple conditions (joined with AND)
198
+ * const whereClause = QueryStatementBuilder.BuildWhere({
199
+ * status: 'active',
200
+ * age: 25,
201
+ * role: 'admin'
202
+ * });
203
+ * // "WHERE status = @status AND age = @age AND role = @role"
204
+ *
205
+ * // No conditions
206
+ * const whereClause = QueryStatementBuilder.BuildWhere();
207
+ * // ""
208
+ * ```
209
+ */
210
+ static BuildWhere(where) {
211
+ if (!where)
212
+ return "";
213
+ const queryParts = [];
214
+ const whereClauses = Object.keys(where).map(col => `${col} = @${col}`);
215
+ queryParts.push("WHERE");
216
+ queryParts.push(whereClauses.join(" AND "));
217
+ return queryParts.join(" ");
218
+ }
219
+ /**
220
+ * Build a SELECT statement with JOIN operations (INNER, LEFT, RIGHT, FULL)
221
+ *
222
+ * Supports single or multiple joins, including nested joins.
223
+ * Combines the base SELECT with JOIN clauses and query options.
224
+ * The join type (INNER, LEFT, RIGHT, FULL) is specified in each Join object.
225
+ *
226
+ * @param fromTable - The primary table to select from
227
+ * @param joins - Single Join object or array of Join objects defining the join operations
228
+ * @param options - Query options including select columns, orderBy, limit, offset
229
+ * @returns Complete SELECT statement with JOIN clauses
230
+ *
231
+ * @example
232
+ * ```typescript
233
+ * // Single INNER JOIN
234
+ * const query = QueryStatementBuilder.BuildJoin(
235
+ * usersTable,
236
+ * { fromTable: ordersTable, joinType: 'INNER', on: { user_id: 'id' } },
237
+ * { select: 'users.*, orders.total' }
238
+ * );
239
+ * // "SELECT users.*, orders.total FROM users INNER JOIN orders ON users.id = orders.user_id"
240
+ *
241
+ * // Multiple joins with different types
242
+ * const query = QueryStatementBuilder.BuildJoin(
243
+ * usersTable,
244
+ * [
245
+ * { fromTable: ordersTable, joinType: 'INNER', on: { user_id: 'id' } },
246
+ * { fromTable: addressesTable, joinType: 'LEFT', on: { address_id: 'id' } }
247
+ * ],
248
+ * { orderBy: 'users.created_at DESC', limit: 10 }
249
+ * );
250
+ *
251
+ * // Nested JOIN
252
+ * const query = QueryStatementBuilder.BuildJoin(
253
+ * usersTable,
254
+ * {
255
+ * fromTable: ordersTable,
256
+ * joinType: 'INNER',
257
+ * on: { user_id: 'id' },
258
+ * join: { fromTable: productsTable, joinType: 'INNER', on: { product_id: 'id' } }
259
+ * }
260
+ * );
261
+ * ```
262
+ */
263
+ static BuildJoin(fromTable, joins, options) {
264
+ var _a;
265
+ const queryParts = [];
266
+ queryParts.push(`SELECT ${(_a = options === null || options === void 0 ? void 0 : options.select) !== null && _a !== void 0 ? _a : "*"}`);
267
+ queryParts.push(`FROM "${fromTable.Name}"`);
268
+ queryParts.push(this.BuildJoinPart(fromTable, joins));
269
+ queryParts.push(this.BuildWhere(options === null || options === void 0 ? void 0 : options.where));
270
+ queryParts.push(this.BuildQueryOptions(options !== null && options !== void 0 ? options : {}));
271
+ return queryParts.join(" ");
272
+ }
273
+ /**
274
+ * Build JOIN clause(s) recursively (helper method)
275
+ *
276
+ * Processes single or multiple join definitions and handles nested joins.
277
+ * Each join includes the JOIN clause (INNER, LEFT, RIGHT, FULL) and ON conditions.
278
+ *
279
+ * @param fromTable - The table being joined from (for ON clause context)
280
+ * @param joins - Single Join object or array of Join objects
281
+ * @returns JOIN clause(s) as a string
282
+ *
283
+ * @example
284
+ * ```typescript
285
+ * // Single INNER JOIN
286
+ * const joinClause = QueryStatementBuilder.BuildJoinPart(
287
+ * usersTable,
288
+ * { fromTable: ordersTable, joinType: 'INNER', on: { user_id: 'id' } }
289
+ * );
290
+ * // "INNER JOIN orders ON users.id = orders.user_id"
291
+ *
292
+ * // LEFT JOIN
293
+ * const joinClause = QueryStatementBuilder.BuildJoinPart(
294
+ * usersTable,
295
+ * { fromTable: profilesTable, joinType: 'LEFT', on: { profile_id: 'id' } }
296
+ * );
297
+ * // "LEFT JOIN profiles ON users.id = profiles.profile_id"
298
+ *
299
+ * // Nested join
300
+ * const joinClause = QueryStatementBuilder.BuildJoinPart(
301
+ * usersTable,
302
+ * {
303
+ * fromTable: ordersTable,
304
+ * joinType: 'INNER',
305
+ * on: { user_id: 'id' },
306
+ * join: { fromTable: productsTable, joinType: 'INNER', on: { product_id: 'id' } }
307
+ * }
308
+ * );
309
+ * // "INNER JOIN orders ON users.id = orders.user_id INNER JOIN products ON orders.id = products.product_id"
310
+ * ```
311
+ */
312
+ static BuildJoinPart(fromTable, joins) {
313
+ const queryParts = [];
314
+ const joinsArray = Array.isArray(joins) ? joins : [joins];
315
+ let currentTable = fromTable;
316
+ for (const join of joinsArray) {
317
+ queryParts.push(`${join.joinType} JOIN ${join.fromTable.Name}`);
318
+ queryParts.push(this.BuildJoinOnPart(currentTable, join.fromTable, join.on));
319
+ currentTable = join.fromTable;
320
+ }
321
+ return queryParts.join(" ");
322
+ }
323
+ /**
324
+ * Build ON clause for JOIN operations (helper method)
325
+ *
326
+ * Creates ON conditions for join operations.
327
+ * Compares the foreign key column in the joined table with the primary key in the source table.
328
+ * Multiple conditions are joined with AND operator.
329
+ *
330
+ * @param table - The source table (left side of the join)
331
+ * @param joinTable - The table being joined (right side of the join)
332
+ * @param on - QueryParameters object where key is the foreign key in joinTable and value is the primary key in table
333
+ * @returns ON clause string for JOIN operations
334
+ *
335
+ * @example
336
+ * ```typescript
337
+ * // Single ON condition
338
+ * // Key: column in joinTable (orders), Value: column in table (users)
339
+ * const onClause = QueryStatementBuilder.BuildJoinOnPart(
340
+ * usersTable,
341
+ * ordersTable,
342
+ * { user_id: 'id' }
343
+ * );
344
+ * // "ON users.id = orders.user_id"
345
+ *
346
+ * // Multiple ON conditions
347
+ * const onClause = QueryStatementBuilder.BuildJoinOnPart(
348
+ * usersTable,
349
+ * ordersTable,
350
+ * [{ user_id: 'id' }, { company_id: 'company_id' }]
351
+ * );
352
+ * // "ON users.id = orders.user_id AND users.company_id = orders.company_id"
353
+ * ```
354
+ */
355
+ static BuildJoinOnPart(table, joinTable, on) {
356
+ const queryParts = [];
357
+ const onArray = Array.isArray(on) ? on : [on];
358
+ for (const onPart of onArray) {
359
+ queryParts.push(`ON ${table.Name}.${Object.values(onPart)[0]} = ${joinTable.Name}.${Object.keys(onPart)[0]}`);
360
+ }
361
+ return queryParts.join(" AND ");
362
+ }
363
+ /**
364
+ * Build query options clause (ORDER BY, LIMIT, OFFSET) (helper method)
365
+ *
366
+ * Processes query options and builds the corresponding SQL clauses.
367
+ * Returns empty string if no options are provided.
368
+ *
369
+ * @param options - Object containing orderBy, limit, and/or offset options
370
+ * @returns Query options clause as a string
371
+ *
372
+ * @example
373
+ * ```typescript
374
+ * // All options
375
+ * const optionsClause = QueryStatementBuilder.BuildQueryOptions({
376
+ * orderBy: 'created_at DESC',
377
+ * limit: 10,
378
+ * offset: 20
379
+ * });
380
+ * // "ORDER BY created_at DESC LIMIT 10 OFFSET 20"
381
+ *
382
+ * // Just ordering
383
+ * const optionsClause = QueryStatementBuilder.BuildQueryOptions({
384
+ * orderBy: 'name ASC'
385
+ * });
386
+ * // "ORDER BY name ASC"
387
+ *
388
+ * // Pagination only
389
+ * const optionsClause = QueryStatementBuilder.BuildQueryOptions({
390
+ * limit: 25,
391
+ * offset: 50
392
+ * });
393
+ * // "LIMIT 25 OFFSET 50"
394
+ * ```
395
+ */
396
+ static BuildQueryOptions(options) {
397
+ const queryParts = [];
398
+ if (options === null || options === void 0 ? void 0 : options.orderBy) {
399
+ queryParts.push(`ORDER BY ${options.orderBy}`);
400
+ }
401
+ if (options === null || options === void 0 ? void 0 : options.limit) {
402
+ queryParts.push(`LIMIT ${options.limit}`);
403
+ if (options === null || options === void 0 ? void 0 : options.offset) {
404
+ queryParts.push(`OFFSET ${options.offset}`);
405
+ }
406
+ }
407
+ return queryParts.join(" ");
408
+ }
409
+ }