@mistriwork/search-postgres 1.2.1 → 1.3.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.
|
@@ -4,10 +4,11 @@ export declare class PostgresTsvectorIndex implements SearchIndex {
|
|
|
4
4
|
private readonly connectionString;
|
|
5
5
|
readonly collectionPrefix: string;
|
|
6
6
|
private pool;
|
|
7
|
+
private poolOpening;
|
|
7
8
|
/** The searchable fields each table held when last read; see `readFields` for when it is read again. */
|
|
8
9
|
private readonly fields;
|
|
9
10
|
constructor(connectionString: string, collectionPrefix: string);
|
|
10
|
-
/** The pool, opened on first use, never at plug-in, so a deployment that declares the connection but serves no searched App never connects. */
|
|
11
|
+
/** The pool, opened on first use with single-flight coalescing, never at plug-in, so a deployment that declares the connection but serves no searched App never connects. */
|
|
11
12
|
private db;
|
|
12
13
|
/** Ends the pool; the next call reopens it. For tests and shutdown — the index itself is tables in Postgres and survives. */
|
|
13
14
|
close(): Promise<void>;
|
|
@@ -15,6 +16,8 @@ export declare class PostgresTsvectorIndex implements SearchIndex {
|
|
|
15
16
|
ensureCollection(name: string, fields: readonly string[]): Promise<void>;
|
|
16
17
|
/** The record's document, replacing the document its tenant and key already had; a document whose collection was never ensured is ensured from its own fields. */
|
|
17
18
|
upsert(collection: string, document: SearchDocument): Promise<void>;
|
|
19
|
+
/** Bulk upsert documents in chunks using multi-row INSERT ... ON CONFLICT DO UPDATE. */
|
|
20
|
+
upsertBatch(collection: string, documents: readonly SearchDocument[]): Promise<void>;
|
|
18
21
|
/**
|
|
19
22
|
* Gone from the index; a document that was never there is gone already, and a collection never ensured holds
|
|
20
23
|
* nothing — as does a name the index cannot hold. With a tenant scope only that tenant's document goes; without
|
package/dist/postgresTsvector.js
CHANGED
|
@@ -114,6 +114,8 @@ const vectorColumn = (field) => `${field}__tsv`;
|
|
|
114
114
|
const indexName = (table, field) => bounded(`${table}_${field}__tsv_idx`);
|
|
115
115
|
/** The unique index that keys a document by its tenant and its id; an untenanted record keys on the empty tenant. */
|
|
116
116
|
const keyIndexSql = (table) => `CREATE UNIQUE INDEX IF NOT EXISTS "${bounded(`${table}__key_idx`)}" ON "${table}" ("id", (coalesce("${TENANT_FIELD}", '')))`;
|
|
117
|
+
/** Tenant equality index so tenant-scoped searches filter by tenant before scanning GIN matches. */
|
|
118
|
+
const tenantIndexSql = (table) => `CREATE INDEX IF NOT EXISTS "${bounded(`${table}__tenant_idx`)}" ON "${table}" ("${TENANT_FIELD}")`;
|
|
117
119
|
/** The searchable fields of a declaration: word characters, without the reserved names, without repeats. */
|
|
118
120
|
const searchableFields = (fields) => {
|
|
119
121
|
const wanted = [];
|
|
@@ -181,21 +183,34 @@ export class PostgresTsvectorIndex {
|
|
|
181
183
|
connectionString;
|
|
182
184
|
collectionPrefix;
|
|
183
185
|
pool;
|
|
186
|
+
poolOpening;
|
|
184
187
|
/** The searchable fields each table held when last read; see `readFields` for when it is read again. */
|
|
185
188
|
fields = new Map();
|
|
186
189
|
constructor(connectionString, collectionPrefix) {
|
|
187
190
|
this.connectionString = connectionString;
|
|
188
191
|
this.collectionPrefix = collectionPrefix;
|
|
189
192
|
}
|
|
190
|
-
/** The pool, opened on first use, never at plug-in, so a deployment that declares the connection but serves no searched App never connects. */
|
|
193
|
+
/** The pool, opened on first use with single-flight coalescing, never at plug-in, so a deployment that declares the connection but serves no searched App never connects. */
|
|
191
194
|
async db() {
|
|
192
|
-
if (
|
|
193
|
-
this.pool
|
|
194
|
-
|
|
195
|
+
if (this.pool)
|
|
196
|
+
return this.pool;
|
|
197
|
+
if (!this.poolOpening) {
|
|
198
|
+
this.poolOpening = openPool(this.connectionString)
|
|
199
|
+
.then((opened) => {
|
|
200
|
+
this.pool = opened;
|
|
201
|
+
return opened;
|
|
202
|
+
})
|
|
203
|
+
.finally(() => {
|
|
204
|
+
this.poolOpening = undefined;
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
return this.poolOpening;
|
|
195
208
|
}
|
|
196
209
|
/** Ends the pool; the next call reopens it. For tests and shutdown — the index itself is tables in Postgres and survives. */
|
|
197
210
|
async close() {
|
|
198
|
-
const
|
|
211
|
+
const opening = this.poolOpening;
|
|
212
|
+
this.poolOpening = undefined;
|
|
213
|
+
const pool = this.pool ?? (opening ? await opening.catch(() => undefined) : undefined);
|
|
199
214
|
this.pool = undefined;
|
|
200
215
|
this.fields.clear();
|
|
201
216
|
if (pool)
|
|
@@ -210,6 +225,7 @@ export class PostgresTsvectorIndex {
|
|
|
210
225
|
if (!held) {
|
|
211
226
|
await pool.query(createTableSql(table, wanted, true));
|
|
212
227
|
await pool.query(keyIndexSql(table));
|
|
228
|
+
await pool.query(tenantIndexSql(table));
|
|
213
229
|
for (const field of wanted) {
|
|
214
230
|
await pool.query(`CREATE INDEX IF NOT EXISTS "${indexName(table, field)}" ON "${table}" USING gin ("${vectorColumn(field)}")`);
|
|
215
231
|
}
|
|
@@ -239,6 +255,7 @@ export class PostgresTsvectorIndex {
|
|
|
239
255
|
await client.query(`DROP TABLE "${table}"`);
|
|
240
256
|
await client.query(`ALTER TABLE "${temp}" RENAME TO "${table}"`);
|
|
241
257
|
await client.query(keyIndexSql(table));
|
|
258
|
+
await client.query(tenantIndexSql(table));
|
|
242
259
|
for (const field of next) {
|
|
243
260
|
await client.query(`CREATE INDEX IF NOT EXISTS "${indexName(table, field)}" ON "${table}" USING gin ("${vectorColumn(field)}")`);
|
|
244
261
|
}
|
|
@@ -279,6 +296,51 @@ export class PostgresTsvectorIndex {
|
|
|
279
296
|
await pool.query(`INSERT INTO "${table}"(${quoted(columns)}) VALUES (${placeholders.join(', ')}) ON CONFLICT ("id", (coalesce("${TENANT_FIELD}", ''))) DO UPDATE SET ${sets}`, values);
|
|
280
297
|
});
|
|
281
298
|
}
|
|
299
|
+
/** Bulk upsert documents in chunks using multi-row INSERT ... ON CONFLICT DO UPDATE. */
|
|
300
|
+
async upsertBatch(collection, documents) {
|
|
301
|
+
if (!documents.length)
|
|
302
|
+
return;
|
|
303
|
+
if (documents.length === 1)
|
|
304
|
+
return this.upsert(collection, documents[0]);
|
|
305
|
+
const table = collectionTable(collection, this.collectionPrefix);
|
|
306
|
+
const fieldSet = new Set();
|
|
307
|
+
for (const doc of documents) {
|
|
308
|
+
for (const key of Object.keys(doc))
|
|
309
|
+
if (key !== 'id' && key !== TENANT_FIELD)
|
|
310
|
+
fieldSet.add(key);
|
|
311
|
+
}
|
|
312
|
+
await this.ensureCollection(table, [...fieldSet]);
|
|
313
|
+
const pool = await this.db();
|
|
314
|
+
/* Deduplicate by (id, tenant) within the batch so ON CONFLICT DO UPDATE never affects the same row twice in one statement. */
|
|
315
|
+
const deduped = new Map();
|
|
316
|
+
for (const doc of documents)
|
|
317
|
+
deduped.set(`${doc[TENANT_FIELD] ?? ''}\0${doc.id}`, doc);
|
|
318
|
+
const uniqueDocs = [...deduped.values()];
|
|
319
|
+
await this.afresh(async (fresh) => {
|
|
320
|
+
const held = (await this.readFields(table, fresh)) ?? [];
|
|
321
|
+
const columns = ['id', ...held, TENANT_FIELD];
|
|
322
|
+
const sets = columns
|
|
323
|
+
.filter((column) => column !== 'id')
|
|
324
|
+
.map((column) => `"${column}" = EXCLUDED."${column}"`)
|
|
325
|
+
.join(', ');
|
|
326
|
+
const chunkSize = Math.max(1, Math.min(100, Math.floor(10_000 / Math.max(1, columns.length))));
|
|
327
|
+
for (let start = 0; start < uniqueDocs.length; start += chunkSize) {
|
|
328
|
+
const batch = uniqueDocs.slice(start, start + chunkSize);
|
|
329
|
+
const values = [];
|
|
330
|
+
const tuples = [];
|
|
331
|
+
let param = 1;
|
|
332
|
+
for (const doc of batch) {
|
|
333
|
+
const placeholders = [];
|
|
334
|
+
for (const column of columns) {
|
|
335
|
+
values.push(column === 'id' ? doc.id : (doc[column] ?? null));
|
|
336
|
+
placeholders.push(`$${param++}`);
|
|
337
|
+
}
|
|
338
|
+
tuples.push(`(${placeholders.join(', ')})`);
|
|
339
|
+
}
|
|
340
|
+
await pool.query(`INSERT INTO "${table}"(${quoted(columns)}) VALUES ${tuples.join(', ')} ON CONFLICT ("id", (coalesce("${TENANT_FIELD}", ''))) DO UPDATE SET ${sets}`, values);
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
}
|
|
282
344
|
/**
|
|
283
345
|
* Gone from the index; a document that was never there is gone already, and a collection never ensured holds
|
|
284
346
|
* nothing — as does a name the index cannot hold. With a tenant scope only that tenant's document goes; without
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mistriwork/search-postgres",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.1",
|
|
4
4
|
"description": "PostgreSQL tsvector + GIN search provider pack for mistri Apps, living beside your deployment's PostgreSQL database.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"mistri",
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
}
|
|
35
35
|
},
|
|
36
36
|
"peerDependencies": {
|
|
37
|
-
"@mistriwork/mistri": "1.
|
|
37
|
+
"@mistriwork/mistri": "1.3.1",
|
|
38
38
|
"pg": "^8.0.0"
|
|
39
39
|
},
|
|
40
40
|
"peerDependenciesMeta": {
|