@atscript/db-postgres 0.1.181 → 0.1.183

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.cjs CHANGED
@@ -2168,9 +2168,10 @@ var PostgresAdapter = class PostgresAdapter extends _atscript_db.BaseDbAdapter {
2168
2168
  async vectorSearch(vector, query, indexName) {
2169
2169
  await this._detectVectorSupport();
2170
2170
  if (!this._supportsVector) throw new Error("Vector search requires the pgvector extension");
2171
- const { sql, params } = this._buildVectorSearchQuery(this._prepareVectorSearch(vector, query, indexName));
2171
+ const ctx = this._prepareVectorSearch(vector, query, indexName);
2172
+ const { sql, params } = this._buildVectorSearchQuery(ctx);
2172
2173
  this._log(sql, params);
2173
- return this._exec().all(sql, params);
2174
+ return (await this._exec().all(sql, params)).map((row) => (0, _atscript_db_sql_tools.addVectorScore)(row, ctx.metric));
2174
2175
  }
2175
2176
  async vectorSearchWithCount(vector, query, indexName) {
2176
2177
  await this._detectVectorSupport();
@@ -2181,9 +2182,10 @@ var PostgresAdapter = class PostgresAdapter extends _atscript_db.BaseDbAdapter {
2181
2182
  this._log(sql, params);
2182
2183
  this._log(countSql, countParams);
2183
2184
  const [data, countRow] = await Promise.all([this._exec().all(sql, params), this._exec().get(countSql, countParams)]);
2185
+ const count = parseCount(countRow?.cnt);
2184
2186
  return {
2185
- data,
2186
- count: parseCount(countRow?.cnt)
2187
+ data: data.map((row) => (0, _atscript_db_sql_tools.addVectorScore)(row, ctx.metric)),
2188
+ count
2187
2189
  };
2188
2190
  }
2189
2191
  /** Resolves vector field and computes shared context for vector search SQL builders. */
@@ -2213,6 +2215,7 @@ var PostgresAdapter = class PostgresAdapter extends _atscript_db.BaseDbAdapter {
2213
2215
  field,
2214
2216
  vec,
2215
2217
  distanceOp,
2218
+ metric: similarityToMetric(vec.similarity),
2216
2219
  where,
2217
2220
  controls,
2218
2221
  threshold,
@@ -2228,7 +2231,7 @@ var PostgresAdapter = class PostgresAdapter extends _atscript_db.BaseDbAdapter {
2228
2231
  };
2229
2232
  return {
2230
2233
  source: (0, _atscript_db_sql_tools.vectorDistanceSource)(pgDialect, ctx.tableName, ctx.where, distExpr, withRows),
2231
- maxDistance: ctx.threshold === void 0 ? void 0 : thresholdToDistance(ctx.threshold, ctx.vec.similarity)
2234
+ maxDistance: ctx.threshold === void 0 ? void 0 : (0, _atscript_db_sql_tools.vectorMaxDistance)(ctx.metric, ctx.threshold)
2232
2235
  };
2233
2236
  }
2234
2237
  _buildVectorSearchQuery(ctx) {
@@ -2456,20 +2459,11 @@ function normalizePgDefault(value, isIdentity) {
2456
2459
  return (0, _atscript_db_sql_tools.unquoteSqlStringLiteral)(castMatch ? castMatch[1] : cleaned) ?? cleaned;
2457
2460
  }
2458
2461
  /**
2459
- * Converts a normalized similarity threshold (0-1) to a pgvector max distance.
2460
- *
2461
- * The threshold is a normalized score matching MongoDB Atlas semantics:
2462
- * cosine score = (1 + cosine_similarity) / 2, range [0, 1]
2463
- * pgvector cosine distance = 1 - cosine_similarity, range [0, 2]
2464
- *
2465
- * Conversion: distance = 2 * (1 - score)
2462
+ * The `$score` scale of a pgvector operator's result: `<=>` is `1 − cos`,
2463
+ * `<->` the straight-line distance, `<#>` the negative inner product.
2466
2464
  */
2467
- function thresholdToDistance(threshold, similarity) {
2468
- switch (similarity) {
2469
- case "euclidean": return threshold;
2470
- case "dotProduct": return -threshold;
2471
- default: return 2 * (1 - threshold);
2472
- }
2465
+ function similarityToMetric(similarity) {
2466
+ return similarity === "euclidean" || similarity === "dotProduct" ? similarity : "cosine";
2473
2467
  }
2474
2468
  /** Maps generic similarity metric to PostgreSQL distance operator. */
2475
2469
  function similarityToPgOp(similarity) {
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ALL_AGGREGATE_FNS, ALL_BUCKET_UNITS, ALL_ISOLATION_LEVELS, ALL_VIEW_CAPABILITIES, BaseDbAdapter, DB_FULLTEXT_LANGUAGES, DbError, DbSpace, bucketTimeZoneUnavailable, constraintViolation, createChangeRecorder, defaultFulltextIndex, describeFulltext, fkKey, isColumnTypeChanged, resolveFulltextIndex, searchIndexNotFoundMessage, searchTermInteger, splitFulltextFields, uniqueKeyTuple, vectorIndexNotFoundMessage } from "@atscript/db";
2
2
  import { resolveAggregateSearch } from "@atscript/db/agg";
3
- import { SEARCH_SOURCE_ALIAS, arithOverflowError, buildAggregateCount, buildAggregateSelect, buildCreateView, buildDelete, buildGeoSearchCount, buildGeoSearchSelect, buildInsert, buildInsertMany, buildJsonColumnCopy, buildJsonifyText, buildKeyViolationCount, buildPartitionedSelect, buildSelect, buildUpdate, buildVectorSearchCount, buildVectorSearchSelect, buildWhere as buildWhere$1, chunkInsertRows, defaultValueForType, defaultValueToSqlLiteral, derivedColumnExpr, fillReplacePayload, finalizeParams, foreignKeySql, geoWindowFromControls, mapQueryErrors, normalizeGeoPointValue, numericOutOfRangeError, orFragment, parseRegexString, quotedJsonPathSegments, renameGeoDistance, replaceColumnsFor, searchRankOrder, sqlStringLiteral, sqlTimeZoneLiteral, stripPartitionRowNumber, unquoteSqlStringLiteral, vectorDistanceSource, writeLimitWhere } from "@atscript/db-sql-tools";
3
+ import { SEARCH_SOURCE_ALIAS, addVectorScore, arithOverflowError, buildAggregateCount, buildAggregateSelect, buildCreateView, buildDelete, buildGeoSearchCount, buildGeoSearchSelect, buildInsert, buildInsertMany, buildJsonColumnCopy, buildJsonifyText, buildKeyViolationCount, buildPartitionedSelect, buildSelect, buildUpdate, buildVectorSearchCount, buildVectorSearchSelect, buildWhere as buildWhere$1, chunkInsertRows, defaultValueForType, defaultValueToSqlLiteral, derivedColumnExpr, fillReplacePayload, finalizeParams, foreignKeySql, geoWindowFromControls, mapQueryErrors, normalizeGeoPointValue, numericOutOfRangeError, orFragment, parseRegexString, quotedJsonPathSegments, renameGeoDistance, replaceColumnsFor, searchRankOrder, sqlStringLiteral, sqlTimeZoneLiteral, stripPartitionRowNumber, unquoteSqlStringLiteral, vectorDistanceSource, vectorMaxDistance, writeLimitWhere } from "@atscript/db-sql-tools";
4
4
  import { BUCKET_MAX_INSTANT, BUCKET_MIN_INSTANT } from "@uniqu/core";
5
5
  //#region src/insert-ignore.ts
6
6
  /**
@@ -2167,9 +2167,10 @@ var PostgresAdapter = class PostgresAdapter extends BaseDbAdapter {
2167
2167
  async vectorSearch(vector, query, indexName) {
2168
2168
  await this._detectVectorSupport();
2169
2169
  if (!this._supportsVector) throw new Error("Vector search requires the pgvector extension");
2170
- const { sql, params } = this._buildVectorSearchQuery(this._prepareVectorSearch(vector, query, indexName));
2170
+ const ctx = this._prepareVectorSearch(vector, query, indexName);
2171
+ const { sql, params } = this._buildVectorSearchQuery(ctx);
2171
2172
  this._log(sql, params);
2172
- return this._exec().all(sql, params);
2173
+ return (await this._exec().all(sql, params)).map((row) => addVectorScore(row, ctx.metric));
2173
2174
  }
2174
2175
  async vectorSearchWithCount(vector, query, indexName) {
2175
2176
  await this._detectVectorSupport();
@@ -2180,9 +2181,10 @@ var PostgresAdapter = class PostgresAdapter extends BaseDbAdapter {
2180
2181
  this._log(sql, params);
2181
2182
  this._log(countSql, countParams);
2182
2183
  const [data, countRow] = await Promise.all([this._exec().all(sql, params), this._exec().get(countSql, countParams)]);
2184
+ const count = parseCount(countRow?.cnt);
2183
2185
  return {
2184
- data,
2185
- count: parseCount(countRow?.cnt)
2186
+ data: data.map((row) => addVectorScore(row, ctx.metric)),
2187
+ count
2186
2188
  };
2187
2189
  }
2188
2190
  /** Resolves vector field and computes shared context for vector search SQL builders. */
@@ -2212,6 +2214,7 @@ var PostgresAdapter = class PostgresAdapter extends BaseDbAdapter {
2212
2214
  field,
2213
2215
  vec,
2214
2216
  distanceOp,
2217
+ metric: similarityToMetric(vec.similarity),
2215
2218
  where,
2216
2219
  controls,
2217
2220
  threshold,
@@ -2227,7 +2230,7 @@ var PostgresAdapter = class PostgresAdapter extends BaseDbAdapter {
2227
2230
  };
2228
2231
  return {
2229
2232
  source: vectorDistanceSource(pgDialect, ctx.tableName, ctx.where, distExpr, withRows),
2230
- maxDistance: ctx.threshold === void 0 ? void 0 : thresholdToDistance(ctx.threshold, ctx.vec.similarity)
2233
+ maxDistance: ctx.threshold === void 0 ? void 0 : vectorMaxDistance(ctx.metric, ctx.threshold)
2231
2234
  };
2232
2235
  }
2233
2236
  _buildVectorSearchQuery(ctx) {
@@ -2455,20 +2458,11 @@ function normalizePgDefault(value, isIdentity) {
2455
2458
  return unquoteSqlStringLiteral(castMatch ? castMatch[1] : cleaned) ?? cleaned;
2456
2459
  }
2457
2460
  /**
2458
- * Converts a normalized similarity threshold (0-1) to a pgvector max distance.
2459
- *
2460
- * The threshold is a normalized score matching MongoDB Atlas semantics:
2461
- * cosine score = (1 + cosine_similarity) / 2, range [0, 1]
2462
- * pgvector cosine distance = 1 - cosine_similarity, range [0, 2]
2463
- *
2464
- * Conversion: distance = 2 * (1 - score)
2461
+ * The `$score` scale of a pgvector operator's result: `<=>` is `1 − cos`,
2462
+ * `<->` the straight-line distance, `<#>` the negative inner product.
2465
2463
  */
2466
- function thresholdToDistance(threshold, similarity) {
2467
- switch (similarity) {
2468
- case "euclidean": return threshold;
2469
- case "dotProduct": return -threshold;
2470
- default: return 2 * (1 - threshold);
2471
- }
2464
+ function similarityToMetric(similarity) {
2465
+ return similarity === "euclidean" || similarity === "dotProduct" ? similarity : "cosine";
2472
2466
  }
2473
2467
  /** Maps generic similarity metric to PostgreSQL distance operator. */
2474
2468
  function similarityToPgOp(similarity) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/db-postgres",
3
- "version": "0.1.181",
3
+ "version": "0.1.183",
4
4
  "description": "PostgreSQL adapter for @atscript/db with pg (node-postgres) driver support.",
5
5
  "keywords": [
6
6
  "atscript",
@@ -43,22 +43,22 @@
43
43
  "access": "public"
44
44
  },
45
45
  "dependencies": {
46
- "@atscript/db-sql-tools": "^0.1.181"
46
+ "@atscript/db-sql-tools": "^0.1.183"
47
47
  },
48
48
  "devDependencies": {
49
- "@atscript/core": "^0.2.12",
50
- "@atscript/typescript": "^0.2.12",
49
+ "@atscript/core": "^0.2.13",
50
+ "@atscript/typescript": "^0.2.13",
51
51
  "@types/pg": "^8.11.0",
52
52
  "@uniqu/core": "^0.2.2",
53
53
  "pg": "^8.13.0",
54
- "unplugin-atscript": "^0.2.12"
54
+ "unplugin-atscript": "^0.2.13"
55
55
  },
56
56
  "peerDependencies": {
57
- "@atscript/core": "^0.2.12",
58
- "@atscript/typescript": "^0.2.12",
57
+ "@atscript/core": "^0.2.13",
58
+ "@atscript/typescript": "^0.2.13",
59
59
  "@uniqu/core": "^0.2.2",
60
60
  "pg": ">=8.0.0",
61
- "@atscript/db": "^0.1.181"
61
+ "@atscript/db": "^0.1.183"
62
62
  },
63
63
  "peerDependenciesMeta": {
64
64
  "pg": {