@verikit/prisma 0.23.6 → 0.24.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
@@ -1,5 +1,25 @@
1
1
  # @verikit/prisma
2
2
 
3
- Prisma ORM storage adapter for VeriKit server resources.
3
+ Prisma ORM adapter for VeriKit server resources.
4
4
 
5
5
  See the [VeriKit documentation](https://verikit.dev) for setup and usage.
6
+
7
+ ## Consistent pagination
8
+
9
+ `listTransaction` is required: `list()`'s records and count queries always run
10
+ through it, in the same transaction, so a concurrent write between them can
11
+ never desync a page from `meta.total`. The adapter only ever sees a single
12
+ model delegate, not the full Prisma client, so it has no way to open a
13
+ transaction on its own pass one built from your `PrismaClient`:
14
+
15
+ ```ts
16
+ createPrismaAdapter(resource, {
17
+ model: prisma.post,
18
+ fields: { title: "title" },
19
+ id: { field: "id" },
20
+ listTransaction: (operation) =>
21
+ prisma.$transaction(
22
+ (tx) => operation(tx.post),
23
+ { isolationLevel: "RepeatableRead" },
24
+ ),
25
+ });
@@ -1,12 +1,8 @@
1
1
  import type { FieldMap, RelationshipMap, Resource } from "@verikit/core";
2
2
  import { type ResourceAdapter } from "@verikit/server";
3
3
  /**
4
- * Structural subset of a generated Prisma model delegate (e.g. `prisma.post`) that this
5
- * adapter drives. Kept loose (`any` args/results) rather than imported from `@prisma/client`:
6
- * a generated client's per-model argument/return types are specific to that model and schema,
7
- * there's no exported type that describes "any model delegate" generically, and every real
8
- * delegate is a structural superset of this anyway (same shape `@verikit/drizzle`'s
9
- * `AnyDrizzleDatabase` uses for the same reason).
4
+ * Structural subset of a Prisma model delegate used by this adapter.
5
+ * Kept generic to avoid coupling to generated model-specific types.
10
6
  */
11
7
  export interface PrismaModelDelegate {
12
8
  findMany(args?: any): Promise<any[]>;
@@ -25,21 +21,21 @@ export interface PrismaModelDelegate {
25
21
  }>;
26
22
  }
27
23
  /**
28
- * Id coercion between the adapter's raw string path segment and the value Prisma's `where`
29
- * expects. Unlike `@verikit/drizzle` (which introspects a real column's `dataType` to coerce
30
- * automatically), a Prisma model delegate exposes no such runtime metadata, so this is
31
- * explicit configuration rather than inference.
24
+ * Runs a list operation with the model delegate bound to a Prisma transaction.
25
+ * For example: `(operation) => prisma.$transaction((tx) => operation(tx.post))`.
26
+ */
27
+ export type PrismaListTransaction = <T>(operation: (model: PrismaModelDelegate) => Promise<T>) => Promise<T>;
28
+ /**
29
+ * Coerces raw string IDs into the type expected by Prisma `where` clauses.
30
+ * Explicit configuration is required because Prisma exposes no runtime ID type metadata.
32
31
  */
33
32
  export interface PrismaIdConfig<TId = unknown> {
34
33
  /** The Prisma scalar name of the model's primary (or other unique) id field. */
35
34
  field: string;
36
35
  /**
37
- * Decodes a route-segment string into the value used in Prisma's `where`. Return
38
- * `undefined` to signal the segment can never correspond to a real record (e.g. a
39
- * non-numeric segment against an `Int` id), which lets `find`/`update`/`delete` report
40
- * "missing" without even querying, mirroring `@verikit/drizzle`'s `coerceId`. Defaults to
41
- * the identity function, which only suits a string-typed id (cuid/uuid); a numeric or
42
- * composite id must supply this.
36
+ * Decodes a route-segment ID for Prisma `where` clauses.
37
+ * Return `undefined` for invalid IDs to skip the query and report "missing".
38
+ * Defaults to identity; numeric or composite IDs require an implementation.
43
39
  */
44
40
  fromPath?: (segment: string) => TId | undefined;
45
41
  /**
@@ -49,37 +45,18 @@ export interface PrismaIdConfig<TId = unknown> {
49
45
  toPath?: (value: TId) => string;
50
46
  }
51
47
  /**
52
- * Which case-insensitive search strategy `.searchable()` fields use. Prisma's `mode:
53
- * "insensitive"` filter is only implemented for PostgreSQL (and MongoDB); passing it on
54
- * SQLite or MySQL throws `PrismaClientValidationError` at query time. SQLite's own `contains`
55
- * is already ASCII-case-insensitive without it; MySQL's case-sensitivity is a property of the
56
- * column's collation, which Prisma can't override from the query API. Omit this (or pass
57
- * `"sqlite"`/`"mysql"`, which take the same code path) unless the datasource is PostgreSQL.
58
- * Only `"sqlite"` is exercised by this package's own test suite; `"postgresql"`'s branch is
59
- * implemented per Prisma's documented behavior but isn't integration-tested here (no
60
- * PostgreSQL instance in this repo's test environment) establish and test your own
61
- * provider's search behavior before relying on it in production.
62
- *
63
- * Separately, unlike `@verikit/drizzle` (which escapes `%`/`_` in the search term before
64
- * building its own `LIKE ... ESCAPE '\'`), this adapter's search goes through Prisma's
65
- * `contains` filter, which has no escape-character option. A search term containing `%` or
66
- * `_` is passed through and interpreted as a SQL wildcard by the underlying database, not
67
- * matched literally. There's no adapter-level fix for this without dropping to raw SQL (and
68
- * losing cross-provider portability with it); a consumer that needs literal-substring search
69
- * semantics must filter or escape those characters itself before calling the adapter.
48
+ * Case-insensitive search strategy for `.searchable()` fields.
49
+ * PostgreSQL uses Prisma's `mode: "insensitive"`; SQLite and MySQL rely on
50
+ * collation. `%`, `_`, and `\` are matched literally across providers.
70
51
  */
71
52
  export type PrismaSearchProvider = "postgresql" | "sqlite" | "mysql";
72
53
  export interface PrismaAdapterOptions<TFields extends FieldMap> {
73
54
  /** The generated Prisma model delegate this adapter reads/writes, e.g. `prisma.post`. */
74
55
  model: PrismaModelDelegate;
75
56
  /**
76
- * Required resource-field-to-Prisma-scalar mapping, covering every field the resource
77
- * declares. Used for reads, writes, search, and sorting. There is no automatic
78
- * same-name fallback (unlike `@verikit/drizzle`'s column resolution) because a Prisma
79
- * delegate has no introspectable schema to fall back against; every field must be listed
80
- * explicitly. Relation fields and arbitrary Prisma `include`/`select` values are out of
81
- * scope see `ResourceAdapter`'s docstring on why relationship loading isn't part of this
82
- * contract yet.
57
+ * Maps every resource field to its Prisma scalar field.
58
+ * All fields must be explicitly mapped; relations and Prisma `include`/`select`
59
+ * values are not supported.
83
60
  */
84
61
  fields: {
85
62
  [K in keyof TFields & string]: string;
@@ -88,6 +65,22 @@ export interface PrismaAdapterOptions<TFields extends FieldMap> {
88
65
  id: PrismaIdConfig;
89
66
  /** See `PrismaSearchProvider`. */
90
67
  provider?: PrismaSearchProvider;
68
+ /**
69
+ * Maximum scoped rows examined when a search term contains `%`, `_`, or `\\`.
70
+ * Prisma cannot escape those LIKE metacharacters consistently across providers,
71
+ * so literal searches are filtered in memory only after a bounded read. A search
72
+ * exceeding this limit fails rather than loading an unbounded table or returning
73
+ * an incomplete page. Defaults to 1,000.
74
+ */
75
+ literalSearchCandidateLimit?: number;
76
+ /**
77
+ * Runs `list()` records and count queries in the same transaction to keep
78
+ * pagination consistent. Required because the adapter cannot open a transaction
79
+ * from a model delegate alone.
80
+ *
81
+ * Use Prisma's `RepeatableRead` isolation for a stable pagination snapshot.
82
+ */
83
+ listTransaction: PrismaListTransaction;
91
84
  }
92
85
  /** A canonical API record returned by the Prisma adapter. */
93
86
  export interface PrismaResourceRecord extends Record<string, unknown> {
@@ -95,13 +88,11 @@ export interface PrismaResourceRecord extends Record<string, unknown> {
95
88
  id: string;
96
89
  }
97
90
  /**
98
- * Builds a `ResourceAdapter` backed by a Prisma model delegate, so `@verikit/server` never
99
- * has to import `@prisma/client` itself. Every operation selects and returns only the
100
- * configured `fields` plus the canonical `id` never a whole model row matching
101
- * `ResourceAdapter`'s contract that adapter records are API records, not ORM rows.
102
- * @throws {Error} If `fields` is missing a mapping for a field the resource declares, or if a
103
- * `.searchable()` field's `fieldType` isn't text-like (`text`/`textarea`/`email`) Prisma's
104
- * `contains` filter only works on `String` scalars.
91
+ * Creates a Prisma-backed `ResourceAdapter`.
92
+ * Selects only configured fields plus `id`, never full model rows.
93
+ *
94
+ * @throws {Error} If a resource field is unmapped or a `.searchable()` field
95
+ * is not text-like.
105
96
  */
106
97
  export declare function createPrismaAdapter<TFields extends FieldMap, TRelationships extends RelationshipMap, TTable = unknown>(resource: Resource<string, TFields, TTable, TRelationships>, options: PrismaAdapterOptions<TFields>): ResourceAdapter<PrismaResourceRecord>;
107
98
  //# sourceMappingURL=create-prisma-adapter.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"create-prisma-adapter.d.ts","sourceRoot":"","sources":["../src/create-prisma-adapter.ts"],"names":[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MAAM,CAAC;CACjC;AAED;;;;GAIG;AACH,MAAM,MAAM,oBAAoB,GAAG,YAAY,GAAG,QAAQ,GAAG,OAAO,CAAC;AAErE,MAAM,WAAW,oBAAoB,CAAC,OAAO,SAAS,QAAQ;IAC5D,yFAAyF;IACzF,KAAK,EAAE,mBAAmB,CAAC;IAC3B;;;;OAIG;IACH,MAAM,EAAE;SAAG,CAAC,IAAI,MAAM,OAAO,GAAG,MAAM,GAAG,MAAM;KAAE,CAAC;IAClD,8EAA8E;IAC9E,EAAE,EAAE,cAAc,CAAC;IACnB,kCAAkC;IAClC,QAAQ,CAAC,EAAE,oBAAoB,CAAC;IAChC;;;;;;OAMG;IACH,2BAA2B,CAAC,EAAE,MAAM,CAAC;IACrC;;;;;;OAMG;IACH,eAAe,EAAE,qBAAqB,CAAC;CACxC;AAED,6DAA6D;AAC7D,MAAM,WAAW,oBAAqB,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IACnE,mEAAmE;IACnE,EAAE,EAAE,MAAM,CAAC;CACZ;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,SAAS,QAAQ,EACxB,cAAc,SAAS,eAAe,EACtC,MAAM,GAAG,OAAO,EAEhB,QAAQ,EAAE,QAAQ,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,cAAc,CAAC,EAC3D,OAAO,EAAE,oBAAoB,CAAC,OAAO,CAAC,GACrC,eAAe,CAAC,oBAAoB,CAAC,CAqVvC"}
@@ -1,13 +1,11 @@
1
1
  import { UniqueConstraintError, } from "@verikit/server";
2
2
  import { buildSelect, isRecordNotFoundError, isUniqueConstraintError, mapFilterToPrisma, mapValuesToData, presentRow, uniqueConstraintFields, } from "./mapping.js";
3
3
  /**
4
- * Builds a `ResourceAdapter` backed by a Prisma model delegate, so `@verikit/server` never
5
- * has to import `@prisma/client` itself. Every operation selects and returns only the
6
- * configured `fields` plus the canonical `id` never a whole model row matching
7
- * `ResourceAdapter`'s contract that adapter records are API records, not ORM rows.
8
- * @throws {Error} If `fields` is missing a mapping for a field the resource declares, or if a
9
- * `.searchable()` field's `fieldType` isn't text-like (`text`/`textarea`/`email`) Prisma's
10
- * `contains` filter only works on `String` scalars.
4
+ * Creates a Prisma-backed `ResourceAdapter`.
5
+ * Selects only configured fields plus `id`, never full model rows.
6
+ *
7
+ * @throws {Error} If a resource field is unmapped or a `.searchable()` field
8
+ * is not text-like.
11
9
  */
12
10
  export function createPrismaAdapter(resource, options) {
13
11
  const { model, id } = options;
@@ -28,6 +26,11 @@ export function createPrismaAdapter(resource, options) {
28
26
  return [name, fields[name]];
29
27
  });
30
28
  const select = buildSelect(fields, id.field);
29
+ const literalSearchCandidateLimit = options.literalSearchCandidateLimit ?? 1_000;
30
+ if (!Number.isInteger(literalSearchCandidateLimit) ||
31
+ literalSearchCandidateLimit < 1) {
32
+ throw new Error("@verikit/prisma: literalSearchCandidateLimit must be a positive integer.");
33
+ }
31
34
  const fromPath = id.fromPath ?? ((segment) => segment);
32
35
  const toPath = id.toPath ?? ((value) => String(value));
33
36
  function present(row) {
@@ -45,6 +48,14 @@ export function createPrismaAdapter(resource, options) {
45
48
  })),
46
49
  };
47
50
  }
51
+ function matchesLiteralSearch(row, term, searchable) {
52
+ const normalizedTerm = term.toLowerCase();
53
+ return searchable.some((scalar) => {
54
+ const value = row[scalar];
55
+ return (typeof value === "string" &&
56
+ value.toLowerCase().includes(normalizedTerm));
57
+ });
58
+ }
48
59
  function scopeWhere(scope) {
49
60
  if (!scope || Object.keys(scope).length === 0)
50
61
  return undefined;
@@ -73,11 +84,25 @@ export function createPrismaAdapter(resource, options) {
73
84
  ? constraints[0]
74
85
  : { AND: constraints };
75
86
  }
87
+ async function findRecord(pathId, scope) {
88
+ const value = fromPath(pathId);
89
+ if (value === undefined) {
90
+ return undefined;
91
+ }
92
+ if (scope && !model.findFirst) {
93
+ throw new Error("@verikit/prisma: scoped reads require a Prisma delegate with findFirst().");
94
+ }
95
+ const row = scope
96
+ ? await model.findFirst({
97
+ where: combinedWhere(scope, { [id.field]: value }),
98
+ select,
99
+ })
100
+ : await model.findUnique({ where: { [id.field]: value }, select });
101
+ return present(row);
102
+ }
76
103
  return {
77
104
  async list(params) {
78
- // A search term against a resource with no searchable fields can never match
79
- // anything; treat it as an unsatisfiable filter (zero results), matching
80
- // @verikit/drizzle's convention for the same case.
105
+ // Search with no searchable fields can never match; return zero results.
81
106
  const permittedSearchScalars = params.searchFields
82
107
  ? searchableScalars
83
108
  .filter(([name]) => params.searchFields.includes(name))
@@ -86,48 +111,55 @@ export function createPrismaAdapter(resource, options) {
86
111
  if (params.search && permittedSearchScalars.length === 0) {
87
112
  return { records: [], total: 0 };
88
113
  }
89
- const where = combinedWhere(params.scope, params.search
114
+ // Prisma `contains` can't escape LIKE metacharacters across all providers.
115
+ // Apply literal matching locally after a bounded candidate read so `%`, `_`,
116
+ // and `\` cannot widen results or load an entire scoped table into memory.
117
+ const literalSearch = params.search !== undefined && /[\\%_]/.test(params.search);
118
+ const where = combinedWhere(params.scope, params.search && !literalSearch
90
119
  ? searchWhere(params.search, permittedSearchScalars)
91
120
  : undefined, params.filters);
92
121
  const sort = params.sort;
93
122
  const sortScalar = sort && fields[sort.field];
94
123
  const orderBy = sort && sortScalar ? { [sortScalar]: sort.direction } : undefined;
95
- // Two independent queries, not one transaction: only the model delegate is
96
- // available here, not the top-level PrismaClient that owns `$transaction`. A
97
- // concurrent write between these two calls can make `total` and `records.length`
98
- // momentarily disagree across a page boundary; a consumer that needs a consistent
99
- // snapshot should pass a delegate bound to an active `$transaction` callback.
100
- const [rows, total] = await Promise.all([
101
- model.findMany({
102
- where,
103
- select,
104
- ...(orderBy && { orderBy }),
105
- skip: (params.page - 1) * params.pageSize,
106
- take: params.pageSize,
107
- }),
108
- model.count({ where }),
109
- ]);
124
+ const readPage = async (listModel) => {
125
+ if (literalSearch) {
126
+ const rows = await listModel.findMany({
127
+ where,
128
+ select,
129
+ ...(orderBy && { orderBy }),
130
+ // Fetch one extra row to distinguish an exact-limit result from an
131
+ // unsafe, incomplete subset without loading the whole table.
132
+ take: literalSearchCandidateLimit + 1,
133
+ });
134
+ if (rows.length > literalSearchCandidateLimit) {
135
+ throw new Error(`@verikit/prisma: literal search for resource "${resource.name}" exceeds the ${literalSearchCandidateLimit}-row candidate limit. Narrow the search or raise literalSearchCandidateLimit.`);
136
+ }
137
+ const matchingRows = rows.filter((row) => matchesLiteralSearch(row, params.search, permittedSearchScalars));
138
+ const offset = (params.page - 1) * params.pageSize;
139
+ return {
140
+ rows: matchingRows.slice(offset, offset + params.pageSize),
141
+ total: matchingRows.length,
142
+ };
143
+ }
144
+ const [rows, total] = await Promise.all([
145
+ listModel.findMany({
146
+ where,
147
+ select,
148
+ ...(orderBy && { orderBy }),
149
+ skip: (params.page - 1) * params.pageSize,
150
+ take: params.pageSize,
151
+ }),
152
+ listModel.count({ where }),
153
+ ]);
154
+ return { rows, total };
155
+ };
156
+ const { rows, total } = await options.listTransaction(readPage);
110
157
  return {
111
158
  records: rows.map((row) => present(row)),
112
159
  total,
113
160
  };
114
161
  },
115
- async find(pathId, scope) {
116
- const value = fromPath(pathId);
117
- if (value === undefined) {
118
- return undefined;
119
- }
120
- if (scope && !model.findFirst) {
121
- throw new Error("@verikit/prisma: scoped reads require a Prisma delegate with findFirst().");
122
- }
123
- const row = scope
124
- ? await model.findFirst({
125
- where: combinedWhere(scope, { [id.field]: value }),
126
- select,
127
- })
128
- : await model.findUnique({ where: { [id.field]: value }, select });
129
- return present(row);
130
- },
162
+ find: findRecord,
131
163
  async create(values) {
132
164
  const data = mapValuesToData(values, fields);
133
165
  try {
@@ -153,10 +185,8 @@ export function createPrismaAdapter(resource, options) {
153
185
  if (scope) {
154
186
  const where = combinedWhere(scope, { [id.field]: value });
155
187
  try {
156
- // returns the written row directly,
157
- // so the scoped write and the canonical-record read happen in one round
158
- // trip instead of two. Older Prisma delegates fall back to updateMany
159
- // plus a follow-up scoped find.
188
+ // Return the updated row directly when supported; older Prisma delegates
189
+ // fall back to `updateMany` followed by a scoped read.
160
190
  if (model.updateManyAndReturn) {
161
191
  const [row] = await model.updateManyAndReturn({
162
192
  where,
@@ -169,7 +199,7 @@ export function createPrismaAdapter(resource, options) {
169
199
  throw new Error("@verikit/prisma: scoped updates require a Prisma delegate with updateMany() or updateManyAndReturn().");
170
200
  }
171
201
  const result = await model.updateMany({ where, data });
172
- return result.count === 0 ? undefined : this.find(pathId, scope);
202
+ return result.count === 0 ? undefined : findRecord(pathId, scope);
173
203
  }
174
204
  catch (error) {
175
205
  if (isUniqueConstraintError(error)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verikit/prisma",
3
- "version": "0.23.6",
3
+ "version": "0.24.0",
4
4
  "description": "Prisma ORM storage adapter for @verikit/server resources.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -36,8 +36,8 @@
36
36
  "dist"
37
37
  ],
38
38
  "dependencies": {
39
- "@verikit/server": "0.23.6",
40
- "@verikit/core": "0.23.6"
39
+ "@verikit/core": "0.24.0",
40
+ "@verikit/server": "0.24.0"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@prisma/adapter-better-sqlite3": "^7.9.1",