@dockstat/sqlite-wrapper 1.1.0 → 1.1.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.
Files changed (3) hide show
  1. package/LICENSE +373 -0
  2. package/README.md +28 -844
  3. package/package.json +4 -4
package/LICENSE ADDED
@@ -0,0 +1,373 @@
1
+ Mozilla Public License Version 2.0
2
+ ==================================
3
+
4
+ 1. Definitions
5
+ --------------
6
+
7
+ 1.1. "Contributor"
8
+ means each individual or legal entity that creates, contributes to
9
+ the creation of, or owns Covered Software.
10
+
11
+ 1.2. "Contributor Version"
12
+ means the combination of the Contributions of others (if any) used
13
+ by a Contributor and that particular Contributor's Contribution.
14
+
15
+ 1.3. "Contribution"
16
+ means Covered Software of a particular Contributor.
17
+
18
+ 1.4. "Covered Software"
19
+ means Source Code Form to which the initial Contributor has attached
20
+ the notice in Exhibit A, the Executable Form of such Source Code
21
+ Form, and Modifications of such Source Code Form, in each case
22
+ including portions thereof.
23
+
24
+ 1.5. "Incompatible With Secondary Licenses"
25
+ means
26
+
27
+ (a) that the initial Contributor has attached the notice described
28
+ in Exhibit B to the Covered Software; or
29
+
30
+ (b) that the Covered Software was made available under the terms of
31
+ version 1.1 or earlier of the License, but not also under the
32
+ terms of a Secondary License.
33
+
34
+ 1.6. "Executable Form"
35
+ means any form of the work other than Source Code Form.
36
+
37
+ 1.7. "Larger Work"
38
+ means a work that combines Covered Software with other material, in
39
+ a separate file or files, that is not Covered Software.
40
+
41
+ 1.8. "License"
42
+ means this document.
43
+
44
+ 1.9. "Licensable"
45
+ means having the right to grant, to the maximum extent possible,
46
+ whether at the time of the initial grant or subsequently, any and
47
+ all of the rights conveyed by this License.
48
+
49
+ 1.10. "Modifications"
50
+ means any of the following:
51
+
52
+ (a) any file in Source Code Form that results from an addition to,
53
+ deletion from, or modification of the contents of Covered
54
+ Software; or
55
+
56
+ (b) any new file in Source Code Form that contains any Covered
57
+ Software.
58
+
59
+ 1.11. "Patent Claims" of a Contributor
60
+ means any patent claim(s), including without limitation, method,
61
+ process, and apparatus claims, in any patent Licensable by such
62
+ Contributor that would be infringed, but for the grant of the
63
+ License, by the making, using, selling, offering for sale, having
64
+ made, import, or transfer of either its Contributions or its
65
+ Contributor Version.
66
+
67
+ 1.12. "Secondary License"
68
+ means either the GNU General Public License, Version 2.0, the GNU
69
+ Lesser General Public License, Version 2.1, the GNU Affero General
70
+ Public License, Version 3.0, or any later versions of those
71
+ licenses.
72
+
73
+ 1.13. "Source Code Form"
74
+ means the form of the work preferred for making modifications.
75
+
76
+ 1.14. "You" (or "Your")
77
+ means an individual or a legal entity exercising rights under this
78
+ License. For legal entities, "You" includes any entity that
79
+ controls, is controlled by, or is under common control with You. For
80
+ purposes of this definition, "control" means (a) the power, direct
81
+ or indirect, to cause the direction or management of such entity,
82
+ whether by contract or otherwise, or (b) ownership of more than
83
+ fifty percent (50%) of the outstanding shares or beneficial
84
+ ownership of such entity.
85
+
86
+ 2. License Grants and Conditions
87
+ --------------------------------
88
+
89
+ 2.1. Grants
90
+
91
+ Each Contributor hereby grants You a world-wide, royalty-free,
92
+ non-exclusive license:
93
+
94
+ (a) under intellectual property rights (other than patent or trademark)
95
+ Licensable by such Contributor to use, reproduce, make available,
96
+ modify, display, perform, distribute, and otherwise exploit its
97
+ Contributions, either on an unmodified basis, with Modifications, or
98
+ as part of a Larger Work; and
99
+
100
+ (b) under Patent Claims of such Contributor to make, use, sell, offer
101
+ for sale, have made, import, and otherwise transfer either its
102
+ Contributions or its Contributor Version.
103
+
104
+ 2.2. Effective Date
105
+
106
+ The licenses granted in Section 2.1 with respect to any Contribution
107
+ become effective for each Contribution on the date the Contributor first
108
+ distributes such Contribution.
109
+
110
+ 2.3. Limitations on Grant Scope
111
+
112
+ The licenses granted in this Section 2 are the only rights granted under
113
+ this License. No additional rights or licenses will be implied from the
114
+ distribution or licensing of Covered Software under this License.
115
+ Notwithstanding Section 2.1(b) above, no patent license is granted by a
116
+ Contributor:
117
+
118
+ (a) for any code that a Contributor has removed from Covered Software;
119
+ or
120
+
121
+ (b) for infringements caused by: (i) Your and any other third party's
122
+ modifications of Covered Software, or (ii) the combination of its
123
+ Contributions with other software (except as part of its Contributor
124
+ Version); or
125
+
126
+ (c) under Patent Claims infringed by Covered Software in the absence of
127
+ its Contributions.
128
+
129
+ This License does not grant any rights in the trademarks, service marks,
130
+ or logos of any Contributor (except as may be necessary to comply with
131
+ the notice requirements in Section 3.4).
132
+
133
+ 2.4. Subsequent Licenses
134
+
135
+ No Contributor makes additional grants as a result of Your choice to
136
+ distribute the Covered Software under a subsequent version of this
137
+ License (see Section 10.2) or under the terms of a Secondary License (if
138
+ permitted under the terms of Section 3.3).
139
+
140
+ 2.5. Representation
141
+
142
+ Each Contributor represents that the Contributor believes its
143
+ Contributions are its original creation(s) or it has sufficient rights
144
+ to grant the rights to its Contributions conveyed by this License.
145
+
146
+ 2.6. Fair Use
147
+
148
+ This License is not intended to limit any rights You have under
149
+ applicable copyright doctrines of fair use, fair dealing, or other
150
+ equivalents.
151
+
152
+ 2.7. Conditions
153
+
154
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
155
+ in Section 2.1.
156
+
157
+ 3. Responsibilities
158
+ -------------------
159
+
160
+ 3.1. Distribution of Source Form
161
+
162
+ All distribution of Covered Software in Source Code Form, including any
163
+ Modifications that You create or to which You contribute, must be under
164
+ the terms of this License. You must inform recipients that the Source
165
+ Code Form of the Covered Software is governed by the terms of this
166
+ License, and how they can obtain a copy of this License. You may not
167
+ attempt to alter or restrict the recipients' rights in the Source Code
168
+ Form.
169
+
170
+ 3.2. Distribution of Executable Form
171
+
172
+ If You distribute Covered Software in Executable Form then:
173
+
174
+ (a) such Covered Software must also be made available in Source Code
175
+ Form, as described in Section 3.1, and You must inform recipients of
176
+ the Executable Form how they can obtain a copy of such Source Code
177
+ Form by reasonable means in a timely manner, at a charge no more
178
+ than the cost of distribution to the recipient; and
179
+
180
+ (b) You may distribute such Executable Form under the terms of this
181
+ License, or sublicense it under different terms, provided that the
182
+ license for the Executable Form does not attempt to limit or alter
183
+ the recipients' rights in the Source Code Form under this License.
184
+
185
+ 3.3. Distribution of a Larger Work
186
+
187
+ You may create and distribute a Larger Work under terms of Your choice,
188
+ provided that You also comply with the requirements of this License for
189
+ the Covered Software. If the Larger Work is a combination of Covered
190
+ Software with a work governed by one or more Secondary Licenses, and the
191
+ Covered Software is not Incompatible With Secondary Licenses, this
192
+ License permits You to additionally distribute such Covered Software
193
+ under the terms of such Secondary License(s), so that the recipient of
194
+ the Larger Work may, at their option, further distribute the Covered
195
+ Software under the terms of either this License or such Secondary
196
+ License(s).
197
+
198
+ 3.4. Notices
199
+
200
+ You may not remove or alter the substance of any license notices
201
+ (including copyright notices, patent notices, disclaimers of warranty,
202
+ or limitations of liability) contained within the Source Code Form of
203
+ the Covered Software, except that You may alter any license notices to
204
+ the extent required to remedy known factual inaccuracies.
205
+
206
+ 3.5. Application of Additional Terms
207
+
208
+ You may choose to offer, and to charge a fee for, warranty, support,
209
+ indemnity or liability obligations to one or more recipients of Covered
210
+ Software. However, You may do so only on Your own behalf, and not on
211
+ behalf of any Contributor. You must make it absolutely clear that any
212
+ such warranty, support, indemnity, or liability obligation is offered by
213
+ You alone, and You hereby agree to indemnify every Contributor for any
214
+ liability incurred by such Contributor as a result of warranty, support,
215
+ indemnity or liability terms You offer. You may include additional
216
+ disclaimers of warranty and limitations of liability specific to any
217
+ jurisdiction.
218
+
219
+ 4. Inability to Comply Due to Statute or Regulation
220
+ ---------------------------------------------------
221
+
222
+ If it is impossible for You to comply with any of the terms of this
223
+ License with respect to some or all of the Covered Software due to
224
+ statute, judicial order, or regulation then You must: (a) comply with
225
+ the terms of this License to the maximum extent possible; and (b)
226
+ describe the limitations and the code they affect. Such description must
227
+ be placed in a text file included with all distributions of the Covered
228
+ Software under this License. Except to the extent prohibited by statute
229
+ or regulation, such description must be sufficiently detailed for a
230
+ recipient of ordinary skill to be able to understand it.
231
+
232
+ 5. Termination
233
+ --------------
234
+
235
+ 5.1. The rights granted under this License will terminate automatically
236
+ if You fail to comply with any of its terms. However, if You become
237
+ compliant, then the rights granted under this License from a particular
238
+ Contributor are reinstated (a) provisionally, unless and until such
239
+ Contributor explicitly and finally terminates Your grants, and (b) on an
240
+ ongoing basis, if such Contributor fails to notify You of the
241
+ non-compliance by some reasonable means prior to 60 days after You have
242
+ come back into compliance. Moreover, Your grants from a particular
243
+ Contributor are reinstated on an ongoing basis if such Contributor
244
+ notifies You of the non-compliance by some reasonable means, this is the
245
+ first time You have received notice of non-compliance with this License
246
+ from such Contributor, and You become compliant prior to 30 days after
247
+ Your receipt of the notice.
248
+
249
+ 5.2. If You initiate litigation against any entity by asserting a patent
250
+ infringement claim (excluding declaratory judgment actions,
251
+ counter-claims, and cross-claims) alleging that a Contributor Version
252
+ directly or indirectly infringes any patent, then the rights granted to
253
+ You by any and all Contributors for the Covered Software under Section
254
+ 2.1 of this License shall terminate.
255
+
256
+ 5.3. In the event of termination under Sections 5.1 or 5.2 above, all
257
+ end user license agreements (excluding distributors and resellers) which
258
+ have been validly granted by You or Your distributors under this License
259
+ prior to termination shall survive termination.
260
+
261
+ ************************************************************************
262
+ * *
263
+ * 6. Disclaimer of Warranty *
264
+ * ------------------------- *
265
+ * *
266
+ * Covered Software is provided under this License on an "as is" *
267
+ * basis, without warranty of any kind, either expressed, implied, or *
268
+ * statutory, including, without limitation, warranties that the *
269
+ * Covered Software is free of defects, merchantable, fit for a *
270
+ * particular purpose or non-infringing. The entire risk as to the *
271
+ * quality and performance of the Covered Software is with You. *
272
+ * Should any Covered Software prove defective in any respect, You *
273
+ * (not any Contributor) assume the cost of any necessary servicing, *
274
+ * repair, or correction. This disclaimer of warranty constitutes an *
275
+ * essential part of this License. No use of any Covered Software is *
276
+ * authorized under this License except under this disclaimer. *
277
+ * *
278
+ ************************************************************************
279
+
280
+ ************************************************************************
281
+ * *
282
+ * 7. Limitation of Liability *
283
+ * -------------------------- *
284
+ * *
285
+ * Under no circumstances and under no legal theory, whether tort *
286
+ * (including negligence), contract, or otherwise, shall any *
287
+ * Contributor, or anyone who distributes Covered Software as *
288
+ * permitted above, be liable to You for any direct, indirect, *
289
+ * special, incidental, or consequential damages of any character *
290
+ * including, without limitation, damages for lost profits, loss of *
291
+ * goodwill, work stoppage, computer failure or malfunction, or any *
292
+ * and all other commercial damages or losses, even if such party *
293
+ * shall have been informed of the possibility of such damages. This *
294
+ * limitation of liability shall not apply to liability for death or *
295
+ * personal injury resulting from such party's negligence to the *
296
+ * extent applicable law prohibits such limitation. Some *
297
+ * jurisdictions do not allow the exclusion or limitation of *
298
+ * incidental or consequential damages, so this exclusion and *
299
+ * limitation may not apply to You. *
300
+ * *
301
+ ************************************************************************
302
+
303
+ 8. Litigation
304
+ -------------
305
+
306
+ Any litigation relating to this License may be brought only in the
307
+ courts of a jurisdiction where the defendant maintains its principal
308
+ place of business and such litigation shall be governed by laws of that
309
+ jurisdiction, without reference to its conflict-of-law provisions.
310
+ Nothing in this Section shall prevent a party's ability to bring
311
+ cross-claims or counter-claims.
312
+
313
+ 9. Miscellaneous
314
+ ----------------
315
+
316
+ This License represents the complete agreement concerning the subject
317
+ matter hereof. If any provision of this License is held to be
318
+ unenforceable, such provision shall be reformed only to the extent
319
+ necessary to make it enforceable. Any law or regulation which provides
320
+ that the language of a contract shall be construed against the drafter
321
+ shall not be used to construe this License against a Contributor.
322
+
323
+ 10. Versions of the License
324
+ ---------------------------
325
+
326
+ 10.1. New Versions
327
+
328
+ Mozilla Foundation is the license steward. Except as provided in Section
329
+ 10.3, no one other than the license steward has the right to modify or
330
+ publish new versions of this License. Each version will be given a
331
+ distinguishing version number.
332
+
333
+ 10.2. Effect of New Versions
334
+
335
+ You may distribute the Covered Software under the terms of the version
336
+ of the License under which You originally received the Covered Software,
337
+ or under the terms of any subsequent version published by the license
338
+ steward.
339
+
340
+ 10.3. Modified Versions
341
+
342
+ If you create software not governed by this License, and you want to
343
+ create a new license for such software, you may create and use a
344
+ modified version of this License if you rename the license and remove
345
+ any references to the name of the license steward (except to note that
346
+ such modified license differs from this License).
347
+
348
+ 10.4. Distributing Source Code Form that is Incompatible With Secondary
349
+ Licenses
350
+
351
+ If You choose to distribute Source Code Form that is Incompatible With
352
+ Secondary Licenses under the terms of this version of the License, the
353
+ notice described in Exhibit B of this License must be attached.
354
+
355
+ Exhibit A - Source Code Form License Notice
356
+ -------------------------------------------
357
+
358
+ This Source Code Form is subject to the terms of the Mozilla Public
359
+ License, v. 2.0. If a copy of the MPL was not distributed with this
360
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
361
+
362
+ If it is not possible or desirable to put the notice in a particular
363
+ file, then You may include the notice in a location (such as a LICENSE
364
+ file in a relevant directory) where a recipient would be likely to look
365
+ for such a notice.
366
+
367
+ You may add additional accurate notices of copyright ownership.
368
+
369
+ Exhibit B - "Incompatible With Secondary Licenses" Notice
370
+ ---------------------------------------------------------
371
+
372
+ This Source Code Form is "Incompatible With Secondary Licenses", as
373
+ defined by the Mozilla Public License, v. 2.0.
package/README.md CHANGED
@@ -1,869 +1,53 @@
1
1
  # @dockstat/sqlite-wrapper
