@mastra/pg 1.9.1-alpha.0 → 1.9.1

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
@@ -709,6 +709,25 @@ var PgVector = class extends MastraVector {
709
709
  return null;
710
710
  }
711
711
  }
712
+ /**
713
+ * Sets search_path on the client connection so that vector operators (e.g. <=>, vector_cosine_ops)
714
+ * are resolvable when the pgvector extension is installed in a non-default schema.
715
+ *
716
+ * PostgreSQL's default search_path is ("$user", public). If the extension lives in a custom schema
717
+ * (e.g. "myapp"), operator classes and distance operators won't resolve without this.
718
+ */
719
+ async ensureSearchPath(client) {
720
+ if (!this.vectorExtensionSchema) {
721
+ await this.detectVectorExtensionSchema(client);
722
+ }
723
+ if (this.vectorExtensionSchema && this.vectorExtensionSchema !== "public" && this.vectorExtensionSchema !== "pg_catalog") {
724
+ const schemas = /* @__PURE__ */ new Set();
725
+ schemas.add(this.vectorExtensionSchema);
726
+ if (this.schema) schemas.add(this.schema);
727
+ schemas.add("public");
728
+ await client.query(`SET search_path TO ${[...schemas].map((s) => `"${s}"`).join(", ")}`);
729
+ }
730
+ }
712
731
  /**
713
732
  * Checks if the installed pgvector version supports halfvec type.
714
733
  * halfvec was introduced in pgvector 0.7.0.
@@ -922,6 +941,7 @@ var PgVector = class extends MastraVector {
922
941
  }
923
942
  const client = await this.pool.connect();
924
943
  try {
944
+ await this.ensureSearchPath(client);
925
945
  await client.query("BEGIN");
926
946
  const translatedFilter = this.transformFilter(filter);
927
947
  const { sql: filterQuery, values: filterValues } = buildFilterQuery(translatedFilter, minScore, topK);
@@ -941,7 +961,23 @@ var PgVector = class extends MastraVector {
941
961
  const qualifiedVectorType = this.getVectorTypeName(indexInfo.vectorType, indexInfo.dimension);
942
962
  const distanceExpr = `embedding ${ops.distanceOperator} '${vectorStr}'::${qualifiedVectorType}`;
943
963
  const scoreExpr = ops.scoreExpr(distanceExpr);
944
- const query = `
964
+ const hasFilter = filterQuery.trim().length > 0;
965
+ const useIndexedOrder = indexInfo.type === "hnsw" && !hasFilter && minScore <= 0;
966
+ const query = useIndexedOrder ? `
967
+ WITH vector_scores AS (
968
+ SELECT
969
+ vector_id as id,
970
+ ${scoreExpr} as score,
971
+ metadata
972
+ ${includeVector ? ", embedding" : ""}
973
+ FROM ${tableName}
974
+ ORDER BY ${distanceExpr}
975
+ LIMIT $2
976
+ )
977
+ SELECT *
978
+ FROM vector_scores
979
+ WHERE score > $1
980
+ ORDER BY score DESC` : `
945
981
  WITH vector_scores AS (
946
982
  SELECT
947
983
  vector_id as id,
@@ -994,6 +1030,7 @@ var PgVector = class extends MastraVector {
994
1030
  const { tableName } = this.getTableName(indexName);
995
1031
  const client = await this.pool.connect();
996
1032
  try {
1033
+ await this.ensureSearchPath(client);
997
1034
  await client.query("BEGIN");
998
1035
  if (deleteFilter) {
999
1036
  this.logger?.debug(`Deleting vectors matching filter before upsert`, { indexName, deleteFilter });
@@ -1244,9 +1281,6 @@ var PgVector = class extends MastraVector {
1244
1281
  }
1245
1282
  });
1246
1283
  }
1247
- if (this.schema && this.vectorExtensionSchema && this.schema !== this.vectorExtensionSchema && this.vectorExtensionSchema !== "pg_catalog") {
1248
- await client.query(`SET search_path TO ${this.getSchemaName()}, "${this.vectorExtensionSchema}"`);
1249
- }
1250
1284
  const qualifiedVectorType = this.getVectorTypeName(vectorType);
1251
1285
  await client.query(`
1252
1286
  CREATE TABLE IF NOT EXISTS ${tableName} (
@@ -1389,6 +1423,7 @@ var PgVector = class extends MastraVector {
1389
1423
  this.describeIndexCache.delete(indexName);
1390
1424
  return;
1391
1425
  }
1426
+ await this.ensureSearchPath(client);
1392
1427
  const effectiveVectorType = existingIndexInfo?.vectorType ?? vectorType;
1393
1428
  const metricOp = this.getVectorOps(effectiveVectorType, metric).operatorClass;
1394
1429
  let indexSQL;
@@ -1739,6 +1774,7 @@ var PgVector = class extends MastraVector {
1739
1774
  });
1740
1775
  }
1741
1776
  client = await this.pool.connect();
1777
+ await this.ensureSearchPath(client);
1742
1778
  const { tableName } = this.getTableName(indexName);
1743
1779
  const indexInfo = await this.getIndexInfo({ indexName });
1744
1780
  const qualifiedVectorType = this.getVectorTypeName(indexInfo.vectorType, indexInfo.dimension);
@@ -1977,6 +2013,7 @@ var PoolAdapter = class {
1977
2013
  constructor($pool) {
1978
2014
  this.$pool = $pool;
1979
2015
  }
2016
+ $pool;
1980
2017
  connect() {
1981
2018
  return this.$pool.connect();
1982
2019
  }
@@ -2045,6 +2082,7 @@ var TransactionClient = class {
2045
2082
  constructor(client) {
2046
2083
  this.client = client;
2047
2084
  }
2085
+ client;
2048
2086
  async none(query, values) {
2049
2087
  await this.client.query(query, values);
2050
2088
  return null;
@@ -5540,6 +5578,22 @@ var ExperimentsPG = class _ExperimentsPG extends ExperimentsStorage {
5540
5578
  conditions.push(`"datasetId" = $${paramIndex++}`);
5541
5579
  queryParams.push(args.datasetId);
5542
5580
  }
5581
+ if (args.targetType) {
5582
+ conditions.push(`"targetType" = $${paramIndex++}`);
5583
+ queryParams.push(args.targetType);
5584
+ }
5585
+ if (args.targetId) {
5586
+ conditions.push(`"targetId" = $${paramIndex++}`);
5587
+ queryParams.push(args.targetId);
5588
+ }
5589
+ if (args.agentVersion) {
5590
+ conditions.push(`"agentVersion" = $${paramIndex++}`);
5591
+ queryParams.push(args.agentVersion);
5592
+ }
5593
+ if (args.status) {
5594
+ conditions.push(`"status" = $${paramIndex++}`);
5595
+ queryParams.push(args.status);
5596
+ }
5543
5597
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
5544
5598
  const countResult = await this.#db.client.one(
5545
5599
  `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`,
@@ -5728,9 +5782,21 @@ var ExperimentsPG = class _ExperimentsPG extends ExperimentsStorage {
5728
5782
  try {
5729
5783
  const { page, perPage: perPageInput } = args.pagination;
5730
5784
  const tableName = getTableName2({ indexName: TABLE_EXPERIMENT_RESULTS, schemaName: getSchemaName2(this.#schema) });
5785
+ const conditions = ['"experimentId" = $1'];
5786
+ const queryParams = [args.experimentId];
5787
+ let paramIndex = 2;
5788
+ if (args.traceId) {
5789
+ conditions.push(`"traceId" = $${paramIndex++}`);
5790
+ queryParams.push(args.traceId);
5791
+ }
5792
+ if (args.status) {
5793
+ conditions.push(`"status" = $${paramIndex++}`);
5794
+ queryParams.push(args.status);
5795
+ }
5796
+ const whereClause = `WHERE ${conditions.join(" AND ")}`;
5731
5797
  const countResult = await this.#db.client.one(
5732
- `SELECT COUNT(*) as count FROM ${tableName} WHERE "experimentId" = $1`,
5733
- [args.experimentId]
5798
+ `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`,
5799
+ queryParams
5734
5800
  );
5735
5801
  const total = parseInt(countResult.count, 10);
5736
5802
  if (total === 0) {
@@ -5740,8 +5806,8 @@ var ExperimentsPG = class _ExperimentsPG extends ExperimentsStorage {
5740
5806
  const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
5741
5807
  const limitValue = perPageInput === false ? total : perPage;
5742
5808
  const rows = await this.#db.client.manyOrNone(
5743
- `SELECT * FROM ${tableName} WHERE "experimentId" = $1 ORDER BY "startedAt" ASC LIMIT $2 OFFSET $3`,
5744
- [args.experimentId, limitValue, offset]
5809
+ `SELECT * FROM ${tableName} ${whereClause} ORDER BY "startedAt" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`,
5810
+ [...queryParams, limitValue, offset]
5745
5811
  );
5746
5812
  return {
5747
5813
  results: (rows || []).map((row) => this.transformExperimentResultRow(row)),