turbine-orm 0.28.0 → 0.28.2

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.
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ /**
3
+ * turbine-orm — Deferred query + QueryInterface option types
4
+ *
5
+ * Split from builder.ts so the class file focuses on SQL assembly / execution.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,251 @@
1
+ "use strict";
2
+ /**
3
+ * turbine-orm — Where-filter type guards and shape helpers
4
+ *
5
+ * Pure detection / fingerprint utilities used by the query builder's WHERE
6
+ * compiler. Kept out of builder.ts so the class file stays about SQL assembly
7
+ * and execution rather than filter-shape bookkeeping.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.VECTOR_DISTANCE_COMPARATORS = exports.VECTOR_METRIC_OPERATORS = exports.TEXT_SEARCH_KEYS = exports.ARRAY_UNIQUE_KEYS = exports.ARRAY_OPERATOR_KEYS = exports.JSONB_UNIQUE_KEYS = exports.JSONB_OPERATOR_KEYS = exports.UPDATE_OPERATOR_KEYS = void 0;
11
+ exports.isWhereOperator = isWhereOperator;
12
+ exports.isUnmatchedPlainObject = isUnmatchedPlainObject;
13
+ exports.fingerprintOperatorShape = fingerprintOperatorShape;
14
+ exports.assertBindableEqualsOperand = assertBindableEqualsOperand;
15
+ exports.sortedKeys = sortedKeys;
16
+ exports.sortedEntries = sortedEntries;
17
+ exports.isJsonFilter = isJsonFilter;
18
+ exports.findJsonUniqueKey = findJsonUniqueKey;
19
+ exports.isArrayFilter = isArrayFilter;
20
+ exports.findArrayUniqueKey = findArrayUniqueKey;
21
+ exports.isTextSearchFilter = isTextSearchFilter;
22
+ exports.validateTextSearchConfig = validateTextSearchConfig;
23
+ exports.isVectorFilter = isVectorFilter;
24
+ exports.isVectorOrderBy = isVectorOrderBy;
25
+ exports.isOrderBySpec = isOrderBySpec;
26
+ exports.normalizeOrderBy = normalizeOrderBy;
27
+ const errors_js_1 = require("../errors.js");
28
+ const utils_js_1 = require("./utils.js");
29
+ // ---------------------------------------------------------------------------
30
+ // Where-operator detection
31
+ // ---------------------------------------------------------------------------
32
+ /** Check if a value is a where operator object (has at least one known operator key) */
33
+ function isWhereOperator(value) {
34
+ if (value === null ||
35
+ value === undefined ||
36
+ typeof value !== 'object' ||
37
+ Array.isArray(value) ||
38
+ value instanceof Date) {
39
+ return false;
40
+ }
41
+ const keys = Object.keys(value);
42
+ return keys.length > 0 && keys.every((k) => utils_js_1.OPERATOR_KEYS.has(k));
43
+ }
44
+ /**
45
+ * True for a *plain object literal* that reached an equality fallthrough
46
+ * without matching any known filter shape — the misspelled-operator case.
47
+ * Class instances (Buffer for bytea, Decimal wrappers, ...) are legitimate
48
+ * bind values and return false, as do arrays and Dates.
49
+ */
50
+ function isUnmatchedPlainObject(value) {
51
+ if (typeof value !== 'object' || value === null || Array.isArray(value) || value instanceof Date)
52
+ return false;
53
+ if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value))
54
+ return false;
55
+ const proto = Object.getPrototypeOf(value);
56
+ return proto === Object.prototype || proto === null;
57
+ }
58
+ /**
59
+ * Fingerprint the SHAPE of a where-operator object. Null-valued `equals` /
60
+ * `not` compile to parameterless `IS NULL` / `IS NOT NULL` (different SQL, no
61
+ * param pushed), so null-ness is part of the shape — without it a cache entry
62
+ * warmed by `{ not: 5 }` would serve `{ not: null }` with a desynced param list.
63
+ */
64
+ function fingerprintOperatorShape(value) {
65
+ const obj = value;
66
+ const opKeys = Object.keys(obj)
67
+ .filter((k) => k !== 'mode')
68
+ .map((k) => ((k === 'equals' || k === 'not') && obj[k] === null ? `${k}:null` : k))
69
+ .sort();
70
+ const modeStr = value.mode === 'insensitive' ? ':i' : '';
71
+ return `op(${opKeys.join(',')}${modeStr})`;
72
+ }
73
+ /**
74
+ * Guard for the value of an `equals` operator reaching the plain-equality
75
+ * operator path. A plain object literal can only legitimately be an equality
76
+ * value on a json/jsonb column — and those route to the JSONB filter branch
77
+ * BEFORE the operator branch, so any plain object that reaches here is a
78
+ * mistake (e.g. `{ equals: { foo: 1 } }` on a text column). Shared by the
79
+ * SQL-build path and the cache-hit param-collect path so a warmed cache can
80
+ * never skip the check.
81
+ */
82
+ function assertBindableEqualsOperand(value, column) {
83
+ if (!isUnmatchedPlainObject(value))
84
+ return;
85
+ throw new errors_js_1.ValidationError(`[turbine] Plain-object value for operator 'equals' on ${column}: ` +
86
+ `objects are only valid 'equals' values on JSON (json/jsonb) columns, ` +
87
+ `where 'equals' is the JSONB containment filter.`);
88
+ }
89
+ /**
90
+ * Object keys in sorted order, mirroring the canonical order used by every
91
+ * cache fingerprint. The SQL-build and cache-hit param-collect paths MUST
92
+ * enumerate object keys in this exact order: fingerprints sort keys, so two
93
+ * where clauses with the same fields in different insertion order share one
94
+ * cache entry — if build/collect iterated insertion order, the cached SQL's
95
+ * `$N` placeholders would bind the wrong values (cross-tenant-leak class).
96
+ * Array order (OR/AND members) is positional and is never sorted.
97
+ */
98
+ function sortedKeys(obj) {
99
+ return Object.keys(obj).sort();
100
+ }
101
+ /** {@link sortedKeys}, but yielding `[key, value]` pairs. */
102
+ function sortedEntries(obj) {
103
+ return Object.entries(obj).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
104
+ }
105
+ // ---------------------------------------------------------------------------
106
+ // Atomic-update / JSONB / Array / text-search / vector key sets
107
+ // ---------------------------------------------------------------------------
108
+ /** Known atomic-update operator keys — used to detect operator objects vs plain JSON values */
109
+ exports.UPDATE_OPERATOR_KEYS = new Set(['set', 'increment', 'decrement', 'multiply', 'divide']);
110
+ /** Known JSONB operator keys */
111
+ exports.JSONB_OPERATOR_KEYS = new Set(['path', 'equals', 'contains', 'hasKey']);
112
+ /**
113
+ * JSONB operator keys that are *unique* to {@link JsonFilter} — they cannot
114
+ * appear in any other where-filter shape, so the presence of one of these is
115
+ * an unambiguous signal that the user meant a JSON filter. Used by the
116
+ * strict-validation path so that `{ contains: 'foo' }` (which is also a valid
117
+ * `WhereOperator` for LIKE) is not misclassified. Note `equals` is NOT in this
118
+ * set: on non-JSON columns it is a plain equality operator (`WhereOperator`),
119
+ * so it must fall through instead of throwing.
120
+ */
121
+ exports.JSONB_UNIQUE_KEYS = new Set(['path', 'hasKey']);
122
+ /** Check if a value is a JSONB filter object */
123
+ function isJsonFilter(value) {
124
+ if (value === null ||
125
+ value === undefined ||
126
+ typeof value !== 'object' ||
127
+ Array.isArray(value) ||
128
+ value instanceof Date) {
129
+ return false;
130
+ }
131
+ const keys = Object.keys(value);
132
+ return keys.length > 0 && keys.some((k) => exports.JSONB_OPERATOR_KEYS.has(k));
133
+ }
134
+ /**
135
+ * Returns the first JSON-unique key found in `value`, or `null` if none.
136
+ * Used to drive the strict-validation error message.
137
+ */
138
+ function findJsonUniqueKey(value) {
139
+ for (const k of Object.keys(value)) {
140
+ if (exports.JSONB_UNIQUE_KEYS.has(k))
141
+ return k;
142
+ }
143
+ return null;
144
+ }
145
+ /** Known Array operator keys */
146
+ exports.ARRAY_OPERATOR_KEYS = new Set(['has', 'hasEvery', 'hasSome', 'isEmpty']);
147
+ /**
148
+ * Array operator keys that are *unique* to {@link ArrayFilter}. None of the
149
+ * array operators currently overlap with `WhereOperator` or `JsonFilter`, so
150
+ * this set equals {@link ARRAY_OPERATOR_KEYS}; it is kept as a separate
151
+ * constant so a future overlap (e.g. a `contains` for arrays) is easy to
152
+ * carve out.
153
+ */
154
+ exports.ARRAY_UNIQUE_KEYS = new Set(['has', 'hasEvery', 'hasSome', 'isEmpty']);
155
+ /** Check if a value is an Array filter object */
156
+ function isArrayFilter(value) {
157
+ if (value === null ||
158
+ value === undefined ||
159
+ typeof value !== 'object' ||
160
+ Array.isArray(value) ||
161
+ value instanceof Date) {
162
+ return false;
163
+ }
164
+ const keys = Object.keys(value);
165
+ return keys.length > 0 && keys.some((k) => exports.ARRAY_OPERATOR_KEYS.has(k));
166
+ }
167
+ /**
168
+ * Returns the first array-unique key found in `value`, or `null` if none.
169
+ * Used to drive the strict-validation error message.
170
+ */
171
+ function findArrayUniqueKey(value) {
172
+ for (const k of Object.keys(value)) {
173
+ if (exports.ARRAY_UNIQUE_KEYS.has(k))
174
+ return k;
175
+ }
176
+ return null;
177
+ }
178
+ /** Known text search operator keys */
179
+ exports.TEXT_SEARCH_KEYS = new Set(['search', 'config']);
180
+ /** Check if a value is a TextSearchFilter object */
181
+ function isTextSearchFilter(value) {
182
+ if (value === null ||
183
+ value === undefined ||
184
+ typeof value !== 'object' ||
185
+ Array.isArray(value) ||
186
+ value instanceof Date) {
187
+ return false;
188
+ }
189
+ const keys = Object.keys(value);
190
+ // Must have 'search' key and only known text search keys
191
+ return keys.includes('search') && keys.every((k) => exports.TEXT_SEARCH_KEYS.has(k));
192
+ }
193
+ /**
194
+ * Validate a text search config name. Only alphanumeric characters and
195
+ * underscores are allowed to prevent SQL injection via the config parameter.
196
+ */
197
+ function validateTextSearchConfig(config) {
198
+ return /^[a-zA-Z0-9_]+$/.test(config);
199
+ }
200
+ /**
201
+ * pgvector distance metric → operator allow-list. This is the ONLY mapping
202
+ * from a user-supplied metric token to a SQL operator; any token not present
203
+ * here is rejected, so a user value can never become an arbitrary operator.
204
+ *
205
+ * - `l2` → `<->` (Euclidean / L2 distance)
206
+ * - `cosine` → `<=>` (cosine distance)
207
+ * - `ip` → `<#>` (negative inner product)
208
+ */
209
+ exports.VECTOR_METRIC_OPERATORS = {
210
+ l2: '<->',
211
+ cosine: '<=>',
212
+ ip: '<#>',
213
+ };
214
+ /** Comparison keys allowed on a {@link VectorDistanceFilter}. */
215
+ exports.VECTOR_DISTANCE_COMPARATORS = {
216
+ lt: '<',
217
+ lte: '<=',
218
+ gt: '>',
219
+ gte: '>=',
220
+ };
221
+ /** Check if a value is a vector distance WHERE filter: `{ distance: { to, metric } }` */
222
+ function isVectorFilter(value) {
223
+ if (value === null || typeof value !== 'object' || Array.isArray(value) || value instanceof Date) {
224
+ return false;
225
+ }
226
+ const dist = value.distance;
227
+ return (typeof dist === 'object' &&
228
+ dist !== null &&
229
+ !Array.isArray(dist) &&
230
+ 'to' in dist &&
231
+ 'metric' in dist);
232
+ }
233
+ /** Check if an orderBy value is a vector KNN ordering: `{ distance: { to, metric } }` */
234
+ function isVectorOrderBy(value) {
235
+ return isVectorFilter(value);
236
+ }
237
+ /** Check if an orderBy value is an explicit `{ sort, nulls? }` spec. */
238
+ function isOrderBySpec(value) {
239
+ return typeof value === 'object' && value !== null && !Array.isArray(value) && 'sort' in value;
240
+ }
241
+ /**
242
+ * Normalize an orderBy value into `{ direction, nulls }`. Accepts a plain
243
+ * direction string or an {@link OrderBySpec}. Used by every ORDER BY compile
244
+ * path (findMany, groupBy, relation inner subqueries).
245
+ */
246
+ function normalizeOrderBy(value) {
247
+ if (isOrderBySpec(value)) {
248
+ return { dir: value.sort.toLowerCase() === 'desc' ? 'DESC' : 'ASC', nulls: value.nulls };
249
+ }
250
+ return { dir: String(value).toLowerCase() === 'desc' ? 'DESC' : 'ASC' };
251
+ }
package/dist/errors.js CHANGED
@@ -24,11 +24,25 @@ export const TurbineErrorCode = {
24
24
  EXCLUSION_VIOLATION: 'TURBINE_E016',
25
25
  UNSUPPORTED_FEATURE: 'TURBINE_E017',
26
26
  };
