@palbase/backend 22.1.0 → 23.0.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.
- package/dist/bin/palbase-backend.cjs +439 -18
- package/dist/bin/palbase-backend.cjs.map +1 -1
- package/dist/bin/palbase-backend.js +4 -4
- package/dist/{chunk-SQC5EIWY.js → chunk-FSGSB42K.js} +11 -6
- package/dist/chunk-FSGSB42K.js.map +1 -0
- package/dist/{chunk-I3ON7MYF.js → chunk-HAF67F2H.js} +73 -16
- package/dist/chunk-HAF67F2H.js.map +1 -0
- package/dist/{chunk-QMVK4X3V.js → chunk-OMRTHM4X.js} +98 -98
- package/dist/chunk-OMRTHM4X.js.map +1 -0
- package/dist/{chunk-74XDEF5J.js → chunk-REZU6UKT.js} +432 -17
- package/dist/chunk-REZU6UKT.js.map +1 -0
- package/dist/{chunk-YL4C5NRY.js → chunk-Y5HXVUMP.js} +2 -2
- package/dist/{chunk-N32VDWKH.js → chunk-ZC6Q2BRD.js} +4 -59
- package/dist/chunk-ZC6Q2BRD.js.map +1 -0
- package/dist/db/env.cjs.map +1 -1
- package/dist/db/env.d.cts +3 -21
- package/dist/db/env.d.ts +3 -21
- package/dist/db/index.cjs +72 -15
- package/dist/db/index.cjs.map +1 -1
- package/dist/db/index.d.cts +3 -2
- package/dist/db/index.d.ts +3 -2
- package/dist/db/index.js +1 -1
- package/dist/{endpoint-BVT6jcVW.d.cts → endpoint-BavvbW4P.d.ts} +77 -7
- package/dist/{endpoint-BVT6jcVW.d.ts → endpoint-i8TTCohk.d.cts} +77 -7
- package/dist/engine/index.cjs +439 -18
- package/dist/engine/index.cjs.map +1 -1
- package/dist/engine/index.d.cts +6 -5
- package/dist/engine/index.d.ts +6 -5
- package/dist/engine/index.js +3 -3
- package/dist/{index-vwHoS0l2.d.ts → index-B3jmmItD.d.ts} +111 -5
- package/dist/{index-CCZqzych.d.ts → index-B7YBEG5w.d.ts} +96 -71
- package/dist/{index-BqCiHao8.d.cts → index-Bmvx1EvJ.d.cts} +111 -5
- package/dist/{index-BS1gW4nV.d.cts → index-E7OscPJT.d.cts} +96 -71
- package/dist/index.cjs +285 -1099
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +89 -1134
- package/dist/index.d.ts +89 -1134
- package/dist/index.js +107 -902
- package/dist/index.js.map +1 -1
- package/dist/openapi/index.cjs +3 -57
- package/dist/openapi/index.cjs.map +1 -1
- package/dist/openapi/index.d.cts +3 -2
- package/dist/openapi/index.d.ts +3 -2
- package/dist/openapi/index.js +5 -22
- package/dist/openapi/index.js.map +1 -1
- package/dist/{registry-Bsuf-orT.d.ts → registry-C3H2uPeZ.d.cts} +13 -169
- package/dist/{registry-BWttGlaT.d.cts → registry-DY3d9l1k.d.ts} +13 -169
- package/dist/{purchases/keys.cjs → stack.cjs} +4 -4
- package/dist/stack.cjs.map +1 -0
- package/dist/stack.d.cts +76 -0
- package/dist/stack.d.ts +76 -0
- package/dist/stack.js +1 -0
- package/docs/README.md +7 -6
- package/docs/llms-full.txt +7 -260
- package/docs/llms.txt +0 -2
- package/package.json +6 -6
- package/template/package.json +1 -1
- package/dist/chunk-74XDEF5J.js.map +0 -1
- package/dist/chunk-I3ON7MYF.js.map +0 -1
- package/dist/chunk-N32VDWKH.js.map +0 -1
- package/dist/chunk-QMVK4X3V.js.map +0 -1
- package/dist/chunk-SQC5EIWY.js.map +0 -1
- package/dist/purchases/keys.cjs.map +0 -1
- package/dist/purchases/keys.d.cts +0 -42
- package/dist/purchases/keys.d.ts +0 -42
- package/dist/purchases/keys.js +0 -1
- package/docs/config.md +0 -147
- package/docs/resources.md +0 -97
- package/template/config/secrets.ts +0 -24
- /package/dist/{chunk-YL4C5NRY.js.map → chunk-Y5HXVUMP.js.map} +0 -0
- /package/dist/{purchases/keys.js.map → stack.js.map} +0 -0
|
@@ -426,7 +426,10 @@ function makeTablesAccessor(ops) {
|
|
|
426
426
|
delete: (id) => ops().delete(name, id),
|
|
427
427
|
findById: (id) => ops().findById(name, id),
|
|
428
428
|
findMany: (query) => ops().findMany(name, query),
|
|
429
|
-
search: (params) => ops().search(name, params)
|
|
429
|
+
search: (params) => ops().search(name, params),
|
|
430
|
+
similar: (id, params) => ops().similar(name, id, params),
|
|
431
|
+
recommend: (params) => ops().recommend(name, params),
|
|
432
|
+
supersede: (id, row) => ops().supersede(name, id, row)
|
|
430
433
|
};
|
|
431
434
|
}
|
|
432
435
|
}
|
|
@@ -435,6 +438,7 @@ function makeTablesAccessor(ops) {
|
|
|
435
438
|
}
|
|
436
439
|
var rawDatabase = makeServiceProxy("Database");
|
|
437
440
|
function makeTypedSurface(raw) {
|
|
441
|
+
const reco = raw;
|
|
438
442
|
const ops = {
|
|
439
443
|
query: (sql, params) => raw.query(sql, params),
|
|
440
444
|
insert: (table, data) => raw.insert(table, data),
|
|
@@ -442,10 +446,13 @@ function makeTypedSurface(raw) {
|
|
|
442
446
|
delete: (table, id) => raw.delete(table, id),
|
|
443
447
|
findById: (table, id) => raw.findById(table, id),
|
|
444
448
|
findMany: (table, query) => raw.findMany(table, query),
|
|
445
|
-
search: (table, params) => raw.search(table, params)
|
|
449
|
+
search: (table, params) => raw.search(table, params),
|
|
450
|
+
similar: (table, id, params) => reco.similar(table, id, params),
|
|
451
|
+
recommend: (table, params) => reco.recommend(table, params),
|
|
452
|
+
supersede: (table, id, row) => raw.supersede(table, id, row)
|
|
446
453
|
};
|
|
447
454
|
return Object.assign(ops, {
|
|
448
|
-
tables: makeTablesAccessor(() =>
|
|
455
|
+
tables: makeTablesAccessor(() => reco),
|
|
449
456
|
transaction(fn) {
|
|
450
457
|
const builder = new TxPlanBuilder();
|
|
451
458
|
return runTxPlan(raw, makeTxTablesAccessor(builder), builder, fn);
|
|
@@ -508,7 +515,6 @@ var Cache = makeServiceProxy("Cache");
|
|
|
508
515
|
var Secrets = makeServiceProxy("Secrets");
|
|
509
516
|
var Log = makeServiceProxy("Log");
|
|
510
517
|
var Notifications = makeServiceProxy("Notifications");
|
|
511
|
-
var Purchases = makeServiceProxy("Purchases");
|
|
512
518
|
var rawFlags = makeServiceProxy("Flags");
|
|
513
519
|
var Flags = Object.assign(
|
|
514
520
|
{
|
|
@@ -1032,7 +1038,42 @@ function searchConfigFor(table) {
|
|
|
1032
1038
|
);
|
|
1033
1039
|
}
|
|
1034
1040
|
const search = t.search;
|
|
1035
|
-
const
|
|
1041
|
+
const synonyms = search?.synonyms !== void 0 && Object.keys(search.synonyms).length > 0 ? { synonyms: search.synonyms } : {};
|
|
1042
|
+
const validity = search?.validity === true ? { validity: true } : {};
|
|
1043
|
+
if (search?.from !== void 0 && search.model !== void 0) {
|
|
1044
|
+
const m = search.model;
|
|
1045
|
+
const embed = {
|
|
1046
|
+
model: m.model,
|
|
1047
|
+
apiKeyName: m.apiKeyName ?? "OPENAI_API_KEY",
|
|
1048
|
+
...m.baseURL !== void 0 ? { baseURL: m.baseURL } : {},
|
|
1049
|
+
...m.dimensions !== void 0 ? { dimensions: m.dimensions } : {}
|
|
1050
|
+
};
|
|
1051
|
+
const metric = search.metric ?? "cosine";
|
|
1052
|
+
const ftsOn = search.text !== false;
|
|
1053
|
+
const ftsColsNew = ftsOn ? Array.isArray(search.text) && search.text.length > 0 ? search.text : search.from : [];
|
|
1054
|
+
if (vectorCols.length > 0) {
|
|
1055
|
+
return {
|
|
1056
|
+
pk,
|
|
1057
|
+
cols,
|
|
1058
|
+
colSet: new Set(cols),
|
|
1059
|
+
ftsCols: ftsColsNew,
|
|
1060
|
+
legs: [{ column: vectorCols[0], metric, embed }],
|
|
1061
|
+
...synonyms,
|
|
1062
|
+
...validity
|
|
1063
|
+
};
|
|
1064
|
+
}
|
|
1065
|
+
return {
|
|
1066
|
+
pk,
|
|
1067
|
+
cols,
|
|
1068
|
+
colSet: new Set(cols),
|
|
1069
|
+
ftsCols: ftsColsNew,
|
|
1070
|
+
legs: [],
|
|
1071
|
+
chunk: { table: `${table}__palbase_chunks`, metric, embed, fts: ftsOn },
|
|
1072
|
+
...synonyms,
|
|
1073
|
+
...validity
|
|
1074
|
+
};
|
|
1075
|
+
}
|
|
1076
|
+
const ftsCols = (Array.isArray(search?.text) ? search.text : void 0) ?? [];
|
|
1036
1077
|
const rawLegs = search?.vector === void 0 ? [] : Array.isArray(search.vector) ? search.vector : [search.vector];
|
|
1037
1078
|
let legs;
|
|
1038
1079
|
if (rawLegs.length > 0) {
|
|
@@ -1058,7 +1099,7 @@ function searchConfigFor(table) {
|
|
|
1058
1099
|
legs = vectorCols.map((column) => ({ column, metric: "cosine" }));
|
|
1059
1100
|
}
|
|
1060
1101
|
if (ftsCols.length === 0 && legs.length === 0) return null;
|
|
1061
|
-
return { pk, cols, colSet: new Set(cols), ftsCols, legs };
|
|
1102
|
+
return { pk, cols, colSet: new Set(cols), ftsCols, legs, ...synonyms, ...validity };
|
|
1062
1103
|
}
|
|
1063
1104
|
function pickLeg(table, legs, using) {
|
|
1064
1105
|
if (legs.length === 0) return null;
|
|
@@ -1074,7 +1115,74 @@ function pickLeg(table, legs, using) {
|
|
|
1074
1115
|
if (legs.length === 1) return legs[0];
|
|
1075
1116
|
throw new Error(`search(${table}): birden \xE7ok vekt\xF6r kolu var \u2014 'using' ile se\xE7in (FR-013) \u2014 salt metin ar\u0131yorsan mode:"text" kullan`);
|
|
1076
1117
|
}
|
|
1118
|
+
var HALF_LIFE_UNIT_SECONDS = { s: 1, m: 60, h: 3600, d: 86400 };
|
|
1119
|
+
function parseHalfLife(s) {
|
|
1120
|
+
const m = /^(\d+)(s|m|h|d)$/.exec(s);
|
|
1121
|
+
const sec = m === null ? 0 : Number(m[1]) * HALF_LIFE_UNIT_SECONDS[m[2]];
|
|
1122
|
+
if (!Number.isFinite(sec) || sec <= 0) {
|
|
1123
|
+
throw new Error(`recency.halfLife "${s}" \xE7\xF6z\xFCmlenemedi \u2014 beklenen: pozitif <say\u0131>+(s|m|h|d), \xF6rn. "30d" (FR-004)`);
|
|
1124
|
+
}
|
|
1125
|
+
return sec;
|
|
1126
|
+
}
|
|
1077
1127
|
var WHERE_OPS = { gt: ">", gte: ">=", lt: "<", lte: "<=", neq: "<>" };
|
|
1128
|
+
function ftsExprOf(ftsCols) {
|
|
1129
|
+
return [...ftsCols].sort().map((c) => `coalesce(t.${quoteIdent(c)},'')`).join(" || ' ' || ");
|
|
1130
|
+
}
|
|
1131
|
+
function expandSynonyms(query, map) {
|
|
1132
|
+
const lower = {};
|
|
1133
|
+
for (const [word, alts] of Object.entries(map)) lower[word.toLowerCase()] = alts;
|
|
1134
|
+
return query.split(/("[^"]*")/).map((seg) => {
|
|
1135
|
+
if (seg.startsWith('"')) return seg;
|
|
1136
|
+
return seg.split(/(\s+)/).map((tok) => {
|
|
1137
|
+
if (tok === "" || /^\s+$/.test(tok)) return tok;
|
|
1138
|
+
const alts = lower[tok.toLowerCase()];
|
|
1139
|
+
return alts !== void 0 && alts.length > 0 ? `(${tok} OR ${alts.join(" OR ")})` : tok;
|
|
1140
|
+
}).join("");
|
|
1141
|
+
}).join("");
|
|
1142
|
+
}
|
|
1143
|
+
var searchLogger = null;
|
|
1144
|
+
function logNoResults(table, query, mode, n) {
|
|
1145
|
+
if (n === 0) {
|
|
1146
|
+
searchLogger?.("palbase.search.no_results", {
|
|
1147
|
+
table,
|
|
1148
|
+
query: (query ?? "").slice(0, 200),
|
|
1149
|
+
mode: mode ?? "hybrid"
|
|
1150
|
+
});
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
async function fetchFacets(live, table, colSet, facets, where, extraWhere = () => "") {
|
|
1154
|
+
const bind = [];
|
|
1155
|
+
const add = (v) => {
|
|
1156
|
+
bind.push(v);
|
|
1157
|
+
return `$${bind.length}`;
|
|
1158
|
+
};
|
|
1159
|
+
const whereSql = compileWhere(table, colSet, where, add) + extraWhere(add);
|
|
1160
|
+
const parts = facets.map(
|
|
1161
|
+
(col) => `(SELECT '${col.replace(/'/g, "''")}' AS f, t.${quoteIdent(col)}::text AS v, count(*) AS n FROM ${quoteIdent(table)} t WHERE true${whereSql} GROUP BY 2 ORDER BY 3 DESC LIMIT 20)`
|
|
1162
|
+
);
|
|
1163
|
+
const rows = await live.unsafe(parts.join(" UNION ALL "), bind);
|
|
1164
|
+
const out = {};
|
|
1165
|
+
for (const col of facets) out[col] = [];
|
|
1166
|
+
for (const r of rows) {
|
|
1167
|
+
if (typeof r.f === "string" && out[r.f] !== void 0) {
|
|
1168
|
+
out[r.f].push({ value: r.v ?? null, count: Number(r.n) });
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
return out;
|
|
1172
|
+
}
|
|
1173
|
+
function validitySql(v, add) {
|
|
1174
|
+
if (v === "all") return "";
|
|
1175
|
+
if (v !== void 0) {
|
|
1176
|
+
const p = add(v.asOf);
|
|
1177
|
+
return ` AND t."valid_from" <= ${p} AND (t."valid_to" IS NULL OR t."valid_to" > ${p})`;
|
|
1178
|
+
}
|
|
1179
|
+
return ` AND t."valid_to" IS NULL`;
|
|
1180
|
+
}
|
|
1181
|
+
function excludeSql(pk, ids, add) {
|
|
1182
|
+
if (ids.length === 0) return "";
|
|
1183
|
+
if (ids.length === 1) return ` AND t.${quoteIdent(pk)} <> ${add(ids[0])}`;
|
|
1184
|
+
return ` AND t.${quoteIdent(pk)} <> ALL(ARRAY[${ids.map((x) => add(x)).join(", ")}])`;
|
|
1185
|
+
}
|
|
1078
1186
|
function compileWhere(table, colSet, where, add) {
|
|
1079
1187
|
const parts = [];
|
|
1080
1188
|
for (const [col, cond] of Object.entries(where)) {
|
|
@@ -1104,6 +1212,15 @@ function compileWhere(table, colSet, where, add) {
|
|
|
1104
1212
|
return parts.length === 0 ? "" : ` AND ${parts.join(" AND ")}`;
|
|
1105
1213
|
}
|
|
1106
1214
|
var cachedVectorSchema = null;
|
|
1215
|
+
var cachedTrgmSchema = null;
|
|
1216
|
+
async function trgmSchemaOf(live) {
|
|
1217
|
+
if (cachedTrgmSchema !== null) return cachedTrgmSchema;
|
|
1218
|
+
const rows = await live.unsafe(
|
|
1219
|
+
"select n.nspname from pg_extension e join pg_namespace n on n.oid = e.extnamespace where e.extname = 'pg_trgm'"
|
|
1220
|
+
);
|
|
1221
|
+
cachedTrgmSchema = rows?.[0]?.nspname ?? "public";
|
|
1222
|
+
return cachedTrgmSchema;
|
|
1223
|
+
}
|
|
1107
1224
|
async function vectorSchemaWithGuc(runner) {
|
|
1108
1225
|
if (cachedVectorSchema !== null) {
|
|
1109
1226
|
await runner.unsafe(
|
|
@@ -1219,12 +1336,128 @@ function createOps(tx) {
|
|
|
1219
1336
|
if (!cfg) {
|
|
1220
1337
|
throw new Error(`search(${table}): tablo aranabilir de\u011Fil \u2014 ne vector kolonu ne search beyan\u0131 var (FR-013)`);
|
|
1221
1338
|
}
|
|
1339
|
+
const excl = params.__excludeIds ?? [];
|
|
1340
|
+
if (params.facets !== void 0) {
|
|
1341
|
+
for (const col of params.facets) {
|
|
1342
|
+
if (!cfg.colSet.has(col)) {
|
|
1343
|
+
throw new Error(`search(${table}): facets kolonu "${col}" tabloda yok (FR-027)`);
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
if (params.validity !== void 0 && cfg.validity !== true) {
|
|
1348
|
+
throw new Error(
|
|
1349
|
+
`search(${table}): validity parametresi verildi ama tablo validity beyan\u0131 ta\u015F\u0131m\u0131yor (FR-029)`
|
|
1350
|
+
);
|
|
1351
|
+
}
|
|
1352
|
+
const validityFor = (adder) => cfg.validity === true ? validitySql(params.validity, adder) : "";
|
|
1222
1353
|
const rawLimit = params.limit ?? 20;
|
|
1223
1354
|
if (typeof rawLimit !== "number" || !Number.isFinite(rawLimit)) {
|
|
1224
1355
|
throw new Error(`search(${table}): limit sonlu bir say\u0131 olmal\u0131, ${String(rawLimit)} verildi (FR-013)`);
|
|
1225
1356
|
}
|
|
1226
1357
|
const limit = Math.min(Math.max(1, Math.trunc(rawLimit)), 100);
|
|
1227
1358
|
const pool = Math.max(limit * 3, 30);
|
|
1359
|
+
if (params.minScore !== void 0 && (typeof params.minScore !== "number" || !Number.isFinite(params.minScore))) {
|
|
1360
|
+
throw new Error(`search(${table}): minScore sonlu bir say\u0131 olmal\u0131, ${String(params.minScore)} verildi (FR-001)`);
|
|
1361
|
+
}
|
|
1362
|
+
let recencyMul = "";
|
|
1363
|
+
if (params.recency !== void 0) {
|
|
1364
|
+
const { field, halfLife } = params.recency;
|
|
1365
|
+
if (!cfg.colSet.has(field)) {
|
|
1366
|
+
throw new Error(`search(${table}): recency.field "${field}" tabloda yok (FR-004)`);
|
|
1367
|
+
}
|
|
1368
|
+
recencyMul = ` * exp(-ln(2) * extract(epoch from (now() - t.${quoteIdent(field)})) / ${parseHalfLife(halfLife)})`;
|
|
1369
|
+
}
|
|
1370
|
+
let boostMul = "";
|
|
1371
|
+
if (params.boost !== void 0) {
|
|
1372
|
+
const { field, weight } = params.boost;
|
|
1373
|
+
if (!cfg.colSet.has(field)) {
|
|
1374
|
+
throw new Error(`search(${table}): boost.field "${field}" tabloda yok (FR-030)`);
|
|
1375
|
+
}
|
|
1376
|
+
if (typeof weight !== "number" || !Number.isFinite(weight)) {
|
|
1377
|
+
throw new Error(`search(${table}): boost.weight sonlu bir say\u0131 olmal\u0131, ${String(weight)} verildi (FR-030)`);
|
|
1378
|
+
}
|
|
1379
|
+
const g = `greatest(t.${quoteIdent(field)},0)`;
|
|
1380
|
+
boostMul = ` * (1 + ${weight} * ${g}/(1+${g}))`;
|
|
1381
|
+
}
|
|
1382
|
+
const scoreMul = boostMul + recencyMul;
|
|
1383
|
+
if (cfg.chunk !== void 0) {
|
|
1384
|
+
const ck = cfg.chunk;
|
|
1385
|
+
const pidQ = quoteIdent(`parent_${cfg.pk}`);
|
|
1386
|
+
const bpr = Math.min(Math.max(1, Math.trunc(params.blocksPerRow ?? 3)), 10);
|
|
1387
|
+
const wantTextC = params.mode !== "vector" && ck.fts && typeof params.query === "string" && params.query !== "";
|
|
1388
|
+
let qvC = Array.isArray(params.vector) ? params.vector : null;
|
|
1389
|
+
if (qvC === null && ck.embed !== void 0 && params.mode !== "text" && typeof params.query === "string" && params.query !== "") {
|
|
1390
|
+
try {
|
|
1391
|
+
qvC = await embedQuery(ck.embed, params.query);
|
|
1392
|
+
} catch (e) {
|
|
1393
|
+
if (!wantTextC) throw e;
|
|
1394
|
+
qvC = null;
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
if (!wantTextC && qvC === null) {
|
|
1398
|
+
throw new Error(
|
|
1399
|
+
`search(${table}): ko\u015Fulabilir kol yok \u2014 metin i\xE7in 'query' (FTS beyan\u0131 gerekir), semantik i\xE7in 'vector' verin (FR-015)`
|
|
1400
|
+
);
|
|
1401
|
+
}
|
|
1402
|
+
const bindC = [];
|
|
1403
|
+
const addC = (v) => {
|
|
1404
|
+
bindC.push(v);
|
|
1405
|
+
return `$${bindC.length}`;
|
|
1406
|
+
};
|
|
1407
|
+
const whereC = compileWhere(table, cfg.colSet, params.where ?? {}, addC) + excludeSql(cfg.pk, excl, addC) + validityFor(addC);
|
|
1408
|
+
const liveC = await at();
|
|
1409
|
+
const K2 = 50;
|
|
1410
|
+
const cpool = Math.max(limit * 9, 90);
|
|
1411
|
+
let semC = "";
|
|
1412
|
+
let kwC = "";
|
|
1413
|
+
if (qvC !== null) {
|
|
1414
|
+
const sch = await vectorSchemaWithGuc(liveC);
|
|
1415
|
+
const op = METRIC_OPERATOR[ck.metric] ?? METRIC_OPERATOR.cosine;
|
|
1416
|
+
const vp = addC(toVectorLiteral(qvC));
|
|
1417
|
+
semC = `SELECT c.${pidQ} AS pid, c.chunk_seq, ROW_NUMBER() OVER (ORDER BY (c.embedding OPERATOR(${quoteIdent(sch)}.${op}) ${vp}::${quoteIdent(sch)}.vector)) AS r FROM ${quoteIdent(ck.table)} c WHERE c.embedding IS NOT NULL ORDER BY r LIMIT ${cpool}`;
|
|
1418
|
+
}
|
|
1419
|
+
let qpC = "";
|
|
1420
|
+
let qpCIdx = -1;
|
|
1421
|
+
if (wantTextC) {
|
|
1422
|
+
const qTextC = cfg.synonyms !== void 0 ? expandSynonyms(params.query, cfg.synonyms) : params.query;
|
|
1423
|
+
qpC = addC(qTextC);
|
|
1424
|
+
qpCIdx = bindC.length - 1;
|
|
1425
|
+
kwC = `SELECT c.${pidQ} AS pid, c.chunk_seq, ROW_NUMBER() OVER (ORDER BY ts_rank_cd(c.palbase_fts, websearch_to_tsquery('simple', ${qpC})) DESC) AS r FROM ${quoteIdent(ck.table)} c WHERE c.palbase_fts @@ websearch_to_tsquery('simple', ${qpC}) ORDER BY r LIMIT ${cpool}`;
|
|
1426
|
+
}
|
|
1427
|
+
const msC = params.minScore === void 0 ? "" : addC(params.minScore);
|
|
1428
|
+
const colListC = cfg.cols.map((c) => `t.${quoteIdent(c)}`).join(", ");
|
|
1429
|
+
const scoreC = scoreMul === "" ? "g._score" : `(g._score)${scoreMul}`;
|
|
1430
|
+
const assembleC = (kwIn, withKwn) => {
|
|
1431
|
+
const kwnCol = withKwn ? `, (SELECT count(*) FROM kw)::int AS _kwn` : "";
|
|
1432
|
+
let fusedSrc;
|
|
1433
|
+
if (semC !== "" && kwIn !== "") {
|
|
1434
|
+
fusedSrc = `WITH sem AS (${semC}), kw AS (${kwIn}), fused AS (SELECT COALESCE(sem.pid, kw.pid) AS pid, COALESCE(sem.chunk_seq, kw.chunk_seq) AS chunk_seq, (COALESCE(1.0/(${K2} + sem.r), 0) + COALESCE(1.0/(${K2} + kw.r), 0))::float8 AS cscore FROM sem FULL OUTER JOIN kw ON sem.pid = kw.pid AND sem.chunk_seq = kw.chunk_seq)`;
|
|
1435
|
+
} else if (semC !== "") {
|
|
1436
|
+
fusedSrc = `WITH sem AS (${semC}), fused AS (SELECT sem.pid, sem.chunk_seq, (1.0/(${K2} + sem.r))::float8 AS cscore FROM sem)`;
|
|
1437
|
+
} else {
|
|
1438
|
+
fusedSrc = `WITH kw AS (${kwIn}), fused AS (SELECT kw.pid, kw.chunk_seq, (1.0/(${K2} + kw.r))::float8 AS cscore FROM kw)`;
|
|
1439
|
+
}
|
|
1440
|
+
const inner = `${fusedSrc}, ranked AS (SELECT f.pid, f.chunk_seq, f.cscore, ROW_NUMBER() OVER (PARTITION BY f.pid ORDER BY f.cscore DESC, f.chunk_seq) AS rn FROM fused f), grouped AS (SELECT r.pid, MAX(r.cscore) AS _score, json_agg(json_build_object('content', c.content, 'score', r.cscore, 'chunkSeq', r.chunk_seq, 'charStart', c.char_start) ORDER BY r.cscore DESC, r.chunk_seq) FILTER (WHERE r.rn <= ${bpr}) AS blocks FROM ranked r JOIN ${quoteIdent(ck.table)} c ON c.${pidQ} = r.pid AND c.chunk_seq = r.chunk_seq GROUP BY r.pid) SELECT ${colListC}, ${scoreC}::float8 AS _score, g.blocks AS blocks${kwnCol} FROM grouped g JOIN ${quoteIdent(table)} t ON t.${quoteIdent(cfg.pk)} = g.pid WHERE true${whereC}`;
|
|
1441
|
+
return msC === "" ? `SELECT * FROM (${inner}) q ORDER BY q._score DESC, q.${quoteIdent(cfg.pk)} LIMIT ${limit}` : `SELECT * FROM (${inner}) q WHERE q._score >= ${msC} ORDER BY q._score DESC, q.${quoteIdent(cfg.pk)} LIMIT ${limit}`;
|
|
1442
|
+
};
|
|
1443
|
+
let rowsC = await liveC.unsafe(assembleC(kwC, kwC !== ""), bindC);
|
|
1444
|
+
if (wantTextC && kwC !== "" && (rowsC.length === 0 || rowsC[0]._kwn === 0)) {
|
|
1445
|
+
const tsch = await trgmSchemaOf(liveC);
|
|
1446
|
+
const trgmKwC = `SELECT c.${pidQ} AS pid, c.chunk_seq, ROW_NUMBER() OVER (ORDER BY ${quoteIdent(tsch)}.word_similarity(${qpC}, coalesce(c.content,'')) DESC) AS r FROM ${quoteIdent(ck.table)} c WHERE ${qpC} OPERATOR(${quoteIdent(tsch)}.<%) coalesce(c.content,'') ORDER BY r LIMIT ${cpool}`;
|
|
1447
|
+
const retryBindC = bindC.slice();
|
|
1448
|
+
if (qpCIdx >= 0) retryBindC[qpCIdx] = params.query;
|
|
1449
|
+
rowsC = await liveC.unsafe(assembleC(trgmKwC, false), retryBindC);
|
|
1450
|
+
}
|
|
1451
|
+
for (const r of rowsC) delete r._kwn;
|
|
1452
|
+
const outC = asTableRows(table, rowsC).map((r) => ({ ...r, blocks: r.blocks ?? [] }));
|
|
1453
|
+
if (params.facets !== void 0 && params.facets.length > 0) {
|
|
1454
|
+
Object.assign(outC, {
|
|
1455
|
+
_facets: await fetchFacets(liveC, table, cfg.colSet, params.facets, params.where ?? {}, validityFor)
|
|
1456
|
+
});
|
|
1457
|
+
}
|
|
1458
|
+
logNoResults(table, params.query, params.mode, outC.length);
|
|
1459
|
+
return outC;
|
|
1460
|
+
}
|
|
1228
1461
|
const wantText = params.mode !== "vector" && cfg.ftsCols.length > 0 && typeof params.query === "string" && params.query !== "";
|
|
1229
1462
|
const anyEmbed = cfg.legs.some((l) => l.embed !== void 0);
|
|
1230
1463
|
const vectorAsked = params.mode !== "text" && (Array.isArray(params.vector) || params.using !== void 0 || params.mode === "vector" || anyEmbed && typeof params.query === "string" && params.query !== "");
|
|
@@ -1249,7 +1482,8 @@ function createOps(tx) {
|
|
|
1249
1482
|
bind.push(v);
|
|
1250
1483
|
return `$${bind.length}`;
|
|
1251
1484
|
};
|
|
1252
|
-
const
|
|
1485
|
+
const userWhere = compileWhere(table, cfg.colSet, params.where ?? {}, add);
|
|
1486
|
+
const whereSql = userWhere + excludeSql(cfg.pk, excl, add) + validityFor(add);
|
|
1253
1487
|
const live = await at();
|
|
1254
1488
|
const K = 50;
|
|
1255
1489
|
let semSql = "";
|
|
@@ -1258,7 +1492,7 @@ function createOps(tx) {
|
|
|
1258
1492
|
const sch = await vectorSchemaWithGuc(live);
|
|
1259
1493
|
const op = METRIC_OPERATOR[leg.metric] ?? METRIC_OPERATOR.cosine;
|
|
1260
1494
|
let exactOrder = "";
|
|
1261
|
-
if (
|
|
1495
|
+
if (userWhere !== "") {
|
|
1262
1496
|
const probeRows = await live.unsafe(
|
|
1263
1497
|
`SELECT count(*)::int AS n FROM (SELECT 1 FROM ${quoteIdent(table)} t WHERE t.${quoteIdent(leg.column)} IS NOT NULL${whereSql} LIMIT ${SELECTIVITY_EXACT_THRESHOLD + 1}) s`,
|
|
1264
1498
|
bind.slice()
|
|
@@ -1271,21 +1505,208 @@ function createOps(tx) {
|
|
|
1271
1505
|
const vp = add(toVectorLiteral(qv));
|
|
1272
1506
|
semSql = `SELECT t.${quoteIdent(cfg.pk)} AS id, ROW_NUMBER() OVER (ORDER BY (t.${quoteIdent(leg.column)} OPERATOR(${quoteIdent(sch)}.${op}) ${vp}::${quoteIdent(sch)}.vector)${exactOrder}) AS r FROM ${quoteIdent(table)} t WHERE t.${quoteIdent(leg.column)} IS NOT NULL${whereSql} ORDER BY r LIMIT ${pool}`;
|
|
1273
1507
|
}
|
|
1508
|
+
let qpRef = "";
|
|
1509
|
+
let qpIdx = -1;
|
|
1274
1510
|
if (wantText) {
|
|
1275
|
-
const
|
|
1511
|
+
const qText = cfg.synonyms !== void 0 ? expandSynonyms(params.query, cfg.synonyms) : params.query;
|
|
1512
|
+
const qp = add(qText);
|
|
1513
|
+
qpIdx = bind.length - 1;
|
|
1514
|
+
qpRef = qp;
|
|
1276
1515
|
kwSql = `SELECT t.${quoteIdent(cfg.pk)} AS id, ROW_NUMBER() OVER (ORDER BY ts_rank_cd(t.palbase_fts, websearch_to_tsquery('simple', ${qp})) DESC) AS r FROM ${quoteIdent(table)} t WHERE t.palbase_fts @@ websearch_to_tsquery('simple', ${qp})${whereSql} ORDER BY r LIMIT ${pool}`;
|
|
1277
1516
|
}
|
|
1278
1517
|
const colList = cfg.cols.map((c) => `t.${quoteIdent(c)}`).join(", ");
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1518
|
+
const msP = params.minScore === void 0 ? "" : add(params.minScore);
|
|
1519
|
+
const hlCol = params.highlight === true && wantText ? `, ts_headline('simple', ${ftsExprOf(cfg.ftsCols)}, websearch_to_tsquery('simple', ${qpRef})) AS _highlight` : "";
|
|
1520
|
+
const assemble = (kwIn, withKwn) => {
|
|
1521
|
+
const kwnCol = withKwn ? `, (SELECT count(*) FROM kw)::int AS _kwn` : "";
|
|
1522
|
+
let inner;
|
|
1523
|
+
let orderScore;
|
|
1524
|
+
if (semSql !== "" && kwIn !== "") {
|
|
1525
|
+
const score = scoreMul === "" ? "fused._score" : `(fused._score)${scoreMul}`;
|
|
1526
|
+
inner = `WITH sem AS (${semSql}), kw AS (${kwIn}), fused AS (SELECT COALESCE(sem.id, kw.id) AS id, (COALESCE(1.0/(${K} + sem.r), 0) + COALESCE(1.0/(${K} + kw.r), 0))::float8 AS _score FROM sem FULL OUTER JOIN kw ON sem.id = kw.id) SELECT ${colList}, ${score} AS _score${hlCol}${kwnCol} FROM fused JOIN ${quoteIdent(table)} t ON t.${quoteIdent(cfg.pk)} = fused.id`;
|
|
1527
|
+
orderScore = scoreMul === "" ? "fused._score" : "_score";
|
|
1528
|
+
} else {
|
|
1529
|
+
const single = semSql !== "" ? `sem AS (${semSql})` : `kw AS (${kwIn})`;
|
|
1530
|
+
const alias = semSql !== "" ? "sem" : "kw";
|
|
1531
|
+
const base = `(1.0/(${K} + ${alias}.r))::float8`;
|
|
1532
|
+
const score = scoreMul === "" ? base : `(${base})${scoreMul}`;
|
|
1533
|
+
inner = `WITH ${single} SELECT ${colList}, ${score} AS _score${hlCol}${semSql !== "" ? "" : kwnCol} FROM ${alias} JOIN ${quoteIdent(table)} t ON t.${quoteIdent(cfg.pk)} = ${alias}.id`;
|
|
1534
|
+
orderScore = "_score";
|
|
1535
|
+
}
|
|
1536
|
+
return msP === "" ? `${inner} ORDER BY ${orderScore} DESC, t.${quoteIdent(cfg.pk)} LIMIT ${limit}` : `SELECT * FROM (${inner}) q WHERE q._score >= ${msP} ORDER BY q._score DESC, q.${quoteIdent(cfg.pk)} LIMIT ${limit}`;
|
|
1537
|
+
};
|
|
1538
|
+
let rows = await live.unsafe(assemble(kwSql, kwSql !== ""), bind);
|
|
1539
|
+
if (wantText && kwSql !== "" && (rows.length === 0 || rows[0]._kwn === 0)) {
|
|
1540
|
+
const tsch = await trgmSchemaOf(live);
|
|
1541
|
+
const expr = ftsExprOf(cfg.ftsCols);
|
|
1542
|
+
const trgmKw = `SELECT t.${quoteIdent(cfg.pk)} AS id, ROW_NUMBER() OVER (ORDER BY ${quoteIdent(tsch)}.word_similarity(${qpRef}, ${expr}) DESC) AS r FROM ${quoteIdent(table)} t WHERE ${qpRef} OPERATOR(${quoteIdent(tsch)}.<%) ${expr}${whereSql} ORDER BY r LIMIT ${pool}`;
|
|
1543
|
+
const retryBind = bind.slice();
|
|
1544
|
+
if (qpIdx >= 0) retryBind[qpIdx] = params.query;
|
|
1545
|
+
rows = await live.unsafe(assemble(trgmKw, false), retryBind);
|
|
1546
|
+
}
|
|
1547
|
+
for (const r of rows) delete r._kwn;
|
|
1548
|
+
const out = asTableRows(table, rows).map((r) => ({ ...r, blocks: [] }));
|
|
1549
|
+
if (params.facets !== void 0 && params.facets.length > 0) {
|
|
1550
|
+
Object.assign(out, {
|
|
1551
|
+
_facets: await fetchFacets(live, table, cfg.colSet, params.facets, params.where ?? {}, validityFor)
|
|
1552
|
+
});
|
|
1553
|
+
}
|
|
1554
|
+
logNoResults(table, params.query, params.mode, out.length);
|
|
1555
|
+
return out;
|
|
1556
|
+
},
|
|
1557
|
+
/**
|
|
1558
|
+
* similar (T018, FR-022): "bu satıra benzeyenler". Hedef vektör DB'den
|
|
1559
|
+
* okunur — satır-modu satırın kendi kolonu, chunk-modu parent chunk'larının
|
|
1560
|
+
* şema-nitelikli avg'ı — ve ana arama search'ün vector yoluyla koşar;
|
|
1561
|
+
* kaynak satır sonuçtan düşer. İKİ tur BİLİNÇLİ (plan T018): target-CTE'li
|
|
1562
|
+
* tek SQL'de "id yok" ile "0 komşu" ayrılamazdı; +1 küçük turla id-yokluğu
|
|
1563
|
+
* adlandırılmış hataya çevrilir. Sonuç şekli search ile aynı (FR-015).
|
|
1564
|
+
*/
|
|
1565
|
+
async similar(table, id, opts = {}) {
|
|
1566
|
+
const cfg = searchConfigFor(table);
|
|
1567
|
+
if (!cfg) {
|
|
1568
|
+
throw new Error(`similar(${table}): tablo aranabilir de\u011Fil \u2014 ne vector kolonu ne search beyan\u0131 var (FR-013)`);
|
|
1569
|
+
}
|
|
1570
|
+
const live = await at();
|
|
1571
|
+
let v;
|
|
1572
|
+
if (cfg.chunk !== void 0) {
|
|
1573
|
+
const sch = await vectorSchemaWithGuc(live);
|
|
1574
|
+
const rows = await live.unsafe(
|
|
1575
|
+
`SELECT ${quoteIdent(sch)}.avg(c.embedding) AS v FROM ${quoteIdent(cfg.chunk.table)} c WHERE c.${quoteIdent(`parent_${cfg.pk}`)} = $1 AND c.embedding IS NOT NULL`,
|
|
1576
|
+
[id]
|
|
1577
|
+
);
|
|
1578
|
+
v = rows?.[0]?.v;
|
|
1282
1579
|
} else {
|
|
1283
|
-
const
|
|
1284
|
-
|
|
1285
|
-
|
|
1580
|
+
const leg = pickLeg(table, cfg.legs, opts.using);
|
|
1581
|
+
if (leg === null) {
|
|
1582
|
+
throw new Error(`similar(${table}): tabloda vekt\xF6r kolonu yok \u2014 benzerlik semantik vekt\xF6r ister (FR-022)`);
|
|
1583
|
+
}
|
|
1584
|
+
const rows = await live.unsafe(
|
|
1585
|
+
`SELECT t.${quoteIdent(leg.column)} AS v FROM ${quoteIdent(table)} t WHERE t.${quoteIdent(cfg.pk)} = $1`,
|
|
1586
|
+
[id]
|
|
1587
|
+
);
|
|
1588
|
+
v = rows?.[0]?.v;
|
|
1589
|
+
}
|
|
1590
|
+
if (typeof v !== "string") {
|
|
1591
|
+
throw new Error(`similar(${table}): id "${String(id)}" bulunamad\u0131 ya da embedding'i yok (FR-022)`);
|
|
1592
|
+
}
|
|
1593
|
+
const p = {
|
|
1594
|
+
vector: JSON.parse(v),
|
|
1595
|
+
mode: "vector",
|
|
1596
|
+
where: opts.where,
|
|
1597
|
+
limit: opts.limit,
|
|
1598
|
+
using: opts.using,
|
|
1599
|
+
minScore: opts.minScore,
|
|
1600
|
+
recency: opts.recency,
|
|
1601
|
+
blocksPerRow: opts.blocksPerRow,
|
|
1602
|
+
validity: opts.validity,
|
|
1603
|
+
boost: opts.boost,
|
|
1604
|
+
__excludeIds: [id]
|
|
1605
|
+
};
|
|
1606
|
+
return ops.search(table, p);
|
|
1607
|
+
},
|
|
1608
|
+
/**
|
|
1609
|
+
* recommend (T018, FR-023): positive/negative id kümelerinden öneri.
|
|
1610
|
+
* Hedef vektör DB-İÇİ CTE'lerle türer: pos = avg(embedding of positives),
|
|
1611
|
+
* negative varsa hedef = pos.v + (pos.v - neg.v) — pgvector avg agregası
|
|
1612
|
+
* ve +/- operatörleri ŞEMA-NİTELİKLİ (M-1: search_path'e güvenilmez).
|
|
1613
|
+
* Vektör matematiği istemciye inmez; bulunamayan positive/negative
|
|
1614
|
+
* adlandırılmış hatadır ve kaynak id'ler sonuçtan düşer.
|
|
1615
|
+
*/
|
|
1616
|
+
async recommend(table, opts) {
|
|
1617
|
+
const positive = opts?.positive;
|
|
1618
|
+
if (!Array.isArray(positive) || positive.length === 0) {
|
|
1619
|
+
throw new Error(`recommend(${table}): positive bo\u015F olamaz \u2014 en az bir kaynak id gerekir (FR-023)`);
|
|
1620
|
+
}
|
|
1621
|
+
const negative = Array.isArray(opts.negative) ? opts.negative : [];
|
|
1622
|
+
const cfg = searchConfigFor(table);
|
|
1623
|
+
if (!cfg) {
|
|
1624
|
+
throw new Error(`recommend(${table}): tablo aranabilir de\u011Fil \u2014 ne vector kolonu ne search beyan\u0131 var (FR-013)`);
|
|
1286
1625
|
}
|
|
1287
|
-
|
|
1288
|
-
|
|
1626
|
+
let leg = null;
|
|
1627
|
+
if (cfg.chunk === void 0) {
|
|
1628
|
+
leg = pickLeg(table, cfg.legs, opts.using);
|
|
1629
|
+
if (leg === null) {
|
|
1630
|
+
throw new Error(`recommend(${table}): tabloda vekt\xF6r kolonu yok \u2014 \xF6neri semantik vekt\xF6r ister (FR-023)`);
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
const live = await at();
|
|
1634
|
+
const sch = await vectorSchemaWithGuc(live);
|
|
1635
|
+
const bind = [];
|
|
1636
|
+
const add = (x) => {
|
|
1637
|
+
bind.push(x);
|
|
1638
|
+
return `$${bind.length}`;
|
|
1639
|
+
};
|
|
1640
|
+
const avgSel = (ids) => {
|
|
1641
|
+
const inList = ids.map((x) => add(x)).join(", ");
|
|
1642
|
+
return cfg.chunk !== void 0 ? `SELECT ${quoteIdent(sch)}.avg(c.embedding) AS v FROM ${quoteIdent(cfg.chunk.table)} c WHERE c.${quoteIdent(`parent_${cfg.pk}`)} IN (${inList}) AND c.embedding IS NOT NULL` : `SELECT ${quoteIdent(sch)}.avg(t.${quoteIdent(leg.column)}) AS v FROM ${quoteIdent(table)} t WHERE t.${quoteIdent(cfg.pk)} IN (${inList}) AND t.${quoteIdent(leg.column)} IS NOT NULL`;
|
|
1643
|
+
};
|
|
1644
|
+
const targetSql = negative.length === 0 ? `WITH pos AS (${avgSel(positive)}) SELECT pos.v AS v, (pos.v IS NULL) AS pos_missing FROM pos` : `WITH pos AS (${avgSel(positive)}), neg AS (${avgSel(negative)}) SELECT (pos.v OPERATOR(${quoteIdent(sch)}.+) (pos.v OPERATOR(${quoteIdent(sch)}.-) neg.v)) AS v, (pos.v IS NULL) AS pos_missing, (neg.v IS NULL) AS neg_missing FROM pos, neg`;
|
|
1645
|
+
const rows = await live.unsafe(targetSql, bind);
|
|
1646
|
+
const r0 = rows?.[0];
|
|
1647
|
+
if (r0 === void 0 || r0.pos_missing === true) {
|
|
1648
|
+
throw new Error(`recommend(${table}): positive id'lerin hi\xE7biri bulunamad\u0131 ya da embedding'i yok (FR-023)`);
|
|
1649
|
+
}
|
|
1650
|
+
if (negative.length > 0 && r0.neg_missing === true) {
|
|
1651
|
+
throw new Error(`recommend(${table}): negative id'leri bulunamad\u0131 ya da embedding'i yok (FR-023)`);
|
|
1652
|
+
}
|
|
1653
|
+
if (typeof r0.v !== "string") {
|
|
1654
|
+
throw new Error(`recommend(${table}): hedef vekt\xF6r hesaplanamad\u0131 (FR-023)`);
|
|
1655
|
+
}
|
|
1656
|
+
const p = {
|
|
1657
|
+
vector: JSON.parse(r0.v),
|
|
1658
|
+
mode: "vector",
|
|
1659
|
+
where: opts.where,
|
|
1660
|
+
limit: opts.limit,
|
|
1661
|
+
using: opts.using,
|
|
1662
|
+
minScore: opts.minScore,
|
|
1663
|
+
recency: opts.recency,
|
|
1664
|
+
blocksPerRow: opts.blocksPerRow,
|
|
1665
|
+
validity: opts.validity,
|
|
1666
|
+
boost: opts.boost,
|
|
1667
|
+
__excludeIds: [...positive, ...negative]
|
|
1668
|
+
};
|
|
1669
|
+
return ops.search(table, p);
|
|
1670
|
+
},
|
|
1671
|
+
/**
|
|
1672
|
+
* supersede (T021, FR-029, C-9): validity'li tabloda satırın YENİ
|
|
1673
|
+
* versiyonunu TEK savepoint'te yazar — eski satır kapatılır
|
|
1674
|
+
* (valid_to = now(), superseded_by = yeni pk), yeni satır eklenir, dönüş
|
|
1675
|
+
* yeni satırdır. Yeni pk CLIENT'ta üretilir (row'da verilmemişse
|
|
1676
|
+
* randomUUID — declared şemaların uuid().defaultRandom() standardı) ki
|
|
1677
|
+
* kapatma UPDATE'i INSERT'ten ÖNCE koşabilsin: 0 satır = zaten superseded
|
|
1678
|
+
* ya da yok → INSERT hiç denenmez; INSERT hatası ise savepoint'le
|
|
1679
|
+
* kapatmayı da geri sarar — yarım supersede diye bir durum yoktur.
|
|
1680
|
+
*/
|
|
1681
|
+
async supersede(table, id, row) {
|
|
1682
|
+
const cfg = searchConfigFor(table);
|
|
1683
|
+
if (cfg === null || cfg.validity !== true) {
|
|
1684
|
+
throw new Error(`supersede(${table}): tablo validity beyan\u0131 ta\u015F\u0131m\u0131yor (FR-029)`);
|
|
1685
|
+
}
|
|
1686
|
+
const live = await at();
|
|
1687
|
+
return live.savepoint(async (sp) => {
|
|
1688
|
+
const newId = row[cfg.pk] ?? crypto.randomUUID();
|
|
1689
|
+
const closed = await sp.unsafe(
|
|
1690
|
+
`UPDATE ${quoteIdent(table)} SET "valid_to" = now(), "superseded_by" = $1 WHERE ${quoteIdent(cfg.pk)} = $2 AND "valid_to" IS NULL RETURNING ${quoteIdent(cfg.pk)}`,
|
|
1691
|
+
[newId, id]
|
|
1692
|
+
);
|
|
1693
|
+
if (closed.length === 0) {
|
|
1694
|
+
throw new Error(`supersede(${table}): id "${String(id)}" zaten superseded ya da yok (FR-029)`);
|
|
1695
|
+
}
|
|
1696
|
+
const data = { ...row, [cfg.pk]: newId };
|
|
1697
|
+
const cols = Object.keys(data);
|
|
1698
|
+
const placeholders = cols.map((_, i) => `$${i + 1}`).join(", ");
|
|
1699
|
+
const rows = await sp.unsafe(
|
|
1700
|
+
`INSERT INTO ${quoteIdent(table)} (${cols.map(quoteIdent).join(", ")}) VALUES (${placeholders}) RETURNING *`,
|
|
1701
|
+
asBindParams(table, cols, data)
|
|
1702
|
+
);
|
|
1703
|
+
if (!rows[0]) {
|
|
1704
|
+
throw new Error(
|
|
1705
|
+
`supersede(${table}): INSERT sat\u0131r d\xF6nd\xFCrmedi \u2014 yazma reddedildi (b\xFCy\xFCk olas\u0131l\u0131kla bir RLS policy'si)`
|
|
1706
|
+
);
|
|
1707
|
+
}
|
|
1708
|
+
return asTableRow(table, rows[0]);
|
|
1709
|
+
});
|
|
1289
1710
|
},
|
|
1290
1711
|
/** A real SAVEPOINT inside the request's transaction. */
|
|
1291
1712
|
async transaction(cb) {
|
|
@@ -1329,6 +1750,7 @@ function createOps(tx) {
|
|
|
1329
1750
|
var currentSchema = {};
|
|
1330
1751
|
function setSchema(schema) {
|
|
1331
1752
|
cachedVectorSchema = null;
|
|
1753
|
+
cachedTrgmSchema = null;
|
|
1332
1754
|
const s = schema;
|
|
1333
1755
|
currentSchema = (s && "default" in s ? s.default : s) ?? {};
|
|
1334
1756
|
}
|
|
@@ -1736,7 +2158,6 @@ async function createApp(opts) {
|
|
|
1736
2158
|
Notifications: modules.Notifications ?? stubModule("Notifications"),
|
|
1737
2159
|
Flags: modules.Flags ?? stubModule("Flags"),
|
|
1738
2160
|
Realtime: modules.Realtime ?? stubModule("Realtime"),
|
|
1739
|
-
Purchases: modules.Purchases ?? stubModule("Purchases"),
|
|
1740
2161
|
// Named, never undefined. A backend started without a secrets client
|
|
1741
2162
|
// that returned `undefined` here would fail inside the handler as
|
|
1742
2163
|
// "Cannot read properties of undefined", which says nothing about what
|