@umituz/web-database 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/package.json +1 -1
  2. package/src/index.ts +27 -0
  3. package/src/query.ts +254 -14
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umituz/web-database",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Database layer for the fleet — the single vendor-coupled module (Neon serverless HTTP driver today): sql(url) raw executor, createDb(url, schema) drizzle factory, Db type alias, query utilities (batchQueries, findFirst, findMany, exists, countRows), and db lifecycle tooling (reset / snapshot / seed)",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
package/src/index.ts CHANGED
@@ -8,15 +8,42 @@ export {
8
8
  } from './lifecycle';
9
9
  export type { SeedSnapshot, SnapshotBytesResult, SnapshotDb, TableSpec } from './lifecycle';
10
10
  export {
11
+ and,
12
+ asc,
11
13
  batchQueries,
12
14
  countRows,
15
+ deleteRow,
16
+ deleteWhere,
17
+ desc,
18
+ eq,
13
19
  exists,
14
20
  findById,
15
21
  findFirst,
16
22
  findMany,
23
+ gt,
24
+ gte,
25
+ ilike,
26
+ inArray,
27
+ insertMany,
28
+ insertRow,
29
+ isNotNull,
30
+ isNull,
31
+ like,
32
+ lt,
33
+ lte,
34
+ ne,
35
+ or,
36
+ softDeleteRow,
37
+ softDeleteWhere,
38
+ updateRow,
39
+ updateWhere,
17
40
  } from './query';
18
41
  export type {
42
+ AnyDb,
19
43
  AnyPgTable,
20
44
  BatchCapableDb,
21
45
  FindManyOptions,
46
+ MutationOptions,
47
+ OrderByItem,
48
+ WhereInput,
22
49
  } from './query';
package/src/query.ts CHANGED
@@ -1,32 +1,118 @@
1
- import { and, count, eq, isNull, sql } from 'drizzle-orm';
2
- import type { InferSelectModel, SQL } from 'drizzle-orm';
1
+ import {
2
+ and,
3
+ asc,
4
+ count,
5
+ desc,
6
+ eq,
7
+ gt,
8
+ gte,
9
+ ilike,
10
+ inArray,
11
+ isNotNull,
12
+ isNull,
13
+ like,
14
+ lt,
15
+ lte,
16
+ ne,
17
+ or,
18
+ sql,
19
+ } from 'drizzle-orm';
20
+ import type { InferInsertModel, InferSelectModel, SQL, SQLWrapper } from 'drizzle-orm';
3
21
  import type { PgTable, TableConfig } from 'drizzle-orm/pg-core';
4
22
  import type { Db } from './driver';
5
23
 
24
+ export {
25
+ and,
26
+ asc,
27
+ desc,
28
+ eq,
29
+ gt,
30
+ gte,
31
+ ilike,
32
+ inArray,
33
+ isNotNull,
34
+ isNull,
35
+ like,
36
+ lt,
37
+ lte,
38
+ ne,
39
+ or,
40
+ };
41
+
6
42
  export type AnyPgTable = PgTable<TableConfig>;
7
43
 