27
+ /**
28
+ * Prefix a human message with its stable error code so logs are greppable
29
+ * without requiring structured field access. Idempotent if the message already
30
+ * starts with `[TURBINE_E0NN]`.
31
+ */
32
+ function formatErrorMessage(code, message) {
33
+ const tag = `[${code}]`;
34
+ if (message.startsWith(tag))
35
+ return message;
36
+ // Empty message → just the code (defensive; callers always pass text today).
37
+ if (!message)
38
+ return tag;
39
+ return `${tag} ${message}`;
40
+ }
27
41
  /** Base error class for all Turbine errors */
28
42
  export class TurbineError extends Error {
29
43
  code;
30
44
  constructor(code, message, options) {
31
- super(message, options);
45
+ super(formatErrorMessage(code, message), options);
32
46
  this.name = 'TurbineError';
33
47
  this.code = code;
34
48
  }
package/dist/powdb.d.ts CHANGED
@@ -9,7 +9,7 @@
9
9
  * seam. The four SQL engines are untouched.
10
10
  *
11
11
  * PowDB realities shape the design (all verified firsthand against a live
12
- * `powdb-server` / the embedded addon, see `docs/strategy/powdb-parity-matrix.md`):
12
+ * `powdb-server` / the embedded addon, see `docs/internal/strategy/powdb-parity-matrix.md`):
13
13
  * - **`RETURNING` (since 0.7.0)** — `create/createMany/update/delete` append the
