@mastra/pg 1.26.0-alpha.4 → 1.26.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.
@@ -3,7 +3,7 @@ name: mastra-pg
3
3
  description: Documentation for @mastra/pg. Use when working with @mastra/pg APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/pg"
6
- version: "1.26.0-alpha.4"
6
+ version: "1.26.0"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.26.0-alpha.4",
2
+ "version": "1.26.0",
3
3
  "package": "@mastra/pg",
4
4
  "exports": {},
5
5
  "modules": {}
package/dist/index.cjs CHANGED
@@ -6136,6 +6136,14 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6136
6136
  }
6137
6137
  async listDatasets(args) {
6138
6138
  try {
6139
+ const orderBy = (0, _mastra_core_storage.resolveListOrderBy)(args.orderBy, [
6140
+ "createdAt",
6141
+ "updatedAt",
6142
+ "name"
6143
+ ], {
6144
+ field: "createdAt",
6145
+ direction: "DESC"
6146
+ });
6139
6147
  const { page, perPage: perPageInput } = args.pagination;
6140
6148
  const tableName = getTableName$5({
6141
6149
  indexName: _mastra_core_storage.TABLE_DATASETS,
@@ -6191,7 +6199,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6191
6199
  const { offset, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
6192
6200
  const limitValue = perPageInput === false ? total : perPage;
6193
6201
  return {
6194
- datasets: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
6202
+ datasets: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${orderBy.field}" ${orderBy.direction}, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
6195
6203
  ...queryParams,
6196
6204
  limitValue,
6197
6205
  offset
@@ -6758,6 +6766,10 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6758
6766
  */
6759
6767
  async #listItems(client, args) {
6760
6768
  try {
6769
+ const orderBy = (0, _mastra_core_storage.resolveListOrderBy)(args.orderBy, ["createdAt", "updatedAt"], {
6770
+ field: "createdAt",
6771
+ direction: "DESC"
6772
+ });
6761
6773
  const { page, perPage: perPageInput } = args.pagination;
6762
6774
  const tableName = getTableName$5({
6763
6775
  indexName: _mastra_core_storage.TABLE_DATASET_ITEMS,
@@ -6808,7 +6820,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6808
6820
  const { offset, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
6809
6821
  const limitValue = perPageInput === false ? total : perPage;
6810
6822
  return {
6811
- items: (await client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
6823
+ items: (await client.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${orderBy.field}" ${orderBy.direction}, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
6812
6824
  ...queryParams,
6813
6825
  limitValue,
6814
6826
  offset
@@ -7368,6 +7380,10 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7368
7380
  }
7369
7381
  async listExperiments(args) {
7370
7382
  try {
7383
+ const orderBy = (0, _mastra_core_storage.resolveListOrderBy)(args.orderBy, ["createdAt", "status"], {
7384
+ field: "createdAt",
7385
+ direction: "DESC"
7386
+ });
7371
7387
  const { page, perPage: perPageInput } = args.pagination;
7372
7388
  const tableName = getTableName$5({
7373
7389
  indexName: _mastra_core_storage.TABLE_EXPERIMENTS,
@@ -7439,7 +7455,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7439
7455
  const { offset, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
7440
7456
  const limitValue = perPageInput === false ? total : perPage;
7441
7457
  return {
7442
- experiments: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7458
+ experiments: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${orderBy.field}" ${orderBy.direction}, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7443
7459
  ...queryParams,
7444
7460
  limitValue,
7445
7461
  offset
@@ -7711,6 +7727,10 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7711
7727
  }
7712
7728
  async listExperimentResults(args) {
7713
7729
  try {
7730
+ const orderBy = (0, _mastra_core_storage.resolveListOrderBy)(args.orderBy, ["startedAt", "createdAt"], {
7731
+ field: "startedAt",
7732
+ direction: "ASC"
7733
+ });
7714
7734
  const { page, perPage: perPageInput } = args.pagination;
7715
7735
  const tableName = getTableName$5({
7716
7736
  indexName: _mastra_core_storage.TABLE_EXPERIMENT_RESULTS,
@@ -7758,7 +7778,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7758
7778
  const { offset, perPage: perPageForResponse } = (0, _mastra_core_storage.calculatePagination)(page, perPageInput, perPage);
7759
7779
  const limitValue = perPageInput === false ? total : perPage;
7760
7780
  return {
7761
- results: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "startedAt" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7781
+ results: (await this.#db.readClient.manyOrNone(`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${orderBy.field}" ${orderBy.direction}, "id" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`, [
7762
7782
  ...queryParams,
7763
7783
  limitValue,
7764
7784
  offset
@@ -17297,7 +17317,7 @@ const TRACE_SELECT = `
17297
17317
  r."name" AS "name",
17298
17318
  r."entityId" AS "entityId",
17299
17319
  r."parentSpanId" AS "parentSpanId",
17300
- r."metadata" AS "metadata",
17320
+ r."metadataRaw" AS "metadata",
17301
17321
  r."input" AS "input",
17302
17322
  r."threadId" AS "threadId",
17303
17323
  r."resourceId" AS "resourceId",
@@ -17515,22 +17535,27 @@ function compileThreadPredicate(predicate, parameterOffset) {
17515
17535
  values: compiled.values
17516
17536
  };
17517
17537
  }
17518
- function compilePostgresTraceScope(schema, selection, relationCollections) {
17538
+ function compilePostgresTraceScope(schema, selection, relationCollections, deltaWindow) {
17519
17539
  const spanTable = qualifiedTable(schema, TABLE_SPAN_EVENTS);
17520
17540
  const scoreTable = qualifiedTable(schema, TABLE_SCORE_EVENTS);
17521
17541
  const feedbackTable = qualifiedTable(schema, TABLE_FEEDBACK_EVENTS);
17522
17542
  const values = [selection.timeRange.from, selection.timeRange.to];
17523
- const ctes = [`root_scope AS MATERIALIZED (
17524
- SELECT *
17525
- FROM ${spanTable} r
17526
- WHERE ${[
17543
+ const rootConditions = [
17527
17544
  `r."parentSpanId" IS NULL`,
17528
17545
  latestRootPredicate$1(spanTable),
17529
17546
  `NOT r."isPending"`,
17530
17547
  `r."endedAt" IS NOT NULL`,
17531
17548
  `r."startedAt" >= $1`,
17532
17549
  `r."startedAt" < $2`
17533
- ].join("\n AND ")}
17550
+ ];
17551
+ if (deltaWindow) {
17552
+ values.push(deltaWindow.xactId, deltaWindow.cursorId, deltaWindow.safeHorizon);
17553
+ rootConditions.push(`(r."xactId", r."cursorId") > ($3::xid8, $4::bigint)`, `r."xactId" < $5::xid8`);
17554
+ }
17555
+ const ctes = [`root_scope AS MATERIALIZED (
17556
+ SELECT *
17557
+ FROM ${spanTable} r
17558
+ WHERE ${rootConditions.join("\n AND ")}
17534
17559
  )`];
17535
17560
  if (relationCollections.has("spans")) ctes.push(`current_spans AS MATERIALIZED (
17536
17561
  SELECT
@@ -17599,8 +17624,18 @@ function compilePostgresTraceScope(schema, selection, relationCollections) {
17599
17624
  values
17600
17625
  };
17601
17626
  }
17602
- function compilePostgresTraceQuery(schema, plan, mode = "data") {
17603
- const { ctes, values } = compilePostgresTraceScope(schema, plan, collectRelationCollections(plan.where));
17627
+ function compilePostgresTraceQuery(schema, plan, mode = "data", safeHorizon) {
17628
+ const relationCollections = collectRelationCollections(plan.where);
17629
+ let deltaWindow;
17630
+ if (plan.paginationMode === "delta") {
17631
+ const watermark = _mastra_core_storage.getTraceQueryDeltaWatermark(plan, "pg");
17632
+ if (watermark === void 0 || safeHorizon === void 0) throw new Error("Delta query requires a cursor and safe horizon");
17633
+ deltaWindow = {
17634
+ ...decodeTraceDeltaWatermark(watermark),
17635
+ safeHorizon
17636
+ };
17637
+ }
17638
+ const { ctes, values } = compilePostgresTraceScope(schema, plan, relationCollections, deltaWindow);
17604
17639
  let predicateSql = "TRUE";
17605
17640
  if (plan.where) {
17606
17641
  const predicate = compilePredicate(plan.where, values.length + 1);
@@ -17608,7 +17643,7 @@ function compilePostgresTraceQuery(schema, plan, mode = "data") {
17608
17643
  values.push(...predicate.values);
17609
17644
  }
17610
17645
  ctes.push(`candidates AS (
17611
- SELECT ${TRACE_SELECT}
17646
+ SELECT ${TRACE_SELECT}${plan.paginationMode === "delta" ? ", r.\"xactId\", r.\"cursorId\"" : ""}
17612
17647
  FROM root_scope r
17613
17648
  WHERE ${predicateSql}
17614
17649
  )`);
@@ -17619,6 +17654,16 @@ SELECT COUNT(*)::text AS count
17619
17654
  FROM candidates`,
17620
17655
  values
17621
17656
  };
17657
+ if (plan.paginationMode === "delta") {
17658
+ values.push(plan.limit + 1);
17659
+ return {
17660
+ text: `${candidates}
17661
+ SELECT * FROM candidates
17662
+ ORDER BY "xactId" ASC, "cursorId" ASC
17663
+ LIMIT $${values.length}`,
17664
+ values
17665
+ };
17666
+ }
17622
17667
  if (plan.result === "groups") {
17623
17668
  const pageCondition = plan.cursor ? `AND "threadId" > $${values.length + 1}` : "";
17624
17669
  if (plan.cursor) values.push(plan.cursor.threadId);
@@ -17830,13 +17875,83 @@ async function getTraceQueryValues(client, schema, plan, timeoutMs) {
17830
17875
  valuesTruncated: rows.length > plan.limit
17831
17876
  });
17832
17877
  }
17878
+ function decodeTraceDeltaWatermark(watermark) {
17879
+ try {
17880
+ return decodeDeltaCursor(watermark);
17881
+ } catch {
17882
+ throw new _mastra_core_storage.TraceQueryCursorError("TRACE_QUERY_CURSOR_MALFORMED");
17883
+ }
17884
+ }
17885
+ function emptyDeltaWatermark(horizon, watermark) {
17886
+ if (watermark !== void 0 && BigInt(decodeTraceDeltaWatermark(watermark).xactId) >= BigInt(horizon)) return watermark;
17887
+ return encodeDeltaCursor(horizon, 0);
17888
+ }
17889
+ async function setRemainingTimeout(transaction, deadline) {
17890
+ const remainingTimeoutMs = Math.floor(deadline - performance.now());
17891
+ if (remainingTimeoutMs <= 0) throw new _mastra_core_storage.TraceQueryExecutionError();
17892
+ await transaction.query(`SELECT set_config('statement_timeout', $1, true)`, [`${remainingTimeoutMs}ms`]);
17893
+ }
17894
+ function traceRowToResult(row) {
17895
+ return {
17896
+ traceId: String(row.traceId),
17897
+ rootSpanId: String(row.rootSpanId),
17898
+ name: row.name,
17899
+ entityId: row.entityId ?? null,
17900
+ parentSpanId: row.parentSpanId ?? null,
17901
+ createdAt: asIsoTimestamp$1(row.startedAt),
17902
+ metadata: row.metadata ?? null,
17903
+ inputPreview: _mastra_core_storage.buildInputPreview(row.input) ?? null,
17904
+ threadId: row.threadId == null ? null : String(row.threadId),
17905
+ resourceId: row.resourceId == null ? null : String(row.resourceId),
17906
+ startedAt: asIsoTimestamp$1(row.startedAt),
17907
+ endedAt: asIsoTimestamp$1(row.endedAt),
17908
+ entityName: row.entityName == null ? null : String(row.entityName),
17909
+ entityType: row.entityType == null ? null : String(row.entityType),
17910
+ environment: row.environment == null ? null : String(row.environment),
17911
+ status: row.status
17912
+ };
17913
+ }
17833
17914
  async function queryTraces(client, schema, plan, timeoutMs) {
17915
+ if (plan.paginationMode === "delta") {
17916
+ assertDeltaPollingEnabled();
17917
+ const watermark = _mastra_core_storage.getTraceQueryDeltaWatermark(plan, "pg");
17918
+ if (watermark !== void 0) decodeTraceDeltaWatermark(watermark);
17919
+ const resolvedTimeoutMs = _mastra_core_storage.resolveTraceQueryTimeoutMs(timeoutMs);
17920
+ const deadline = performance.now() + resolvedTimeoutMs;
17921
+ return runWithPostgresTraceQueryTimeout(client, resolvedTimeoutMs, async (transaction) => {
17922
+ await setRemainingTimeout(transaction, deadline);
17923
+ const horizon = await readSafeXactHorizon(transaction);
17924
+ let rows = [];
17925
+ if (watermark !== void 0) {
17926
+ await setRemainingTimeout(transaction, deadline);
17927
+ const query = compilePostgresTraceQuery(schema, plan, "data", horizon);
17928
+ rows = await transaction.any(query.text, query.values);
17929
+ }
17930
+ const visible = rows.slice(0, plan.limit);
17931
+ const last = visible.at(-1);
17932
+ return _mastra_core_storage.traceQueryResponseSchema.parse({
17933
+ traces: visible.map(traceRowToResult),
17934
+ delta: {
17935
+ limit: plan.limit,
17936
+ hasMore: rows.length > plan.limit
17937
+ },
17938
+ deltaCursor: _mastra_core_storage.encodeTraceQueryDeltaCursor(plan, "pg", last ? encodeDeltaCursor(last.xactId, last.cursorId) : emptyDeltaWatermark(horizon, watermark))
17939
+ });
17940
+ }, { repeatableRead: true });
17941
+ }
17834
17942
  if (plan.paginationMode === "page") {
17835
17943
  const resolvedTimeoutMs = _mastra_core_storage.resolveTraceQueryTimeoutMs(timeoutMs);
17836
17944
  const deadline = performance.now() + resolvedTimeoutMs;
17837
17945
  const countQuery = compilePostgresTraceQuery(schema, plan, "count");
17838
17946
  const dataQuery = compilePostgresTraceQuery(schema, plan);
17839
- const { total, rows } = await runWithPostgresTraceQueryTimeout(client, resolvedTimeoutMs, async (transaction) => {
17947
+ const { total, rows, deltaCursor } = await runWithPostgresTraceQueryTimeout(client, resolvedTimeoutMs, async (transaction) => {
17948
+ let deltaCursor;
17949
+ if (deltaPollingFeatureEnabled() && typeof _mastra_core_storage.encodeTraceQueryDeltaCursor === "function") {
17950
+ await setRemainingTimeout(transaction, deadline);
17951
+ const horizon = await readSafeXactHorizon(transaction);
17952
+ deltaCursor = _mastra_core_storage.encodeTraceQueryDeltaCursor(plan, "pg", encodeDeltaCursor(horizon, 0));
17953
+ }
17954
+ if (deltaCursor !== void 0) await setRemainingTimeout(transaction, deadline);
17840
17955
  const countRows = await transaction.any(countQuery.text, countQuery.values);
17841
17956
  const remainingTimeoutMs = Math.floor(deadline - performance.now());
17842
17957
  if (remainingTimeoutMs <= 0) throw new _mastra_core_storage.TraceQueryExecutionError();
@@ -17844,29 +17959,14 @@ async function queryTraces(client, schema, plan, timeoutMs) {
17844
17959
  const rows = await transaction.any(dataQuery.text, dataQuery.values);
17845
17960
  return {
17846
17961
  total: Number(countRows[0]?.count ?? 0),
17847
- rows
17962
+ rows,
17963
+ deltaCursor
17848
17964
  };
17849
17965
  }, { repeatableRead: true });
17850
- const traces = rows.map((row) => ({
17851
- traceId: String(row.traceId),
17852
- rootSpanId: String(row.rootSpanId),
17853
- name: row.name,
17854
- entityId: row.entityId ?? null,
17855
- parentSpanId: row.parentSpanId ?? null,
17856
- createdAt: asIsoTimestamp$1(row.startedAt),
17857
- metadata: row.metadata ?? null,
17858
- inputPreview: _mastra_core_storage.buildInputPreview(row.input) ?? null,
17859
- threadId: row.threadId == null ? null : String(row.threadId),
17860
- resourceId: row.resourceId == null ? null : String(row.resourceId),
17861
- startedAt: asIsoTimestamp$1(row.startedAt),
17862
- endedAt: asIsoTimestamp$1(row.endedAt),
17863
- entityName: row.entityName == null ? null : String(row.entityName),
17864
- entityType: row.entityType == null ? null : String(row.entityType),
17865
- environment: row.environment == null ? null : String(row.environment),
17866
- status: row.status
17867
- }));
17966
+ const traces = rows.map(traceRowToResult);
17868
17967
  return _mastra_core_storage.traceQueryResponseSchema.parse({
17869
17968
  traces,
17969
+ ...deltaCursor === void 0 ? {} : { deltaCursor },
17870
17970
  pagination: {
17871
17971
  total,
17872
17972
  page: plan.page,
@@ -17889,24 +17989,7 @@ async function queryTraces(client, schema, plan, timeoutMs) {
17889
17989
  }) : null }
17890
17990
  });
17891
17991
  }
17892
- const traces = visibleRows.map((row) => ({
17893
- traceId: String(row.traceId),
17894
- rootSpanId: String(row.rootSpanId),
17895
- name: row.name,
17896
- entityId: row.entityId ?? null,
17897
- parentSpanId: row.parentSpanId ?? null,
17898
- createdAt: asIsoTimestamp$1(row.startedAt),
17899
- metadata: row.metadata ?? null,
17900
- inputPreview: _mastra_core_storage.buildInputPreview(row.input) ?? null,
17901
- threadId: row.threadId == null ? null : String(row.threadId),
17902
- resourceId: row.resourceId == null ? null : String(row.resourceId),
17903
- startedAt: asIsoTimestamp$1(row.startedAt),
17904
- endedAt: asIsoTimestamp$1(row.endedAt),
17905
- entityName: row.entityName == null ? null : String(row.entityName),
17906
- entityType: row.entityType == null ? null : String(row.entityType),
17907
- environment: row.environment == null ? null : String(row.environment),
17908
- status: row.status
17909
- }));
17992
+ const traces = visibleRows.map(traceRowToResult);
17910
17993
  const last = traces.at(-1);
17911
17994
  return _mastra_core_storage.traceQueryResponseSchema.parse({
17912
17995
  traces,
@@ -18645,7 +18728,7 @@ async function dangerouslyClearTracing(client, schema) {
18645
18728
  * Use it through `MastraCompositeStore` with a dedicated Postgres connection.
18646
18729
  */
18647
18730
  function wrapError(op, error, details) {
18648
- if (error instanceof _mastra_core_error.MastraError || error instanceof _mastra_core_storage.TraceQueryExecutionError || error instanceof _mastra_core_storage.TraceQueryResourceLimitError) throw error;
18731
+ if (error instanceof _mastra_core_error.MastraError || error instanceof _mastra_core_storage.TraceQueryCursorError || error instanceof _mastra_core_storage.TraceQueryExecutionError || error instanceof _mastra_core_storage.TraceQueryResourceLimitError) throw error;
18649
18732
  throw new _mastra_core_error.MastraError({
18650
18733
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", op, "FAILED"),
18651
18734
  domain: _mastra_core_error.ErrorDomain.STORAGE,