8
- export type BatchCapableDb = {
9
- batch?: <T extends readonly unknown[]>(queries: readonly [...T]) => Promise<{ [K in keyof T]: Awaited<T[K]> }>;
10
- select: Db['select'];
44
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
45
+ export type AnyDb = Db<any> | {
46
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
47
+ select: Db<any>['select'];
48
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
49
+ insert: Db<any>['insert'];
50
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
51
+ update: Db<any>['update'];
52
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
53
+ delete: Db<any>['delete'];
54
+ batch?: unknown;
11
55
  };
12
56
 
57
+ export type BatchCapableDb = AnyDb;
58
+
13
59
  type TableColumns<T extends AnyPgTable> = T['_']['columns'];
14
60
 
15
- type WhereInput<T extends AnyPgTable> =
61
+ type WhereObject<T extends AnyPgTable> = {
62
+ [K in keyof TableColumns<T>]?: unknown;
63
+ };
64
+
65
+ export type WhereInput<T extends AnyPgTable> =
16
66
  | SQL
67
+ | WhereObject<T>
17
68
  | undefined
18
69
  | ((cols: TableColumns<T>) => SQL | undefined);
19
70
 
71
+ export type OrderByItem = SQL | SQLWrapper;
72
+
20
73
  export interface FindManyOptions<T extends AnyPgTable> {
21
74
  where?: WhereInput<T>;
22
75
  limit?: number;
23
76
  offset?: number;
24
- orderBy?: SQL | SQL[] | ((cols: TableColumns<T>) => SQL | SQL[]);
77
+ orderBy?: OrderByItem | OrderByItem[] | ((cols: TableColumns<T>) => OrderByItem | OrderByItem[]);
25
78
  withDeleted?: boolean;
26
79
  }
27
80
 
81
+ export interface MutationOptions {
82
+ withDeleted?: boolean;
83
+ }
84
+
85
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
86
+ if (value === null || typeof value !== 'object') return false;
87
+ const proto = Object.getPrototypeOf(value);
88
+ return proto === null || proto === Object.prototype;
89
+ }
90
+
28
91
  function resolveWhere<T extends AnyPgTable>(table: T, where?: WhereInput<T>, withDeleted = false): SQL | undefined {
29
- const customCondition = typeof where === 'function' ? where(table as unknown as TableColumns<T>) : where;
92
+ let customCondition: SQL | undefined;
93
+
94
+ if (typeof where === 'function') {
95
+ customCondition = where(table as unknown as TableColumns<T>);
96
+ } else if (isPlainObject(where)) {
97
+ const tableCols = table as unknown as Record<string, unknown>;
98
+ const conditions: SQL[] = [];
99
+ for (const [key, val] of Object.entries(where)) {
100
+ const col = tableCols[key];
101
+ if (col && typeof col === 'object') {
102
+ if (val === null) {
103
+ conditions.push(isNull(col as never));
104
+ } else if (Array.isArray(val)) {
105
+ conditions.push(inArray(col as never, val));
106
+ } else {
107
+ conditions.push(eq(col as never, val));
108
+ }
109
+ }
110
+ }
111
+ customCondition = conditions.length > 0 ? and(...conditions) : undefined;
112
+ } else {
113
+ customCondition = where;
114
+ }
115
+
30
116
  const hasDeletedAt = 'deletedAt' in table && Boolean((table as Record<string, unknown>).deletedAt);
31
117
 
32
118
  if (!withDeleted && hasDeletedAt) {
@@ -37,6 +123,13 @@ function resolveWhere<T extends AnyPgTable>(table: T, where?: WhereInput<T>, wit
37
123
  return customCondition;
38
124
  }
39
125
 
126
+ function currentTimestampForColumn(col: unknown): unknown {
127
+ if (col && typeof col === 'object' && 'dataType' in col && (col as { dataType: string }).dataType === 'string') {
128
+ return new Date().toISOString();
129
+ }
130
+ return new Date();
131
+ }
132
+
40
133
  export async function batchQueries<T extends Record<string, PromiseLike<unknown>>>(
41
134
  db: BatchCapableDb,
42
135
  queries: T
@@ -46,12 +139,13 @@ export async function batchQueries<T extends readonly PromiseLike<unknown>[]>(
46
139
  queries: readonly [...T]
47
140
  ): Promise<{ [K in keyof T]: Awaited<T[K]> }>;
48
141
  export async function batchQueries(
49
- db: BatchCapableDb,
142
+ db: AnyDb,
50
143
  queries: Record<string, PromiseLike<unknown>> | readonly PromiseLike<unknown>[]
51
144
  ): Promise<unknown> {
145
+ const hasBatch = typeof (db as { batch?: unknown }).batch === 'function';
52
146
  if (Array.isArray(queries)) {
53
- if (typeof db.batch === 'function') {
54
- return db.batch(queries as never);
147
+ if (hasBatch) {
148
+ return (db as unknown as { batch: (items: readonly unknown[]) => Promise<unknown[]> }).batch(queries);
55
149
  }
56
150
  return Promise.all(queries);
57
151
  }
@@ -61,8 +155,8 @@ export async function batchQueries(
61
155
  const promiseList = keys.map((key) => queryMap[key]);
62
156
 
63
157
  let results: unknown[];
64
- if (typeof db.batch === 'function') {
65
- results = (await db.batch(promiseList as never)) as unknown[];
158
+ if (hasBatch) {
159
+ results = (await (db as unknown as { batch: (items: readonly unknown[]) => Promise<unknown[]> }).batch(promiseList)) as unknown[];
66
160
  } else {
67
161
  results = await Promise.all(promiseList);
68
162
  }
@@ -109,7 +203,7 @@ export async function findMany<T extends AnyPgTable>(
109
203
  ? options.orderBy(table as unknown as TableColumns<T>)
110
204
  : options.orderBy;
111
205
  const orderClause = Array.isArray(order) ? order : [order];
112
- query = (query as never as { orderBy: (...clauses: SQL[]) => typeof query }).orderBy(...orderClause);
206
+ query = (query as never as { orderBy: (...clauses: OrderByItem[]) => typeof query }).orderBy(...orderClause);
113
207
  }
114
208
 
115
209
  if (typeof options?.offset === 'number') {
@@ -166,3 +260,149 @@ export async function findById<T extends AnyPgTable & { id: unknown }>(
166
260
  options
167
261
  );
168
262
  }
263
+
264
+ export async function insertRow<T extends AnyPgTable>(
265
+ db: AnyDb,
266
+ table: T,
267
+ values: InferInsertModel<T>
268
+ ): Promise<InferSelectModel<T>> {
269
+ const rows = (await (db
270
+ .insert(table as never)
271
+ .values(values as never)
272
+ .returning() as unknown as Promise<InferSelectModel<T>[]>));
273
+ const row = rows[0];
274
+ if (!row) {
275
+ throw new Error('Insert failed to return row');
276
+ }
277
+ return row;
278
+ }
279
+
280
+ export async function insertMany<T extends AnyPgTable>(
281
+ db: AnyDb,
282
+ table: T,
283
+ values: InferInsertModel<T>[]
284
+ ): Promise<InferSelectModel<T>[]> {
285
+ if (values.length === 0) return [];
286
+ return (await (db
287
+ .insert(table as never)
288
+ .values(values as never)
289
+ .returning() as unknown as Promise<InferSelectModel<T>[]>));
290
+ }
291
+
292
+ export async function updateRow<T extends AnyPgTable & { id: unknown }>(
293
+ db: AnyDb,
294
+ table: T,
295
+ id: string,
296
+ values: Partial<InferInsertModel<T>>,
297
+ options?: MutationOptions
298
+ ): Promise<InferSelectModel<T> | null> {
299
+ const patch: Record<string, unknown> = { ...values };
300
+ if ('updatedAt' in table && patch.updatedAt === undefined) {
301
+ patch.updatedAt = currentTimestampForColumn((table as Record<string, unknown>).updatedAt);
302
+ }
303
+
304
+ let condition: SQL = eq(table.id as never, id);
305
+ if (!options?.withDeleted && 'deletedAt' in table) {
306
+ condition = and(condition, isNull((table as Record<string, unknown>).deletedAt as never)) as SQL;
307
+ }
308
+
309
+ const rows = (await (db
310
+ .update(table as never)
311
+ .set(patch as never)
312
+ .where(condition)
313
+ .returning() as unknown as Promise<InferSelectModel<T>[]>));
314
+ return rows[0] ?? null;
315
+ }
316
+
317
+ export async function updateWhere<T extends AnyPgTable>(
318
+ db: AnyDb,
319
+ table: T,
320
+ where: WhereInput<T>,
321
+ values: Partial<InferInsertModel<T>>,
322
+ options?: MutationOptions
323
+ ): Promise<InferSelectModel<T>[]> {
324
+ const patch: Record<string, unknown> = { ...values };
325
+ if ('updatedAt' in table && patch.updatedAt === undefined) {
326
+ patch.updatedAt = currentTimestampForColumn((table as Record<string, unknown>).updatedAt);
327
+ }
328
+
329
+ const condition = resolveWhere(table, where, options?.withDeleted);
330
+ let query = db.update(table as never).set(patch as never);
331
+ if (condition) {
332
+ query = (query as never as { where: (c: SQL) => typeof query }).where(condition);
333
+ }
334
+
335
+ return (await (query as never as { returning: () => Promise<InferSelectModel<T>[]> }).returning());
336
+ }
337
+
338
+ export async function softDeleteRow<T extends AnyPgTable & { id: unknown }>(
339
+ db: AnyDb,
340
+ table: T,
341
+ id: string
342
+ ): Promise<InferSelectModel<T> | null> {
343
+ const col = (table as Record<string, unknown>).deletedAt;
344
+ const timestamp = currentTimestampForColumn(col);
345
+ const patch: Record<string, unknown> = { deletedAt: timestamp };
346
+ if ('updatedAt' in table) {
347
+ patch.updatedAt = currentTimestampForColumn((table as Record<string, unknown>).updatedAt);
348
+ }
349
+
350
+ let condition: SQL = eq(table.id as never, id);
351
+ if ('deletedAt' in table) {
352
+ condition = and(condition, isNull(col as never)) as SQL;
353
+ }
354
+
355
+ const rows = (await (db
356
+ .update(table as never)
357
+ .set(patch as never)
358
+ .where(condition)
359
+ .returning() as unknown as Promise<InferSelectModel<T>[]>));
360
+ return rows[0] ?? null;
361
+ }
362
+
363
+ export async function softDeleteWhere<T extends AnyPgTable>(
364
+ db: AnyDb,
365
+ table: T,
366
+ where: WhereInput<T>
367
+ ): Promise<InferSelectModel<T>[]> {
368
+ const col = (table as Record<string, unknown>).deletedAt;
369
+ const timestamp = currentTimestampForColumn(col);
370
+ const patch: Record<string, unknown> = { deletedAt: timestamp };
371
+ if ('updatedAt' in table) {
372
+ patch.updatedAt = currentTimestampForColumn((table as Record<string, unknown>).updatedAt);
373
+ }
374
+
375
+ const condition = resolveWhere(table, where, false);
376
+ let query = db.update(table as never).set(patch as never);
377
+ if (condition) {
378
+ query = (query as never as { where: (c: SQL) => typeof query }).where(condition);
379
+ }
380
+
381
+ return (await (query as never as { returning: () => Promise<InferSelectModel<T>[]> }).returning());
382
+ }
383
+
384
+ export async function deleteRow<T extends AnyPgTable & { id: unknown }>(
385
+ db: AnyDb,
386
+ table: T,
387
+ id: string
388
+ ): Promise<InferSelectModel<T> | null> {
389
+ const rows = (await (db
390
+ .delete(table as never)
391
+ .where(eq(table.id as never, id))
392
+ .returning() as unknown as Promise<InferSelectModel<T>[]>));
393
+ return rows[0] ?? null;
394
+ }
395
+
396
+ export async function deleteWhere<T extends AnyPgTable>(
397
+ db: AnyDb,
398
+ table: T,
399
+ where: WhereInput<T>
400
+ ): Promise<InferSelectModel<T>[]> {
401
+ const condition = resolveWhere(table, where, true);
402
+ let query = db.delete(table as never);
403
+ if (condition) {
404
+ query = (query as never as { where: (c: SQL) => typeof query }).where(condition);
405
+ }
406
+
407
+ return (await (query as never as { returning: () => Promise<InferSelectModel<T>[]> }).returning());
408
+ }