14
14
  * trailing `returning` keyword (`RETURNING *`, all columns) and read the
15
15
  * affected rows back in one round-trip. `upsert` is the lone exception (its
package/dist/powdb.js CHANGED
@@ -9,7 +9,7 @@
9
9
  * seam. The four SQL engines are untouched.
10
10
  *
11
11
  * PowDB realities shape the design (all verified firsthand against a live
12
- * `powdb-server` / the embedded addon, see `docs/strategy/powdb-parity-matrix.md`):
12
+ * `powdb-server` / the embedded addon, see `docs/internal/strategy/powdb-parity-matrix.md`):
13
13
  * - **`RETURNING` (since 0.7.0)** — `create/createMany/update/delete` append the
14
14
  * trailing `returning` keyword (`RETURNING *`, all columns) and read the
15
15
  * affected rows back in one round-trip. `upsert` is the lone exception (its
package/dist/powql.d.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  * it separate also means the four SQL engines are untouched.
11
11
  *
12
12
  * Behavioural deltas from the SQL path, all driven by PowDB's wire reality (see
13
- * `docs/strategy/powdb-parity-matrix.md`, every row verified against a live
13
+ * `docs/internal/strategy/powdb-parity-matrix.md`, every row verified against a live
14
14
  * server):
15
15
  * - `create`/`createMany`/`update`/`delete` use PowDB 0.7.0's trailing
