chloedb 0.0.0-stage → 0.3.5

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/common.d.ts ADDED
@@ -0,0 +1,176 @@
1
+ /** A value ChloeDB stores or answers: an INT (a number, or a BigInt past
2
+ * 2^53), FLOAT, text or keyword, BOOL, a TIMESTAMP (ISO 8601 text in UTC),
3
+ * a vector (numbers), a list, or null. */
4
+ export type Value = null | boolean | number | bigint | string | Value[] | { [k: string]: Value };
5
+
6
+ /** A value written: what ChloeDB answers, and also `Date`s (TIMESTAMPs),
7
+ * typed arrays (vectors) and `Map`s (sparse term weights). */
8
+ export type Input = Value | Date | Float32Array | Float64Array | Int32Array | Map<string, number> | Input[] | { [k: string]: Input };
9
+
10
+ /** A row: field name to value. */
11
+ export type Row = Record<string, Input>;
12
+
13
+ /** Query parameters, `:name` in the SQL: values, `{embed: text, field?}`
14
+ * (the text's vector by an embedded field's model), `{embed: {image:
15
+ * base64}}`, or `{vector_of: key, field?}` (a stored row's vector). */
16
+ export type Params = Record<string, Input | { embed: string | { image: string } | { audio: string }; field?: string; table?: string } | { vector_of: Input; field?: string; table?: string }>;
17
+
18
+ /** A field of a schema in its short form. */
19
+ export interface Field {
20
+ name: string;
21
+ type: string;
22
+ [option: string]: unknown;
23
+ }
24
+
25
+ /** A table's schema in its short form. */
26
+ export interface Schema {
27
+ table: string;
28
+ key?: string;
29
+ fields: Field[];
30
+ [option: string]: unknown;
31
+ }
32
+
33
+ /** A plan of the plan IR, as `Database.plan` and `Client.explain` give it. */
34
+ export type Plan = Record<string, unknown>;
35
+
36
+ export declare class ChloeDBError extends Error {
37
+ constructor(message: string, options?: { status?: number; answer?: unknown; cause?: unknown; code?: ErrorCode });
38
+ /** The HTTP status, for an error a server answered. */
39
+ status?: number;
40
+ /** The server's answer, its JSON. */
41
+ answer?: unknown;
42
+ /** The error's stable code (see `errorCode`). */
43
+ code: ErrorCode;
44
+ }
45
+
46
+ /** A bad schema, query, value or request (400, 413, 422). Code "bad_request". */
47
+ export declare class BadRequestError extends ChloeDBError {}
48
+ /** No token, or one without the rights needed (401, 403). Code "unauthorized". */
49
+ export declare class UnauthorizedError extends ChloeDBError {}
50
+ /** No such row, table, route or cursor (404). Code "not_found". */
51
+ export declare class NotFoundError extends ChloeDBError {}
52
+ /** Refused by the state it met (409). Code "conflict". */
53
+ export declare class ConflictError extends ChloeDBError {}
54
+ /** A coordinator wrote some shards and not others. Code "partial_write". */
55
+ export declare class PartialWriteError extends ChloeDBError {}
56
+ /** The database is open elsewhere, or another writer holds it. Code "busy". */
57
+ export declare class BusyError extends ChloeDBError {}
58
+ /** Refused for the server's load before any work (429). Code "overloaded". */
59
+ export declare class OverloadedError extends ChloeDBError {}
60
+ /** A deadline passed (504, a query's timeoutMs). Code "timeout". */
61
+ export declare class DeadlineError extends ChloeDBError {}
62
+ /** No copy can serve it now (503). Code "unavailable". */
63
+ export declare class UnavailableError extends ChloeDBError {}
64
+
65
+ /** `ChloeDBError` by its name when ChloeDB was called Strata: the same class. */
66
+ export { ChloeDBError as StrataError };
67
+
68
+ /** A query's answer. Iterating gives each row as an object. */
69
+ export declare class Result<T extends Record<string, Value> = Record<string, Value>> implements Iterable<T> {
70
+ columns: string[];
71
+ rows: Value[][];
72
+ /** Each row's primary key. */
73
+ keys: Value[];
74
+ /** The score each row was ranked by. */
75
+ scores: (number | null)[];
76
+ /** What the engine did: segments, candidates, time per stage. */
77
+ stats: Record<string, unknown>;
78
+ /** The server's time for it, in milliseconds (`Client` only). */
79
+ tookMs?: number;
80
+ /** The request's id in the rank log (`queryLogged`). */
81
+ request?: string;
82
+ /** An interleaved query's: per row, the ranking that placed it. */
83
+ teams?: (string | null)[];
84
+ readonly length: number;
85
+ /** More rows matched than this answer holds, by a cut the query did not
86
+ * write: a ranked query without LIMIT, or a fused page past its candidates. */
87
+ readonly truncated: boolean;
88
+ /** The row count a ranked query without LIMIT was cut to (100). */
89
+ readonly implicitLimit: number | undefined;
90
+ /** Row `i` (negative counts from the end) as an object. */
91
+ at(i: number): T | undefined;
92
+ /** Every row as an object. */
93
+ objects(): T[];
94
+ /** One column's values. */
95
+ column(name: string): Value[];
96
+ /** The first column of the first row, or null: a count, a sum. */
97
+ scalar(): Value;
98
+ [Symbol.iterator](): Iterator<T>;
99
+ }
100
+
101
+ export interface SearchOptions {
102
+ limit?: number;
103
+ /** An SQL condition, with `params` for its placeholders. */
104
+ where?: string;
105
+ columns?: string | string[];
106
+ mode?: "auto" | "text" | "vector" | "hybrid";
107
+ textFields?: string[];
108
+ vectorField?: string;
109
+ params?: Params;
110
+ table?: string;
111
+ /** Through a `Client`: a write the answer must see ({@link ReadAfter}). */
112
+ minSeqNo?: number;
113
+ minSeqNos?: number[];
114
+ /** Its deadline in ms, as `query` takes it. */
115
+ timeoutMs?: number;
116
+ /** A `Database`'s only: a memory budget of its own, in bytes. */
117
+ memory?: number;
118
+ /** A `Database`'s only: stops it when it aborts. */
119
+ signal?: AbortSignal;
120
+ }
121
+
122
+ /** The writes a read must see: `minSeqNo`, the `seqNo` a server's write
123
+ * answered, or `minSeqNos`, the `seqNos` a coordinator's did (one per
124
+ * shard). The copy that answers holds them; a replica waits up to a second.
125
+ * A Database in this process ignores them: it reads every write. */
126
+ export interface ReadAfter {
127
+ minSeqNo?: number;
128
+ minSeqNos?: number[];
129
+ }
130
+
131
+ /** The stable code of an error, the same in this process, from a server
132
+ * and in chloedb-py: the server's JSON `code` when it gives one, else the
133
+ * kind the message starts with ("busy: ..."), else the HTTP status. */
134
+ export type ErrorCode = "bad_request" | "unauthorized" | "not_found" | "conflict" | "partial_write" | "busy" | "overloaded" | "timeout" | "memory" | "unavailable" | "corrupt" | "io" | "internal" | "error" | (string & {});
135
+
136
+ export declare function errorCode(message: string, status?: number, answer?: unknown): ErrorCode;
137
+
138
+ export interface LogOptions {
139
+ /** Whom it served: a user, a session. */
140
+ context?: string;
141
+ request?: string;
142
+ /** The ranking's name (an A/B arm). */
143
+ variant?: string;
144
+ /** Logs that many rows past the OFFSET. */
145
+ candidates?: number;
146
+ /** When it was served (a Date, or microseconds); now by default. */
147
+ ts?: Date | number;
148
+ table?: string;
149
+ /** A second SELECT, interleaved with the first by team draft. */
150
+ interleave?: string;
151
+ variants?: string[];
152
+ }
153
+
154
+ export interface ExportOptions {
155
+ table?: string;
156
+ events?: { table: string; user: string; item: string; time: string; action?: string };
157
+ history?: number;
158
+ window?: string | number;
159
+ grades?: Record<string, number>;
160
+ since?: Date | number;
161
+ until?: Date | number;
162
+ }
163
+
164
+ /** What `Database` and `Client` share. */
165
+ export declare abstract class Searchable {
166
+ abstract schema(table?: string): Promise<Schema>;
167
+ abstract tables(): Promise<Schema[]>;
168
+ abstract query(sql: string, params?: Params | null): Promise<Result>;
169
+ /** The rows that best match `text`: BM25 over the text fields, the
170
+ * similarity of an embedded vector field, or both fused by RRF. */
171
+ search(text: string, options?: SearchOptions): Promise<Result>;
172
+ /** Runs a SELECT ranked by an ORDER BY and logs what it served. */
173
+ queryLogged(sql: string, params?: Params | null, options?: LogOptions): Promise<Result>;
174
+ /** The log table's rows as records for training. */
175
+ exportRankLog(options?: ExportOptions): Promise<Record<string, Value>[]>;
176
+ }
package/common.js ADDED
@@ -0,0 +1,359 @@
1
+ // What `Database` (index.js, the database in this process) and `Client`
2
+ // (client.js, chloedb-server over HTTP) share: errors, answers, JSON with
3
+ // 64-bit integers, and `search` and the rank log on top of `query`.
4
+ //
5
+ // This module runs anywhere JavaScript does: it imports nothing.
6
+
7
+ /** An error from the database: a bad schema, query, value or file, or an
8
+ * error a server answered (`status`, the HTTP status, and `answer`, its
9
+ * JSON, are set then). */
10
+ export class ChloeDBError extends Error {
11
+ constructor(message, { status, answer, cause, code } = {}) {
12
+ super(message, cause === undefined ? undefined : { cause });
13
+ this.name = "ChloeDBError";
14
+ if (status !== undefined) this.status = status;
15
+ if (answer !== undefined) this.answer = answer;
16
+ /** The error's stable code (see `errorCode`). */
17
+ this.code = code ?? errorCode(String(message ?? ""), status, answer);
18
+ }
19
+ }
20
+
21
+ /** `ChloeDBError` by its name when ChloeDB was called Strata: the same
22
+ * class, so `instanceof` either one holds for every error. */
23
+ export const StrataError = ChloeDBError;
24
+
25
+ // The engine's message prefixes (chloedb::Error's Display), and their codes.
26
+ const PREFIXES = [
27
+ ["busy:", "busy"],
28
+ ["timeout:", "timeout"],
29
+ ["memory:", "memory"],
30
+ ["unavailable:", "unavailable"],
31
+ ["corrupt database:", "corrupt"],
32
+ ["I/O error:", "io"],
33
+ ["schema error:", "bad_request"],
34
+ ["query error:", "bad_request"],
35
+ ];
36
+ const STATUSES = { 400: "bad_request", 401: "unauthorized", 403: "unauthorized", 404: "not_found", 408: "timeout", 409: "conflict", 413: "bad_request", 422: "bad_request", 429: "overloaded", 503: "unavailable", 504: "timeout" };
37
+
38
+ /**
39
+ * The stable code of an error, the same in this process and from a server
40
+ * (and in chloedb-py): the server's JSON `code` when it gives one, else
41
+ * "partial_write" for a coordinator's partial write, else the kind the
42
+ * message starts with ("busy: ...", as the engine words its errors), else
43
+ * the HTTP status. One of "bad_request", "unauthorized", "not_found",
44
+ * "conflict", "partial_write", "busy", "overloaded", "timeout", "memory",
45
+ * "unavailable", "corrupt", "io", "internal" (another 5xx) and "error".
46
+ */
47
+ export function errorCode(message, status, answer) {
48
+ if (answer && typeof answer === "object") {
49
+ if (typeof answer.code === "string" && answer.code) return answer.code;
50
+ if (answer.partial === true) return "partial_write";
51
+ }
52
+ const text = String(message).trimStart();
53
+ for (const [prefix, code] of PREFIXES) if (text.startsWith(prefix)) return code;
54
+ if (status != null) return STATUSES[status] ?? (status >= 500 ? "internal" : "error");
55
+ return "error";
56
+ }
57
+
58
+ function subclass(name) {
59
+ const C = class extends ChloeDBError {
60
+ constructor(message, options) {
61
+ super(message, options);
62
+ this.name = name;
63
+ }
64
+ };
65
+ Object.defineProperty(C, "name", { value: name });
66
+ return C;
67
+ }
68
+
69
+ /** A bad schema, query, value or request (400, 413, 422). */
70
+ export const BadRequestError = subclass("BadRequestError");
71
+ /** No token, or one without the rights the request needs (401, 403). */
72
+ export const UnauthorizedError = subclass("UnauthorizedError");
73
+ /** No such row, table, route or cursor (404). */
74
+ export const NotFoundError = subclass("NotFoundError");
75
+ /** Refused by the state it met (409): a conditional write's `ifSeqNo`, an
76
+ * idempotency key still running, a read past the server's last write. */
77
+ export const ConflictError = subclass("ConflictError");
78
+ /** A coordinator wrote some shards and not others: send it again with the
79
+ * same idempotency key. */
80
+ export const PartialWriteError = subclass("PartialWriteError");
81
+ /** The database is open elsewhere, or another writer holds it. */
82
+ export const BusyError = subclass("BusyError");
83
+ /** Refused for the server's load before any work (429). */
84
+ export const OverloadedError = subclass("OverloadedError");
85
+ /** A deadline passed: a query's `timeoutMs`, a coordinator's wait (504). */
86
+ export const DeadlineError = subclass("DeadlineError");
87
+ /** No copy can serve it now (503). */
88
+ export const UnavailableError = subclass("UnavailableError");
89
+
90
+ const ERRORS = {
91
+ bad_request: BadRequestError,
92
+ unauthorized: UnauthorizedError,
93
+ not_found: NotFoundError,
94
+ conflict: ConflictError,
95
+ partial_write: PartialWriteError,
96
+ busy: BusyError,
97
+ overloaded: OverloadedError,
98
+ timeout: DeadlineError,
99
+ unavailable: UnavailableError,
100
+ };
101
+
102
+ /** A ChloeDBError of the class its code names. */
103
+ export function makeError(message, options = {}) {
104
+ const code = options.code ?? errorCode(String(message), options.status, options.answer);
105
+ return new (ERRORS[code] ?? ChloeDBError)(message, { ...options, code });
106
+ }
107
+
108
+ // ---------------------------------------------------------------- JSON
109
+
110
+ // A BigInt has no JSON form: it is written as this marker in a string,
111
+ // which `encode` then replaces with its digits.
112
+ const BIG = "\u0000strata-bigint:";
113
+ const BIG_TEXT = /"\\u0000strata-bigint:(-?\d+)"/g;
114
+
115
+ function replacer(_key, v) {
116
+ if (typeof v === "bigint") return BIG + v.toString();
117
+ if (ArrayBuffer.isView(v) && !(v instanceof DataView)) return Array.from(v);
118
+ if (v instanceof Map) return Object.fromEntries(v);
119
+ if (v instanceof Set) return Array.from(v);
120
+ return v;
121
+ }
122
+
123
+ /** A value as JSON text, as ChloeDB reads it: typed arrays (`Float32Array`)
124
+ * become arrays of numbers, a `Map` an object, a `Date` ISO 8601 text, and
125
+ * a BigInt a JSON integer, whole (a 64-bit key). */
126
+ export function encode(value) {
127
+ const s = JSON.stringify(value === undefined ? null : value, replacer);
128
+ return s.includes("strata-bigint:") ? s.replace(BIG_TEXT, "$1") : s;
129
+ }
130
+
131
+ // Whether JSON.parse hands a reviver the number's text (V8 since Node 21,
132
+ // recent browsers): then integers past 2^53 can come back whole.
133
+ const SOURCE_TEXT = (() => {
134
+ try {
135
+ let ok = false;
136
+ JSON.parse("1", (_k, v, c) => {
137
+ ok = c?.source === "1";
138
+ return v;
139
+ });
140
+ return ok;
141
+ } catch {
142
+ return false;
143
+ }
144
+ })();
145
+
146
+ const LONG_DIGITS = /\d{16}/;
147
+ const INTEGER = /^-?\d+$/;
148
+
149
+ function reviver(_key, v, c) {
150
+ return typeof v === "number" && !Number.isSafeInteger(v) && c?.source && INTEGER.test(c.source) ? BigInt(c.source) : v;
151
+ }
152
+
153
+ /** JSON text as values: an integer that a number cannot hold exactly (past
154
+ * 2^53, a 64-bit key) as a BigInt, where the runtime tells its digits. */
155
+ export function decode(text) {
156
+ if (text === "" || text === undefined || text === null) return null;
157
+ return SOURCE_TEXT && LONG_DIGITS.test(text) ? JSON.parse(text, reviver) : JSON.parse(text);
158
+ }
159
+
160
+ // ---------------------------------------------------------------- answers
161
+
162
+ /** A query's answer: `columns`, `rows` (arrays of values in column order),
163
+ * each row's primary key in `keys` and the score it was ranked by in
164
+ * `scores`, and what the engine did in `stats`.
165
+ *
166
+ * Iterating gives each row as an object of column to value; `at(i)` is row
167
+ * `i` as one, and `length` the number of rows. */
168
+ export class Result {
169
+ constructor({ columns = [], rows = [], keys = [], scores = [], stats = {}, took_ms, request, teams } = {}) {
170
+ this.columns = columns;
171
+ this.rows = rows;
172
+ this.keys = keys ?? [];
173
+ this.scores = scores ?? [];
174
+ this.stats = stats ?? {};
175
+ /** The server's time for it, in milliseconds (`Client` only). */
176
+ this.tookMs = took_ms;
177
+ /** The request's id in the rank log (`queryLogged`). */
178
+ this.request = request;
179
+ /** An interleaved query's: per row, the ranking that placed it. */
180
+ this.teams = teams;
181
+ }
182
+
183
+ get length() {
184
+ return this.rows.length;
185
+ }
186
+
187
+ /** More rows matched than this answer holds, by a cut the query did not
188
+ * write: a ranked query without LIMIT (`implicitLimit`), or a page of a
189
+ * fused ranking past its candidates. */
190
+ get truncated() {
191
+ return this.stats?.truncated === true;
192
+ }
193
+
194
+ /** The row count a ranked query without LIMIT was cut to (100), or
195
+ * undefined when the query gave its own LIMIT. */
196
+ get implicitLimit() {
197
+ return this.stats?.implicit_limit ?? undefined;
198
+ }
199
+
200
+ #object(r) {
201
+ const o = {};
202
+ for (let i = 0; i < this.columns.length; i++) o[this.columns[i]] = r[i];
203
+ return o;
204
+ }
205
+
206
+ /** Row `i` (negative counts from the end) as an object, or undefined. */
207
+ at(i) {
208
+ const r = this.rows.at(i);
209
+ return r === undefined ? undefined : this.#object(r);
210
+ }
211
+
212
+ *[Symbol.iterator]() {
213
+ for (const r of this.rows) yield this.#object(r);
214
+ }
215
+
216
+ /** Every row as an object of column to value. */
217
+ objects() {
218
+ return this.rows.map((r) => this.#object(r));
219
+ }
220
+
221
+ /** One column's values. */
222
+ column(name) {
223
+ const i = this.columns.indexOf(name);
224
+ if (i < 0) throw new ChloeDBError(`no column ${name}: the columns are ${this.columns.join(", ")}`);
225
+ return this.rows.map((r) => r[i]);
226
+ }
227
+
228
+ /** The first column of the first row (null if there is none): a count, a
229
+ * sum. */
230
+ scalar() {
231
+ return this.rows[0]?.[0] ?? null;
232
+ }
233
+
234
+ toJSON() {
235
+ return { columns: this.columns, rows: this.rows, keys: this.keys, scores: this.scores, stats: this.stats };
236
+ }
237
+ }
238
+
239
+ /** A read's `Result`, or the number of rows a write wrote. */
240
+ export function resultOrWritten(a) {
241
+ return a && "rows" in a ? new Result(a) : Number(a.written);
242
+ }
243
+
244
+ // ---------------------------------------------------------------- shared
245
+
246
+ /** The short schema form in reading order: table, key, the table's
247
+ * options, fields, and each field's name and type first. */
248
+ export function orderedSchema(s) {
249
+ const out = { table: s.table };
250
+ for (const k of ["key", "shard_by", "cluster_by", "retain", "retain_by", "edges"]) {
251
+ if (s[k] !== undefined && s[k] !== null) out[k] = s[k];
252
+ }
253
+ out.fields = s.fields.map((f) => ({ name: f.name, type: f.type, ...f }));
254
+ return out;
255
+ }
256
+
257
+ /** A name as an SQL identifier, whatever it is. */
258
+ export function quote(name) {
259
+ return '"' + String(name).replace(/"/g, '""') + '"';
260
+ }
261
+
262
+ /** A table's name in SQL: as it is when it is a plain name, else quoted. */
263
+ export function ident(name) {
264
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ? name : quote(name);
265
+ }
266
+
267
+ /** Leaves out the entries whose value is undefined or null. */
268
+ export function given(o) {
269
+ const out = {};
270
+ for (const [k, v] of Object.entries(o)) if (v !== undefined && v !== null) out[k] = v;
271
+ return out;
272
+ }
273
+
274
+ function time(t) {
275
+ return t instanceof Date ? t.toISOString() : t;
276
+ }
277
+
278
+ /** `search` and the rank log, shared by `Database` and `Client`, which give
279
+ * `schema()`, `tables()`, `_embedded()` (the embedded vector fields whose
280
+ * model is open), `query`, `_queryLogged` and `_exportRankLog`. */
281
+ export class Searchable {
282
+ /**
283
+ * Runs a SELECT ranked by an ORDER BY and logs what it served to a log
284
+ * table, for training on later: one row per row answered, with its
285
+ * position, its score and the values its ranking read (`features()`).
286
+ * `result.request` is the request's id, which labels its rows later.
287
+ */
288
+ async queryLogged(sql, params = null, { context, request, variant, candidates, ts, table = "rank_log", interleave, variants } = {}) {
289
+ const il = interleave == null ? undefined : given({ sql: interleave, variants: variants?.length ? [...variants] : undefined });
290
+ const log = given({ table, request, context, variant, candidates, ts: time(ts), interleave: il });
291
+ return this._queryLogged(sql, params, log);
292
+ }
293
+
294
+ /** The log table's rows as records for training, from one snapshot, each
295
+ * context's in the order served: the row's columns, `features` as
296
+ * served, and `label` (see chloedb-py's `export_rank_log`). */
297
+ async exportRankLog({ table = "rank_log", events, history = 0, window, grades, since, until } = {}) {
298
+ return this._exportRankLog(given({ table, events, history, window, grades, since: time(since), until: time(until) }));
299
+ }
300
+
301
+ /**
302
+ * The rows that best match `text`.
303
+ *
304
+ * `mode` "text" ranks by BM25 over the text fields, "vector" by the
305
+ * similarity of an embedded vector field to the text's embedding, and
306
+ * "hybrid" fuses both by reciprocal rank (RRF). "auto" is hybrid when the
307
+ * table has an embedded field whose model is open here, and text
308
+ * otherwise. `where` is an SQL condition, with `params` for its
309
+ * placeholders. `timeoutMs` bounds it as `query` takes it; a `Database`
310
+ * also takes `memory` and `signal`, as its `query` does.
311
+ */
312
+ async search(text, { limit = 10, where, columns = "*", mode = "auto", textFields, vectorField, params, table, minSeqNo, minSeqNos, timeoutMs, memory, signal } = {}) {
313
+ // A client's query takes timeoutMs alone: a server's queries share its
314
+ // memory budget.
315
+ if ((memory != null || signal != null) && !this._local) throw new TypeError(`${this.constructor.name}.search() takes no ${memory != null ? "memory" : "signal"}`);
316
+ const s = await this.schema(table);
317
+ if (textFields == null) {
318
+ const texts = s.fields.filter((f) => f.type === "text" && (f.indexed ?? true));
319
+ const generated = texts.filter((f) => f.from).map((f) => f.name);
320
+ textFields = generated.length ? generated : texts.map((f) => f.name);
321
+ }
322
+ textFields = [...textFields];
323
+ if (vectorField == null) {
324
+ const embedded = await this._embedded(s.table);
325
+ vectorField = embedded[0] ?? null;
326
+ }
327
+ if (mode === "auto") mode = vectorField && textFields.length ? "hybrid" : vectorField ? "vector" : "text";
328
+ if (!["text", "vector", "hybrid"].includes(mode)) throw new ChloeDBError('mode is "auto", "text", "vector" or "hybrid"');
329
+ const scores = [];
330
+ if (mode === "text" || mode === "hybrid") {
331
+ if (!textFields.length) throw new ChloeDBError(`${s.table} has no indexed text field to search`);
332
+ for (const f of textFields) scores.push(`bm25(${quote(f)}, :_q)`);
333
+ }
334
+ if (mode === "vector" || mode === "hybrid") {
335
+ if (!vectorField) throw new ChloeDBError(`${s.table} has no embedded vector field with its model open`);
336
+ scores.push(`similarity(${quote(vectorField)}, :_v)`);
337
+ }
338
+ const fields = new Set(s.fields.map((f) => f.name.toLowerCase()));
339
+ const name = (c) => (fields.has(c.toLowerCase()) ? quote(c) : c);
340
+ const cols = typeof columns === "string" ? columns : [...columns].map((c) => name(c.trim())).join(", ");
341
+ const order = scores.length === 1 ? scores[0] : `rrf(${scores.join(", ")})`;
342
+ let sql = `SELECT ${cols} FROM ${ident(s.table)}`;
343
+ if (where != null && String(where).trim()) sql += ` WHERE ${where}`;
344
+ sql += ` ORDER BY ${order} DESC LIMIT ${Math.trunc(Number(limit))}`;
345
+ const p = { ...(params ?? {}) };
346
+ if (order.includes("bm25")) p._q = text;
347
+ if (order.includes("similarity")) p._v = { embed: text, field: vectorField, ...(table == null ? {} : { table: s.table }) };
348
+ const opts = Object.fromEntries(Object.entries({ minSeqNo, minSeqNos, timeoutMs, memory, signal }).filter(([, v]) => v != null));
349
+ return Object.keys(opts).length ? this.query(sql, p, opts) : this.query(sql, p);
350
+ }
351
+ }
352
+
353
+ /** The schema of `table` (any case) among `tables`, or the first. */
354
+ export function pickTable(tables, table) {
355
+ if (table == null) return tables[0];
356
+ const t = tables.find((t) => t.table.toLowerCase() === String(table).toLowerCase());
357
+ if (!t) throw new ChloeDBError(`no such table: ${table}`);
358
+ return t;
359
+ }