@umituz/web-database 1.1.0 → 1.2.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/README.md CHANGED
@@ -15,6 +15,12 @@ Before this package, `neon()` + `drizzle(neon(url))` boilerplate (and the `@neon
15
15
  | `createDb(url, schema?)` | drizzle factory over the vendor driver — the only sanctioned way to build a `db` | `.` or `/driver` |
16
16
  | `sql(url)` | raw vendor executor (tagged-template queries) for scripts that shouldn't go through drizzle | `.` or `/driver` |
17
17
  | `Db` | the database type alias used across the fleet (`web-hono`'s `CrudDb`, `SnapshotDb` derive from it) | `.` or `/driver` |
18
+ | `batchQueries(db, queries)` | single HTTP roundtrip batch runner over Neon HTTP batching (named record or array) | `.` or `/query` |
19
+ | `findFirst(db, table, where?, options?)` | soft-delete aware single record query (`deletedAt IS NULL` auto-applied) | `.` or `/query` |
20
+ | `findMany(db, table, options?)` | soft-delete aware collection query with limit, offset, and orderBy | `.` or `/query` |
21
+ | `exists(db, table, where?, options?)` | soft-delete aware lightweight boolean existence probe (`SELECT 1 LIMIT 1`) | `.` or `/query` |
22
+ | `countRows(db, table, where?, options?)` | soft-delete aware exact count query | `.` or `/query` |
23
+ | `findById(db, table, id, options?)` | primary key lookup helper | `.` or `/query` |
18
24
  | `resetTables` / `snapshotToSeed` / `seedFromSnapshot` / `snapshotToBytes` | lifecycle tooling: prefix-guarded drops, snapshot export, snapshot import | `.` or `/lifecycle` |
19
25
 
20
26
  `resetTables` keeps the fleet's shared-database safety: it drops only tables carrying your project prefix and hard-stops the moment it sees a prefix-less table.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@umituz/web-database",
3
- "version": "1.1.0",
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, and db lifecycle tooling (reset / snapshot / seed)",
3
+ "version": "1.2.0",
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",
7
7
  "types": "./src/index.ts",
@@ -10,6 +10,7 @@
10
10
  ".": "./src/index.ts",
11
11
  "./driver": "./src/driver.ts",
12
12
  "./lifecycle": "./src/lifecycle.ts",
13
+ "./query": "./src/query.ts",
13
14
  "./package.json": "./package.json"
14
15
  },
15
16
  "files": [
package/src/index.ts CHANGED
@@ -7,3 +7,16 @@ export {
7
7
  snapshotToSeed,
8
8
  } from './lifecycle';
9
9
  export type { SeedSnapshot, SnapshotBytesResult, SnapshotDb, TableSpec } from './lifecycle';
10
+ export {
11
+ batchQueries,
12
+ countRows,
13
+ exists,
14
+ findById,
15
+ findFirst,
16
+ findMany,
17
+ } from './query';
18
+ export type {
19
+ AnyPgTable,
20
+ BatchCapableDb,
21
+ FindManyOptions,
22
+ } from './query';
package/src/query.ts ADDED
@@ -0,0 +1,168 @@
1
+ import { and, count, eq, isNull, sql } from 'drizzle-orm';
2
+ import type { InferSelectModel, SQL } from 'drizzle-orm';
3
+ import type { PgTable, TableConfig } from 'drizzle-orm/pg-core';
4
+ import type { Db } from './driver';
5
+
6
+ export type AnyPgTable = PgTable<TableConfig>;
7
+
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'];
11
+ };
12
+
13
+ type TableColumns<T extends AnyPgTable> = T['_']['columns'];
14
+
15
+ type WhereInput<T extends AnyPgTable> =
16
+ | SQL
17
+ | undefined
18
+ | ((cols: TableColumns<T>) => SQL | undefined);
19
+
20
+ export interface FindManyOptions<T extends AnyPgTable> {
21
+ where?: WhereInput<T>;
22
+ limit?: number;
23
+ offset?: number;
24
+ orderBy?: SQL | SQL[] | ((cols: TableColumns<T>) => SQL | SQL[]);
25
+ withDeleted?: boolean;
26
+ }
27
+
28
+ 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;
30
+ const hasDeletedAt = 'deletedAt' in table && Boolean((table as Record<string, unknown>).deletedAt);
31
+
32
+ if (!withDeleted && hasDeletedAt) {
33
+ const aliveCondition = isNull((table as Record<string, unknown>).deletedAt as never);
34
+ return customCondition ? and(customCondition, aliveCondition) : aliveCondition;
35
+ }
36
+
37
+ return customCondition;
38
+ }
39
+
40
+ export async function batchQueries<T extends Record<string, PromiseLike<unknown>>>(
41
+ db: BatchCapableDb,
42
+ queries: T
43
+ ): Promise<{ [K in keyof T]: Awaited<T[K]> }>;
44
+ export async function batchQueries<T extends readonly PromiseLike<unknown>[]>(
45
+ db: BatchCapableDb,
46
+ queries: readonly [...T]
47
+ ): Promise<{ [K in keyof T]: Awaited<T[K]> }>;
48
+ export async function batchQueries(
49
+ db: BatchCapableDb,
50
+ queries: Record<string, PromiseLike<unknown>> | readonly PromiseLike<unknown>[]
51
+ ): Promise<unknown> {
52
+ if (Array.isArray(queries)) {
53
+ if (typeof db.batch === 'function') {
54
+ return db.batch(queries as never);
55
+ }
56
+ return Promise.all(queries);
57
+ }
58
+
59
+ const queryMap = queries as Record<string, PromiseLike<unknown>>;
60
+ const keys = Object.keys(queryMap);
61
+ const promiseList = keys.map((key) => queryMap[key]);
62
+
63
+ let results: unknown[];
64
+ if (typeof db.batch === 'function') {
65
+ results = (await db.batch(promiseList as never)) as unknown[];
66
+ } else {
67
+ results = await Promise.all(promiseList);
68
+ }
69
+
70
+ const out: Record<string, unknown> = {};
71
+ for (let i = 0; i < keys.length; i++) {
72
+ const key = keys[i];
73
+ if (key !== undefined) {
74
+ out[key] = results[i];
75
+ }
76
+ }
77
+ return out;
78
+ }
79
+
80
+ export async function findFirst<T extends AnyPgTable>(
81
+ db: BatchCapableDb,
82
+ table: T,
83
+ where?: WhereInput<T>,
84
+ options?: { withDeleted?: boolean }
85
+ ): Promise<InferSelectModel<T> | null> {
86
+ const condition = resolveWhere(table, where, options?.withDeleted);
87
+ let query = db.select().from(table as never);
88
+ if (condition) {
89
+ query = (query as never as { where: (c: SQL) => typeof query }).where(condition);
90
+ }
91
+ const rows = (await (query as never as { limit: (n: number) => Promise<InferSelectModel<T>[]> }).limit(1)) as InferSelectModel<T>[];
92
+ return rows[0] ?? null;
93
+ }
94
+
95
+ export async function findMany<T extends AnyPgTable>(
96
+ db: BatchCapableDb,
97
+ table: T,
98
+ options?: FindManyOptions<T>
99
+ ): Promise<InferSelectModel<T>[]> {
100
+ const condition = resolveWhere(table, options?.where, options?.withDeleted);
101
+ let query = db.select().from(table as never);
102
+
103
+ if (condition) {
104
+ query = (query as never as { where: (c: SQL) => typeof query }).where(condition);
105
+ }
106
+
107
+ if (options?.orderBy) {
108
+ const order = typeof options.orderBy === 'function'
109
+ ? options.orderBy(table as unknown as TableColumns<T>)
110
+ : options.orderBy;
111
+ const orderClause = Array.isArray(order) ? order : [order];
112
+ query = (query as never as { orderBy: (...clauses: SQL[]) => typeof query }).orderBy(...orderClause);
113
+ }
114
+
115
+ if (typeof options?.offset === 'number') {
116
+ query = (query as never as { offset: (n: number) => typeof query }).offset(options.offset);
117
+ }
118
+
119
+ if (typeof options?.limit === 'number') {
120
+ query = (query as never as { limit: (n: number) => typeof query }).limit(options.limit);
121
+ }
122
+
123
+ return (await (query as never as Promise<InferSelectModel<T>[]>)) as InferSelectModel<T>[];
124
+ }
125
+
126
+ export async function exists<T extends AnyPgTable>(
127
+ db: BatchCapableDb,
128
+ table: T,
129
+ where?: WhereInput<T>,
130
+ options?: { withDeleted?: boolean }
131
+ ): Promise<boolean> {
132
+ const condition = resolveWhere(table, where, options?.withDeleted);
133
+ let query = db.select({ marker: sql`1` }).from(table as never);
134
+ if (condition) {
135
+ query = (query as never as { where: (c: SQL) => typeof query }).where(condition);
136
+ }
137
+ const rows = await (query as never as { limit: (n: number) => Promise<unknown[]> }).limit(1);
138
+ return rows.length > 0;
139
+ }
140
+
141
+ export async function countRows<T extends AnyPgTable>(
142
+ db: BatchCapableDb,
143
+ table: T,
144
+ where?: WhereInput<T>,
145
+ options?: { withDeleted?: boolean }
146
+ ): Promise<number> {
147
+ const condition = resolveWhere(table, where, options?.withDeleted);
148
+ let query = db.select({ total: count() }).from(table as never);
149
+ if (condition) {
150
+ query = (query as never as { where: (c: SQL) => typeof query }).where(condition);
151
+ }
152
+ const [row] = await (query as never as Promise<{ total: number }[]>);
153
+ return Number(row?.total ?? 0);
154
+ }
155
+
156
+ export async function findById<T extends AnyPgTable & { id: unknown }>(
157
+ db: BatchCapableDb,
158
+ table: T,
159
+ id: string,
160
+ options?: { withDeleted?: boolean }
161
+ ): Promise<InferSelectModel<T> | null> {
162
+ return findFirst(
163
+ db,
164
+ table,
165
+ eq(table.id as never, id),
166
+ options
167
+ );
168
+ }