16
16
  * `returning` keyword (`RETURNING *`, all columns) to surface affected rows
package/dist/powql.js CHANGED
@@ -10,7 +10,7 @@
10
10
  * it separate also means the four SQL engines are untouched.
11
11
  *
12
12
  * Behavioural deltas from the SQL path, all driven by PowDB's wire reality (see
13
- * `docs/strategy/powdb-parity-matrix.md`, every row verified against a live
13
+ * `docs/internal/strategy/powdb-parity-matrix.md`, every row verified against a live
14
14
  * server):
15
15
  * - `create`/`createMany`/`update`/`delete` use PowDB 0.7.0's trailing
16
16
  * `returning` keyword (`RETURNING *`, all columns) to surface affected rows
@@ -11,129 +11,10 @@
11
11
  * metadata — nothing is hardcoded.
12
12
  */
13
13
  import type pg from 'pg';
14
- import type { Dialect } from '../dialect.js';
15
14
  import type { SchemaMetadata } from '../schema.js';
16
- import type { AggregateArgs, AggregateResult, CountArgs, CreateArgs, CreateManyArgs, DeleteArgs, DeleteManyArgs, FindManyArgs, FindManyStreamArgs, FindUniqueArgs, GlobalFilters, GroupByArgs, QueryResult, RelationLoadStrategy, TypedWithClause, UpdateArgs, UpdateManyArgs, UpsertArgs, WithClause } from './types.js';
17
- /**
18
- * Runs a SQL statement and resolves its raw result. Passed to a
19
- * {@link DeferredQuery.reselect} plan so it can run the write and the follow-up
20
- * SELECT through the same timeout/instrumentation path as the primary query.
21
- */
22
- export type ReselectExecutor = (sql: string, params: unknown[], preparedName?: string) => Promise<pg.QueryResult>;
23
- export interface DeferredQuery<T> {
24
- /** SQL text with $1, $2 placeholders */
25
- sql: string;
26
- /** Bound parameter values */
27
- params: unknown[];
28
- /** How to transform the raw pg.QueryResult into the final value */
29
- transform: (result: pg.QueryResult) => T;
30
- /** Tag for debugging / logging */
31
- tag: string;
32
- /** Prepared statement name (t_<16hex>). Set when SQL cache is enabled. */
33
- preparedName?: string;
34
- /**
35
- * Execution plan for dialects whose {@link Dialect.resultStrategy} is
36
- * `'reselect'` (no RETURNING — e.g. MySQL). Owns the statement ordering: it
37
- * runs the write and the follow-up row-fetching SELECT(s) via `exec`, and
38
- * resolves the result whose rows {@link DeferredQuery.transform} consumes.
39
- * Absent for `'returning'`/`'output'` dialects (the statement returns its own
40
- * rows), so the PostgreSQL path never allocates or consults it.
41
- */
42
- reselect?: (exec: ReselectExecutor) => Promise<pg.QueryResult>;
43
- }
44
- /** Middleware function type — imported from client to avoid circular deps */
45
- export type MiddlewareFn = (params: {
46
- model: string;
47
- action: string;
48
- args: Record<string, unknown>;
49
- }, next: (params: {
50
- model: string;
51
- action: string;
52
- args: Record<string, unknown>;
53
- }) => Promise<unknown>) => Promise<unknown>;
54
- /** Emitted after every query execution (success or failure). */
55
- export interface QueryEvent {
56
- sql: string;
57
- params: unknown[];
58
- duration: number;
59
- model: string;
60
- action: string;
61
- rows: number;
62
- timestamp: Date;
63
- error?: Error;
64
- }
65
- export type QueryEventListener = (event: QueryEvent) => void;
66
- /** Options passed from TurbineClient to QueryInterface */
67
- export interface QueryInterfaceOptions {
68
- /** Default LIMIT applied to findMany() when no limit is specified */
69
- defaultLimit?: number;
70
- /**
71
- * Log a one-time warning when {@link QueryInterface.findMany} is called
72
- * without a `limit`. Defaults to `true` so that accidental unbounded
73
- * queries are surfaced loudly during development. Pass `false` to silence
74
- * the warning entirely (e.g. for CLI tooling that intentionally streams
75
- * full tables).
76
- */
77
- warnOnUnlimited?: boolean;
78
- /**
79
- * Enable prepared statements. When true, queries are submitted with a
80
- * `{ name, text, values }` object to the pg driver, which caches the
81
- * parse+plan on the server per connection.
82
- *
83
- * Default: `true` for Turbine-owned pools, `false` for external pools
84
- * (serverless drivers may not support named statements).
85
- */
86
- preparedStatements?: boolean;
87
- /**
88
- * Enable the SQL template cache. When true, repeated queries with the
89
- * same shape (same keys, operators, relations — different values) reuse
90
- * cached SQL text instead of rebuilding from scratch.
91
- *
92
- * Default: `true`. Set to `false` as a nuclear kill switch.
93
- */
94
- sqlCache?: boolean;
95
- /** SQL dialect implementation. Defaults to PostgreSQL. */
96
- dialect?: Dialect;
97
- /**
98
- * Interpret offset-less timestamp strings (Postgres `timestamp` without
99
- * time zone, and the JSON emitted by nested-relation subqueries) as UTC.
100
- * This is the Prisma/Rails/Django convention and makes results independent
101
- * of the server's local time zone. Default: `true`. Set `false` to restore
102
- * the pre-0.26 behavior (JS local-time interpretation).
103
- */
104
- utcTimestamps?: boolean;
105
- /**
106
- * Client-level default relation-loading strategy for `with` clauses. Per-query
107
- * `relationLoadStrategy` args override this; both default to `'join'`.
108
- */
109
- relationLoadStrategy?: RelationLoadStrategy;
110
- /**
111
- * How nested-relation subqueries encode each row's JSON: `'object'` (default,
112
- * `json_build_object`) or `'positional'` (`json_build_array`, key-less — see
113
- * {@link Dialect.buildJsonArray}). Positional is Postgres-only in v1; a
114
- * `with` clause on any other dialect throws `UnsupportedFeatureError` (E017).
115
- */
116
- jsonEncoding?: 'object' | 'positional';
117
- /**
118
- * Automatic WHERE filters keyed by table accessor, AND-merged into every
119
- * query on that table and every relation subquery targeting it (soft-delete /
120
- * multi-tenancy). Function values are evaluated at query-build time. See
121
- * {@link GlobalFilters}.
122
- */
123
- globalFilters?: GlobalFilters;
124
- /** @internal Set by TransactionClient — signals that this QI runs inside an active transaction. */
125
- _txScoped?: boolean;
126
- /** @internal Callback from TurbineClient for query event emission. */
127
- _onQuery?: (event: QueryEvent) => void;
128
- /**
129
- * @internal Factory that builds the per-table query interface. Defaults to
130
- * `new QueryInterface` (the SQL path). Non-SQL backends (PowDB) supply a
131
- * factory returning a structurally-compatible interface that generates their
132
- * own query language instead of SQL. The SQL dialects never set this, so their
133
- * `table()` behavior is byte-identical.
134
- */
135
- queryInterfaceFactory?: (pool: pg.Pool, table: string, schema: SchemaMetadata, middlewares: MiddlewareFn[], options: QueryInterfaceOptions) => QueryInterface<object>;
136
- }
15
+ import type { AggregateArgs, AggregateResult, CountArgs, CreateArgs, CreateManyArgs, DeleteArgs, DeleteManyArgs, FindManyArgs, FindManyStreamArgs, FindUniqueArgs, GroupByArgs, QueryResult, TypedWithClause, UpdateArgs, UpdateManyArgs, UpsertArgs, WithClause } from './types.js';
16
+ export type { DeferredQuery, MiddlewareFn, QueryEvent, QueryEventListener, QueryInterfaceOptions, ReselectExecutor, } from './deferred.js';
17
+ import type { DeferredQuery, MiddlewareFn, QueryInterfaceOptions } from './deferred.js';
137
18
  export declare class QueryInterface<T extends object, R extends object = {}> {
138
19
  private readonly pool;
139
20
  private readonly table;