2
2
 
3
- A comprehensive TypeScript wrapper around Bun's `bun:sqlite` with type-safe table creation, advanced query building, and full SQLite feature support.
3
+ ![Bun](https://img.shields.io/badge/Bun-%23000000.svg?style=for-the-badge&logo=bun&logoColor=white)
4
+ ![SQLite](https://img.shields.io/badge/sqlite-%2307405e.svg?style=for-the-badge&logo=sqlite&logoColor=white)
5
+ ![TypeScript](https://img.shields.io/badge/typescript-%23007ACC.svg?style=for-the-badge&logo=typescript&logoColor=white)
4
6
 
5
- ## Features
7
+ **A fast, type-safe TypeScript wrapper for Bun's `bun:sqlite`.**
8
+ Schema-first table helpers, an expressive chainable QueryBuilder, safe defaults (WHERE required for destructive ops), JSON + generated columns, and production-minded pragmas & transactions.
6
9
 
7
- * **Type-safe table creation** with column helpers and comprehensive constraint support
8
- * **Expressive QueryBuilder** with chainable operations for SELECT, INSERT, UPDATE, DELETE
9
- * **Advanced WHERE conditions** including regex filtering, raw SQL, operators, and more
10
- * **Conflict resolution** for INSERT operations (OR IGNORE, OR REPLACE, etc.)
11
- * **Safety features** requiring WHERE conditions for UPDATE/DELETE operations
12
- * **Full SQLite support** including JSON columns, generated columns, foreign keys, and more
13
- * **Performance optimizations** with proper parameter binding and transaction support
10
+ ## Install
11
+ > Requires **Bun** runtime
14
12
 
15
- ---
13
+ ```bash
14
+ bun add @dockstat/sqlite-wrapper
15
+ ````
16
16
 
17
- ## Quick Start
17
+ ## 10-second quickstart
18
18
 
19
19
  ```ts
20
- import { DB, column, sql } from "@dockstat/sqlite-wrapper";
20
+ import { DB, column } from "@dockstat/sqlite-wrapper";
21
21
 
22
- interface User {
23
- id?: number;
24
- name: string;
25
- email: string;
26
- type: string;
27
- active?: boolean;
28
- metadata?: object;
29
- created_at?: number;
30
- updated_at?: number;
31
- }
22
+ const db = new DB("app.db", { pragmas: [["journal_mode","WAL"], ["foreign_keys","ON"]] });
32
23
 
33
- // Create database with optimized settings
34
- const db = new DB("app.db", {
35
- pragmas: [
36
- ["journal_mode", "WAL"],
37
- ["synchronous", "NORMAL"],
38
- ["foreign_keys", "ON"],
39
- ["cache_size", -64000]
40
- ]
41
- });
42
-
43
- // Create table with type-safe column definitions
44
24
  db.createTable("users", {
45
- id: column.id(), // INTEGER PRIMARY KEY AUTOINCREMENT
25
+ id: column.id(),
46
26
  name: column.text({ notNull: true }),
47
27
  email: column.text({ unique: true, notNull: true }),
48
- type: column.enum(["admin", "user", "guest"], { default: "user" }),
49
- active: column.boolean({ default: true }),
50
- metadata: column.json({ validateJson: true }),
51
- created_at: column.createdAt(), // Auto-timestamp
52
- updated_at: column.updatedAt()
28
+ created_at: column.createdAt()
53
29
  });
54
30
 
55
- // Query with the powerful QueryBuilder
56
- const users = db.table<User>("users")
57
- .select(["id", "name", "email"])
31
+ const users = db.table("users")
32
+ .select(["id","name","email"])
58
33
  .where({ active: true })
59
- .whereRgx({ email: /@company\.com$/i })
60
- .orderBy("created_at")
61
- .desc()
34
+ .orderBy("created_at").desc()
62
35
  .limit(10)
63
36
  .all();
64
-
65
- console.log(users);
66
- ```
67
-
68
- ---
69
-
70
- ## Table Creation
71
-
72
- ### Modern Column Helpers (Recommended)
73
-
74
- Create tables with type-safe column definitions and comprehensive SQLite feature support:
75
-
76
- ```ts
77
- import { DB, column, sql } from "@dockstat/sqlite-wrapper";
78
-
79
- db.createTable("products", {
80
- // Primary keys and auto-increment
81
- id: column.id(), // INTEGER PRIMARY KEY AUTOINCREMENT
82
- uuid: column.uuid({ generateDefault: true }),
83
-
84
- // Text columns with constraints
85
- name: column.text({ notNull: true }),
86
- description: column.text({ length: 1000 }),
87
- sku: column.varchar(50, { unique: true }),
88
-
89
- // Numeric columns
90
- price: column.numeric({ precision: 10, scale: 2, check: "price > 0" }),
91
- quantity: column.integer({ default: 0, check: "quantity >= 0" }),
92
- weight: column.real(),
93
-
94
- // Boolean with validation
95
- active: column.boolean({ default: true }),
96
-
97
- // Enums with validation
98
- category: column.enum(["electronics", "clothing", "books"], {
99
- default: "electronics"
100
- }),
101
-
102
- // JSON data
103
- specifications: column.json({ validateJson: true }),
104
- tags: column.json(),
105
-
106
- // Dates and timestamps
107
- manufactured_date: column.date(),
108
- created_at: column.createdAt(), // Auto-managed
109
- updated_at: column.updatedAt(),
110
-
111
- // Foreign keys
112
- supplier_id: column.foreignKey("suppliers", "id", {
113
- onDelete: "SET NULL",
114
- onUpdate: "CASCADE"
115
- }),
116
-
117
- // Generated columns
118
- display_price: {
119
- type: "TEXT",
120
- generated: {
121
- expression: "printf('$%.2f', price)",
122
- stored: false // VIRTUAL column
123
- }
124
- }
125
- }, {
126
- constraints: {
127
- // Table-level constraints
128
- unique: [["sku", "supplier_id"]], // Composite unique
129
- check: ["price > 0 OR category = 'free'"],
130
- foreignKeys: [{
131
- columns: ["supplier_id"],
132
- references: {
133
- table: "suppliers",
134
- columns: ["id"],
135
- onDelete: "CASCADE"
136
- }
137
- }]
138
- },
139
- comment: "Product catalog with full specifications"
140
- });
141
- ```
142
-
143
- ### Available Column Types
144
-
145
- ```ts
146
- // Integer types
147
- column.integer()
148
- column.integer({ size: "BIGINT" })
149
- column.id() // INTEGER PRIMARY KEY AUTOINCREMENT
150
-
151
- // Text types
152
- column.text()
153
- column.varchar(255)
154
- column.char(10)
155
- column.uuid()
156
-
157
- // Numeric types
158
- column.real()
159
- column.numeric({ precision: 10, scale: 2 })
160
- column.numeric({ variant: "DECIMAL" })
161
-
162
- // Date/Time types
163
- column.date()
164
- column.time()
165
- column.datetime()
166
- column.timestamp()
167
- column.createdAt() // Auto-managed creation timestamp
168
- column.updatedAt() // Auto-managed update timestamp
169
-
170
- // Special types
171
- column.boolean() // INTEGER with CHECK constraint
172
- column.json() // TEXT with optional validation
173
- column.blob()
174
- column.enum(["value1", "value2"])
175
-
176
- // Foreign keys
177
- column.foreignKey("other_table", "other_column", {
178
- onDelete: "CASCADE",
179
- onUpdate: "RESTRICT"
180
- })
181
- ```
182
-
183
- ### Column Constraints
184
-
185
- All column helpers support comprehensive constraints:
186
-
187
- ```ts
188
- column.text({
189
- notNull: true,
190
- unique: true,
191
- default: "default_value",
192
- check: "length(column_name) > 0",
193
- collate: "NOCASE",
194
- comment: "User description"
195
- })
196
-
197
- // Default value expressions
198
- column.timestamp({
199
- default: sql.currentTimestamp()
200
- })
201
-
202
- column.text({
203
- default: sql.raw("upper(hex(randomblob(16)))")
204
- })
205
- ```
206
-
207
- ### Legacy Table Creation
208
-
209
- Object-style (still supported):
210
-
211
- ```ts
212
- db.createTable("posts", {
213
- id: "INTEGER PRIMARY KEY AUTOINCREMENT",
214
- title: "TEXT NOT NULL",
215
- body: "TEXT",
216
- author_id: "INTEGER NOT NULL",
217
- published: "INTEGER NOT NULL DEFAULT 0"
218
- }, { ifNotExists: true });
219
- ```
220
-
221
- String-style (still supported):
222
-
223
- ```ts
224
- db.createTable("events", `
225
- id INTEGER PRIMARY KEY,
226
- name TEXT NOT NULL,
227
- occurred_at INTEGER NOT NULL
228
- `);
229
- ```
230
-
231
- ---
232
-
233
- ## Query Building
234
-
235
- ### SELECT Operations
236
-
237
- ```ts
238
- // Basic selection
239
- const users = db.table<User>("users")
240
- .select(["id", "name", "email"])
241
- .where({ active: true })
242
- .all();
243
-
244
- // Complex conditions
245
- const results = db.table<User>("users")
246
- .where({ type: "admin" })
247
- .whereIn("id", [1, 2, 3, 4, 5])
248
- .whereOp("created_at", ">", Date.now() - 86400000)
249
- .whereRaw("name LIKE ?", ["%admin%"])
250
- .whereRgx({ email: /@company\.com$/i }) // Client-side regex
251
- .orderBy("created_at")
252
- .desc()
253
- .limit(50)
254
- .offset(100)
255
- .all();
256
-
257
- // Result methods
258
- const allUsers = db.table<User>("users").all();
259
- const firstUser = db.table<User>("users").first();
260
- const singleUser = db.table<User>("users").where({ id: 1 }).get();
261
- const userCount = db.table<User>("users").where({ active: true }).count();
262
- const userExists = db.table<User>("users").where({ email: "test@example.com" }).exists();
263
-
264
- // Single values
265
- const userName = db.table<User>("users").where({ id: 1 }).value("name");
266
- const allNames = db.table<User>("users").pluck("name");
267
- ```
268
-
269
- ### INSERT Operations
270
-
271
- ```ts
272
- // Single insert
273
- const result = db.table<User>("users").insert({
274
- name: "John Doe",
275
- email: "john@example.com",
276
- type: "user"
277
- });
278
- console.log(`Inserted user with ID: ${result.insertId}`);
279
-
280
- // Bulk insert
281
- const users = [
282
- { name: "Alice", email: "alice@example.com" },
283
- { name: "Bob", email: "bob@example.com" }
284
- ];
285
- const bulkResult = db.table<User>("users").insert(users);
286
-
287
- // Conflict resolution
288
- db.table<User>("users").insertOrIgnore(userData);
289
- db.table<User>("users").insertOrReplace(userData);
290
-
291
- // Custom conflict resolution
292
- db.table<User>("users").insert(userData, {
293
- orIgnore: true,
294
- orReplace: false,
295
- orAbort: false,
296
- orFail: false,
297
- orRollback: false
298
- });
299
-
300
- // Insert and get back the row
301
- const newUser = db.table<User>("users").insertAndGet({
302
- name: "Jane",
303
- email: "jane@example.com"
304
- });
305
-
306
- // Batch insert with transaction
307
- db.table<User>("users").insertBatch(largeUserArray);
308
- ```
309
-
310
- ### UPDATE Operations
311
-
312
- All UPDATE operations require WHERE conditions for safety:
313
-
314
- ```ts
315
- // Basic update
316
- const result = db.table<User>("users")
317
- .where({ id: 1 })
318
- .update({ name: "Updated Name" });
319
-
320
- // Complex conditions
321
- db.table<User>("users")
322
- .where({ type: "user" })
323
- .whereRgx({ email: /@oldcompany\.com$/i })
324
- .update({ type: "migrated_user" });
325
-
326
- // Increment/decrement
327
- db.table<User>("users")
328
- .where({ id: 1 })
329
- .increment("login_count", 1);
330
-
331
- // Upsert (insert or update)
332
- db.table<User>("users").upsert({
333
- id: 1,
334
- name: "John",
335
- email: "john@example.com"
336
- });
337
-
338
- // Update and get affected rows
339
- const updatedUsers = db.table<User>("users")
340
- .where({ active: false })
341
- .updateAndGet({ active: true });
342
-
343
- // Batch update
344
- db.table<User>("users").updateBatch([
345
- { where: { id: 1 }, data: { name: "User 1" } },
346
- { where: { id: 2 }, data: { name: "User 2" } }
347
- ]);
348
- ```
349
-
350
- ### DELETE Operations
351
-
352
- All DELETE operations require WHERE conditions for safety:
353
-
354
- ```ts
355
- // Basic delete
356
- const result = db.table<User>("users")
357
- .where({ active: false })
358
- .delete();
359
-
360
- // Complex conditions
361
- db.table<User>("users")
362
- .where({ type: "temporary" })
363
- .whereOp("created_at", "<", Date.now() - 604800000)
364
- .delete();
365
-
366
- // Delete and get deleted rows
367
- const deletedUsers = db.table<User>("users")
368
- .where({ active: false })
369
- .deleteAndGet();
370
-
371
- // Soft delete
372
- db.table<User>("users")
373
- .where({ id: 1 })
374
- .softDelete("deleted_at", Date.now());
375
-
376
- // Restore soft deleted
377
- db.table<User>("users")
378
- .where({ id: 1 })
379
- .restore("deleted_at");
380
-
381
- // Utility methods
382
- db.table<User>("users").deleteOlderThan("created_at", Date.now() - 2592000000);
383
- db.table<User>("users").deleteDuplicates(["email"]);
384
- db.table<User>("users").truncate(); // Delete all rows
385
-
386
- // Batch delete
387
- db.table<User>("users").deleteBatch([
388
- { type: "temp" },
389
- { active: false }
390
- ]);
391
- ```
392
-
393
- ---
394
-
395
- ## Advanced Features
396
-
397
- ### JSON Column Support
398
-
399
- ```ts
400
- interface UserWithMetadata {
401
- id: number;
402
- name: string;
403
- metadata: {
404
- preferences: object;
405
- settings: object;
406
- };
407
- }
408
-
409
- // Configure JSON columns for automatic serialization/deserialization
410
- const users = db.table<UserWithMetadata>("users", {
411
- jsonColumns: ["metadata"]
412
- });
413
-
414
- // Insert with automatic JSON serialization
415
- users.insert({
416
- name: "John",
417
- metadata: {
418
- preferences: { theme: "dark" },
419
- settings: { notifications: true }
420
- }
421
- });
422
-
423
- // Query returns properly deserialized objects
424
- const user = users.where({ id: 1 }).first();
425
- console.log(user.metadata.preferences.theme); // "dark"
426
- ```
427
-
428
- ### Regex Filtering
429
-
430
- ```ts
431
- // Client-side regex filtering
432
- const gmailUsers = db.table<User>("users")
433
- .where({ active: true }) // SQL filter first
434
- .whereRgx({ email: /@gmail\.com$/i }) // Then regex filter
435
- .all();
436
-
437
- // Multiple regex conditions
438
- const results = db.table<User>("users")
439
- .whereRgx({
440
- email: /@(gmail|yahoo)\.com$/i,
441
- name: /^[A-Z]/
442
- })
443
- .all();
444
- ```
445
-
446
- ### Raw SQL and Advanced Conditions
447
-
448
- ```ts
449
- // Raw WHERE expressions
450
- db.table<User>("users")
451
- .whereRaw("created_at > ? AND (type = ? OR type = ?)", [
452
- Date.now() - 86400000,
453
- "admin",
454
- "moderator"
455
- ])
456
- .all();
457
-
458
- // Operator helpers
459
- db.table<User>("users")
460
- .whereOp("created_at", ">=", startDate)
461
- .whereOp("created_at", "<=", endDate)
462
- .whereOp("name", "LIKE", "%john%")
463
- .all();
464
-
465
- // BETWEEN clauses
466
- db.table<User>("users")
467
- .whereBetween("created_at", startDate, endDate)
468
- .whereNotBetween("age", 0, 18)
469
- .all();
470
-
471
- // NULL checks
472
- db.table<User>("users")
473
- .whereNull("deleted_at")
474
- .whereNotNull("email")
475
- .all();
476
-
477
- // IN clauses
478
- db.table<User>("users")
479
- .whereIn("type", ["admin", "moderator"])
480
- .whereNotIn("status", ["banned", "suspended"])
481
- .all();
482
37
  ```
483
38
 
484
- ### Database Configuration
39
+ ## Why use it?
485
40
 
486
- ```ts
487
- // Constructor options
488
- const db = new DB("app.db", {
489
- pragmas: [
490
- ["journal_mode", "WAL"],
491
- ["synchronous", "NORMAL"],
492
- ["foreign_keys", "ON"],
493
- ["cache_size", -64000],
494
- ["temp_store", "memory"]
495
- ],
496
- loadExtensions: [
497
- "/path/to/regexp_extension.so"
498
- ]
499
- });
41
+ * ⚡ Bun-native, high-performance bindings
42
+ * 🔒 Type-safe table & query APIs (compile-time checks)
43
+ * 🧭 Full SQLite feature support: JSON, generated columns, foreign keys, indexes
44
+ * 🛡️ Safety-first defaults — prevents accidental full-table updates/deletes
45
+ * 🚀 Designed for production workflows: WAL, pragmatic PRAGMAs, bulk ops, transactions
500
46
 
501
- // Runtime PRAGMA management
502
- db.pragma("cache_size", -32000);
503
- const journalMode = db.pragma("journal_mode");
47
+ ## Docs & examples
504
48
 
505
- // Extension loading
506
- db.loadExtension("/path/to/custom_extension.so");
507
-
508
- // Database info
509
- const tableInfo = db.getTableInfo("users");
510
- const foreignKeys = db.getForeignKeys("users");
511
- const indexes = db.getIndexes("users");
512
- ```
513
-
514
- ---
515
-
516
- ## Performance Considerations
517
-
518
- ### Query Optimization
519
-
520
- 1. **Use SQL filters before regex**: Always use `.where()` conditions to reduce the dataset before applying `.whereRgx()` filters.
521
-
522
- ```ts
523
- // Good: SQL filter first, then regex
524
- db.table<User>("users")
525
- .where({ active: true, type: "user" }) // Reduces dataset
526
- .whereRgx({ email: /@company\.com$/i }) // Then regex filter
527
- .all();
49
+ See full technical docs in `docs/technical.md` and `examples/` for e-commerce, migrations, and transactions.
528
50
 
529
- // Avoid: Regex on entire table
530
- db.table<User>("users")
531
- .whereRgx({ email: /@company\.com$/i })
532
- .all();
533
- ```
534
-
535
- 2. **Use appropriate indexes**: Create indexes on frequently queried columns.
536
-
537
- ```ts
538
- db.createIndex("idx_users_email", "users", "email", { unique: true });
539
- db.createIndex("idx_users_created_at", "users", "created_at");
540
- db.createIndex("idx_users_type_active", "users", ["type", "active"]);
541
- ```
542
-
543
- 3. **Batch operations**: Use bulk operations for better performance.
544
-
545
- ```ts
546
- // Good: Bulk insert
547
- db.table<User>("users").insertBatch(largeArray);
548
-
549
- // Avoid: Individual inserts
550
- largeArray.forEach(user => db.table<User>("users").insert(user));
551
- ```
552
-
553
- ### Transaction Management
554
-
555
- ```ts
556
- // Manual transactions
557
- db.begin();
558
- try {
559
- db.table<User>("users").insert(userData1);
560
- db.table<User>("users").insert(userData2);
561
- db.commit();
562
- } catch (error) {
563
- db.rollback();
564
- throw error;
565
- }
566
-
567
- // Automatic transaction wrapper
568
- const result = db.transaction(() => {
569
- const user = db.table<User>("users").insert(userData);
570
- db.table("audit_log").insert({ action: "user_created", user_id: user.insertId });
571
- return user;
572
- });
573
- ```
574
-
575
- ### Memory and Performance Tips
576
-
577
- - Use `PRAGMA cache_size` to tune memory usage
578
- - Enable WAL mode for better concurrency
579
- - Use `PRAGMA optimize` periodically for query optimization
580
- - Consider `WITHOUT ROWID` tables for specific use cases
581
- - Use `PRAGMA vacuum` to reclaim space after large deletions
582
-
583
- ---
584
-
585
- ## Error Handling and Safety
586
-
587
- ### Required WHERE Conditions
588
-
589
- UPDATE and DELETE operations require WHERE conditions to prevent accidental data modification:
590
-
591
- ```ts
592
- // This will throw an error
593
- try {
594
- db.table<User>("users").update({ active: false });
595
- } catch (error) {
596
- console.error("UPDATE requires WHERE conditions");
597
- }
598
-
599
- // This is safe
600
- db.table<User>("users")
601
- .where({ type: "temporary" })
602
- .update({ active: false });
603
- ```
604
-
605
- ### Type Safety
606
-
607
- The library provides comprehensive TypeScript support:
608
-
609
- ```ts
610
- interface StrictUser {
611
- id: number;
612
- name: string;
613
- email: string;
614
- }
615
-
616
- const users = db.table<StrictUser>("users");
617
-
618
- // TypeScript will enforce correct column names
619
- users.select(["id", "name"]); // ✓ Valid
620
- users.select(["invalid_column"]); // ✗ TypeScript error
621
-
622
- // TypeScript will enforce correct data types
623
- users.insert({ name: "John", email: "john@example.com" }); // ✓ Valid
624
- users.insert({ name: 123 }); // ✗ TypeScript error
625
- ```
626
-
627
- ### Parameter Binding
628
-
629
- All queries use proper parameter binding to prevent SQL injection:
630
-
631
- ```ts
632
- // Safe - uses parameter binding
633
- db.table<User>("users")
634
- .whereRaw("name = ? AND email = ?", [userName, userEmail])
635
- .all();
636
-
637
- // Parameters are automatically escaped
638
- db.table<User>("users")
639
- .where({ name: "O'Reilly" }) // Automatically handled
640
- .all();
641
- ```
642
-
643
- ---
644
-
645
- ## API Reference
646
-
647
- ### DB Class
648
-
649
- ```ts
650
- constructor(path: string, options?: {
651
- pragmas?: Array<[string, any]>;
652
- loadExtensions?: string[];
653
- })
654
-
655
- // Table operations
656
- table<T>(tableName: string, jsonConfig?: JsonColumnConfig<T>): QueryBuilder<T>
657
- createTable(tableName: string, columns: CreateTableColumns, options?: TableOptions): void
658
- dropTable(tableName: string, options?: { ifExists?: boolean }): void
659
-
660
- // Index operations
661
- createIndex(name: string, table: string, columns: string | string[], options?: IndexOptions): void
662
- dropIndex(name: string, options?: { ifExists?: boolean }): void
663
-
664
- // Database operations
665
- pragma(name: string, value?: any): any
666
- loadExtension(path: string): void
667
- exec(sql: string): void
668
- prepare(sql: string): Statement
669
- transaction<T>(fn: () => T): T
670
- begin(): void
671
- commit(): void
672
- rollback(): void
673
- close(): void
674
-
675
- // Introspection
676
- getTableInfo(tableName: string): TableInfo[]
677
- getForeignKeys(tableName: string): ForeignKeyInfo[]
678
- getIndexes(tableName: string): IndexInfo[]
679
- getSchema(): SchemaInfo[]
680
- ```
681
-
682
- ### QueryBuilder Class
683
-
684
- ```ts
685
- // WHERE conditions
686
- where(conditions: WhereCondition<T>): this
687
- whereRgx(conditions: RegexCondition<T>): this
688
- whereRaw(expr: string, params?: any[]): this
689
- whereExpr(expr: string, params?: any[]): this
690
- whereIn(column: keyof T, values: any[]): this
691
- whereNotIn(column: keyof T, values: any[]): this
692
- whereOp(column: keyof T, op: string, value: any): this
693
- whereBetween(column: keyof T, min: any, max: any): this
694
- whereNotBetween(column: keyof T, min: any, max: any): this
695
- whereNull(column: keyof T): this
696
- whereNotNull(column: keyof T): this
697
-
698
- // SELECT operations
699
- select(columns: ColumnNames<T>): this
700
- orderBy(column: keyof T): this
701
- asc(): this
702
- desc(): this
703
- limit(amount: number): this
704
- offset(start: number): this
705
-
706
- // Result execution
707
- all(): T[]
708
- get(): T | null
709
- first(): T | null
710
- count(): number
711
- exists(): boolean
712
- value<K extends keyof T>(column: K): T[K] | null
713
- pluck<K extends keyof T>(column: K): T[K][]
714
-
715
- // INSERT operations
716
- insert(data: Partial<T> | Partial<T>[], options?: InsertOptions): InsertResult
717
- insertOrIgnore(data: Partial<T> | Partial<T>[]): InsertResult
718
- insertOrReplace(data: Partial<T> | Partial<T>[]): InsertResult
719
- insertAndGet(data: Partial<T>, options?: InsertOptions): T | null
720
- insertBatch(rows: Partial<T>[], options?: InsertOptions): InsertResult
721
-
722
- // UPDATE operations
723
- update(data: Partial<T>): UpdateResult
724
- upsert(data: Partial<T>): UpdateResult
725
- increment(column: keyof T, amount?: number): UpdateResult
726
- decrement(column: keyof T, amount?: number): UpdateResult
727
- updateAndGet(data: Partial<T>): T[]
728
- updateBatch(updates: Array<{ where: Partial<T>; data: Partial<T> }>): UpdateResult
729
-
730
- // DELETE operations
731
- delete(): DeleteResult
732
- deleteAndGet(): T[]
733
- softDelete(deletedColumn?: keyof T, deletedValue?: any): DeleteResult
734
- restore(deletedColumn?: keyof T): DeleteResult
735
- deleteBatch(conditions: Array<Partial<T>>): DeleteResult
736
- truncate(): DeleteResult
737
- deleteOlderThan(timestampColumn: keyof T, olderThan: number): DeleteResult
738
- deleteDuplicates(columns: Array<keyof T>): DeleteResult
739
- ```
740
-
741
- ### Result Types
742
-
743
- ```ts
744
- interface InsertResult {
745
- insertId: number;
746
- changes: number;
747
- }
748
-
749
- interface UpdateResult {
750
- changes: number;
751
- }
752
-
753
- interface DeleteResult {
754
- changes: number;
755
- }
756
-
757
- interface InsertOptions {
758
- orIgnore?: boolean;
759
- orReplace?: boolean;
760
- orAbort?: boolean;
761
- orFail?: boolean;
762
- orRollback?: boolean;
763
- }
764
- ```
765
-
766
- ---
767
-
768
- ## Examples
769
-
770
- ### E-commerce Product Catalog
771
-
772
- ```ts
773
- import { DB, column, sql } from "@dockstat/sqlite-wrapper";
774
-
775
- interface Product {
776
- id?: number;
777
- name: string;
778
- sku: string;
779
- price: number;
780
- category: string;
781
- specifications?: object;
782
- active?: boolean;
783
- created_at?: number;
784
- updated_at?: number;
785
- }
786
-
787
- const db = new DB("ecommerce.db");
788
-
789
- // Create products table
790
- db.createTable("products", {
791
- id: column.id(),
792
- name: column.text({ notNull: true }),
793
- sku: column.varchar(50, { unique: true, notNull: true }),
794
- price: column.numeric({ precision: 10, scale: 2, check: "price > 0" }),
795
- category: column.enum(["electronics", "clothing", "books"], {
796
- default: "electronics"
797
- }),
798
- specifications: column.json({ validateJson: true }),
799
- active: column.boolean({ default: true }),
800
- created_at: column.createdAt(),
801
- updated_at: column.updatedAt()
802
- });
803
-
804
- // Query products
805
- const activeProducts = db.table<Product>("products")
806
- .where({ active: true })
807
- .whereOp("price", "<=", 100)
808
- .orderBy("created_at")
809
- .desc()
810
- .all();
811
-
812
- // Update pricing
813
- db.table<Product>("products")
814
- .where({ category: "electronics" })
815
- .whereOp("price", ">", 1000)
816
- .increment("price", -50); // $50 discount
817
- ```
818
-
819
- ### User Management System
820
-
821
- ```ts
822
- interface User {
823
- id?: number;
824
- username: string;
825
- email: string;
826
- role: string;
827
- profile?: object;
828
- active?: boolean;
829
- last_login?: number;
830
- created_at?: number;
831
- }
832
-
833
- // Create users with comprehensive constraints
834
- db.createTable("users", {
835
- id: column.id(),
836
- username: column.varchar(50, {
837
- unique: true,
838
- notNull: true,
839
- check: "length(username) >= 3"
840
- }),
841
- email: column.text({
842
- unique: true,
843
- notNull: true,
844
- check: "email LIKE '%@%.%'"
845
- }),
846
- role: column.enum(["admin", "moderator", "user"], { default: "user" }),
847
- profile: column.json(),
848
- active: column.boolean({ default: true }),
849
- last_login: column.timestamp(),
850
- created_at: column.createdAt()
851
- }, {
852
- constraints: {
853
- unique: [["username", "email"]]
854
- }
855
- });
856
-
857
- // Find inactive users
858
- const inactiveUsers = db.table<User>("users")
859
- .where({ active: true })
860
- .whereOp("last_login", "<", Date.now() - 2592000000) // 30 days
861
- .all();
862
-
863
- // Bulk role assignment
864
- db.table<User>("users")
865
- .whereIn("id", [1, 2, 3, 4, 5])
866
- .update({ role: "moderator" });
867
- ```
51
+ ## License
868
52
 
869
- This comprehensive wrapper provides everything you need for robust SQLite operations in TypeScript applications with type safety, performance optimizations, and modern development practices.
53
+ MIT maintained by Dockstat. Contributions welcome.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dockstat/sqlite-wrapper",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "A TypeScript wrapper around bun:sqlite with type-safe query building",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -35,16 +35,16 @@
35
35
  "orm"
36
36
  ],
37
37
  "author": "Its4Nik",
38
- "license": "MIT",
38
+ "license": "MPL-2.0",
39
39
  "repository": {
40
40
  "type": "git",
41
- "url": "https://github.com/Its4Nik/DockStat",
41
+ "url": "https://github.com/Its4Nik/DockStat/packages/sqlite-wrapper",
42
42
  "directory": "packages/sqlite-wrapper"
43
43
  },
44
44
  "bugs": {
45
45
  "url": "https://github.com/Its4Nik/DockStat/issues"
46
46
  },
47
- "homepage": "https://github.com/Its4Nik/DockStat/tree/main/packages/sqlite-wrapper",
47
+ "homepage": "https://outline.itsnik.de/s/9d88c471-373e-4ef2-a955-b1058eb7dc99/doc/dockstatsqlite-wrapper-Lxt4IphXI5",
48
48
  "engines": {
49
49
  "bun": ">=1.0.0"
50
50
  },