turbine-orm 0.95.0 → 0.96.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.
@@ -9,7 +9,7 @@
9
9
  * delegating methods (buildGroupBy / buildAggregate).
10
10
  */
11
11
  import { UnsupportedFeatureError, ValidationError } from '../errors.js';
12
- import { isTemporalInfinity, ownLookup, parseDbDate, resolveColumnName, suggestKey, warnRedundantSortTerm, } from '../query-utils.js';
12
+ import { coerceTemporalValue, isTemporalInfinity, ownLookup, parseDbDate, resolveColumnName, suggestKey, warnRedundantSortTerm, } from '../query-utils.js';
13
13
  import { snakeToCamel } from '../schema.js';
14
14
  import { compileReadExpr } from './expr.js';
15
15
  import { assertEqualityOperand, dedupeColumnList, isJsonPathOrderBy, isUnmatchedPlainObject, isVectorOrderBy, isWhereOperator, JSON_RANGE_OPERATORS, normalizeOrderBy, orderByEntries, setOwn, } from './filters.js';
@@ -786,7 +786,19 @@ function buildHavingScalarClauses(qi, field, value, params, groupKeys) {
786
786
  const HAVING_COMPARISONS = { equals: '=', not: '!=', ...JSON_RANGE_OPERATORS };
787
787
  const HAVING_OPERATORS = new Set([...Object.keys(HAVING_COMPARISONS), 'in', 'notIn']);
788
788
  export function buildHavingNumericClauses(qi, expr, filter, params, operandType) {
789
- const bind = (value) => operandType === undefined ? value : whereMod.textComparedOperand(qi, operandType, value);
789
+ // A `_min` / `_max` operand is compared with a stored cell, so it binds as a
790
+ // where operand against that column does: a Date on a zone-less temporal
791
+ // column becomes the UTC-component literal (raw, node-postgres would render it
792
+ // in the PROCESS zone and the comparison would be hours off), and on MySQL a
793
+ // number against text binds as text.
794
+ const bind = (value) => {
795
+ if (operandType === undefined)
796
+ return value;
797
+ const temporal = value instanceof Date
798
+ ? coerceTemporalValue(operandType, value, whereMod.utcDateTimeRewrite(qi, operandType))
799
+ : value;
800
+ return whereMod.textComparedOperand(qi, operandType, temporal);
801
+ };
790
802
  const bindList = (value) => operandType !== undefined && Array.isArray(value) ? value.map(bind) : value;
791
803
  if (filter === null) {
792
804
  throw new ValidationError(`Invalid having filter on "${expr}" for table "${qi.table}": expected a value or operator object.`);
@@ -1413,9 +1413,19 @@ export interface ConnectOrCreateOp<T, TR extends object = {}> {
1413
1413
  where: Partial<T>;
1414
1414
  create: CreateDataInput<T, TR>;
1415
1415
  }
1416
+ /**
1417
+ * Nested `createMany` op (one-to-many relations): rows inserted in one batch,
1418
+ * each without nested relation writes of its own, optionally skipping rows that
1419
+ * collide with a unique key.
1420
+ */
1421
+ export interface NestedCreateManyOp<T> {
1422
+ data: OptionalInput<T> | OptionalInput<T>[];
1423
+ skipDuplicates?: boolean | undefined;
1424
+ }
1416
1425
  /** Nested write ops valid inside `create()` data for a relation field. */
1417
1426
  export interface NestedCreateOp<T, TR extends object = {}> {
1418
1427
  create?: CreateDataInput<T, TR> | CreateDataInput<T, TR>[] | undefined;
1428
+ createMany?: NestedCreateManyOp<T> | undefined;
1419
1429
  connect?: Partial<T> | Partial<T>[] | undefined;
1420
1430
  connectOrCreate?: ConnectOrCreateOp<T, TR> | ConnectOrCreateOp<T, TR>[] | undefined;
1421
1431
  }
@@ -1453,11 +1463,15 @@ export interface NestedToOneUpdateOp<T, TR extends object = {}> extends NestedTo
1453
1463
  update?: {
1454
1464
  data: UpdateDataInput<T, TR>;
1455
1465
  } | undefined;
1456
- upsert?: NestedUpsertOpItem<T, TR> | undefined;
1466
+ /** `where` is optional: without it the row is the one this record points at. */
1467
+ upsert?: (Omit<NestedUpsertOpItem<T, TR>, 'where'> & {
1468
+ where?: Partial<T> | undefined;
1469
+ }) | undefined;
1457
1470
  }
1458
1471
  /** Nested write ops valid inside `update()` data for a relation field. */
1459
1472
  export interface NestedUpdateOp<T, TR extends object = {}> {
1460
1473
  create?: CreateDataInput<T, TR> | CreateDataInput<T, TR>[] | undefined;
1474
+ createMany?: NestedCreateManyOp<T> | undefined;
1461
1475
  connect?: Partial<T> | Partial<T>[] | undefined;
1462
1476
  connectOrCreate?: ConnectOrCreateOp<T, TR> | ConnectOrCreateOp<T, TR>[] | undefined;
1463
1477
  disconnect?: Partial<T> | Partial<T>[] | undefined;
package/dist/schema.d.ts CHANGED
@@ -429,13 +429,14 @@ export interface PrismaModelMap {
429
429
  compoundUniques: Record<string, string[]>;
430
430
  /**
431
431
  * Prisma CLIENT-side default per Prisma field name. Prisma's
432
- * `@default(uuid())` / `@default(cuid())` / `@updatedAt` (and `@default(now())`
433
- * when the migration left no database default) are filled by the Prisma
434
- * client, not the database, so the columns commonly have NO db default and a
435
- * Prisma call site omits them. The compat adapter fills these on create
436
- * (`uuid` / `cuid` / `now`) and touches `updatedAt` fields on
437
- * update/updateMany/upsert, exactly like Prisma. Emitted by
438
- * `migrate-from-prisma` only for columns the database does not default.
432
+ * `@default(uuid())` / `@default(cuid())` / `@default(now())` / `@updatedAt`
433
+ * are filled by the Prisma client, not the database, so the columns commonly
434
+ * have NO db default and a Prisma call site omits them. The compat adapter
435
+ * fills these on create (`uuid` / `cuid` / `now`), at every depth of a nested
436
+ * write, and touches `updatedAt` fields on update/updateMany/upsert, exactly
437
+ * like Prisma. `migrate-from-prisma` emits `uuid` / `cuid` only for columns the
438
+ * database does not default, and `now` / `updatedAt` always: Prisma stamps
439
+ * them with the app's clock even when the column has a database default.
439
440
  */
440
441
  clientDefaults?: Record<string, 'uuid' | 'cuid' | 'now' | 'updatedAt'>;
441
442
  }
@@ -109,8 +109,10 @@ export declare class TransactionState {
109
109
  private readonly root;
110
110
  /** Frames whose SAVEPOINT is set and not yet released or rolled back, outermost first. */
111
111
  private readonly openFrames;
112
- /** Statements sent on the connection that have not answered yet. */
112
+ /** Statements sent on the connection (or queued to be) that have not answered yet. */
113
113
  private onWire;
114
+ /** Settles when the last statement handed to {@link send} has answered; it never rejects. */
115
+ private wireTail;
114
116
  /** A cancellable statement owns admission until its listener and delivery settle. */
115
117
  private exclusive;
116
118
  /** Statements and savepoint blocks started through the transaction that have not settled. */
@@ -219,6 +221,17 @@ export declare class TransactionState {
219
221
  screenRaw(sql: unknown): boolean;
220
222
  private assertAvailable;
221
223
  /** Put one statement on the wire, counted for {@link whenIdle} and recorded on failure. */
224
+ /**
225
+ * Send one statement, after every statement sent before it has answered.
226
+ *
227
+ * A transaction owns ONE connection, and `Promise.all([tx.a(), tx.b()])` (or a
228
+ * batched relation load, whose sibling loads start together) handed both to
229
+ * the driver at once. pg queues the second on the client itself, which it
230
+ * reports as deprecated and pg 9 removes; other drivers do not queue at all.
231
+ * The order is kept here instead, in call order, unless the driver pipelines.
232
+ * `recheck` runs after the wait and before sending, so a statement queued
233
+ * behind one that aborted or ended the transaction is refused rather than sent.
234
+ */
222
235
  private send;
223
236
  private settled;
224
237
  /** Record `err` as the first failure, unless one is already recorded. */
@@ -71,8 +71,10 @@ export class TransactionState {
71
71
  root;
72
72
  /** Frames whose SAVEPOINT is set and not yet released or rolled back, outermost first. */
73
73
  openFrames = [];
74
- /** Statements sent on the connection that have not answered yet. */
74
+ /** Statements sent on the connection (or queued to be) that have not answered yet. */
75
75
  onWire = 0;
76
+ /** Settles when the last statement handed to {@link send} has answered; it never rejects. */
77
+ wireTail = Promise.resolve();
76
78
  /** A cancellable statement owns admission until its listener and delivery settle. */
77
79
  exclusive = false;
78
80
  /** Statements and savepoint blocks started through the transaction that have not settled. */
@@ -226,7 +228,13 @@ export class TransactionState {
226
228
  this.settled();
227
229
  });
228
230
  }
229
- const result = await this.send(statement);
231
+ const result = await this.send(statement, () => {
232
+ // Re-read after waiting for the statements queued ahead of this one: one
233
+ // of them may have ended or aborted the transaction meanwhile.
234
+ this.assertOpen();
235
+ if (!recovery)
236
+ this.assertNotAborted();
237
+ });
230
238
  if (recovery)
231
239
  this.clearAbort();
232
240
  return result;
@@ -277,18 +285,52 @@ export class TransactionState {
277
285
  throw new ValidationError('A cancellable cursor requires an otherwise idle transaction connection.');
278
286
  }
279
287
  /** Put one statement on the wire, counted for {@link whenIdle} and recorded on failure. */
280
- async send(statement) {
288
+ /**
289
+ * Send one statement, after every statement sent before it has answered.
290
+ *
291
+ * A transaction owns ONE connection, and `Promise.all([tx.a(), tx.b()])` (or a
292
+ * batched relation load, whose sibling loads start together) handed both to
293
+ * the driver at once. pg queues the second on the client itself, which it
294
+ * reports as deprecated and pg 9 removes; other drivers do not queue at all.
295
+ * The order is kept here instead, in call order, unless the driver pipelines.
296
+ * `recheck` runs after the wait and before sending, so a statement queued
297
+ * behind one that aborted or ended the transaction is refused rather than sent.
298
+ */
299
+ async send(statement, recheck, inOrder = true) {
300
+ // A driver that pipelines (`supportsPipelining`) takes concurrent
301
+ // statements by design and answers them in order; the batch
302
+ // `$transaction([...])` path relies on dispatching them all at once there.
303
+ const ordered = inOrder && this.client.supportsPipelining !== true;
304
+ // Nothing ahead: send now, with no extra turn of the event loop.
305
+ const queued = ordered && this.onWire > 0;
281
306
  this.onWire++;
307
+ const previous = this.wireTail;
308
+ let done = () => { };
309
+ if (ordered) {
310
+ this.wireTail = new Promise((resolve) => {
311
+ done = resolve;
312
+ });
313
+ }
314
+ let sent = false;
282
315
  try {
316
+ if (queued) {
317
+ await previous;
318
+ recheck?.();
319
+ }
320
+ sent = true;
283
321
  return await statement();
284
322
  }
285
323
  catch (err) {
324
+ // A refusal by `recheck` is not a statement failure: nothing was sent.
325
+ if (!sent)
326
+ throw err;
286
327
  this.noteFailure(err);
287
328
  if (this.abortsOnError && reportedByServer(err))
288
329
  this.noteDead(err);
289
330
  throw err;
290
331
  }
291
332
  finally {
333
+ done();
292
334
  this.settled();
293
335
  }
294
336
  }
@@ -443,7 +485,9 @@ export class TransactionState {
443
485
  }
444
486
  this.assertNotAborted();
445
487
  const name = `sp_${++this.savepointCount}`;
446
- await this.control(this.dialect.savepointStatement(name));
488
+ // In order: a statement issued before this block and still queued
489
+ // behind one on the wire belongs outside the savepoint.
490
+ await this.control(this.dialect.savepointStatement(name), true);
447
491
  const opened = {
448
492
  state: this,
449
493
  parent,
@@ -547,10 +591,21 @@ export class TransactionState {
547
591
  * Typed INSIDE the statement, so the failure the state records is the Turbine
548
592
  * error and not the driver's.
549
593
  */
550
- async control(sql) {
594
+ async control(sql, inOrder = false) {
551
595
  this.assertOpen();
552
596
  this.assertAvailable();
553
- await this.send(() => sendControl(this.client, sql));
597
+ // RELEASE and ROLLBACK TO are not ordered behind statements still on the
598
+ // wire: a ROLLBACK TO after a statement cut short by its deadline is how
599
+ // that statement's outcome is settled, and it must not wait for the
600
+ // statement to end. A SAVEPOINT is (`inOrder`): sent past a statement
601
+ // queued before it, it would open the block around that statement, and
602
+ // the block's rollback would undo a statement that reported success.
603
+ await this.send(() => sendControl(this.client, sql), inOrder
604
+ ? () => {
605
+ this.assertOpen();
606
+ this.assertNotAborted();
607
+ }
608
+ : undefined, inOrder);
554
609
  }
555
610
  }
556
611
  /** The state carried by a transaction-scoped pool, or undefined for any other pool. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "turbine-orm",
3
- "version": "0.95.0",
3
+ "version": "0.96.0",
4
4
  "description": "Postgres-native TypeScript ORM, runs on Neon, Vercel Postgres, Cloudflare, Supabase. Streaming cursors, typed errors, single-query nested relations. One dependency, no WASM engine",
5
5
  "type": "module",
6
6
  "//exports": "Each subpath declares its types PER CONDITION. A single shared top-level \"types\" resolves to the ESM declarations for `require` too, which is TS1479 (\"is an ES module ... cannot be require()d\") for any CJS consumer on moduleResolution node16/nodenext. The require condition points at dist/cjs, which ships its own {\"type\":\"commonjs\"} package.json, so those declarations are CJS declarations. Gated in CI by publint + @arethetypeswrong/cli + a real .cts consumer typecheck (see the package-types job in ci.yml).",