@dockstat/sqlite-wrapper 1.2.4 → 1.2.6

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/README.md CHANGED
@@ -19,16 +19,29 @@ bun add @dockstat/sqlite-wrapper
19
19
  ```ts
20
20
  import { DB, column } from "@dockstat/sqlite-wrapper";
21
21
 
22
- const db = new DB("app.db", { pragmas: [["journal_mode","WAL"], ["foreign_keys","ON"]] });
22
+ type User = {
23
+ id?: number,
24
+ name: string,
25
+ active: boolean,
26
+ email: string,
27
+ }
23
28
 
24
- db.createTable("users", {
29
+ const db = new DB("app.db", {
30
+ pragmas: [
31
+ ["journal_mode","WAL"],
32
+ ["foreign_keys","ON"]
33
+ ]
34
+ });
35
+
36
+ const userTable = db.createTable<User>("users", {
25
37
  id: column.id(),
26
38
  name: column.text({ notNull: true }),
39
+ active: column.boolean(),
27
40
  email: column.text({ unique: true, notNull: true }),
28
41
  created_at: column.createdAt()
29
42
  });
30
43
 
31
- const users = db.table("users")
44
+ const users = userTable
32
45
  .select(["id","name","email"])
33
46
  .where({ active: true })
34
47
  .orderBy("created_at").desc()
package/index.ts CHANGED
@@ -102,7 +102,7 @@ class DB {
102
102
  tableName: string,
103
103
  jsonConfig?: JsonColumnConfig<T>
104
104
  ): QueryBuilder<T> {
105
- logger.debug(`Creating QueryBuilder for table: ${tableName}`)
105
+ logger.debug(`Creating QueryBuilder for table: ${tableName} - JSONConfig: ${JSON.stringify(jsonConfig)}`)
106
106
  return new QueryBuilder<T>(this.db, tableName, jsonConfig)
107
107
  }
108
108
 
@@ -209,8 +209,8 @@ class DB {
209
209
  */
210
210
  createTable<_T extends Record<string, unknown>>(
211
211
  tableName: string,
212
- columns: string | Record<string, string> | TableSchema,
213
- options?: TableOptions
212
+ columns: string | Record<string, string> | Partial<Record<Extract<keyof _T, string>, ColumnDefinition>> | TableSchema,
213
+ options?: TableOptions<_T>,
214
214
  ): QueryBuilder<_T> {
215
215
  const temp = options?.temporary ? 'TEMPORARY ' : ''
216
216
  const ifNot = options?.ifNotExists ? 'IF NOT EXISTS ' : ''
@@ -277,7 +277,7 @@ class DB {
277
277
  this.setTableComment(tableName, options.comment)
278
278
  }
279
279
 
280
- return this.table<_T>(tableName)
280
+ return this.table<_T>(tableName, options?.jsonConfig)
281
281
  }
282
282
 
283
283
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dockstat/sqlite-wrapper",
3
- "version": "1.2.4",
3
+ "version": "1.2.6",
4
4
  "description": "A TypeScript wrapper around bun:sqlite with type-safe query building",
5
5
  "type": "module",
6
6
  "main": "./index.ts",
@@ -34,24 +34,24 @@ export abstract class BaseQueryBuilder<T extends Record<string, unknown>> {
34
34
  whereConditions: [],
35
35
  whereParams: [],
36
36
  regexConditions: [],
37
- jsonColumns: jsonConfig?.jsonColumns,
37
+ jsonColumns: jsonConfig,
38
38
  }
39
39
  }
40
40
 
41
41
  /**
42
42
  * Reset query builder state
43
43
  */
44
- protected reset(): void {
45
- this.state.whereConditions = []
46
- this.state.whereParams = []
47
- this.state.regexConditions = []
48
- // Reset any ordering, limit, offset, selected columns if present
49
- if ('orderColumn' in this) (this as any).orderColumn = undefined
50
- if ('orderDirection' in this) (this as any).orderDirection = 'ASC'
51
- if ('limitValue' in this) (this as any).limitValue = undefined
52
- if ('offsetValue' in this) (this as any).offsetValue = undefined
53
- if ('selectedColumns' in this) (this as any).selectedColumns = ['*']
54
- }
44
+ protected reset(): void {
45
+ this.state.whereConditions = []
46
+ this.state.whereParams = []
47
+ this.state.regexConditions = []
48
+ // Reset any ordering, limit, offset, selected columns if present
49
+ if ('orderColumn' in this) (this as any).orderColumn = undefined
50
+ if ('orderDirection' in this) (this as any).orderDirection = 'ASC'
51
+ if ('limitValue' in this) (this as any).limitValue = undefined
52
+ if ('offsetValue' in this) (this as any).offsetValue = undefined
53
+ if ('selectedColumns' in this) (this as any).selectedColumns = ['*']
54
+ }
55
55
 
56
56
  /**
57
57
  * Get the database instance
@@ -197,11 +197,16 @@ export abstract class BaseQueryBuilder<T extends Record<string, unknown>> {
197
197
  * Transform row data before inserting/updating to database (serialize JSON columns).
198
198
  */
199
199
  protected transformRowToDb(row: Partial<T>): DatabaseRowData {
200
- if (!this.state.jsonColumns || !row) return row as DatabaseRowData
200
+ this.logger.debug(`Transforming row (${JSON.stringify(row)}) to row Data`)
201
+ if (!this.state.jsonColumns || !row) {
202
+ return row as DatabaseRowData
203
+ }
201
204
 
202
205
  const transformed: DatabaseRowData = { ...row } as DatabaseRowData
206
+
203
207
  for (const column of this.state.jsonColumns) {
204
208
  const columnKey = String(column)
209
+ this.logger.debug(`Checking: ${columnKey}`)
205
210
  if (
206
211
  transformed[columnKey] !== undefined &&
207
212
  transformed[columnKey] !== null
@@ -9,6 +9,7 @@ import { WhereQueryBuilder } from "./where";
9
9
  export class InsertQueryBuilder<
10
10
  T extends Record<string, unknown>,
11
11
  > extends WhereQueryBuilder<T> {
12
+
12
13
  /**
13
14
  * Insert a single row or multiple rows into the table.
14
15
  *
@@ -20,11 +21,16 @@ export class InsertQueryBuilder<
20
21
  data: Partial<T> | Partial<T>[],
21
22
  options?: InsertOptions,
22
23
  ): InsertResult {
24
+ this.getLogger().debug(`Building Data Array: ${data}`)
23
25
  const rows = Array.isArray(data) ? data : [data];
24
26
 
27
+
28
+
25
29
  // Transform rows to handle JSON serialization
26
30
  const transformedRows = rows.map((row) => this.transformRowToDb(row));
27
31
 
32
+ this.getLogger().debug(`Transformed row: ${JSON.stringify(transformedRows)}`)
33
+
28
34
  if (transformedRows.length === 0) {
29
35
  throw new Error("insert: data cannot be empty");
30
36
  }
package/types.ts CHANGED
@@ -1,4 +1,3 @@
1
- // Enhanced types.ts with comprehensive SQLite support
2
1
  import type { Database, SQLQueryBindings } from "bun:sqlite";
3
2
 
4
3
  /**
@@ -223,6 +222,9 @@ export interface ColumnDefinition extends ColumnConstraints {
223
222
  */
224
223
  export type TableSchema = Record<string, ColumnDefinition>;
225
224
 
225
+
226
+ export type TypedTableSchema<T extends string = string> = Record<T, ColumnDefinition>;
227
+
226
228
  /**
227
229
  * Table constraint types
228
230
  */
@@ -248,7 +250,7 @@ export interface TableConstraints {
248
250
  /**
249
251
  * Enhanced table options
250
252
  */
251
- export interface TableOptions {
253
+ export interface TableOptions<T> {
252
254
  /** Add IF NOT EXISTS clause */
253
255
  ifNotExists?: boolean;
254
256
  /** Create WITHOUT ROWID table */
@@ -259,6 +261,8 @@ export interface TableOptions {
259
261
  temporary?: boolean;
260
262
  /** Table comment */
261
263
  comment?: string;
264
+
265
+ jsonConfig?: JsonColumnConfig<T>
262
266
  }
263
267
 
264
268
  /**
@@ -372,7 +376,7 @@ export const column = {
372
376
  * Create a JSON column (stored as TEXT)
373
377
  */
374
378
  json: (
375
- constraints?: ColumnConstraints & { validateJson?: boolean },
379
+ constraints: ColumnConstraints & { validateJson?: boolean },
376
380
  ): ColumnDefinition => ({
377
381
  type: SQLiteTypes.JSON,
378
382
  check: constraints?.validateJson
@@ -431,8 +435,8 @@ export const column = {
431
435
  length: 36,
432
436
  default: constraints?.generateDefault
433
437
  ? defaultExpr(
434
- "lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))",
435
- )
438
+ "lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))",
439
+ )
436
440
  : constraints?.default,
437
441
  ...constraints,
438
442
  }),
@@ -601,9 +605,7 @@ export interface InsertOptions {
601
605
  /**
602
606
  * JSON column configuration
603
607
  */
604
- export interface JsonColumnConfig<T> {
605
- jsonColumns?: Array<keyof T>;
606
- }
608
+ export type JsonColumnConfig<T> = Array<keyof T>
607
609
 
608
610
  /**
609
611
  * Generic database row type