@mastra/pg 1.23.0-alpha.5 → 1.23.0-alpha.6

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/dist/index.js CHANGED
@@ -5553,6 +5553,17 @@ var ChannelsPG = class ChannelsPG extends ChannelsStorage {
5553
5553
  function jsonbArg(value) {
5554
5554
  return value === void 0 || value === null ? null : JSON.stringify(value);
5555
5555
  }
5556
+ function parseStoredJSON(value) {
5557
+ if (typeof value === "string") try {
5558
+ return JSON.parse(value);
5559
+ } catch {
5560
+ return value;
5561
+ }
5562
+ return value;
5563
+ }
5564
+ function parseOptionalJSON(value, emptyValue) {
5565
+ return value === null || value === void 0 ? emptyValue : parseStoredJSON(value);
5566
+ }
5556
5567
  var DatasetsPG = class DatasetsPG extends DatasetsStorage {
5557
5568
  #db;
5558
5569
  #schema;
@@ -5729,6 +5740,8 @@ var DatasetsPG = class DatasetsPG extends DatasetsStorage {
5729
5740
  };
5730
5741
  }
5731
5742
  transformItemRow(row) {
5743
+ const metadata = parseOptionalJSON(row.metadata, void 0);
5744
+ const emptyValue = metadata?.__purged === true ? null : void 0;
5732
5745
  return {
5733
5746
  id: row.id,
5734
5747
  datasetId: row.datasetId,
@@ -5736,20 +5749,22 @@ var DatasetsPG = class DatasetsPG extends DatasetsStorage {
5736
5749
  externalId: row.externalId ?? null,
5737
5750
  organizationId: row.organizationId ?? null,
5738
5751
  projectId: row.projectId ?? null,
5739
- input: safelyParseJSON(row.input),
5740
- groundTruth: row.groundTruth ? safelyParseJSON(row.groundTruth) : void 0,
5741
- expectedTrajectory: row.expectedTrajectory ? safelyParseJSON(row.expectedTrajectory) : void 0,
5742
- toolMocks: row.toolMocks ? safelyParseJSON(row.toolMocks) : void 0,
5743
- unmockedToolPolicy: row.unmockedToolPolicy ?? void 0,
5744
- scorerIds: row.scorerIds ? safelyParseJSON(row.scorerIds) : void 0,
5745
- requestContext: row.requestContext ? safelyParseJSON(row.requestContext) : void 0,
5746
- metadata: row.metadata ? safelyParseJSON(row.metadata) : void 0,
5747
- source: row.source ? safelyParseJSON(row.source) : void 0,
5752
+ input: row.input === null ? null : parseStoredJSON(row.input),
5753
+ groundTruth: parseOptionalJSON(row.groundTruth, emptyValue),
5754
+ expectedTrajectory: parseOptionalJSON(row.expectedTrajectory, emptyValue),
5755
+ toolMocks: parseOptionalJSON(row.toolMocks, emptyValue),
5756
+ unmockedToolPolicy: row.unmockedToolPolicy ?? emptyValue,
5757
+ scorerIds: parseOptionalJSON(row.scorerIds, emptyValue),
5758
+ requestContext: parseOptionalJSON(row.requestContext, emptyValue),
5759
+ metadata,
5760
+ source: parseOptionalJSON(row.source, emptyValue),
5748
5761
  createdAt: ensureDate(row.createdAtZ || row.createdAt),
5749
5762
  updatedAt: ensureDate(row.updatedAtZ || row.updatedAt)
5750
5763
  };
5751
5764
  }
5752
5765
  transformItemRowFull(row) {
5766
+ const metadata = parseOptionalJSON(row.metadata, void 0);
5767
+ const emptyValue = metadata?.__purged === true ? null : void 0;
5753
5768
  return {
5754
5769
  id: row.id,
5755
5770
  datasetId: row.datasetId,
@@ -5759,15 +5774,15 @@ var DatasetsPG = class DatasetsPG extends DatasetsStorage {
5759
5774
  projectId: row.projectId ?? null,
5760
5775
  validTo: row.validTo,
5761
5776
  isDeleted: Boolean(row.isDeleted),
5762
- input: safelyParseJSON(row.input),
5763
- groundTruth: row.groundTruth ? safelyParseJSON(row.groundTruth) : void 0,
5764
- expectedTrajectory: row.expectedTrajectory ? safelyParseJSON(row.expectedTrajectory) : void 0,
5765
- toolMocks: row.toolMocks ? safelyParseJSON(row.toolMocks) : void 0,
5766
- unmockedToolPolicy: row.unmockedToolPolicy ?? void 0,
5767
- scorerIds: row.scorerIds ? safelyParseJSON(row.scorerIds) : void 0,
5768
- requestContext: row.requestContext ? safelyParseJSON(row.requestContext) : void 0,
5769
- metadata: row.metadata ? safelyParseJSON(row.metadata) : void 0,
5770
- source: row.source ? safelyParseJSON(row.source) : void 0,
5777
+ input: row.input === null ? null : parseStoredJSON(row.input),
5778
+ groundTruth: parseOptionalJSON(row.groundTruth, emptyValue),
5779
+ expectedTrajectory: parseOptionalJSON(row.expectedTrajectory, emptyValue),
5780
+ toolMocks: parseOptionalJSON(row.toolMocks, emptyValue),
5781
+ unmockedToolPolicy: row.unmockedToolPolicy ?? emptyValue,
5782
+ scorerIds: parseOptionalJSON(row.scorerIds, emptyValue),
5783
+ requestContext: parseOptionalJSON(row.requestContext, emptyValue),
5784
+ metadata,
5785
+ source: parseOptionalJSON(row.source, emptyValue),
5771
5786
  createdAt: ensureDate(row.createdAtZ || row.createdAt),
5772
5787
  updatedAt: ensureDate(row.updatedAtZ || row.updatedAt)
5773
5788
  };
@@ -6343,6 +6358,52 @@ var DatasetsPG = class DatasetsPG extends DatasetsStorage {
6343
6358
  }, error);
6344
6359
  }
6345
6360
  }
6361
+ async _doPurgeItem({ id, datasetId }) {
6362
+ try {
6363
+ const datasetsTable = getTableName$5({
6364
+ indexName: TABLE_DATASETS,
6365
+ schemaName: getSchemaName$5(this.#schema)
6366
+ });
6367
+ const itemsTable = getTableName$5({
6368
+ indexName: TABLE_DATASET_ITEMS,
6369
+ schemaName: getSchemaName$5(this.#schema)
6370
+ });
6371
+ const experimentsTable = getTableName$5({
6372
+ indexName: TABLE_EXPERIMENTS,
6373
+ schemaName: getSchemaName$5(this.#schema)
6374
+ });
6375
+ const experimentResultsTable = getTableName$5({
6376
+ indexName: TABLE_EXPERIMENT_RESULTS,
6377
+ schemaName: getSchemaName$5(this.#schema)
6378
+ });
6379
+ const purgedAt = (/* @__PURE__ */ new Date()).toISOString();
6380
+ const purgedMetadata = JSON.stringify({
6381
+ __purged: true,
6382
+ purgedAt
6383
+ });
6384
+ await this.#db.client.tx(async (t) => {
6385
+ if (!await t.oneOrNone(`SELECT "id" FROM ${datasetsTable} WHERE "id" = $1 FOR UPDATE`, [datasetId])) return;
6386
+ if (!await t.oneOrNone(`SELECT "id" FROM ${itemsTable} WHERE "id" = $1 AND "datasetId" = $2 LIMIT 1 FOR UPDATE`, [id, datasetId])) return;
6387
+ await t.none(`UPDATE ${itemsTable} SET "input" = 'null'::jsonb, "groundTruth" = NULL, "expectedTrajectory" = NULL, "toolMocks" = NULL, "unmockedToolPolicy" = NULL, "scorerIds" = NULL, "requestContext" = NULL, "metadata" = $2::jsonb, "source" = NULL WHERE "id" = $1 AND "datasetId" = $3`, [
6388
+ id,
6389
+ purgedMetadata,
6390
+ datasetId
6391
+ ]);
6392
+ if ((await t.one(`SELECT to_regclass($1) IS NOT NULL AND to_regclass($2) IS NOT NULL AS exists`, [experimentResultsTable, experimentsTable])).exists) await t.none(`UPDATE ${experimentResultsTable} SET "input" = 'null'::jsonb, "output" = NULL, "groundTruth" = NULL, "error" = NULL, "toolMockReport" = NULL, "tags" = NULL, "comment" = NULL, "metadata" = $2::jsonb WHERE "itemId" = $1 AND "experimentId" IN (SELECT "id" FROM ${experimentsTable} WHERE "datasetId" = $3)`, [
6393
+ id,
6394
+ purgedMetadata,
6395
+ datasetId
6396
+ ]);
6397
+ });
6398
+ } catch (error) {
6399
+ if (error instanceof MastraError) throw error;
6400
+ throw new MastraError({
6401
+ id: createStorageErrorId("PG", "PURGE_ITEM", "FAILED"),
6402
+ domain: ErrorDomain.STORAGE,
6403
+ category: ErrorCategory.THIRD_PARTY
6404
+ }, error);
6405
+ }
6406
+ }
6346
6407
  async _doBatchInsertItems(input) {
6347
6408
  try {
6348
6409
  if (input.items.length === 0) return [];
@@ -6994,7 +7055,7 @@ var ExperimentsPG = class ExperimentsPG extends ExperimentsStorage {
6994
7055
  itemDatasetVersion: row.itemDatasetVersion != null ? row.itemDatasetVersion : null,
6995
7056
  organizationId: row.organizationId ?? null,
6996
7057
  projectId: row.projectId ?? null,
6997
- input: safelyParseJSON(row.input),
7058
+ input: row.input === null ? null : safelyParseJSON(row.input),
6998
7059
  output: row.output ? safelyParseJSON(row.output) : null,
6999
7060
  groundTruth: row.groundTruth ? safelyParseJSON(row.groundTruth) : null,
7000
7061
  metadata: row.metadata ? safelyParseJSON(row.metadata) : null,
@@ -7296,58 +7357,65 @@ var ExperimentsPG = class ExperimentsPG extends ExperimentsStorage {
7296
7357
  }, error);
7297
7358
  }
7298
7359
  }
7360
+ async #resolvePurgeMetadata(t, datasetId, itemId) {
7361
+ if (!datasetId) return null;
7362
+ const datasetsTable = getTableName$5({
7363
+ indexName: TABLE_DATASETS,
7364
+ schemaName: getSchemaName$5(this.#schema)
7365
+ });
7366
+ const itemsTable = getTableName$5({
7367
+ indexName: TABLE_DATASET_ITEMS,
7368
+ schemaName: getSchemaName$5(this.#schema)
7369
+ });
7370
+ if (!await t.oneOrNone(`SELECT "id" FROM ${datasetsTable} WHERE "id" = $1 FOR UPDATE`, [datasetId])) return null;
7371
+ return (await t.oneOrNone(`SELECT "metadata" FROM ${itemsTable}
7372
+ WHERE "id" = $1 AND "datasetId" = $2 AND "metadata"->>'__purged' = 'true'
7373
+ LIMIT 1`, [itemId, datasetId]))?.metadata ?? null;
7374
+ }
7299
7375
  async addExperimentResult(input) {
7300
7376
  try {
7301
7377
  const id = input.id ?? crypto.randomUUID();
7302
- const now = /* @__PURE__ */ new Date();
7303
- const nowIso = now.toISOString();
7304
- await this.#db.insert({
7305
- tableName: TABLE_EXPERIMENT_RESULTS,
7306
- record: {
7378
+ const resultsTable = getTableName$5({
7379
+ indexName: TABLE_EXPERIMENT_RESULTS,
7380
+ schemaName: getSchemaName$5(this.#schema)
7381
+ });
7382
+ const experimentsTable = getTableName$5({
7383
+ indexName: TABLE_EXPERIMENTS,
7384
+ schemaName: getSchemaName$5(this.#schema)
7385
+ });
7386
+ const row = await this.#db.client.tx(async (t) => {
7387
+ const owner = await t.oneOrNone(`SELECT "datasetId" FROM ${experimentsTable} WHERE "id" = $1`, [input.experimentId]);
7388
+ const purgeMetadata = await this.#resolvePurgeMetadata(t, owner?.datasetId, input.itemId);
7389
+ const nowIso = (/* @__PURE__ */ new Date()).toISOString();
7390
+ return t.one(`INSERT INTO ${resultsTable} (
7391
+ "id", "experimentId", "itemId", "itemDatasetVersion", "organizationId", "projectId",
7392
+ "input", "output", "groundTruth", "metadata", "error", "startedAt", "completedAt",
7393
+ "retryCount", "attempt", "traceId", "status", "tags", "toolMockReport", "createdAt"
7394
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)
7395
+ RETURNING *`, [
7307
7396
  id,
7308
- experimentId: input.experimentId,
7309
- itemId: input.itemId,
7310
- itemDatasetVersion: input.itemDatasetVersion ?? null,
7311
- organizationId: input.organizationId ?? null,
7312
- projectId: input.projectId ?? null,
7313
- input: input.input,
7314
- output: input.output ?? null,
7315
- groundTruth: input.groundTruth ?? null,
7316
- metadata: input.metadata ?? null,
7317
- error: input.error ?? null,
7318
- startedAt: input.startedAt.toISOString(),
7319
- completedAt: input.completedAt.toISOString(),
7320
- retryCount: input.retryCount,
7321
- attempt: input.attempt ?? 0,
7322
- traceId: input.traceId ?? null,
7323
- status: input.status ?? null,
7324
- tags: input.tags ?? null,
7325
- toolMockReport: input.toolMockReport ?? null,
7326
- createdAt: nowIso
7327
- }
7397
+ input.experimentId,
7398
+ input.itemId,
7399
+ input.itemDatasetVersion ?? null,
7400
+ input.organizationId ?? null,
7401
+ input.projectId ?? null,
7402
+ JSON.stringify(purgeMetadata ? null : input.input),
7403
+ purgeMetadata || input.output == null ? null : JSON.stringify(input.output),
7404
+ purgeMetadata || input.groundTruth == null ? null : JSON.stringify(input.groundTruth),
7405
+ JSON.stringify(purgeMetadata ?? input.metadata ?? null),
7406
+ purgeMetadata || input.error == null ? null : JSON.stringify(input.error),
7407
+ input.startedAt.toISOString(),
7408
+ input.completedAt.toISOString(),
7409
+ input.retryCount,
7410
+ input.attempt ?? 0,
7411
+ input.traceId ?? null,
7412
+ input.status ?? null,
7413
+ purgeMetadata || input.tags == null ? null : JSON.stringify(input.tags),
7414
+ purgeMetadata || input.toolMockReport == null ? null : JSON.stringify(input.toolMockReport),
7415
+ nowIso
7416
+ ]);
7328
7417
  });
7329
- return {
7330
- id,
7331
- experimentId: input.experimentId,
7332
- itemId: input.itemId,
7333
- itemDatasetVersion: input.itemDatasetVersion ?? null,
7334
- organizationId: input.organizationId ?? null,
7335
- projectId: input.projectId ?? null,
7336
- input: input.input,
7337
- output: input.output ?? null,
7338
- groundTruth: input.groundTruth ?? null,
7339
- metadata: input.metadata ?? null,
7340
- error: input.error ?? null,
7341
- startedAt: input.startedAt,
7342
- completedAt: input.completedAt,
7343
- retryCount: input.retryCount,
7344
- attempt: input.attempt ?? 0,
7345
- traceId: input.traceId ?? null,
7346
- status: input.status ?? null,
7347
- tags: input.tags ?? null,
7348
- toolMockReport: input.toolMockReport ?? null,
7349
- createdAt: now
7350
- };
7418
+ return this.transformExperimentResultRow(row);
7351
7419
  } catch (error) {
7352
7420
  throw new MastraError({
7353
7421
  id: createStorageErrorId("PG", "ADD_EXPERIMENT_RESULT", "FAILED"),
@@ -7362,8 +7430,14 @@ var ExperimentsPG = class ExperimentsPG extends ExperimentsStorage {
7362
7430
  indexName: TABLE_EXPERIMENT_RESULTS,
7363
7431
  schemaName: getSchemaName$5(this.#schema)
7364
7432
  });
7433
+ const experimentsTable = getTableName$5({
7434
+ indexName: TABLE_EXPERIMENTS,
7435
+ schemaName: getSchemaName$5(this.#schema)
7436
+ });
7365
7437
  const attempt = input.attempt ?? 0;
7366
7438
  const row = await this.#db.client.tx(async (t) => {
7439
+ const owner = await t.oneOrNone(`SELECT "datasetId" FROM ${experimentsTable} WHERE "id" = $1`, [input.experimentId]);
7440
+ const purgeMetadata = await this.#resolvePurgeMetadata(t, owner?.datasetId, input.itemId);
7367
7441
  const existing = await t.oneOrNone(`SELECT "id" FROM ${tableName} WHERE "experimentId" = $1 AND "itemId" = $2 AND COALESCE("attempt", 0) = $3 FOR UPDATE`, [
7368
7442
  input.experimentId,
7369
7443
  input.itemId,
@@ -7383,19 +7457,19 @@ var ExperimentsPG = class ExperimentsPG extends ExperimentsStorage {
7383
7457
  input.itemDatasetVersion ?? null,
7384
7458
  input.organizationId ?? null,
7385
7459
  input.projectId ?? null,
7386
- JSON.stringify(input.input),
7387
- input.output != null ? JSON.stringify(input.output) : null,
7388
- input.groundTruth != null ? JSON.stringify(input.groundTruth) : null,
7389
- input.metadata != null ? JSON.stringify(input.metadata) : null,
7390
- input.error != null ? JSON.stringify(input.error) : null,
7460
+ JSON.stringify(purgeMetadata ? null : input.input),
7461
+ purgeMetadata || input.output == null ? null : JSON.stringify(input.output),
7462
+ purgeMetadata || input.groundTruth == null ? null : JSON.stringify(input.groundTruth),
7463
+ JSON.stringify(purgeMetadata ?? input.metadata ?? null),
7464
+ purgeMetadata || input.error == null ? null : JSON.stringify(input.error),
7391
7465
  input.startedAt.toISOString(),
7392
7466
  input.completedAt.toISOString(),
7393
7467
  input.retryCount,
7394
7468
  attempt,
7395
7469
  input.traceId ?? null,
7396
7470
  input.status ?? null,
7397
- input.tags != null ? JSON.stringify(input.tags) : null,
7398
- input.toolMockReport != null ? JSON.stringify(input.toolMockReport) : null,
7471
+ purgeMetadata || input.tags == null ? null : JSON.stringify(input.tags),
7472
+ purgeMetadata || input.toolMockReport == null ? null : JSON.stringify(input.toolMockReport),
7399
7473
  (/* @__PURE__ */ new Date()).toISOString()
7400
7474
  ]);
7401
7475
  }
@@ -7409,19 +7483,19 @@ var ExperimentsPG = class ExperimentsPG extends ExperimentsStorage {
7409
7483
  input.itemDatasetVersion ?? null,
7410
7484
  input.organizationId ?? null,
7411
7485
  input.projectId ?? null,
7412
- JSON.stringify(input.input),
7413
- input.output != null ? JSON.stringify(input.output) : null,
7414
- input.groundTruth != null ? JSON.stringify(input.groundTruth) : null,
7415
- input.metadata != null ? JSON.stringify(input.metadata) : null,
7416
- input.error != null ? JSON.stringify(input.error) : null,
7486
+ JSON.stringify(purgeMetadata ? null : input.input),
7487
+ purgeMetadata || input.output == null ? null : JSON.stringify(input.output),
7488
+ purgeMetadata || input.groundTruth == null ? null : JSON.stringify(input.groundTruth),
7489
+ JSON.stringify(purgeMetadata ?? input.metadata ?? null),
7490
+ purgeMetadata || input.error == null ? null : JSON.stringify(input.error),
7417
7491
  input.startedAt.toISOString(),
7418
7492
  input.completedAt.toISOString(),
7419
7493
  input.retryCount,
7420
7494
  attempt,
7421
7495
  input.traceId ?? null,
7422
7496
  input.status ?? null,
7423
- input.tags != null ? JSON.stringify(input.tags) : null,
7424
- input.toolMockReport != null ? JSON.stringify(input.toolMockReport) : null
7497
+ purgeMetadata || input.tags == null ? null : JSON.stringify(input.tags),
7498
+ purgeMetadata || input.toolMockReport == null ? null : JSON.stringify(input.toolMockReport)
7425
7499
  ]);
7426
7500
  });
7427
7501
  return this.transformExperimentResultRow(row);
@@ -7439,39 +7513,34 @@ var ExperimentsPG = class ExperimentsPG extends ExperimentsStorage {
7439
7513
  indexName: TABLE_EXPERIMENT_RESULTS,
7440
7514
  schemaName: getSchemaName$5(this.#schema)
7441
7515
  });
7442
- const setClauses = [];
7443
- const values = [];
7444
- let paramIndex = 1;
7445
- if (input.status !== void 0) {
7446
- setClauses.push(`"status" = $${paramIndex++}`);
7447
- values.push(input.status);
7448
- }
7449
- if (input.tags !== void 0) {
7450
- setClauses.push(`"tags" = $${paramIndex++}`);
7451
- values.push(JSON.stringify(input.tags));
7452
- }
7453
- if (input.comment !== void 0) {
7454
- setClauses.push(`"comment" = $${paramIndex++}`);
7455
- values.push(input.comment);
7456
- }
7457
- if (setClauses.length === 0) {
7458
- const existing = await this.#getExperimentResultById(this.#db.client, { id: input.id });
7459
- if (!existing) throw new MastraError({
7460
- id: createStorageErrorId("PG", "UPDATE_EXPERIMENT_RESULT", "NOT_FOUND"),
7461
- domain: ErrorDomain.STORAGE,
7462
- category: ErrorCategory.USER,
7463
- details: { resultId: input.id }
7464
- });
7465
- return existing;
7466
- }
7467
- values.push(input.id);
7468
- let whereClause = `"id" = $${paramIndex}`;
7469
- if (input.experimentId) {
7470
- paramIndex++;
7471
- values.push(input.experimentId);
7472
- whereClause += ` AND "experimentId" = $${paramIndex}`;
7473
- }
7474
- const row = await this.#db.client.oneOrNone(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE ${whereClause} RETURNING *`, values);
7516
+ const experimentsTable = getTableName$5({
7517
+ indexName: TABLE_EXPERIMENTS,
7518
+ schemaName: getSchemaName$5(this.#schema)
7519
+ });
7520
+ const row = await this.#db.client.tx(async (t) => {
7521
+ const owner = await t.oneOrNone(`SELECT e."datasetId", r."itemId"
7522
+ FROM ${tableName} r
7523
+ JOIN ${experimentsTable} e ON e."id" = r."experimentId"
7524
+ WHERE r."id" = $1${input.experimentId !== void 0 ? " AND r.\"experimentId\" = $2" : ""}`, input.experimentId !== void 0 ? [input.id, input.experimentId] : [input.id]);
7525
+ if (!owner) return null;
7526
+ const purgeMetadata = await this.#resolvePurgeMetadata(t, owner.datasetId, owner.itemId);
7527
+ return t.oneOrNone(`UPDATE ${tableName}
7528
+ SET "status" = CASE WHEN $2 THEN $3 ELSE "status" END,
7529
+ "tags" = CASE WHEN $4 THEN NULL WHEN $5 THEN $6::jsonb ELSE "tags" END,
7530
+ "comment" = CASE WHEN $4 THEN NULL WHEN $7 THEN $8 ELSE "comment" END
7531
+ WHERE "id" = $1${input.experimentId !== void 0 ? " AND \"experimentId\" = $9" : ""}
7532
+ RETURNING *`, [
7533
+ input.id,
7534
+ input.status !== void 0,
7535
+ input.status ?? null,
7536
+ Boolean(purgeMetadata),
7537
+ input.tags !== void 0,
7538
+ input.tags === void 0 ? null : JSON.stringify(input.tags),
7539
+ input.comment !== void 0,
7540
+ input.comment ?? null,
7541
+ ...input.experimentId !== void 0 ? [input.experimentId] : []
7542
+ ]);
7543
+ });
7475
7544
  if (!row) throw new MastraError({
7476
7545
  id: createStorageErrorId("PG", "UPDATE_EXPERIMENT_RESULT", "NOT_FOUND"),
7477
7546
  domain: ErrorDomain.STORAGE,
@@ -10871,12 +10940,13 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
10871
10940
  /**
10872
10941
  * Reads one page of messages together with the total row count.
10873
10942
  *
10874
- * `COUNT(*) OVER ()` reports the count over the whole WHERE result on the same
10875
- * statement as the page, so the page costs one database round-trip instead of
10876
- * two. The page and the count also come from one snapshot, so the count always
10877
- * describes the returned rows. A separate `COUNT(*)` runs only when the page is
10878
- * empty and the caller asked for a page after the last row, because a window
10879
- * function has no row to carry the count on.
10943
+ * Every page query carries a skinny scalar `(SELECT COUNT(*) ...)` subquery that
10944
+ * reports the total over the whole WHERE result on the same statement as the page,
10945
+ * so the page costs one database round-trip instead of two. The page and the count
10946
+ * also come from one snapshot, so the count always describes the returned rows. A
10947
+ * separate `COUNT(*)` runs only as a fallback when the page is empty and the caller
10948
+ * asked for a page after the last row, because there is then no row to carry the
10949
+ * count on.
10880
10950
  */
10881
10951
  async #fetchMessagePage({ selectStatement, tableName, whereClause, orderByStatement, queryParams, perPageInput, perPage, offset }) {
10882
10952
  const limitClause = perPageInput === false ? "" : ` LIMIT $${queryParams.length + 1} OFFSET $${queryParams.length + 2}`;
@@ -10885,7 +10955,7 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
10885
10955
  perPage,
10886
10956
  offset
10887
10957
  ];
10888
- const rows = await this.#db.readClient.manyOrNone(`${selectStatement}, COUNT(*) OVER () AS "__total" FROM ${tableName} ${whereClause} ${orderByStatement}${limitClause}`, dataParams) || [];
10958
+ const rows = await this.#db.readClient.manyOrNone(`${selectStatement}, (SELECT COUNT(*) FROM ${tableName} ${whereClause}) AS "__total" FROM ${tableName} ${whereClause} ${orderByStatement}${limitClause}`, dataParams) || [];
10889
10959
  if (rows.length > 0) return {
10890
10960
  total: Number(rows[0].__total),
10891
10961
  messages: rows
@@ -10924,7 +10994,7 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
10924
10994
  const metadataFilter = validateStorageMetadataFilter(filter?.metadata);
10925
10995
  try {
10926
10996
  const { field, direction } = this.parseOrderBy(orderBy, "ASC");
10927
- const orderByStatement = `ORDER BY COALESCE("${field}Z", "${field}") ${direction}`;
10997
+ const orderByStatement = `ORDER BY "${field}" ${direction}`;
10928
10998
  const selectStatement = `SELECT id, content, role, type, "createdAt", "createdAtZ", thread_id AS "threadId", "resourceId"`;
10929
10999
  const tableName = getTableName$3({
10930
11000
  indexName: TABLE_MESSAGES,
@@ -11072,7 +11142,7 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
11072
11142
  const metadataFilter = validateStorageMetadataFilter(filter?.metadata);
11073
11143
  try {
11074
11144
  const { field, direction } = this.parseOrderBy(orderBy, "ASC");
11075
- const orderByStatement = `ORDER BY COALESCE("${field}Z", "${field}") ${direction}`;
11145
+ const orderByStatement = `ORDER BY "${field}" ${direction}`;
11076
11146
  const selectStatement = `SELECT id, content, role, type, "createdAt", "createdAtZ", thread_id AS "threadId", "resourceId"`;
11077
11147
  const tableName = getTableName$3({
11078
11148
  indexName: TABLE_MESSAGES,