@constructive-io/query-builder 2.3.3

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/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2025 Constructive <developers@constructive.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,283 @@
1
+ # QueryBuilder
2
+
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml">
9
+ <img height="20" src="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/constructive-io/constructive/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
12
+ <a href="https://www.npmjs.com/package/@constructive-io/query-builder"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=packages%2Fquery-builder%2Fpackage.json"/></a>
13
+ </p>
14
+
15
+ A robust TypeScript-based SQL query builder that supports dynamic generation of `SELECT`, `INSERT`, `UPDATE`, `DELETE`, and stored procedure/function calls. Designed with flexibility and ease of use in mind, it handles advanced SQL features like `JOIN`, `GROUP BY`, `ORDER BY`, and schema-qualified queries.
16
+
17
+ ## Features
18
+
19
+ - Build SQL queries dynamically for:
20
+ - **SELECT**
21
+ - **INSERT**
22
+ - **UPDATE**
23
+ - **DELETE**
24
+ - **Stored procedure calls**
25
+ - Support for:
26
+ - **Dynamic WHERE clauses**
27
+ - **JOINs** with schema handling
28
+ - **GROUP BY**, **ORDER BY**, and **LIMIT**
29
+ - **Schema-qualified entities**
30
+ - **Positional and named parameters** for procedure calls
31
+ - SQL-safe identifier and value escaping.
32
+ - Type-safe value formatting based on `string`, `number`, `boolean`, or `null`.
33
+
34
+ ## Installation
35
+
36
+ Install via npm:
37
+
38
+ ```sh
39
+ npm install @constructive-io/query-builder
40
+ ```
41
+
42
+ ## Getting Started
43
+
44
+ ### Import the Library
45
+
46
+ ```ts
47
+ import { QueryBuilder } from '@constructive-io/query-builder';
48
+ ```
49
+
50
+ ## Usage
51
+
52
+ ### SELECT Query
53
+
54
+ ```ts
55
+ const query = new QueryBuilder()
56
+ .table('users')
57
+ .select(['id', 'name', 'email'])
58
+ .where('age', '>', 18)
59
+ .limit(10)
60
+ .build();
61
+
62
+ console.log(query);
63
+ // Output: SELECT id, name, email FROM users WHERE age > 18 LIMIT 10;
64
+ ```
65
+
66
+ ---
67
+
68
+ ### INSERT Query
69
+
70
+ ```ts
71
+ const query = new QueryBuilder()
72
+ .table('users')
73
+ .insert({ name: 'John', email: 'john@example.com', age: 30 })
74
+ .build();
75
+
76
+ console.log(query);
77
+ // Output: INSERT INTO users (name, email, age) VALUES ('John', 'john@example.com', 30);
78
+ ```
79
+
80
+ ---
81
+
82
+ ### UPDATE Query
83
+
84
+ ```ts
85
+ const query = new QueryBuilder()
86
+ .table('users')
87
+ .update({ name: 'John Doe' })
88
+ .where('id', '=', '1')
89
+ .build();
90
+
91
+ console.log(query);
92
+ // Output: UPDATE users SET name = 'John Doe' WHERE id = '1';
93
+ ```
94
+
95
+ ---
96
+
97
+ ### DELETE Query
98
+
99
+ ```ts
100
+ const query = new QueryBuilder()
101
+ .table('users')
102
+ .delete()
103
+ .where('id', '=', '1')
104
+ .build();
105
+
106
+ console.log(query);
107
+ // Output: DELETE FROM users WHERE id = '1';
108
+ ```
109
+
110
+ ---
111
+
112
+ ### Procedure Call (Positional Parameters)
113
+
114
+ ```ts
115
+ const query = new QueryBuilder()
116
+ .call('my_procedure', [1, 'test', true])
117
+ .build();
118
+
119
+ console.log(query);
120
+ // Output: SELECT my_procedure(1, 'test', true);
121
+ ```
122
+
123
+ ---
124
+
125
+ ### Procedure Call (Named Parameters)
126
+
127
+ ```ts
128
+ const query = new QueryBuilder()
129
+ .call('my_procedure', { id: 42, status: 'active', is_admin: true })
130
+ .build();
131
+
132
+ console.log(query);
133
+ // Output: SELECT my_procedure(id := 42, status := 'active', is_admin := true);
134
+ ```
135
+
136
+ ### Procedure Call with Schema
137
+
138
+ ```ts
139
+ const query = new QueryBuilder()
140
+ .schema('public')
141
+ .call('my_procedure', { id: 42, is_active: true })
142
+ .build();
143
+
144
+ console.log(query);
145
+ // Output: SELECT public.my_procedure(id := 42, is_active := true);
146
+ ```
147
+
148
+ ### JOIN Query
149
+
150
+ ```ts
151
+ const query = new QueryBuilder()
152
+ .table('orders')
153
+ .select(['orders.id', 'customers.name'])
154
+ .join('INNER', 'customers', 'orders.customer_id = customers.id')
155
+ .build();
156
+
157
+ console.log(query);
158
+ // Output: SELECT orders.id, customers.name FROM orders INNER JOIN customers ON orders.customer_id = customers.id;
159
+ ```
160
+
161
+ ### GROUP BY Query
162
+
163
+ ```ts
164
+ const query = new QueryBuilder()
165
+ .table('orders')
166
+ .select(['customer_id', 'SUM(total) AS total_sum'])
167
+ .groupBy(['customer_id'])
168
+ .build();
169
+
170
+ console.log(query);
171
+ // Output: SELECT customer_id, SUM(total) AS total_sum FROM orders GROUP BY customer_id;
172
+ ```
173
+
174
+ ### ORDER BY Query
175
+
176
+ ```ts
177
+ const query = new QueryBuilder()
178
+ .table('products')
179
+ .select(['id', 'name', 'price'])
180
+ .orderBy('price', 'DESC')
181
+ .orderBy('name', 'ASC')
182
+ .build();
183
+
184
+ console.log(query);
185
+ // Output: SELECT id, name, price FROM products ORDER BY price DESC, name ASC;
186
+ ```
187
+
188
+ ## Error Handling
189
+
190
+ ### No Table or Procedure Specified
191
+
192
+ If no table or procedure is specified, `build()` will throw an error:
193
+
194
+ ```ts
195
+ const query = new QueryBuilder();
196
+ query.select(['id']).build(); // Throws Error
197
+
198
+ // Error: Table name or procedure name is not specified.
199
+ ```
200
+
201
+ ## Running Tests
202
+
203
+ Tests are written in Jest. Run the test suite with:
204
+
205
+ ```sh
206
+ npm test:watch
207
+ ```
208
+
209
+ ---
210
+
211
+ ## Education and Tutorials
212
+
213
+ 1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
214
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
215
+
216
+ 2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
217
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
218
+
219
+ 3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
220
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
221
+
222
+ 4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
223
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
224
+
225
+ 5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
226
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
227
+
228
+ 6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
229
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
230
+
231
+ 7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
232
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
233
+
234
+ ## Related Constructive Tooling
235
+
236
+ ### 🧪 Testing
237
+
238
+ * [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
239
+ * [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
240
+ * [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
241
+ * [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
242
+
243
+ ### 🧠 Parsing & AST
244
+
245
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
246
+ * [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
247
+ * [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
248
+ * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
249
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
250
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
251
+ * [pg-ast](https://www.npmjs.com/package/pg-ast): **🔍 Low-level AST tools** and transformations for Postgres query structures.
252
+
253
+ ### 🚀 API & Dev Tools
254
+
255
+ * [@constructive-io/graphql-server](https://github.com/constructive-io/constructive/tree/main/graphql/server): **⚡ Express-based API server** powered by PostGraphile to expose a secure, scalable GraphQL API over your Postgres database.
256
+ * [@constructive-io/graphql-explorer](https://github.com/constructive-io/constructive/tree/main/graphql/explorer): **🔎 Visual API explorer** with GraphiQL for browsing across all databases and schemas—useful for debugging, documentation, and API prototyping.
257
+
258
+ ### 🔁 Streaming & Uploads
259
+
260
+ * [etag-hash](https://github.com/constructive-io/constructive/tree/main/streaming/etag-hash): **🏷️ S3-compatible ETags** created by streaming and hashing file uploads in chunks.
261
+ * [etag-stream](https://github.com/constructive-io/constructive/tree/main/streaming/etag-stream): **🔄 ETag computation** via Node stream transformer during upload or transfer.
262
+ * [uuid-hash](https://github.com/constructive-io/constructive/tree/main/streaming/uuid-hash): **🆔 Deterministic UUIDs** generated from hashed content, great for deduplication and asset referencing.
263
+ * [uuid-stream](https://github.com/constructive-io/constructive/tree/main/streaming/uuid-stream): **🌊 Streaming UUID generation** based on piped file content—ideal for upload pipelines.
264
+ * [@constructive-io/s3-streamer](https://github.com/constructive-io/constructive/tree/main/streaming/s3-streamer): **📤 Direct S3 streaming** for large files with support for metadata injection and content validation.
265
+ * [@constructive-io/upload-names](https://github.com/constructive-io/constructive/tree/main/streaming/upload-names): **📂 Collision-resistant filenames** utility for structured and unique file names for uploads.
266
+
267
+ ### 🧰 CLI & Codegen
268
+
269
+ * [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
270
+ * [@constructive-io/cli](https://github.com/constructive-io/constructive/tree/main/packages/cli): **🖥️ Command-line toolkit** for managing Constructive projects—supports database scaffolding, migrations, seeding, code generation, and automation.
271
+ * [@constructive-io/graphql-codegen](https://github.com/constructive-io/constructive/tree/main/graphql/codegen): **✨ GraphQL code generation** (types, operations, SDK) from schema/endpoint introspection.
272
+ * [@constructive-io/query-builder](https://github.com/constructive-io/constructive/tree/main/packages/query-builder): **🏗️ SQL constructor** providing a robust TypeScript-based query builder for dynamic generation of `SELECT`, `INSERT`, `UPDATE`, `DELETE`, and stored procedure calls—supports advanced SQL features like `JOIN`, `GROUP BY`, and schema-qualified queries.
273
+ * [@constructive-io/graphql-query](https://github.com/constructive-io/constructive/tree/main/graphql/query): **🧩 Fluent GraphQL builder** for PostGraphile schemas. ⚡ Schema-aware via introspection, 🧩 composable and ergonomic for building deeply nested queries.
274
+
275
+ ## Credits
276
+
277
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
278
+
279
+ ## Disclaimer
280
+
281
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
282
+
283
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
@@ -0,0 +1,234 @@
1
+ const RESERVED_KEYWORDS = new Set([
2
+ 'SELECT', 'FROM', 'WHERE', 'INSERT', 'UPDATE', 'DELETE', 'TABLE', 'USER',
3
+ ]);
4
+ export class QueryBuilder {
5
+ schemaName = null;
6
+ entityName = null;
7
+ columns = [];
8
+ values = {};
9
+ whereConditions = [];
10
+ joins = [];
11
+ groupByColumns = [];
12
+ orderByColumns = [];
13
+ limitValue = null;
14
+ parameters = [];
15
+ valueTypes = {};
16
+ isProcedureCall = false;
17
+ schema(schema) {
18
+ this.schemaName = schema;
19
+ return this;
20
+ }
21
+ table(name) {
22
+ this.entityName = name;
23
+ return this;
24
+ }
25
+ select(columns = ['*']) {
26
+ this.columns = columns;
27
+ return this;
28
+ }
29
+ insert(values) {
30
+ this.values = values;
31
+ return this;
32
+ }
33
+ update(values) {
34
+ this.values = values;
35
+ return this;
36
+ }
37
+ delete() {
38
+ return this;
39
+ }
40
+ call(procedure, args = []) {
41
+ this.isProcedureCall = true; // Mark as a procedure call
42
+ const escapedProcedure = this.escapeIdentifier(procedure);
43
+ const escapedSchema = this.schemaName ? `${this.escapeIdentifier(this.schemaName)}.` : '';
44
+ let argsClause = '()';
45
+ if (Array.isArray(args)) {
46
+ // Handle array of arguments
47
+ const formattedArgs = args.map((arg) => this.formatValue('', arg)).join(', ');
48
+ argsClause = args.length > 0 ? `(${formattedArgs})` : '()';
49
+ }
50
+ else if (typeof args === 'object' && args !== null) {
51
+ // Handle keyed object for named parameters
52
+ const formattedArgs = Object.entries(args)
53
+ .map(([key, value]) => `${this.escapeIdentifier(key)} := ${this.formatValue(key, value)}`)
54
+ .join(', ');
55
+ argsClause = Object.keys(args).length > 0 ? `(${formattedArgs})` : '()';
56
+ }
57
+ this.entityName = `${escapedSchema}${escapedProcedure}${argsClause}`;
58
+ return this;
59
+ }
60
+ where(column, operator, value) {
61
+ this.whereConditions.push({ column, operator, value });
62
+ this.parameters.push(value);
63
+ return this;
64
+ }
65
+ join(type, table, on, schema = null) {
66
+ this.joins.push({ type, schema, table, on });
67
+ return this;
68
+ }
69
+ groupBy(columns) {
70
+ this.groupByColumns.push(...columns);
71
+ return this;
72
+ }
73
+ orderBy(column, direction = 'ASC') {
74
+ this.orderByColumns.push({ column, direction });
75
+ return this;
76
+ }
77
+ limit(limit) {
78
+ this.limitValue = limit;
79
+ return this;
80
+ }
81
+ setTypes(types) {
82
+ this.valueTypes = { ...this.valueTypes, ...types };
83
+ return this;
84
+ }
85
+ build() {
86
+ if (!this.entityName) {
87
+ throw new Error('Table name or procedure name is not specified.');
88
+ }
89
+ let query;
90
+ if (this.isProcedureCall) {
91
+ query = this.buildProcedureCall();
92
+ }
93
+ else if (this.columns.length > 0) {
94
+ query = this.buildSelectQuery();
95
+ }
96
+ else if (Object.keys(this.values).length > 0 && this.whereConditions.length > 0) {
97
+ query = this.buildUpdateQuery();
98
+ }
99
+ else if (Object.keys(this.values).length > 0) {
100
+ query = this.buildInsertQuery();
101
+ }
102
+ else {
103
+ query = this.buildDeleteQuery();
104
+ }
105
+ return query;
106
+ }
107
+ buildSelectQuery() {
108
+ const columns = this.columns.map((col) => this.escapeIdentifier(col)).join(', ');
109
+ const joins = this.buildJoinClause();
110
+ const whereClause = this.buildWhereClause();
111
+ const groupByClause = this.buildGroupByClause();
112
+ const orderByClause = this.buildOrderByClause();
113
+ const limitClause = this.limitValue !== null ? ` LIMIT ${this.limitValue}` : '';
114
+ const fullyQualifiedTable = this.getFullyQualifiedTable();
115
+ return `SELECT ${columns} FROM ${fullyQualifiedTable}${joins}${whereClause}${groupByClause}${orderByClause}${limitClause};`;
116
+ }
117
+ buildProcedureCall() {
118
+ if (!this.entityName) {
119
+ throw new Error('Procedure name is not specified.');
120
+ }
121
+ const procedureCall = this.entityName;
122
+ const columns = this.columns.map((col) => this.escapeIdentifier(col)).join(', ');
123
+ if (this.columns.length > 0) {
124
+ // If specific columns are selected
125
+ return `SELECT ${columns} FROM ${procedureCall};`;
126
+ }
127
+ // Default: SELECT procedure()
128
+ return `SELECT ${procedureCall};`;
129
+ }
130
+ buildInsertQuery() {
131
+ const columns = Object.keys(this.values).map((col) => this.escapeIdentifier(col)).join(', ');
132
+ const values = Object.entries(this.values)
133
+ .map(([key, value]) => this.formatValue(key, value)) // Use formatValue here
134
+ .join(', ');
135
+ const fullyQualifiedTable = this.getFullyQualifiedTable();
136
+ return `INSERT INTO ${fullyQualifiedTable} (${columns}) VALUES (${values});`;
137
+ }
138
+ buildUpdateQuery() {
139
+ const setClause = Object.entries(this.values)
140
+ .map(([key, value]) => `${this.escapeIdentifier(key)} = ${this.formatValue(key, value)}`) // Use formatValue here
141
+ .join(', ');
142
+ const whereClause = this.buildWhereClause();
143
+ const fullyQualifiedTable = this.getFullyQualifiedTable();
144
+ return `UPDATE ${fullyQualifiedTable} SET ${setClause}${whereClause};`;
145
+ }
146
+ buildDeleteQuery() {
147
+ const fullyQualifiedTable = this.getFullyQualifiedTable();
148
+ const whereClause = this.buildWhereClause();
149
+ return `DELETE FROM ${fullyQualifiedTable}${whereClause};`;
150
+ }
151
+ buildJoinClause() {
152
+ return this.joins
153
+ .map(({ type, schema, table, on }) => {
154
+ const fullyQualifiedJoinTable = schema
155
+ ? `${this.escapeIdentifier(schema)}.${this.escapeIdentifier(table)}`
156
+ : this.escapeIdentifier(table);
157
+ return ` ${type} JOIN ${fullyQualifiedJoinTable} ON ${on}`;
158
+ })
159
+ .join('');
160
+ }
161
+ buildWhereClause() {
162
+ if (this.whereConditions.length === 0) {
163
+ return '';
164
+ }
165
+ const conditions = this.whereConditions
166
+ .map(({ column, operator, value }) => `${this.escapeIdentifier(column)} ${operator} ${this.formatValue(column, value)}`)
167
+ .join(' AND ');
168
+ return ` WHERE ${conditions}`;
169
+ }
170
+ buildGroupByClause() {
171
+ if (this.groupByColumns.length === 0) {
172
+ return '';
173
+ }
174
+ const groupBy = this.groupByColumns.map((col) => this.escapeIdentifier(col)).join(', ');
175
+ return ` GROUP BY ${groupBy}`;
176
+ }
177
+ buildOrderByClause() {
178
+ if (this.orderByColumns.length === 0) {
179
+ return '';
180
+ }
181
+ const orderBy = this.orderByColumns
182
+ .map(({ column, direction }) => `${this.escapeIdentifier(column)} ${direction}`)
183
+ .join(', ');
184
+ return ` ORDER BY ${orderBy}`;
185
+ }
186
+ escapeIdentifier(identifier) {
187
+ if (this.needsQuoting(identifier)) {
188
+ return `"${identifier.replace(/"/g, '""')}"`;
189
+ }
190
+ return identifier;
191
+ }
192
+ needsQuoting(identifier) {
193
+ return (RESERVED_KEYWORDS.has(identifier.toUpperCase()) ||
194
+ /[^a-zA-Z0-9_]/.test(identifier) ||
195
+ /^\d/.test(identifier));
196
+ }
197
+ formatValue(column, value) {
198
+ const typeHint = this.valueTypes[column];
199
+ if (typeHint) {
200
+ switch (typeHint) {
201
+ case 'string':
202
+ return `'${value.replace(/'/g, "''")}'`;
203
+ case 'number':
204
+ return `${value}`;
205
+ case 'boolean':
206
+ return value ? 'true' : 'false';
207
+ case 'null':
208
+ return 'NULL';
209
+ default:
210
+ throw new Error(`Unsupported type hint: ${typeHint}`);
211
+ }
212
+ }
213
+ if (typeof value === 'string') {
214
+ return `'${value.replace(/'/g, "''")}'`;
215
+ }
216
+ else if (typeof value === 'number' || typeof value === 'boolean') {
217
+ return `${value}`;
218
+ }
219
+ else if (value === null) {
220
+ return 'NULL';
221
+ }
222
+ else {
223
+ throw new Error(`Unsupported value type: ${typeof value}`);
224
+ }
225
+ }
226
+ getFullyQualifiedTable() {
227
+ const escapedSchema = this.schemaName ? this.escapeIdentifier(this.schemaName) : null;
228
+ const escapedTable = this.escapeIdentifier(this.entityName);
229
+ if (escapedSchema) {
230
+ return `${escapedSchema}.${escapedTable}`;
231
+ }
232
+ return escapedTable;
233
+ }
234
+ }
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@constructive-io/query-builder",
3
+ "version": "2.3.3",
4
+ "author": "Constructive <developers@constructive.io>",
5
+ "description": "PostgreSQL Query Builder",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/constructive-io/constructive",
10
+ "license": "MIT",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/constructive-io/constructive"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/constructive-io/constructive/issues"
21
+ },
22
+ "scripts": {
23
+ "clean": "makage clean",
24
+ "prepack": "npm run build",
25
+ "build": "makage build",
26
+ "build:dev": "makage build --dev",
27
+ "lint": "eslint . --fix",
28
+ "test": "jest --passWithNoTests",
29
+ "test:watch": "jest --watch"
30
+ },
31
+ "keywords": [
32
+ "query",
33
+ "builder",
34
+ "sql",
35
+ "constructive",
36
+ "database"
37
+ ],
38
+ "devDependencies": {
39
+ "makage": "^0.1.8"
40
+ },
41
+ "gitHead": "22cfe32e994e26a6490e04e28bab26d1e7e6345c"
42
+ }
@@ -0,0 +1,43 @@
1
+ type ValueType = 'string' | 'number' | 'boolean' | 'null';
2
+ export declare class QueryBuilder {
3
+ private schemaName;
4
+ private entityName;
5
+ private columns;
6
+ private values;
7
+ private whereConditions;
8
+ private joins;
9
+ private groupByColumns;
10
+ private orderByColumns;
11
+ private limitValue;
12
+ private parameters;
13
+ private valueTypes;
14
+ private isProcedureCall;
15
+ schema(schema: string): this;
16
+ table(name: string): this;
17
+ select(columns?: string[]): this;
18
+ insert(values: Record<string, any>): this;
19
+ update(values: Record<string, any>): this;
20
+ delete(): this;
21
+ call(procedure: string, args?: any[] | Record<string, any>): this;
22
+ where(column: string, operator: string, value: any): this;
23
+ join(type: 'INNER' | 'LEFT' | 'RIGHT' | 'FULL', table: string, on: string, schema?: string | null): this;
24
+ groupBy(columns: string[]): this;
25
+ orderBy(column: string, direction?: 'ASC' | 'DESC'): this;
26
+ limit(limit: number): this;
27
+ setTypes(types: Record<string, ValueType>): this;
28
+ build(): string;
29
+ private buildSelectQuery;
30
+ private buildProcedureCall;
31
+ private buildInsertQuery;
32
+ private buildUpdateQuery;
33
+ private buildDeleteQuery;
34
+ private buildJoinClause;
35
+ private buildWhereClause;
36
+ private buildGroupByClause;
37
+ private buildOrderByClause;
38
+ private escapeIdentifier;
39
+ private needsQuoting;
40
+ private formatValue;
41
+ private getFullyQualifiedTable;
42
+ }
43
+ export {};
@@ -0,0 +1,238 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QueryBuilder = void 0;
4
+ const RESERVED_KEYWORDS = new Set([
5
+ 'SELECT', 'FROM', 'WHERE', 'INSERT', 'UPDATE', 'DELETE', 'TABLE', 'USER',
6
+ ]);
7
+ class QueryBuilder {
8
+ schemaName = null;
9
+ entityName = null;
10
+ columns = [];
11
+ values = {};
12
+ whereConditions = [];
13
+ joins = [];
14
+ groupByColumns = [];
15
+ orderByColumns = [];
16
+ limitValue = null;
17
+ parameters = [];
18
+ valueTypes = {};
19
+ isProcedureCall = false;
20
+ schema(schema) {
21
+ this.schemaName = schema;
22
+ return this;
23
+ }
24
+ table(name) {
25
+ this.entityName = name;
26
+ return this;
27
+ }
28
+ select(columns = ['*']) {
29
+ this.columns = columns;
30
+ return this;
31
+ }
32
+ insert(values) {
33
+ this.values = values;
34
+ return this;
35
+ }
36
+ update(values) {
37
+ this.values = values;
38
+ return this;
39
+ }
40
+ delete() {
41
+ return this;
42
+ }
43
+ call(procedure, args = []) {
44
+ this.isProcedureCall = true; // Mark as a procedure call
45
+ const escapedProcedure = this.escapeIdentifier(procedure);
46
+ const escapedSchema = this.schemaName ? `${this.escapeIdentifier(this.schemaName)}.` : '';
47
+ let argsClause = '()';
48
+ if (Array.isArray(args)) {
49
+ // Handle array of arguments
50
+ const formattedArgs = args.map((arg) => this.formatValue('', arg)).join(', ');
51
+ argsClause = args.length > 0 ? `(${formattedArgs})` : '()';
52
+ }
53
+ else if (typeof args === 'object' && args !== null) {
54
+ // Handle keyed object for named parameters
55
+ const formattedArgs = Object.entries(args)
56
+ .map(([key, value]) => `${this.escapeIdentifier(key)} := ${this.formatValue(key, value)}`)
57
+ .join(', ');
58
+ argsClause = Object.keys(args).length > 0 ? `(${formattedArgs})` : '()';
59
+ }
60
+ this.entityName = `${escapedSchema}${escapedProcedure}${argsClause}`;
61
+ return this;
62
+ }
63
+ where(column, operator, value) {
64
+ this.whereConditions.push({ column, operator, value });
65
+ this.parameters.push(value);
66
+ return this;
67
+ }
68
+ join(type, table, on, schema = null) {
69
+ this.joins.push({ type, schema, table, on });
70
+ return this;
71
+ }
72
+ groupBy(columns) {
73
+ this.groupByColumns.push(...columns);
74
+ return this;
75
+ }
76
+ orderBy(column, direction = 'ASC') {
77
+ this.orderByColumns.push({ column, direction });
78
+ return this;
79
+ }
80
+ limit(limit) {
81
+ this.limitValue = limit;
82
+ return this;
83
+ }
84
+ setTypes(types) {
85
+ this.valueTypes = { ...this.valueTypes, ...types };
86
+ return this;
87
+ }
88
+ build() {
89
+ if (!this.entityName) {
90
+ throw new Error('Table name or procedure name is not specified.');
91
+ }
92
+ let query;
93
+ if (this.isProcedureCall) {
94
+ query = this.buildProcedureCall();
95
+ }
96
+ else if (this.columns.length > 0) {
97
+ query = this.buildSelectQuery();
98
+ }
99
+ else if (Object.keys(this.values).length > 0 && this.whereConditions.length > 0) {
100
+ query = this.buildUpdateQuery();
101
+ }
102
+ else if (Object.keys(this.values).length > 0) {
103
+ query = this.buildInsertQuery();
104
+ }
105
+ else {
106
+ query = this.buildDeleteQuery();
107
+ }
108
+ return query;
109
+ }
110
+ buildSelectQuery() {
111
+ const columns = this.columns.map((col) => this.escapeIdentifier(col)).join(', ');
112
+ const joins = this.buildJoinClause();
113
+ const whereClause = this.buildWhereClause();
114
+ const groupByClause = this.buildGroupByClause();
115
+ const orderByClause = this.buildOrderByClause();
116
+ const limitClause = this.limitValue !== null ? ` LIMIT ${this.limitValue}` : '';
117
+ const fullyQualifiedTable = this.getFullyQualifiedTable();
118
+ return `SELECT ${columns} FROM ${fullyQualifiedTable}${joins}${whereClause}${groupByClause}${orderByClause}${limitClause};`;
119
+ }
120
+ buildProcedureCall() {
121
+ if (!this.entityName) {
122
+ throw new Error('Procedure name is not specified.');
123
+ }
124
+ const procedureCall = this.entityName;
125
+ const columns = this.columns.map((col) => this.escapeIdentifier(col)).join(', ');
126
+ if (this.columns.length > 0) {
127
+ // If specific columns are selected
128
+ return `SELECT ${columns} FROM ${procedureCall};`;
129
+ }
130
+ // Default: SELECT procedure()
131
+ return `SELECT ${procedureCall};`;
132
+ }
133
+ buildInsertQuery() {
134
+ const columns = Object.keys(this.values).map((col) => this.escapeIdentifier(col)).join(', ');
135
+ const values = Object.entries(this.values)
136
+ .map(([key, value]) => this.formatValue(key, value)) // Use formatValue here
137
+ .join(', ');
138
+ const fullyQualifiedTable = this.getFullyQualifiedTable();
139
+ return `INSERT INTO ${fullyQualifiedTable} (${columns}) VALUES (${values});`;
140
+ }
141
+ buildUpdateQuery() {
142
+ const setClause = Object.entries(this.values)
143
+ .map(([key, value]) => `${this.escapeIdentifier(key)} = ${this.formatValue(key, value)}`) // Use formatValue here
144
+ .join(', ');
145
+ const whereClause = this.buildWhereClause();
146
+ const fullyQualifiedTable = this.getFullyQualifiedTable();
147
+ return `UPDATE ${fullyQualifiedTable} SET ${setClause}${whereClause};`;
148
+ }
149
+ buildDeleteQuery() {
150
+ const fullyQualifiedTable = this.getFullyQualifiedTable();
151
+ const whereClause = this.buildWhereClause();
152
+ return `DELETE FROM ${fullyQualifiedTable}${whereClause};`;
153
+ }
154
+ buildJoinClause() {
155
+ return this.joins
156
+ .map(({ type, schema, table, on }) => {
157
+ const fullyQualifiedJoinTable = schema
158
+ ? `${this.escapeIdentifier(schema)}.${this.escapeIdentifier(table)}`
159
+ : this.escapeIdentifier(table);
160
+ return ` ${type} JOIN ${fullyQualifiedJoinTable} ON ${on}`;
161
+ })
162
+ .join('');
163
+ }
164
+ buildWhereClause() {
165
+ if (this.whereConditions.length === 0) {
166
+ return '';
167
+ }
168
+ const conditions = this.whereConditions
169
+ .map(({ column, operator, value }) => `${this.escapeIdentifier(column)} ${operator} ${this.formatValue(column, value)}`)
170
+ .join(' AND ');
171
+ return ` WHERE ${conditions}`;
172
+ }
173
+ buildGroupByClause() {
174
+ if (this.groupByColumns.length === 0) {
175
+ return '';
176
+ }
177
+ const groupBy = this.groupByColumns.map((col) => this.escapeIdentifier(col)).join(', ');
178
+ return ` GROUP BY ${groupBy}`;
179
+ }
180
+ buildOrderByClause() {
181
+ if (this.orderByColumns.length === 0) {
182
+ return '';
183
+ }
184
+ const orderBy = this.orderByColumns
185
+ .map(({ column, direction }) => `${this.escapeIdentifier(column)} ${direction}`)
186
+ .join(', ');
187
+ return ` ORDER BY ${orderBy}`;
188
+ }
189
+ escapeIdentifier(identifier) {
190
+ if (this.needsQuoting(identifier)) {
191
+ return `"${identifier.replace(/"/g, '""')}"`;
192
+ }
193
+ return identifier;
194
+ }
195
+ needsQuoting(identifier) {
196
+ return (RESERVED_KEYWORDS.has(identifier.toUpperCase()) ||
197
+ /[^a-zA-Z0-9_]/.test(identifier) ||
198
+ /^\d/.test(identifier));
199
+ }
200
+ formatValue(column, value) {
201
+ const typeHint = this.valueTypes[column];
202
+ if (typeHint) {
203
+ switch (typeHint) {
204
+ case 'string':
205
+ return `'${value.replace(/'/g, "''")}'`;
206
+ case 'number':
207
+ return `${value}`;
208
+ case 'boolean':
209
+ return value ? 'true' : 'false';
210
+ case 'null':
211
+ return 'NULL';
212
+ default:
213
+ throw new Error(`Unsupported type hint: ${typeHint}`);
214
+ }
215
+ }
216
+ if (typeof value === 'string') {
217
+ return `'${value.replace(/'/g, "''")}'`;
218
+ }
219
+ else if (typeof value === 'number' || typeof value === 'boolean') {
220
+ return `${value}`;
221
+ }
222
+ else if (value === null) {
223
+ return 'NULL';
224
+ }
225
+ else {
226
+ throw new Error(`Unsupported value type: ${typeof value}`);
227
+ }
228
+ }
229
+ getFullyQualifiedTable() {
230
+ const escapedSchema = this.schemaName ? this.escapeIdentifier(this.schemaName) : null;
231
+ const escapedTable = this.escapeIdentifier(this.entityName);
232
+ if (escapedSchema) {
233
+ return `${escapedSchema}.${escapedTable}`;
234
+ }
235
+ return escapedTable;
236
+ }
237
+ }
238
+ exports.QueryBuilder = QueryBuilder;