workers-qb 0.0.1

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Gabriel Massadas
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,262 @@
1
+ # workers-qb
2
+
3
+ Zero dependencies Query Builder for [Cloudflare D1](https://blog.cloudflare.com/introducing-d1/)
4
+ [Workers](https://developers.cloudflare.com/workers/)
5
+
6
+ This module provides a simple standardized interface while keeping the
7
+ benefits and speed of using raw queries over a traditional ORM.
8
+
9
+ `workers-qb` is not intended to provide ORM-like functionality, rather to make it easier to interact with the database from
10
+ code for direct SQL access using convenient wrapper methods.
11
+
12
+ Read the documentation [Here](https://workers-qb.massadas.com/)!
13
+
14
+ ## Features
15
+
16
+ - [x] Zero dependencies.
17
+ - [x] Fully typed/TypeScript support
18
+ - [x] SQL Type checking with compatible IDE's
19
+ - [x] Insert/Update/Select/Delete queries
20
+ - [x] Create/drop tables
21
+ - [x] Keep where conditions simple in code
22
+ - [ ] Bulk insert/update
23
+ - [ ] Named parameters (waiting for full support in D1)
24
+
25
+ ## Installation
26
+
27
+ ```
28
+ npm install workers-qb
29
+ ```
30
+
31
+ ## Basic Usage
32
+
33
+ ```ts
34
+ import { D1QB } from 'workers-qb'
35
+ const qb = new D1QB(env.DB)
36
+
37
+ const fetched = await qb.fetchOne({
38
+ tableName: 'employees',
39
+ fields: 'count(*) as count',
40
+ where: {
41
+ conditions: 'active = ?1',
42
+ params: [true],
43
+ },
44
+ })
45
+
46
+ console.log(`Company has ${fetched.results.count} active employees`)
47
+ ```
48
+
49
+ #### Fetching a single record
50
+
51
+ ```ts
52
+ const qb = new D1QB(env.DB)
53
+
54
+ const fetched = await qb.fetchOne({
55
+ tableName: 'employees',
56
+ fields: 'count(*) as count',
57
+ where: {
58
+ conditions: 'department = ?1',
59
+ params: ['HQ'],
60
+ },
61
+ })
62
+
63
+ console.log(`There are ${fetched.results.count} employees in the HR department`)
64
+ ```
65
+
66
+ #### Fetching multiple records
67
+
68
+ ```ts
69
+ import { OrderTypes } from 'workers-qb'
70
+ const qb = new D1QB(env.DB)
71
+
72
+ const fetched = await qb.fetchAll({
73
+ tableName: 'employees',
74
+ fields: ['role', 'count(*) as count'],
75
+ where: {
76
+ conditions: 'department = ?1',
77
+ params: ['HR'],
78
+ },
79
+ groupBy: 'role',
80
+ orderBy: {
81
+ count: OrderTypes.DESC,
82
+ },
83
+ })
84
+
85
+ console.log(`Roles in the HR department:`)
86
+
87
+ fetched.results.forEach((employee) => {
88
+ console.log(`${employee.role} has ${employee.count} employees`)
89
+ })
90
+ ```
91
+
92
+ #### Inserting rows
93
+
94
+ ```ts
95
+ const qb = new D1QB(env.DB)
96
+
97
+ const inserted = await qb.insert({
98
+ tableName: 'employees',
99
+ data: {
100
+ name: 'Joe',
101
+ role: 'manager',
102
+ department: 'store',
103
+ },
104
+ returning: '*',
105
+ })
106
+
107
+ console.log(inserted) // This will contain the data after SQL triggers and primary keys that are automated
108
+ ```
109
+
110
+ #### Updating rows
111
+
112
+ ```ts
113
+ const updated = await qb.update({
114
+ tableName: 'employees',
115
+ data: {
116
+ role: 'CEO',
117
+ department: 'HQ',
118
+ },
119
+ where: {
120
+ conditions: 'id = ?1',
121
+ params: [123],
122
+ },
123
+ })
124
+
125
+ console.log(`Lines affected in this query: ${updated.changes}`)
126
+ ```
127
+
128
+ #### Deleting rows
129
+
130
+ ```ts
131
+ const deleted = await qb.delete({
132
+ tableName: 'employees',
133
+ where: {
134
+ conditions: 'id = ?1',
135
+ params: [123],
136
+ },
137
+ })
138
+
139
+ console.log(`Lines affected in this query: ${deleted.changes}`)
140
+ ```
141
+
142
+ #### Dropping and creating tables
143
+
144
+ ```ts
145
+ const created = await qb.createTable({
146
+ tableName: 'testTable',
147
+ schema: `
148
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
149
+ name TEXT NOT NULL
150
+ `,
151
+ ifNotExists: true,
152
+ })
153
+
154
+ const dropped = await qb.dropTable({
155
+ tableName: 'testTable',
156
+ })
157
+ ```
158
+
159
+ ## Development
160
+
161
+ ### Set up tools and environment
162
+
163
+ You need to have [Node.js](https://nodejs.org/en/download/) installed. Node includes npm as its default package manager.
164
+
165
+ Open the whole package folder with a good code editor, preferably [Visual Studio Code](https://code.visualstudio.com/download). Consider installing VS Code extensions [ES Lint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) and [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode).
166
+
167
+ In the VS Code top menu: **Terminal** -> **New Terminal**
168
+
169
+ ### Install dependencies
170
+
171
+ Install dependencies with npm:
172
+
173
+ ```bash
174
+ npm i
175
+ ```
176
+
177
+ ### Write your code
178
+
179
+ Write your code in **src** folder, and unit test in **test** folder.
180
+
181
+ The VS Code shortcuts for formatting of a code file are: <kbd>Shift</kbd> + <kbd>Alt</kbd> + <kbd>F</kbd> (Windows); <kbd>Shift</kbd> + <kbd>Option (Alt)</kbd> + <kbd>F</kbd> (MacOS); <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>I</kbd> (Linux).
182
+
183
+ ### Test
184
+
185
+ Test your code with Jest framework:
186
+
187
+ ```bash
188
+ npm run test
189
+ ```
190
+
191
+ **Note:** This project uses [husky](https://typicode.github.io/husky/), [pinst](https://github.com/typicode/pinst) and [commitlint](https://commitlint.js.org/) to automatically execute test and [lint commit message](https://www.conventionalcommits.org/) before every commit.
192
+
193
+ ### Build
194
+
195
+ Build production (distribution) files in your **dist** folder:
196
+
197
+ ```bash
198
+ npm run build
199
+ ```
200
+
201
+ It generates CommonJS (in **dist/cjs** folder), ES Modules (in **dist/esm** folder), bundled and minified UMD (in **dist/umd** folder), as well as TypeScript declaration files (in **dist/types** folder).
202
+
203
+ ### Try it before publishing
204
+
205
+ Run:
206
+
207
+ ```bash
208
+ npm link
209
+ ```
210
+
211
+ [npm link](https://docs.npmjs.com/cli/v6/commands/npm-link) will create a symlink in the global folder, which may be **{prefix}/lib/node_modules/workers-qb** or **C:\Users\<username>\AppData\Roaming\npm\node_modules\workers-qb**.
212
+
213
+ Create an empty folder elsewhere, you don't even need to `npm init` (to generate **package.json**). Open the folder with VS Code, open a terminal and just run:
214
+
215
+ ```bash
216
+ npm link workers-qb
217
+ ```
218
+
219
+ This will create a symbolic link from globally-installed workers-qb to **node_modules/** of the current folder.
220
+
221
+ You can then create a, for example, **testsql.ts** file with the content:
222
+
223
+ ```ts
224
+ import { D1QB } from 'workers-qb'
225
+ const qb = new D1QB(env.DB)
226
+
227
+ console.log('Creating table...')
228
+ const created = await qb.createTable({
229
+ tableName: 'testTable',
230
+ schema: `
231
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
232
+ name TEXT NOT NULL
233
+ `,
234
+ ifNotExists: true,
235
+ })
236
+ console.log(created)
237
+
238
+ console.log('Inserting rows...')
239
+ const inserted = await qb.insert({
240
+ tableName: 'testTable',
241
+ data: {
242
+ name: 'my name',
243
+ },
244
+ returning: '*',
245
+ })
246
+ console.log(inserted)
247
+
248
+ console.log('Selecting rows...')
249
+ const selected = await qb.fetchAll({
250
+ tableName: 'testTable',
251
+ fields: '*',
252
+ })
253
+ console.log(selected)
254
+ ```
255
+
256
+ If you don't see any linting errors in VS Code, if you put your mouse cursor over `D1QB` and see its type, then it's all good.
257
+
258
+ Whenever you want to uninstall the globally-installed workers-qb and remove the symlink in the global folder, run:
259
+
260
+ ```bash
261
+ npm uninstall workers-qb -g
262
+ ```
@@ -0,0 +1,249 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (_) try {
29
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.QueryBuilder = void 0;
51
+ var enums_1 = require("./enums");
52
+ var QueryBuilder = /** @class */ (function () {
53
+ function QueryBuilder() {
54
+ }
55
+ QueryBuilder.prototype.execute = function (params) {
56
+ return __awaiter(this, void 0, void 0, function () {
57
+ return __generator(this, function (_a) {
58
+ throw new Error('Execute method not implemented');
59
+ });
60
+ });
61
+ };
62
+ QueryBuilder.prototype.createTable = function (params) {
63
+ return __awaiter(this, void 0, void 0, function () {
64
+ return __generator(this, function (_a) {
65
+ return [2 /*return*/, this.execute({
66
+ query: "CREATE TABLE " + (params.ifNotExists ? 'IF NOT EXISTS' : '') + " " + params.tableName + " (" + params.schema + ")",
67
+ })];
68
+ });
69
+ });
70
+ };
71
+ QueryBuilder.prototype.dropTable = function (params) {
72
+ return __awaiter(this, void 0, void 0, function () {
73
+ return __generator(this, function (_a) {
74
+ return [2 /*return*/, this.execute({
75
+ query: "DROP TABLE " + (params.ifExists ? 'IF EXISTS' : '') + " " + params.tableName,
76
+ })];
77
+ });
78
+ });
79
+ };
80
+ QueryBuilder.prototype.fetchOne = function (params) {
81
+ return __awaiter(this, void 0, void 0, function () {
82
+ var data;
83
+ return __generator(this, function (_a) {
84
+ switch (_a.label) {
85
+ case 0: return [4 /*yield*/, this.execute({
86
+ query: this._select(__assign(__assign({}, params), { limit: 1 })),
87
+ arguments: params.where ? params.where.params : undefined,
88
+ fetchType: enums_1.FetchTypes.ALL,
89
+ })];
90
+ case 1:
91
+ data = _a.sent();
92
+ return [2 /*return*/, __assign(__assign({}, data), { results: data.results[0] })];
93
+ }
94
+ });
95
+ });
96
+ };
97
+ QueryBuilder.prototype.fetchAll = function (params) {
98
+ return __awaiter(this, void 0, void 0, function () {
99
+ return __generator(this, function (_a) {
100
+ return [2 /*return*/, this.execute({
101
+ query: this._select(params),
102
+ arguments: params.where ? params.where.params : undefined,
103
+ fetchType: enums_1.FetchTypes.ALL,
104
+ })];
105
+ });
106
+ });
107
+ };
108
+ QueryBuilder.prototype.insert = function (params) {
109
+ return __awaiter(this, void 0, void 0, function () {
110
+ return __generator(this, function (_a) {
111
+ return [2 /*return*/, this.execute({
112
+ query: this._insert(params),
113
+ arguments: Object.values(params.data),
114
+ fetchType: enums_1.FetchTypes.ALL,
115
+ })];
116
+ });
117
+ });
118
+ };
119
+ QueryBuilder.prototype.update = function (params) {
120
+ return __awaiter(this, void 0, void 0, function () {
121
+ return __generator(this, function (_a) {
122
+ return [2 /*return*/, this.execute({
123
+ query: this._update(params),
124
+ arguments: params.where && params.where.params
125
+ ? params.where.params.concat(Object.values(params.data))
126
+ : Object.values(params.data),
127
+ fetchType: enums_1.FetchTypes.ALL,
128
+ })];
129
+ });
130
+ });
131
+ };
132
+ QueryBuilder.prototype.delete = function (params) {
133
+ return __awaiter(this, void 0, void 0, function () {
134
+ return __generator(this, function (_a) {
135
+ return [2 /*return*/, this.execute({
136
+ query: this._delete(params),
137
+ arguments: params.where ? params.where.params : undefined,
138
+ fetchType: enums_1.FetchTypes.ALL,
139
+ })];
140
+ });
141
+ });
142
+ };
143
+ QueryBuilder.prototype._onConflict = function (resolution) {
144
+ if (resolution) {
145
+ return "OR " + resolution + " ";
146
+ }
147
+ return '';
148
+ };
149
+ QueryBuilder.prototype._insert = function (params) {
150
+ var columns = Object.keys(params.data).join(', ');
151
+ var values = [];
152
+ Object.keys(params.data).forEach(function (key, index) {
153
+ values.push("?" + (index + 1));
154
+ });
155
+ return ("INSERT " + this._onConflict(params.onConflict) + "INTO " + params.tableName + " (" + columns + ") VALUES(" + values.join(', ') + ")" + this._returning(params.returning));
156
+ };
157
+ QueryBuilder.prototype._update = function (params) {
158
+ var _a;
159
+ var whereParamsLength = params.where && params.where.params ? Object.keys(params.where.params).length : 0;
160
+ var set = [];
161
+ Object.entries(params.data).forEach(function (_a, index) {
162
+ var key = _a[0], value = _a[1];
163
+ set.push(key + " = ?" + (whereParamsLength + index + 1));
164
+ });
165
+ return ("UPDATE " + this._onConflict(params.onConflict) + params.tableName + " SET " + set.join(', ') +
166
+ this._where((_a = params.where) === null || _a === void 0 ? void 0 : _a.conditions) +
167
+ this._returning(params.returning));
168
+ };
169
+ QueryBuilder.prototype._delete = function (params) {
170
+ var _a;
171
+ return "DELETE FROM " + params.tableName + this._where((_a = params.where) === null || _a === void 0 ? void 0 : _a.conditions) + this._returning(params.returning);
172
+ };
173
+ QueryBuilder.prototype._select = function (params) {
174
+ var _a;
175
+ return ("SELECT " + this._fields(params.fields) + " FROM " + params.tableName +
176
+ this._join(params.join) +
177
+ this._where((_a = params.where) === null || _a === void 0 ? void 0 : _a.conditions) +
178
+ this._groupBy(params.groupBy) +
179
+ this._having(params.having) +
180
+ this._orderBy(params.orderBy) +
181
+ this._limit(params.limit) +
182
+ this._offset(params.offset));
183
+ };
184
+ QueryBuilder.prototype._fields = function (value) {
185
+ if (typeof value === 'string')
186
+ return value;
187
+ return value.join(', ');
188
+ };
189
+ QueryBuilder.prototype._where = function (value) {
190
+ if (!value)
191
+ return '';
192
+ if (typeof value === 'string')
193
+ return " WHERE " + value;
194
+ return " WHERE " + value.join(' AND ');
195
+ };
196
+ QueryBuilder.prototype._join = function (value) {
197
+ if (!value)
198
+ return '';
199
+ var type = value.type ? " " + value.type : '';
200
+ return type + " JOIN " + value.table + " ON " + value.on;
201
+ };
202
+ QueryBuilder.prototype._groupBy = function (value) {
203
+ if (!value)
204
+ return '';
205
+ if (typeof value === 'string')
206
+ return " GROUP BY " + value;
207
+ return " GROUP BY " + value.join(', ');
208
+ };
209
+ QueryBuilder.prototype._having = function (value) {
210
+ if (!value)
211
+ return '';
212
+ return " HAVING " + value;
213
+ };
214
+ QueryBuilder.prototype._orderBy = function (value) {
215
+ if (!value)
216
+ return '';
217
+ if (typeof value === 'string')
218
+ return " ORDER BY " + value;
219
+ if (value.constructor.name.toLowerCase() === 'array') {
220
+ // @ts-ignore
221
+ return " ORDER BY " + value.join(', ');
222
+ }
223
+ var order = [];
224
+ Object.entries(value).forEach(function (_a) {
225
+ var key = _a[0], item = _a[1];
226
+ order.push(key + " " + item);
227
+ });
228
+ return " ORDER BY " + order.join(', ');
229
+ };
230
+ QueryBuilder.prototype._limit = function (value) {
231
+ if (!value)
232
+ return '';
233
+ return " LIMIT " + value;
234
+ };
235
+ QueryBuilder.prototype._offset = function (value) {
236
+ if (!value)
237
+ return '';
238
+ return " OFFSET " + value;
239
+ };
240
+ QueryBuilder.prototype._returning = function (value) {
241
+ if (!value)
242
+ return '';
243
+ if (typeof value === 'string')
244
+ return " RETURNING " + value;
245
+ return " RETURNING " + value.join(', ');
246
+ };
247
+ return QueryBuilder;
248
+ }());
249
+ exports.QueryBuilder = QueryBuilder;
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
18
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
19
+ return new (P || (P = Promise))(function (resolve, reject) {
20
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
21
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
22
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
23
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
24
+ });
25
+ };
26
+ var __generator = (this && this.__generator) || function (thisArg, body) {
27
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
28
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
29
+ function verb(n) { return function (v) { return step([n, v]); }; }
30
+ function step(op) {
31
+ if (f) throw new TypeError("Generator is already executing.");
32
+ while (_) try {
33
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
34
+ if (y = 0, t) op = [op[0] & 2, t.value];
35
+ switch (op[0]) {
36
+ case 0: case 1: t = op; break;
37
+ case 4: _.label++; return { value: op[1], done: false };
38
+ case 5: _.label++; y = op[1]; op = [0]; continue;
39
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
40
+ default:
41
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
42
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
43
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
44
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
45
+ if (t[2]) _.ops.pop();
46
+ _.trys.pop(); continue;
47
+ }
48
+ op = body.call(thisArg, _);
49
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
50
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
51
+ }
52
+ };
53
+ Object.defineProperty(exports, "__esModule", { value: true });
54
+ exports.D1QB = void 0;
55
+ var Builder_1 = require("./Builder");
56
+ var enums_1 = require("./enums");
57
+ var D1QB = /** @class */ (function (_super) {
58
+ __extends(D1QB, _super);
59
+ function D1QB(db) {
60
+ var _this = _super.call(this) || this;
61
+ _this.db = db;
62
+ return _this;
63
+ }
64
+ D1QB.prototype.execute = function (params) {
65
+ return __awaiter(this, void 0, void 0, function () {
66
+ var stmt;
67
+ return __generator(this, function (_a) {
68
+ stmt = this.db.prepare(params.query);
69
+ if (params.arguments) {
70
+ stmt = stmt.bind.apply(stmt, params.arguments);
71
+ }
72
+ if (params.fetchType === enums_1.FetchTypes.ONE) {
73
+ return [2 /*return*/, stmt.first()];
74
+ }
75
+ else if (params.fetchType === enums_1.FetchTypes.ALL) {
76
+ return [2 /*return*/, stmt.all()];
77
+ }
78
+ return [2 /*return*/, stmt.run()];
79
+ });
80
+ });
81
+ };
82
+ return D1QB;
83
+ }(Builder_1.QueryBuilder));
84
+ exports.D1QB = D1QB;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.JoinTypes = exports.ConflictTypes = exports.FetchTypes = exports.OrderTypes = void 0;
4
+ var OrderTypes;
5
+ (function (OrderTypes) {
6
+ OrderTypes["ASC"] = "ASC";
7
+ OrderTypes["DESC"] = "DESC";
8
+ })(OrderTypes = exports.OrderTypes || (exports.OrderTypes = {}));
9
+ var FetchTypes;
10
+ (function (FetchTypes) {
11
+ FetchTypes["ONE"] = "ONE";
12
+ FetchTypes["ALL"] = "ALL";
13
+ })(FetchTypes = exports.FetchTypes || (exports.FetchTypes = {}));
14
+ var ConflictTypes;
15
+ (function (ConflictTypes) {
16
+ ConflictTypes["ROLLBACK"] = "ROLLBACK";
17
+ ConflictTypes["ABORT"] = "ABORT";
18
+ ConflictTypes["FAIL"] = "FAIL";
19
+ ConflictTypes["IGNORE"] = "IGNORE";
20
+ ConflictTypes["REPLACE"] = "REPLACE";
21
+ })(ConflictTypes = exports.ConflictTypes || (exports.ConflictTypes = {}));
22
+ var JoinTypes;
23
+ (function (JoinTypes) {
24
+ JoinTypes["INNER"] = "INNER";
25
+ JoinTypes["LEFT"] = "LEFT";
26
+ JoinTypes["CROSS"] = "CROSS";
27
+ })(JoinTypes = exports.JoinTypes || (exports.JoinTypes = {}));
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FetchTypes = exports.OrderTypes = exports.D1QB = exports.QueryBuilder = void 0;
4
+ var Builder_1 = require("./Builder");
5
+ Object.defineProperty(exports, "QueryBuilder", { enumerable: true, get: function () { return Builder_1.QueryBuilder; } });
6
+ var Databases_1 = require("./Databases");
7
+ Object.defineProperty(exports, "D1QB", { enumerable: true, get: function () { return Databases_1.D1QB; } });
8
+ var enums_1 = require("./enums");
9
+ Object.defineProperty(exports, "OrderTypes", { enumerable: true, get: function () { return enums_1.OrderTypes; } });
10
+ Object.defineProperty(exports, "FetchTypes", { enumerable: true, get: function () { return enums_1.FetchTypes; } });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,246 @@
1
+ var __assign = (this && this.__assign) || function () {
2
+ __assign = Object.assign || function(t) {
3
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
4
+ s = arguments[i];
5
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6
+ t[p] = s[p];
7
+ }
8
+ return t;
9
+ };
10
+ return __assign.apply(this, arguments);
11
+ };
12
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
13
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
14
+ return new (P || (P = Promise))(function (resolve, reject) {
15
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
16
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
17
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
18
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
19
+ });
20
+ };
21
+ var __generator = (this && this.__generator) || function (thisArg, body) {
22
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
23
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
24
+ function verb(n) { return function (v) { return step([n, v]); }; }
25
+ function step(op) {
26
+ if (f) throw new TypeError("Generator is already executing.");
27
+ while (_) try {
28
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
29
+ if (y = 0, t) op = [op[0] & 2, t.value];
30
+ switch (op[0]) {
31
+ case 0: case 1: t = op; break;
32
+ case 4: _.label++; return { value: op[1], done: false };
33
+ case 5: _.label++; y = op[1]; op = [0]; continue;
34
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
35
+ default:
36
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
37
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
38
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
39
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
40
+ if (t[2]) _.ops.pop();
41
+ _.trys.pop(); continue;
42
+ }
43
+ op = body.call(thisArg, _);
44
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
45
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
46
+ }
47
+ };
48
+ import { FetchTypes } from './enums';
49
+ var QueryBuilder = /** @class */ (function () {
50
+ function QueryBuilder() {
51
+ }
52
+ QueryBuilder.prototype.execute = function (params) {
53
+ return __awaiter(this, void 0, void 0, function () {
54
+ return __generator(this, function (_a) {
55
+ throw new Error('Execute method not implemented');
56
+ });
57
+ });
58
+ };
59
+ QueryBuilder.prototype.createTable = function (params) {
60
+ return __awaiter(this, void 0, void 0, function () {
61
+ return __generator(this, function (_a) {
62
+ return [2 /*return*/, this.execute({
63
+ query: "CREATE TABLE " + (params.ifNotExists ? 'IF NOT EXISTS' : '') + " " + params.tableName + " (" + params.schema + ")",
64
+ })];
65
+ });
66
+ });
67
+ };
68
+ QueryBuilder.prototype.dropTable = function (params) {
69
+ return __awaiter(this, void 0, void 0, function () {
70
+ return __generator(this, function (_a) {
71
+ return [2 /*return*/, this.execute({
72
+ query: "DROP TABLE " + (params.ifExists ? 'IF EXISTS' : '') + " " + params.tableName,
73
+ })];
74
+ });
75
+ });
76
+ };
77
+ QueryBuilder.prototype.fetchOne = function (params) {
78
+ return __awaiter(this, void 0, void 0, function () {
79
+ var data;
80
+ return __generator(this, function (_a) {
81
+ switch (_a.label) {
82
+ case 0: return [4 /*yield*/, this.execute({
83
+ query: this._select(__assign(__assign({}, params), { limit: 1 })),
84
+ arguments: params.where ? params.where.params : undefined,
85
+ fetchType: FetchTypes.ALL,
86
+ })];
87
+ case 1:
88
+ data = _a.sent();
89
+ return [2 /*return*/, __assign(__assign({}, data), { results: data.results[0] })];
90
+ }
91
+ });
92
+ });
93
+ };
94
+ QueryBuilder.prototype.fetchAll = function (params) {
95
+ return __awaiter(this, void 0, void 0, function () {
96
+ return __generator(this, function (_a) {
97
+ return [2 /*return*/, this.execute({
98
+ query: this._select(params),
99
+ arguments: params.where ? params.where.params : undefined,
100
+ fetchType: FetchTypes.ALL,
101
+ })];
102
+ });
103
+ });
104
+ };
105
+ QueryBuilder.prototype.insert = function (params) {
106
+ return __awaiter(this, void 0, void 0, function () {
107
+ return __generator(this, function (_a) {
108
+ return [2 /*return*/, this.execute({
109
+ query: this._insert(params),
110
+ arguments: Object.values(params.data),
111
+ fetchType: FetchTypes.ALL,
112
+ })];
113
+ });
114
+ });
115
+ };
116
+ QueryBuilder.prototype.update = function (params) {
117
+ return __awaiter(this, void 0, void 0, function () {
118
+ return __generator(this, function (_a) {
119
+ return [2 /*return*/, this.execute({
120
+ query: this._update(params),
121
+ arguments: params.where && params.where.params
122
+ ? params.where.params.concat(Object.values(params.data))
123
+ : Object.values(params.data),
124
+ fetchType: FetchTypes.ALL,
125
+ })];
126
+ });
127
+ });
128
+ };
129
+ QueryBuilder.prototype.delete = function (params) {
130
+ return __awaiter(this, void 0, void 0, function () {
131
+ return __generator(this, function (_a) {
132
+ return [2 /*return*/, this.execute({
133
+ query: this._delete(params),
134
+ arguments: params.where ? params.where.params : undefined,
135
+ fetchType: FetchTypes.ALL,
136
+ })];
137
+ });
138
+ });
139
+ };
140
+ QueryBuilder.prototype._onConflict = function (resolution) {
141
+ if (resolution) {
142
+ return "OR " + resolution + " ";
143
+ }
144
+ return '';
145
+ };
146
+ QueryBuilder.prototype._insert = function (params) {
147
+ var columns = Object.keys(params.data).join(', ');
148
+ var values = [];
149
+ Object.keys(params.data).forEach(function (key, index) {
150
+ values.push("?" + (index + 1));
151
+ });
152
+ return ("INSERT " + this._onConflict(params.onConflict) + "INTO " + params.tableName + " (" + columns + ") VALUES(" + values.join(', ') + ")" + this._returning(params.returning));
153
+ };
154
+ QueryBuilder.prototype._update = function (params) {
155
+ var _a;
156
+ var whereParamsLength = params.where && params.where.params ? Object.keys(params.where.params).length : 0;
157
+ var set = [];
158
+ Object.entries(params.data).forEach(function (_a, index) {
159
+ var key = _a[0], value = _a[1];
160
+ set.push(key + " = ?" + (whereParamsLength + index + 1));
161
+ });
162
+ return ("UPDATE " + this._onConflict(params.onConflict) + params.tableName + " SET " + set.join(', ') +
163
+ this._where((_a = params.where) === null || _a === void 0 ? void 0 : _a.conditions) +
164
+ this._returning(params.returning));
165
+ };
166
+ QueryBuilder.prototype._delete = function (params) {
167
+ var _a;
168
+ return "DELETE FROM " + params.tableName + this._where((_a = params.where) === null || _a === void 0 ? void 0 : _a.conditions) + this._returning(params.returning);
169
+ };
170
+ QueryBuilder.prototype._select = function (params) {
171
+ var _a;
172
+ return ("SELECT " + this._fields(params.fields) + " FROM " + params.tableName +
173
+ this._join(params.join) +
174
+ this._where((_a = params.where) === null || _a === void 0 ? void 0 : _a.conditions) +
175
+ this._groupBy(params.groupBy) +
176
+ this._having(params.having) +
177
+ this._orderBy(params.orderBy) +
178
+ this._limit(params.limit) +
179
+ this._offset(params.offset));
180
+ };
181
+ QueryBuilder.prototype._fields = function (value) {
182
+ if (typeof value === 'string')
183
+ return value;
184
+ return value.join(', ');
185
+ };
186
+ QueryBuilder.prototype._where = function (value) {
187
+ if (!value)
188
+ return '';
189
+ if (typeof value === 'string')
190
+ return " WHERE " + value;
191
+ return " WHERE " + value.join(' AND ');
192
+ };
193
+ QueryBuilder.prototype._join = function (value) {
194
+ if (!value)
195
+ return '';
196
+ var type = value.type ? " " + value.type : '';
197
+ return type + " JOIN " + value.table + " ON " + value.on;
198
+ };
199
+ QueryBuilder.prototype._groupBy = function (value) {
200
+ if (!value)
201
+ return '';
202
+ if (typeof value === 'string')
203
+ return " GROUP BY " + value;
204
+ return " GROUP BY " + value.join(', ');
205
+ };
206
+ QueryBuilder.prototype._having = function (value) {
207
+ if (!value)
208
+ return '';
209
+ return " HAVING " + value;
210
+ };
211
+ QueryBuilder.prototype._orderBy = function (value) {
212
+ if (!value)
213
+ return '';
214
+ if (typeof value === 'string')
215
+ return " ORDER BY " + value;
216
+ if (value.constructor.name.toLowerCase() === 'array') {
217
+ // @ts-ignore
218
+ return " ORDER BY " + value.join(', ');
219
+ }
220
+ var order = [];
221
+ Object.entries(value).forEach(function (_a) {
222
+ var key = _a[0], item = _a[1];
223
+ order.push(key + " " + item);
224
+ });
225
+ return " ORDER BY " + order.join(', ');
226
+ };
227
+ QueryBuilder.prototype._limit = function (value) {
228
+ if (!value)
229
+ return '';
230
+ return " LIMIT " + value;
231
+ };
232
+ QueryBuilder.prototype._offset = function (value) {
233
+ if (!value)
234
+ return '';
235
+ return " OFFSET " + value;
236
+ };
237
+ QueryBuilder.prototype._returning = function (value) {
238
+ if (!value)
239
+ return '';
240
+ if (typeof value === 'string')
241
+ return " RETURNING " + value;
242
+ return " RETURNING " + value.join(', ');
243
+ };
244
+ return QueryBuilder;
245
+ }());
246
+ export { QueryBuilder };
@@ -0,0 +1,81 @@
1
+ var __extends = (this && this.__extends) || (function () {
2
+ var extendStatics = function (d, b) {
3
+ extendStatics = Object.setPrototypeOf ||
4
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
6
+ return extendStatics(d, b);
7
+ };
8
+ return function (d, b) {
9
+ if (typeof b !== "function" && b !== null)
10
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
11
+ extendStatics(d, b);
12
+ function __() { this.constructor = d; }
13
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14
+ };
15
+ })();
16
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
17
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
18
+ return new (P || (P = Promise))(function (resolve, reject) {
19
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
20
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
23
+ });
24
+ };
25
+ var __generator = (this && this.__generator) || function (thisArg, body) {
26
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
27
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
28
+ function verb(n) { return function (v) { return step([n, v]); }; }
29
+ function step(op) {
30
+ if (f) throw new TypeError("Generator is already executing.");
31
+ while (_) try {
32
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
33
+ if (y = 0, t) op = [op[0] & 2, t.value];
34
+ switch (op[0]) {
35
+ case 0: case 1: t = op; break;
36
+ case 4: _.label++; return { value: op[1], done: false };
37
+ case 5: _.label++; y = op[1]; op = [0]; continue;
38
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
39
+ default:
40
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
41
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
42
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
43
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
44
+ if (t[2]) _.ops.pop();
45
+ _.trys.pop(); continue;
46
+ }
47
+ op = body.call(thisArg, _);
48
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
49
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
50
+ }
51
+ };
52
+ import { QueryBuilder } from './Builder';
53
+ import { FetchTypes } from './enums';
54
+ var D1QB = /** @class */ (function (_super) {
55
+ __extends(D1QB, _super);
56
+ function D1QB(db) {
57
+ var _this = _super.call(this) || this;
58
+ _this.db = db;
59
+ return _this;
60
+ }
61
+ D1QB.prototype.execute = function (params) {
62
+ return __awaiter(this, void 0, void 0, function () {
63
+ var stmt;
64
+ return __generator(this, function (_a) {
65
+ stmt = this.db.prepare(params.query);
66
+ if (params.arguments) {
67
+ stmt = stmt.bind.apply(stmt, params.arguments);
68
+ }
69
+ if (params.fetchType === FetchTypes.ONE) {
70
+ return [2 /*return*/, stmt.first()];
71
+ }
72
+ else if (params.fetchType === FetchTypes.ALL) {
73
+ return [2 /*return*/, stmt.all()];
74
+ }
75
+ return [2 /*return*/, stmt.run()];
76
+ });
77
+ });
78
+ };
79
+ return D1QB;
80
+ }(QueryBuilder));
81
+ export { D1QB };
@@ -0,0 +1,24 @@
1
+ export var OrderTypes;
2
+ (function (OrderTypes) {
3
+ OrderTypes["ASC"] = "ASC";
4
+ OrderTypes["DESC"] = "DESC";
5
+ })(OrderTypes || (OrderTypes = {}));
6
+ export var FetchTypes;
7
+ (function (FetchTypes) {
8
+ FetchTypes["ONE"] = "ONE";
9
+ FetchTypes["ALL"] = "ALL";
10
+ })(FetchTypes || (FetchTypes = {}));
11
+ export var ConflictTypes;
12
+ (function (ConflictTypes) {
13
+ ConflictTypes["ROLLBACK"] = "ROLLBACK";
14
+ ConflictTypes["ABORT"] = "ABORT";
15
+ ConflictTypes["FAIL"] = "FAIL";
16
+ ConflictTypes["IGNORE"] = "IGNORE";
17
+ ConflictTypes["REPLACE"] = "REPLACE";
18
+ })(ConflictTypes || (ConflictTypes = {}));
19
+ export var JoinTypes;
20
+ (function (JoinTypes) {
21
+ JoinTypes["INNER"] = "INNER";
22
+ JoinTypes["LEFT"] = "LEFT";
23
+ JoinTypes["CROSS"] = "CROSS";
24
+ })(JoinTypes || (JoinTypes = {}));
@@ -0,0 +1,4 @@
1
+ import { QueryBuilder } from './Builder';
2
+ import { D1QB } from './Databases';
3
+ import { OrderTypes, FetchTypes } from './enums';
4
+ export { QueryBuilder, D1QB, OrderTypes, FetchTypes };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,37 @@
1
+ import { Delete, Insert, Join, Result, ResultOne, SelectAll, SelectOne, Update } from './interfaces';
2
+ import { ConflictTypes, FetchTypes, OrderTypes } from './enums';
3
+ export declare class QueryBuilder {
4
+ execute(params: {
5
+ query: String;
6
+ arguments?: (string | number | boolean | null)[];
7
+ fetchType?: FetchTypes;
8
+ }): Promise<any>;
9
+ createTable(params: {
10
+ tableName: string;
11
+ schema: string;
12
+ ifNotExists?: boolean;
13
+ }): Promise<Result>;
14
+ dropTable(params: {
15
+ tableName: string;
16
+ ifExists?: boolean;
17
+ }): Promise<Result>;
18
+ fetchOne(params: SelectOne): Promise<ResultOne>;
19
+ fetchAll(params: SelectAll): Promise<Result>;
20
+ insert(params: Insert): Promise<Result>;
21
+ update(params: Update): Promise<Result>;
22
+ delete(params: Delete): Promise<Result>;
23
+ _onConflict(resolution?: string | ConflictTypes): string;
24
+ _insert(params: Insert): string;
25
+ _update(params: Update): string;
26
+ _delete(params: Delete): string;
27
+ _select(params: SelectAll): string;
28
+ _fields(value: string | Array<string>): string;
29
+ _where(value?: string | Array<string>): string;
30
+ _join(value?: Join): string;
31
+ _groupBy(value?: string | Array<string>): string;
32
+ _having(value?: string): string;
33
+ _orderBy(value?: string | Array<string> | Record<string, string | OrderTypes>): string;
34
+ _limit(value?: number): string;
35
+ _offset(value?: number): string;
36
+ _returning(value?: string | Array<string>): string;
37
+ }
@@ -0,0 +1,11 @@
1
+ import { QueryBuilder } from './Builder';
2
+ import { FetchTypes } from './enums';
3
+ export declare class D1QB extends QueryBuilder {
4
+ private db;
5
+ constructor(db: any);
6
+ execute(params: {
7
+ query: String;
8
+ arguments?: (string | number | boolean | null)[];
9
+ fetchType?: FetchTypes;
10
+ }): Promise<any>;
11
+ }
@@ -0,0 +1,20 @@
1
+ export declare enum OrderTypes {
2
+ ASC = "ASC",
3
+ DESC = "DESC"
4
+ }
5
+ export declare enum FetchTypes {
6
+ ONE = "ONE",
7
+ ALL = "ALL"
8
+ }
9
+ export declare enum ConflictTypes {
10
+ ROLLBACK = "ROLLBACK",
11
+ ABORT = "ABORT",
12
+ FAIL = "FAIL",
13
+ IGNORE = "IGNORE",
14
+ REPLACE = "REPLACE"
15
+ }
16
+ export declare enum JoinTypes {
17
+ INNER = "INNER",
18
+ LEFT = "LEFT",
19
+ CROSS = "CROSS"
20
+ }
@@ -0,0 +1,5 @@
1
+ import { QueryBuilder } from './Builder';
2
+ import { D1QB } from './Databases';
3
+ import { OrderTypes, FetchTypes } from './enums';
4
+ import { Where, Insert, Update, Delete, SelectAll, SelectOne } from './interfaces';
5
+ export { QueryBuilder, D1QB, OrderTypes, FetchTypes, Where, Insert, Update, Delete, SelectAll, SelectOne };
@@ -0,0 +1,57 @@
1
+ import { ConflictTypes, JoinTypes, OrderTypes } from './enums';
2
+ export interface Where {
3
+ conditions: string | Array<string>;
4
+ params?: (string | boolean | number | null)[];
5
+ }
6
+ export interface Join {
7
+ type?: string | JoinTypes;
8
+ table: string;
9
+ on: string;
10
+ }
11
+ export interface SelectOne {
12
+ tableName: string;
13
+ fields: string | Array<string>;
14
+ where?: Where;
15
+ join?: Join;
16
+ groupBy?: string | Array<string>;
17
+ having?: string;
18
+ orderBy?: string | Array<string> | Record<string, string | OrderTypes>;
19
+ offset?: number;
20
+ }
21
+ export interface SelectAll extends SelectOne {
22
+ limit?: number;
23
+ }
24
+ export interface Insert {
25
+ tableName: string;
26
+ data: Record<string, string | boolean | number | null>;
27
+ returning?: string | Array<string>;
28
+ onConflict?: string | ConflictTypes;
29
+ }
30
+ export interface Update {
31
+ tableName: string;
32
+ data: Record<string, string | boolean | number | null>;
33
+ where: Where;
34
+ returning?: string | Array<string>;
35
+ onConflict?: string | ConflictTypes;
36
+ }
37
+ export interface Delete {
38
+ tableName: string;
39
+ where: Where;
40
+ returning?: string | Array<string>;
41
+ }
42
+ export interface Result {
43
+ changes?: number;
44
+ duration: number;
45
+ lastRowId?: number;
46
+ results?: Array<Record<string, string | boolean | number | null>>;
47
+ served_by: string;
48
+ success: boolean;
49
+ }
50
+ export interface ResultOne {
51
+ changes?: number;
52
+ duration: number;
53
+ lastRowId?: number;
54
+ results?: Record<string, string | boolean | number | null>;
55
+ served_by: string;
56
+ success: boolean;
57
+ }
@@ -0,0 +1 @@
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["workers-qb"]=t():e["workers-qb"]=t()}(this,(function(){return(()=>{"use strict";var e={501:function(e,t,r){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},n.apply(this,arguments)},o=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function u(e){try{s(n.next(e))}catch(e){i(e)}}function c(e){try{s(n.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(u,c)}s((n=n.apply(e,t||[])).next())}))},i=this&&this.__generator||function(e,t){var r,n,o,i,u={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;u;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return u.label++,{value:i[1],done:!1};case 5:u.label++,n=i[1],i=[0];continue;case 7:i=u.ops.pop(),u.trys.pop();continue;default:if(!((o=(o=u.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){u=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){u.label=i[1];break}if(6===i[0]&&u.label<o[1]){u.label=o[1],o=i;break}if(o&&u.label<o[2]){u.label=o[2],u.ops.push(i);break}o[2]&&u.ops.pop(),u.trys.pop();continue}i=t.call(e,u)}catch(e){i=[6,e],n=0}finally{r=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.QueryBuilder=void 0;var u=r(40),c=function(){function e(){}return e.prototype.execute=function(e){return o(this,void 0,void 0,(function(){return i(this,(function(e){throw new Error("Execute method not implemented")}))}))},e.prototype.createTable=function(e){return o(this,void 0,void 0,(function(){return i(this,(function(t){return[2,this.execute({query:"CREATE TABLE "+(e.ifNotExists?"IF NOT EXISTS":"")+" "+e.tableName+" ("+e.schema+")"})]}))}))},e.prototype.dropTable=function(e){return o(this,void 0,void 0,(function(){return i(this,(function(t){return[2,this.execute({query:"DROP TABLE "+(e.ifExists?"IF EXISTS":"")+" "+e.tableName})]}))}))},e.prototype.fetchOne=function(e){return o(this,void 0,void 0,(function(){var t;return i(this,(function(r){switch(r.label){case 0:return[4,this.execute({query:this._select(n(n({},e),{limit:1})),arguments:e.where?e.where.params:void 0,fetchType:u.FetchTypes.ALL})];case 1:return t=r.sent(),[2,n(n({},t),{results:t.results[0]})]}}))}))},e.prototype.fetchAll=function(e){return o(this,void 0,void 0,(function(){return i(this,(function(t){return[2,this.execute({query:this._select(e),arguments:e.where?e.where.params:void 0,fetchType:u.FetchTypes.ALL})]}))}))},e.prototype.insert=function(e){return o(this,void 0,void 0,(function(){return i(this,(function(t){return[2,this.execute({query:this._insert(e),arguments:Object.values(e.data),fetchType:u.FetchTypes.ALL})]}))}))},e.prototype.update=function(e){return o(this,void 0,void 0,(function(){return i(this,(function(t){return[2,this.execute({query:this._update(e),arguments:e.where&&e.where.params?e.where.params.concat(Object.values(e.data)):Object.values(e.data),fetchType:u.FetchTypes.ALL})]}))}))},e.prototype.delete=function(e){return o(this,void 0,void 0,(function(){return i(this,(function(t){return[2,this.execute({query:this._delete(e),arguments:e.where?e.where.params:void 0,fetchType:u.FetchTypes.ALL})]}))}))},e.prototype._onConflict=function(e){return e?"OR "+e+" ":""},e.prototype._insert=function(e){var t=Object.keys(e.data).join(", "),r=[];return Object.keys(e.data).forEach((function(e,t){r.push("?"+(t+1))})),"INSERT "+this._onConflict(e.onConflict)+"INTO "+e.tableName+" ("+t+") VALUES("+r.join(", ")+")"+this._returning(e.returning)},e.prototype._update=function(e){var t,r=e.where&&e.where.params?Object.keys(e.where.params).length:0,n=[];return Object.entries(e.data).forEach((function(e,t){var o=e[0];e[1],n.push(o+" = ?"+(r+t+1))})),"UPDATE "+this._onConflict(e.onConflict)+e.tableName+" SET "+n.join(", ")+this._where(null===(t=e.where)||void 0===t?void 0:t.conditions)+this._returning(e.returning)},e.prototype._delete=function(e){var t;return"DELETE FROM "+e.tableName+this._where(null===(t=e.where)||void 0===t?void 0:t.conditions)+this._returning(e.returning)},e.prototype._select=function(e){var t;return"SELECT "+this._fields(e.fields)+" FROM "+e.tableName+this._join(e.join)+this._where(null===(t=e.where)||void 0===t?void 0:t.conditions)+this._groupBy(e.groupBy)+this._having(e.having)+this._orderBy(e.orderBy)+this._limit(e.limit)+this._offset(e.offset)},e.prototype._fields=function(e){return"string"==typeof e?e:e.join(", ")},e.prototype._where=function(e){return e?"string"==typeof e?" WHERE "+e:" WHERE "+e.join(" AND "):""},e.prototype._join=function(e){return e?(e.type?" "+e.type:"")+" JOIN "+e.table+" ON "+e.on:""},e.prototype._groupBy=function(e){return e?"string"==typeof e?" GROUP BY "+e:" GROUP BY "+e.join(", "):""},e.prototype._having=function(e){return e?" HAVING "+e:""},e.prototype._orderBy=function(e){if(!e)return"";if("string"==typeof e)return" ORDER BY "+e;if("array"===e.constructor.name.toLowerCase())return" ORDER BY "+e.join(", ");var t=[];return Object.entries(e).forEach((function(e){var r=e[0],n=e[1];t.push(r+" "+n)}))," ORDER BY "+t.join(", ")},e.prototype._limit=function(e){return e?" LIMIT "+e:""},e.prototype._offset=function(e){return e?" OFFSET "+e:""},e.prototype._returning=function(e){return e?"string"==typeof e?" RETURNING "+e:" RETURNING "+e.join(", "):""},e}();t.QueryBuilder=c},513:function(e,t,r){var n,o=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),i=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function u(e){try{s(n.next(e))}catch(e){i(e)}}function c(e){try{s(n.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(u,c)}s((n=n.apply(e,t||[])).next())}))},u=this&&this.__generator||function(e,t){var r,n,o,i,u={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;u;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return u.label++,{value:i[1],done:!1};case 5:u.label++,n=i[1],i=[0];continue;case 7:i=u.ops.pop(),u.trys.pop();continue;default:if(!((o=(o=u.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){u=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){u.label=i[1];break}if(6===i[0]&&u.label<o[1]){u.label=o[1],o=i;break}if(o&&u.label<o[2]){u.label=o[2],u.ops.push(i);break}o[2]&&u.ops.pop(),u.trys.pop();continue}i=t.call(e,u)}catch(e){i=[6,e],n=0}finally{r=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.D1QB=void 0;var c=r(501),s=r(40),a=function(e){function t(t){var r=e.call(this)||this;return r.db=t,r}return o(t,e),t.prototype.execute=function(e){return i(this,void 0,void 0,(function(){var t;return u(this,(function(r){return t=this.db.prepare(e.query),e.arguments&&(t=t.bind.apply(t,e.arguments)),e.fetchType===s.FetchTypes.ONE?[2,t.first()]:e.fetchType===s.FetchTypes.ALL?[2,t.all()]:[2,t.run()]}))}))},t}(c.QueryBuilder);t.D1QB=a},40:(e,t)=>{var r,n,o,i;Object.defineProperty(t,"__esModule",{value:!0}),t.JoinTypes=t.ConflictTypes=t.FetchTypes=t.OrderTypes=void 0,(i=t.OrderTypes||(t.OrderTypes={})).ASC="ASC",i.DESC="DESC",(o=t.FetchTypes||(t.FetchTypes={})).ONE="ONE",o.ALL="ALL",(n=t.ConflictTypes||(t.ConflictTypes={})).ROLLBACK="ROLLBACK",n.ABORT="ABORT",n.FAIL="FAIL",n.IGNORE="IGNORE",n.REPLACE="REPLACE",(r=t.JoinTypes||(t.JoinTypes={})).INNER="INNER",r.LEFT="LEFT",r.CROSS="CROSS"}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,r),i.exports}var n={};return(()=>{var e=n;Object.defineProperty(e,"__esModule",{value:!0}),e.FetchTypes=e.OrderTypes=e.D1QB=e.QueryBuilder=void 0;var t=r(501);Object.defineProperty(e,"QueryBuilder",{enumerable:!0,get:function(){return t.QueryBuilder}});var o=r(513);Object.defineProperty(e,"D1QB",{enumerable:!0,get:function(){return o.D1QB}});var i=r(40);Object.defineProperty(e,"OrderTypes",{enumerable:!0,get:function(){return i.OrderTypes}}),Object.defineProperty(e,"FetchTypes",{enumerable:!0,get:function(){return i.FetchTypes}})})(),n})()}));
package/package.json ADDED
@@ -0,0 +1,85 @@
1
+ {
2
+ "name": "workers-qb",
3
+ "version": "0.0.1",
4
+ "description": "Zero dependencies Query Builder for Cloudflare D1 Workers",
5
+ "main": "dist/cjs/index.js",
6
+ "module": "dist/esm/index.js",
7
+ "umd:main": "dist/umd/index.js",
8
+ "types": "dist/types/index.d.js",
9
+ "scripts": {
10
+ "_postinstall": "husky install",
11
+ "prepublishOnly": "pinst --disable",
12
+ "postpublish": "pinst --enable",
13
+ "build": "npm run build:cjs && npm run build:esm && npm run build:umd && npm run build:types",
14
+ "build:cjs": "node tools/cleanup cjs && tsc -p config/tsconfig.cjs.json",
15
+ "build:esm": "node tools/cleanup esm && tsc -p config/tsconfig.esm.json",
16
+ "build:umd": "node tools/cleanup umd && webpack --config config/webpack.config.js",
17
+ "build:types": "node tools/cleanup types && tsc -p config/tsconfig.types.json",
18
+ "clean": "node tools/cleanup",
19
+ "package": "npm run build && npm pack",
20
+ "test": "jest --no-cache --runInBand",
21
+ "test:cov": "jest --coverage --no-cache --runInBand",
22
+ "addscope": "node tools/packagejson name @g4brym/workers-qb",
23
+ "prettify": "prettier . --write --ignore-unknown",
24
+ "prepare": "husky install"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "files": [
30
+ "dist"
31
+ ],
32
+ "keywords": [
33
+ "cloudflare",
34
+ "worker",
35
+ "workers",
36
+ "serverless",
37
+ "cloudflare d1",
38
+ "d1sql",
39
+ "sql builder",
40
+ "query builder",
41
+ "cloudflare sql",
42
+ "workers sql",
43
+ "cf",
44
+ "optional",
45
+ "middleware",
46
+ "query",
47
+ "parameters",
48
+ "typescript",
49
+ "npm",
50
+ "package",
51
+ "cjs",
52
+ "esm",
53
+ "umd",
54
+ "typed"
55
+ ],
56
+ "author": "Gabriel Massadas",
57
+ "license": "MIT",
58
+ "homepage": "https://github.com/G4brym/workers-qb",
59
+ "repository": {
60
+ "type": "git",
61
+ "url": "git@github.com:G4brym/workers-qb.git"
62
+ },
63
+ "bugs": {
64
+ "url": "https://github.com/G4brym/workers-qb/issues"
65
+ },
66
+ "devDependencies": {
67
+ "@commitlint/cli": "^13.1.0",
68
+ "@commitlint/config-conventional": "^13.1.0",
69
+ "@types/jest": "^27.0.1",
70
+ "@typescript-eslint/eslint-plugin": "^4.31.1",
71
+ "@typescript-eslint/parser": "^4.31.1",
72
+ "eslint": "^7.32.0",
73
+ "eslint-config-prettier": "^8.3.0",
74
+ "eslint-plugin-prettier": "^4.0.0",
75
+ "husky": "^7.0.2",
76
+ "jest": "^28.1.2",
77
+ "pinst": "^2.1.6",
78
+ "prettier": "^2.4.0",
79
+ "ts-jest": "^28.0.5",
80
+ "ts-loader": "^9.2.5",
81
+ "typescript": "^4.4.3",
82
+ "webpack": "^5.52.1",
83
+ "webpack-cli": "^4.8.0"
84
+ }
85
+ }