@umituz/web-database 1.2.1 → 1.4.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.
- package/package.json +2 -2
- package/src/index.ts +28 -0
- package/src/query.ts +263 -7
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@umituz/web-database",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.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",
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"scripts": {
|
|
22
22
|
"typecheck": "tsc --noEmit",
|
|
23
23
|
"lint": "eslint .",
|
|
24
|
-
"test": "vitest run",
|
|
24
|
+
"test": "vitest run --no-file-parallelism",
|
|
25
25
|
"test:watch": "vitest",
|
|
26
26
|
"prepublishOnly": "npm run typecheck && npm run lint && npm test",
|
|
27
27
|
"version:patch": "npm version patch -m 'chore: release v%s'",
|
package/src/index.ts
CHANGED
|
@@ -8,16 +8,44 @@ 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
|
+
incrementRow,
|
|
28
|
+
insertMany,
|
|
29
|
+
insertRow,
|
|
30
|
+
isNotNull,
|
|
31
|
+
isNull,
|
|
32
|
+
like,
|
|
33
|
+
lt,
|
|
34
|
+
lte,
|
|
35
|
+
ne,
|
|
36
|
+
or,
|
|
37
|
+
rawSql,
|
|
38
|
+
softDeleteRow,
|
|
39
|
+
softDeleteWhere,
|
|
40
|
+
updateRow,
|
|
41
|
+
updateWhere,
|
|
17
42
|
} from './query';
|
|
18
43
|
export type {
|
|
19
44
|
AnyDb,
|
|
20
45
|
AnyPgTable,
|
|
21
46
|
BatchCapableDb,
|
|
22
47
|
FindManyOptions,
|
|
48
|
+
MutationOptions,
|
|
49
|
+
OrderByItem,
|
|
50
|
+
WhereInput,
|
|
23
51
|
} from './query';
|
package/src/query.ts
CHANGED
|
@@ -1,14 +1,57 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
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';
|
|
21
|
+
import type { PgColumn, 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
|
+
sql as rawSql,
|
|
41
|
+
};
|
|
42
|
+
|
|
6
43
|
export type AnyPgTable = PgTable<TableConfig>;
|
|
7
44
|
|
|
8
45
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
9
46
|
export type AnyDb = Db<any> | {
|
|
10
47
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
11
48
|
select: Db<any>['select'];
|
|
49
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
50
|
+
insert: Db<any>['insert'];
|
|
51
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
52
|
+
update: Db<any>['update'];
|
|
53
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
54
|
+
delete: Db<any>['delete'];
|
|
12
55
|
batch?: unknown;
|
|
13
56
|
};
|
|
14
57
|
|
|
@@ -16,21 +59,61 @@ export type BatchCapableDb = AnyDb;
|
|
|
16
59
|
|
|
17
60
|
type TableColumns<T extends AnyPgTable> = T['_']['columns'];
|
|
18
61
|
|
|
19
|
-
type
|
|
62
|
+
type WhereObject<T extends AnyPgTable> = {
|
|
63
|
+
[K in keyof TableColumns<T>]?: unknown;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
export type WhereInput<T extends AnyPgTable> =
|
|
20
67
|
| SQL
|
|
68
|
+
| WhereObject<T>
|
|
21
69
|
| undefined
|
|
22
70
|
| ((cols: TableColumns<T>) => SQL | undefined);
|
|
23
71
|
|
|
72
|
+
export type OrderByItem = SQL | SQLWrapper;
|
|
73
|
+
|
|
24
74
|
export interface FindManyOptions<T extends AnyPgTable> {
|
|
25
75
|
where?: WhereInput<T>;
|
|
26
76
|
limit?: number;
|
|
27
77
|
offset?: number;
|
|
28
|
-
orderBy?:
|
|
78
|
+
orderBy?: OrderByItem | OrderByItem[] | ((cols: TableColumns<T>) => OrderByItem | OrderByItem[]);
|
|
79
|
+
withDeleted?: boolean;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface MutationOptions {
|
|
29
83
|
withDeleted?: boolean;
|
|
30
84
|
}
|
|
31
85
|
|
|
86
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
87
|
+
if (value === null || typeof value !== 'object') return false;
|
|
88
|
+
const proto = Object.getPrototypeOf(value);
|
|
89
|
+
return proto === null || proto === Object.prototype;
|
|
90
|
+
}
|
|
91
|
+
|
|
32
92
|
function resolveWhere<T extends AnyPgTable>(table: T, where?: WhereInput<T>, withDeleted = false): SQL | undefined {
|
|
33
|
-
|
|
93
|
+
let customCondition: SQL | undefined;
|
|
94
|
+
|
|
95
|
+
if (typeof where === 'function') {
|
|
96
|
+
customCondition = where(table as unknown as TableColumns<T>);
|
|
97
|
+
} else if (isPlainObject(where)) {
|
|
98
|
+
const tableCols = table as unknown as Record<string, unknown>;
|
|
99
|
+
const conditions: SQL[] = [];
|
|
100
|
+
for (const [key, val] of Object.entries(where)) {
|
|
101
|
+
const col = tableCols[key];
|
|
102
|
+
if (col && typeof col === 'object') {
|
|
103
|
+
if (val === null) {
|
|
104
|
+
conditions.push(isNull(col as never));
|
|
105
|
+
} else if (Array.isArray(val)) {
|
|
106
|
+
conditions.push(inArray(col as never, val));
|
|
107
|
+
} else {
|
|
108
|
+
conditions.push(eq(col as never, val));
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
customCondition = conditions.length > 0 ? and(...conditions) : undefined;
|
|
113
|
+
} else {
|
|
114
|
+
customCondition = where;
|
|
115
|
+
}
|
|
116
|
+
|
|
34
117
|
const hasDeletedAt = 'deletedAt' in table && Boolean((table as Record<string, unknown>).deletedAt);
|
|
35
118
|
|
|
36
119
|
if (!withDeleted && hasDeletedAt) {
|
|
@@ -41,6 +124,13 @@ function resolveWhere<T extends AnyPgTable>(table: T, where?: WhereInput<T>, wit
|
|
|
41
124
|
return customCondition;
|
|
42
125
|
}
|
|
43
126
|
|
|
127
|
+
function currentTimestampForColumn(col: unknown): unknown {
|
|
128
|
+
if (col && typeof col === 'object' && 'dataType' in col && (col as { dataType: string }).dataType === 'string') {
|
|
129
|
+
return new Date().toISOString();
|
|
130
|
+
}
|
|
131
|
+
return new Date();
|
|
132
|
+
}
|
|
133
|
+
|
|
44
134
|
export async function batchQueries<T extends Record<string, PromiseLike<unknown>>>(
|
|
45
135
|
db: BatchCapableDb,
|
|
46
136
|
queries: T
|
|
@@ -114,7 +204,7 @@ export async function findMany<T extends AnyPgTable>(
|
|
|
114
204
|
? options.orderBy(table as unknown as TableColumns<T>)
|
|
115
205
|
: options.orderBy;
|
|
116
206
|
const orderClause = Array.isArray(order) ? order : [order];
|
|
117
|
-
query = (query as never as { orderBy: (...clauses:
|
|
207
|
+
query = (query as never as { orderBy: (...clauses: OrderByItem[]) => typeof query }).orderBy(...orderClause);
|
|
118
208
|
}
|
|
119
209
|
|
|
120
210
|
if (typeof options?.offset === 'number') {
|
|
@@ -171,3 +261,169 @@ export async function findById<T extends AnyPgTable & { id: unknown }>(
|
|
|
171
261
|
options
|
|
172
262
|
);
|
|
173
263
|
}
|
|
264
|
+
|
|
265
|
+
export async function insertRow<T extends AnyPgTable>(
|
|
266
|
+
db: AnyDb,
|
|
267
|
+
table: T,
|
|
268
|
+
values: InferInsertModel<T>
|
|
269
|
+
): Promise<InferSelectModel<T>> {
|
|
270
|
+
const rows = (await (db
|
|
271
|
+
.insert(table as never)
|
|
272
|
+
.values(values as never)
|
|
273
|
+
.returning() as unknown as Promise<InferSelectModel<T>[]>));
|
|
274
|
+
const row = rows[0];
|
|
275
|
+
if (!row) {
|
|
276
|
+
throw new Error('Insert failed to return row');
|
|
277
|
+
}
|
|
278
|
+
return row;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export async function insertMany<T extends AnyPgTable>(
|
|
282
|
+
db: AnyDb,
|
|
283
|
+
table: T,
|
|
284
|
+
values: InferInsertModel<T>[]
|
|
285
|
+
): Promise<InferSelectModel<T>[]> {
|
|
286
|
+
if (values.length === 0) return [];
|
|
287
|
+
return (await (db
|
|
288
|
+
.insert(table as never)
|
|
289
|
+
.values(values as never)
|
|
290
|
+
.returning() as unknown as Promise<InferSelectModel<T>[]>));
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export async function updateRow<T extends AnyPgTable & { id: unknown }>(
|
|
294
|
+
db: AnyDb,
|
|
295
|
+
table: T,
|
|
296
|
+
id: string,
|
|
297
|
+
values: Partial<InferInsertModel<T>>,
|
|
298
|
+
options?: MutationOptions
|
|
299
|
+
): Promise<InferSelectModel<T> | null> {
|
|
300
|
+
const patch: Record<string, unknown> = { ...values };
|
|
301
|
+
if ('updatedAt' in table && patch.updatedAt === undefined) {
|
|
302
|
+
patch.updatedAt = currentTimestampForColumn((table as Record<string, unknown>).updatedAt);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
let condition: SQL = eq(table.id as never, id);
|
|
306
|
+
if (!options?.withDeleted && 'deletedAt' in table) {
|
|
307
|
+
condition = and(condition, isNull((table as Record<string, unknown>).deletedAt as never)) as SQL;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const rows = (await (db
|
|
311
|
+
.update(table as never)
|
|
312
|
+
.set(patch as never)
|
|
313
|
+
.where(condition)
|
|
314
|
+
.returning() as unknown as Promise<InferSelectModel<T>[]>));
|
|
315
|
+
return rows[0] ?? null;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export async function updateWhere<T extends AnyPgTable>(
|
|
319
|
+
db: AnyDb,
|
|
320
|
+
table: T,
|
|
321
|
+
where: WhereInput<T>,
|
|
322
|
+
values: Partial<InferInsertModel<T>>,
|
|
323
|
+
options?: MutationOptions
|
|
324
|
+
): Promise<InferSelectModel<T>[]> {
|
|
325
|
+
const patch: Record<string, unknown> = { ...values };
|
|
326
|
+
if ('updatedAt' in table && patch.updatedAt === undefined) {
|
|
327
|
+
patch.updatedAt = currentTimestampForColumn((table as Record<string, unknown>).updatedAt);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const condition = resolveWhere(table, where, options?.withDeleted);
|
|
331
|
+
let query = db.update(table as never).set(patch as never);
|
|
332
|
+
if (condition) {
|
|
333
|
+
query = (query as never as { where: (c: SQL) => typeof query }).where(condition);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
return (await (query as never as { returning: () => Promise<InferSelectModel<T>[]> }).returning());
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export async function softDeleteRow<T extends AnyPgTable & { id: unknown }>(
|
|
340
|
+
db: AnyDb,
|
|
341
|
+
table: T,
|
|
342
|
+
id: string
|
|
343
|
+
): Promise<InferSelectModel<T> | null> {
|
|
344
|
+
const col = (table as Record<string, unknown>).deletedAt;
|
|
345
|
+
const timestamp = currentTimestampForColumn(col);
|
|
346
|
+
const patch: Record<string, unknown> = { deletedAt: timestamp };
|
|
347
|
+
if ('updatedAt' in table) {
|
|
348
|
+
patch.updatedAt = currentTimestampForColumn((table as Record<string, unknown>).updatedAt);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
let condition: SQL = eq(table.id as never, id);
|
|
352
|
+
if ('deletedAt' in table) {
|
|
353
|
+
condition = and(condition, isNull(col as never)) as SQL;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const rows = (await (db
|
|
357
|
+
.update(table as never)
|
|
358
|
+
.set(patch as never)
|
|
359
|
+
.where(condition)
|
|
360
|
+
.returning() as unknown as Promise<InferSelectModel<T>[]>));
|
|
361
|
+
return rows[0] ?? null;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
export async function softDeleteWhere<T extends AnyPgTable>(
|
|
365
|
+
db: AnyDb,
|
|
366
|
+
table: T,
|
|
367
|
+
where: WhereInput<T>
|
|
368
|
+
): Promise<InferSelectModel<T>[]> {
|
|
369
|
+
const col = (table as Record<string, unknown>).deletedAt;
|
|
370
|
+
const timestamp = currentTimestampForColumn(col);
|
|
371
|
+
const patch: Record<string, unknown> = { deletedAt: timestamp };
|
|
372
|
+
if ('updatedAt' in table) {
|
|
373
|
+
patch.updatedAt = currentTimestampForColumn((table as Record<string, unknown>).updatedAt);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
const condition = resolveWhere(table, where, false);
|
|
377
|
+
let query = db.update(table as never).set(patch as never);
|
|
378
|
+
if (condition) {
|
|
379
|
+
query = (query as never as { where: (c: SQL) => typeof query }).where(condition);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
return (await (query as never as { returning: () => Promise<InferSelectModel<T>[]> }).returning());
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
export async function deleteRow<T extends AnyPgTable & { id: unknown }>(
|
|
386
|
+
db: AnyDb,
|
|
387
|
+
table: T,
|
|
388
|
+
id: string
|
|
389
|
+
): Promise<InferSelectModel<T> | null> {
|
|
390
|
+
const rows = (await (db
|
|
391
|
+
.delete(table as never)
|
|
392
|
+
.where(eq(table.id as never, id))
|
|
393
|
+
.returning() as unknown as Promise<InferSelectModel<T>[]>));
|
|
394
|
+
return rows[0] ?? null;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
export async function deleteWhere<T extends AnyPgTable>(
|
|
398
|
+
db: AnyDb,
|
|
399
|
+
table: T,
|
|
400
|
+
where: WhereInput<T>
|
|
401
|
+
): Promise<InferSelectModel<T>[]> {
|
|
402
|
+
const condition = resolveWhere(table, where, true);
|
|
403
|
+
let query = db.delete(table as never);
|
|
404
|
+
if (condition) {
|
|
405
|
+
query = (query as never as { where: (c: SQL) => typeof query }).where(condition);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
return (await (query as never as { returning: () => Promise<InferSelectModel<T>[]> }).returning());
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
export async function incrementRow<T extends AnyPgTable & { id: unknown }>(
|
|
412
|
+
db: AnyDb,
|
|
413
|
+
table: T,
|
|
414
|
+
id: string,
|
|
415
|
+
increments: Partial<Record<keyof T['_']['columns'] & string, number>>,
|
|
416
|
+
extraValues?: Partial<InferInsertModel<T>>,
|
|
417
|
+
options?: MutationOptions
|
|
418
|
+
): Promise<InferSelectModel<T> | null> {
|
|
419
|
+
const patch: Record<string, unknown> = { ...extraValues };
|
|
420
|
+
for (const [colName, delta] of Object.entries(increments)) {
|
|
421
|
+
if (typeof delta === 'number') {
|
|
422
|
+
const col = (table as unknown as Record<string, unknown>)[colName] as PgColumn;
|
|
423
|
+
if (col) {
|
|
424
|
+
patch[colName] = sql`${col} + ${delta}`;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
return updateRow(db, table, id, patch as Partial<InferInsertModel<T>>, options);
|
|
429
|
+
}
|