@mastra/pg 0.0.0-commonjs-20250227130920

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 ADDED
@@ -0,0 +1,1035 @@
1
+ import { MastraVector } from '@mastra/core/vector';
2
+ import pg from 'pg';
3
+ import { BaseFilterTranslator } from '@mastra/core/filter';
4
+ import { MastraStorage } from '@mastra/core/storage';
5
+ import pgPromise from 'pg-promise';
6
+
7
+ // src/vector/index.ts
8
+ var PGFilterTranslator = class extends BaseFilterTranslator {
9
+ getSupportedOperators() {
10
+ return {
11
+ ...BaseFilterTranslator.DEFAULT_OPERATORS,
12
+ custom: ["$contains", "$size"]
13
+ };
14
+ }
15
+ translate(filter) {
16
+ if (this.isEmpty(filter)) {
17
+ return filter;
18
+ }
19
+ this.validateFilter(filter);
20
+ return this.translateNode(filter);
21
+ }
22
+ translateNode(node, currentPath = "") {
23
+ const withPath = (result2) => currentPath ? { [currentPath]: result2 } : result2;
24
+ if (this.isPrimitive(node)) {
25
+ return withPath({ $eq: this.normalizeComparisonValue(node) });
26
+ }
27
+ if (Array.isArray(node)) {
28
+ return withPath({ $in: this.normalizeArrayValues(node) });
29
+ }
30
+ if (node instanceof RegExp) {
31
+ return withPath(this.translateRegexPattern(node.source, node.flags));
32
+ }
33
+ const entries = Object.entries(node);
34
+ const result = {};
35
+ if ("$options" in node && !("$regex" in node)) {
36
+ throw new Error("$options is not valid without $regex");
37
+ }
38
+ if ("$regex" in node) {
39
+ const options = node.$options || "";
40
+ return withPath(this.translateRegexPattern(node.$regex, options));
41
+ }
42
+ for (const [key, value] of entries) {
43
+ if (key === "$options") continue;
44
+ const newPath = currentPath ? `${currentPath}.${key}` : key;
45
+ if (this.isLogicalOperator(key)) {
46
+ result[key] = Array.isArray(value) ? value.map((filter) => this.translateNode(filter)) : this.translateNode(value);
47
+ } else if (this.isOperator(key)) {
48
+ if (this.isArrayOperator(key) && !Array.isArray(value) && key !== "$elemMatch") {
49
+ result[key] = [value];
50
+ } else if (this.isBasicOperator(key) && Array.isArray(value)) {
51
+ result[key] = JSON.stringify(value);
52
+ } else {
53
+ result[key] = value;
54
+ }
55
+ } else if (typeof value === "object" && value !== null) {
56
+ const hasOperators = Object.keys(value).some((k) => this.isOperator(k));
57
+ if (hasOperators) {
58
+ result[newPath] = this.translateNode(value);
59
+ } else {
60
+ Object.assign(result, this.translateNode(value, newPath));
61
+ }
62
+ } else {
63
+ result[newPath] = this.translateNode(value);
64
+ }
65
+ }
66
+ return result;
67
+ }
68
+ translateRegexPattern(pattern, options = "") {
69
+ if (!options) return { $regex: pattern };
70
+ const flags = options.split("").filter((f) => "imsux".includes(f)).join("");
71
+ return { $regex: flags ? `(?${flags})${pattern}` : pattern };
72
+ }
73
+ };
74
+
75
+ // src/vector/sql-builder.ts
76
+ var createBasicOperator = (symbol) => {
77
+ return (key, paramIndex) => ({
78
+ sql: `CASE
79
+ WHEN $${paramIndex}::text IS NULL THEN metadata#>>'{${handleKey(key)}}' IS ${symbol === "=" ? "" : "NOT"} NULL
80
+ ELSE metadata#>>'{${handleKey(key)}}' ${symbol} $${paramIndex}::text
81
+ END`,
82
+ needsValue: true
83
+ });
84
+ };
85
+ var createNumericOperator = (symbol) => {
86
+ return (key, paramIndex) => ({
87
+ sql: `(metadata#>>'{${handleKey(key)}}')::numeric ${symbol} $${paramIndex}`,
88
+ needsValue: true
89
+ });
90
+ };
91
+ function buildElemMatchConditions(value, paramIndex) {
92
+ if (typeof value !== "object" || Array.isArray(value)) {
93
+ throw new Error("$elemMatch requires an object with conditions");
94
+ }
95
+ const conditions = [];
96
+ const values = [];
97
+ Object.entries(value).forEach(([field, val]) => {
98
+ const nextParamIndex = paramIndex + values.length;
99
+ let paramOperator;
100
+ let paramKey;
101
+ let paramValue;
102
+ if (field.startsWith("$")) {
103
+ paramOperator = field;
104
+ paramKey = "";
105
+ paramValue = val;
106
+ } else if (typeof val === "object" && !Array.isArray(val)) {
107
+ const [op, opValue] = Object.entries(val || {})[0] || [];
108
+ paramOperator = op;
109
+ paramKey = field;
110
+ paramValue = opValue;
111
+ } else {
112
+ paramOperator = "$eq";
113
+ paramKey = field;
114
+ paramValue = val;
115
+ }
116
+ const operatorFn = FILTER_OPERATORS[paramOperator];
117
+ if (!operatorFn) {
118
+ throw new Error(`Invalid operator: ${paramOperator}`);
119
+ }
120
+ const result = operatorFn(paramKey, nextParamIndex, paramValue);
121
+ const sql = result.sql.replaceAll("metadata#>>", "elem#>>");
122
+ conditions.push(sql);
123
+ if (result.needsValue) {
124
+ values.push(paramValue);
125
+ }
126
+ });
127
+ return {
128
+ sql: conditions.join(" AND "),
129
+ values
130
+ };
131
+ }
132
+ var FILTER_OPERATORS = {
133
+ $eq: createBasicOperator("="),
134
+ $ne: createBasicOperator("!="),
135
+ $gt: createNumericOperator(">"),
136
+ $gte: createNumericOperator(">="),
137
+ $lt: createNumericOperator("<"),
138
+ $lte: createNumericOperator("<="),
139
+ // Array Operators
140
+ $in: (key, paramIndex) => ({
141
+ sql: `metadata#>>'{${handleKey(key)}}' = ANY($${paramIndex}::text[])`,
142
+ needsValue: true
143
+ }),
144
+ $nin: (key, paramIndex) => ({
145
+ sql: `metadata#>>'{${handleKey(key)}}' != ALL($${paramIndex}::text[])`,
146
+ needsValue: true
147
+ }),
148
+ $all: (key, paramIndex) => ({
149
+ sql: `CASE WHEN array_length($${paramIndex}::text[], 1) IS NULL THEN false
150
+ ELSE (metadata#>'{${handleKey(key)}}')::jsonb ?& $${paramIndex}::text[] END`,
151
+ needsValue: true
152
+ }),
153
+ $elemMatch: (key, paramIndex, value) => {
154
+ const { sql, values } = buildElemMatchConditions(value, paramIndex);
155
+ return {
156
+ sql: `(
157
+ CASE
158
+ WHEN jsonb_typeof(metadata->'${handleKey(key)}') = 'array' THEN
159
+ EXISTS (
160
+ SELECT 1
161
+ FROM jsonb_array_elements(metadata->'${handleKey(key)}') as elem
162
+ WHERE ${sql}
163
+ )
164
+ ELSE FALSE
165
+ END
166
+ )`,
167
+ needsValue: true,
168
+ transformValue: () => values
169
+ };
170
+ },
171
+ // Element Operators
172
+ $exists: (key) => ({
173
+ sql: `metadata ? '${key}'`,
174
+ needsValue: false
175
+ }),
176
+ // Logical Operators
177
+ $and: (key) => ({ sql: `(${key})`, needsValue: false }),
178
+ $or: (key) => ({ sql: `(${key})`, needsValue: false }),
179
+ $not: (key) => ({ sql: `NOT (${key})`, needsValue: false }),
180
+ $nor: (key) => ({ sql: `NOT (${key})`, needsValue: false }),
181
+ // Regex Operators
182
+ $regex: (key, paramIndex) => ({
183
+ sql: `metadata#>>'{${handleKey(key)}}' ~ $${paramIndex}`,
184
+ needsValue: true
185
+ }),
186
+ $contains: (key, paramIndex) => ({
187
+ sql: `metadata @> $${paramIndex}::jsonb`,
188
+ needsValue: true,
189
+ transformValue: (value) => {
190
+ const parts = key.split(".");
191
+ return JSON.stringify(parts.reduceRight((value2, key2) => ({ [key2]: value2 }), value));
192
+ }
193
+ }),
194
+ $size: (key, paramIndex) => ({
195
+ sql: `(
196
+ CASE
197
+ WHEN jsonb_typeof(metadata#>'{${handleKey(key)}}') = 'array' THEN
198
+ jsonb_array_length(metadata#>'{${handleKey(key)}}') = $${paramIndex}
199
+ ELSE FALSE
200
+ END
201
+ )`,
202
+ needsValue: true
203
+ })
204
+ };
205
+ var handleKey = (key) => {
206
+ return key.replace(/\./g, ",");
207
+ };
208
+ function buildFilterQuery(filter, minScore) {
209
+ const values = [minScore];
210
+ function buildCondition(key, value, parentPath) {
211
+ if (["$and", "$or", "$not", "$nor"].includes(key)) {
212
+ return handleLogicalOperator(key, value);
213
+ }
214
+ if (!value || typeof value !== "object") {
215
+ values.push(value);
216
+ return `metadata#>>'{${handleKey(key)}}' = $${values.length}`;
217
+ }
218
+ const [[operator, operatorValue] = []] = Object.entries(value);
219
+ if (operator === "$not") {
220
+ const entries = Object.entries(operatorValue);
221
+ const conditions2 = entries.map(([nestedOp, nestedValue]) => {
222
+ if (!FILTER_OPERATORS[nestedOp]) {
223
+ throw new Error(`Invalid operator in $not condition: ${nestedOp}`);
224
+ }
225
+ const operatorFn2 = FILTER_OPERATORS[nestedOp];
226
+ const operatorResult2 = operatorFn2(key, values.length + 1);
227
+ if (operatorResult2.needsValue) {
228
+ values.push(nestedValue);
229
+ }
230
+ return operatorResult2.sql;
231
+ }).join(" AND ");
232
+ return `NOT (${conditions2})`;
233
+ }
234
+ const operatorFn = FILTER_OPERATORS[operator];
235
+ const operatorResult = operatorFn(key, values.length + 1, operatorValue);
236
+ if (operatorResult.needsValue) {
237
+ const transformedValue = operatorResult.transformValue ? operatorResult.transformValue(operatorValue) : operatorValue;
238
+ if (Array.isArray(transformedValue) && operator === "$elemMatch") {
239
+ values.push(...transformedValue);
240
+ } else {
241
+ values.push(transformedValue);
242
+ }
243
+ }
244
+ return operatorResult.sql;
245
+ }
246
+ function handleLogicalOperator(key, value, parentPath) {
247
+ if (key === "$not") {
248
+ const entries = Object.entries(value);
249
+ const conditions3 = entries.map(([fieldKey, fieldValue]) => buildCondition(fieldKey, fieldValue)).join(" AND ");
250
+ return `NOT (${conditions3})`;
251
+ }
252
+ if (!value || value.length === 0) {
253
+ switch (key) {
254
+ case "$and":
255
+ case "$nor":
256
+ return "true";
257
+ // Empty $and/$nor match everything
258
+ case "$or":
259
+ return "false";
260
+ // Empty $or matches nothing
261
+ default:
262
+ return "true";
263
+ }
264
+ }
265
+ const joinOperator = key === "$or" || key === "$nor" ? "OR" : "AND";
266
+ const conditions2 = value.map((f) => {
267
+ const entries = Object.entries(f);
268
+ if (entries.length === 0) return "";
269
+ const [firstKey, firstValue] = entries[0] || [];
270
+ if (["$and", "$or", "$not", "$nor"].includes(firstKey)) {
271
+ return buildCondition(firstKey, firstValue);
272
+ }
273
+ return entries.map(([k, v]) => buildCondition(k, v)).join(` ${joinOperator} `);
274
+ });
275
+ const joined = conditions2.join(` ${joinOperator} `);
276
+ const operatorFn = FILTER_OPERATORS[key];
277
+ return operatorFn(joined, 0, value).sql;
278
+ }
279
+ if (!filter) {
280
+ return { sql: "", values };
281
+ }
282
+ const conditions = Object.entries(filter).map(([key, value]) => buildCondition(key, value)).filter(Boolean).join(" AND ");
283
+ return { sql: conditions ? `WHERE ${conditions}` : "", values };
284
+ }
285
+
286
+ // src/vector/index.ts
287
+ var PgVector = class extends MastraVector {
288
+ pool;
289
+ indexCache = /* @__PURE__ */ new Map();
290
+ constructor(connectionString) {
291
+ super();
292
+ const basePool = new pg.Pool({
293
+ connectionString,
294
+ max: 20,
295
+ // Maximum number of clients in the pool
296
+ idleTimeoutMillis: 3e4,
297
+ // Close idle connections after 30 seconds
298
+ connectionTimeoutMillis: 2e3
299
+ // Fail fast if can't connect
300
+ });
301
+ const telemetry = this.__getTelemetry();
302
+ this.pool = telemetry?.traceClass(basePool, {
303
+ spanNamePrefix: "pg-vector",
304
+ attributes: {
305
+ "vector.type": "postgres"
306
+ }
307
+ }) ?? basePool;
308
+ }
309
+ transformFilter(filter) {
310
+ const pgFilter = new PGFilterTranslator();
311
+ const translatedFilter = pgFilter.translate(filter ?? {});
312
+ return translatedFilter;
313
+ }
314
+ async getIndexInfo(indexName) {
315
+ if (!this.indexCache.has(indexName)) {
316
+ this.indexCache.set(indexName, await this.describeIndex(indexName));
317
+ }
318
+ return this.indexCache.get(indexName);
319
+ }
320
+ async query(indexName, queryVector, topK = 10, filter, includeVector = false, minScore = 0, options) {
321
+ const client = await this.pool.connect();
322
+ try {
323
+ const vectorStr = `[${queryVector.join(",")}]`;
324
+ const translatedFilter = this.transformFilter(filter);
325
+ const { sql: filterQuery, values: filterValues } = buildFilterQuery(translatedFilter, minScore);
326
+ const indexInfo = await this.getIndexInfo(indexName);
327
+ if (indexInfo.type === "hnsw") {
328
+ const calculatedEf = options?.ef ?? Math.max(topK, (indexInfo?.config?.m ?? 16) * topK);
329
+ const searchEf = Math.min(1e3, Math.max(1, calculatedEf));
330
+ await client.query(`SET LOCAL hnsw.ef_search = ${searchEf}`);
331
+ }
332
+ if (indexInfo.type === "ivfflat" && options?.probes) {
333
+ await client.query(`SET LOCAL ivfflat.probes = ${options.probes}`);
334
+ }
335
+ const query = `
336
+ WITH vector_scores AS (
337
+ SELECT
338
+ vector_id as id,
339
+ 1 - (embedding <=> '${vectorStr}'::vector) as score,
340
+ metadata
341
+ ${includeVector ? ", embedding" : ""}
342
+ FROM ${indexName}
343
+ ${filterQuery}
344
+ )
345
+ SELECT *
346
+ FROM vector_scores
347
+ WHERE score > $1
348
+ ORDER BY score DESC
349
+ LIMIT ${topK}`;
350
+ const result = await client.query(query, filterValues);
351
+ return result.rows.map(({ id, score, metadata, embedding }) => ({
352
+ id,
353
+ score,
354
+ metadata,
355
+ ...includeVector && embedding && { vector: JSON.parse(embedding) }
356
+ }));
357
+ } finally {
358
+ client.release();
359
+ }
360
+ }
361
+ async upsert(indexName, vectors, metadata, ids) {
362
+ const client = await this.pool.connect();
363
+ try {
364
+ await client.query("BEGIN");
365
+ const vectorIds = ids || vectors.map(() => crypto.randomUUID());
366
+ for (let i = 0; i < vectors.length; i++) {
367
+ const query = `
368
+ INSERT INTO ${indexName} (vector_id, embedding, metadata)
369
+ VALUES ($1, $2::vector, $3::jsonb)
370
+ ON CONFLICT (vector_id)
371
+ DO UPDATE SET
372
+ embedding = $2::vector,
373
+ metadata = $3::jsonb
374
+ RETURNING embedding::text
375
+ `;
376
+ await client.query(query, [vectorIds[i], `[${vectors[i]?.join(",")}]`, JSON.stringify(metadata?.[i] || {})]);
377
+ }
378
+ await client.query("COMMIT");
379
+ return vectorIds;
380
+ } catch (error) {
381
+ await client.query("ROLLBACK");
382
+ throw error;
383
+ } finally {
384
+ client.release();
385
+ }
386
+ }
387
+ async createIndex(indexName, dimension, metric = "cosine", indexConfig = {}, defineIndex = true) {
388
+ const client = await this.pool.connect();
389
+ try {
390
+ if (!indexName.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) {
391
+ throw new Error("Invalid index name format");
392
+ }
393
+ if (!Number.isInteger(dimension) || dimension <= 0) {
394
+ throw new Error("Dimension must be a positive integer");
395
+ }
396
+ const extensionCheck = await client.query(`
397
+ SELECT EXISTS (
398
+ SELECT 1 FROM pg_available_extensions WHERE name = 'vector'
399
+ );
400
+ `);
401
+ if (!extensionCheck.rows[0].exists) {
402
+ throw new Error("PostgreSQL vector extension is not available. Please install it first.");
403
+ }
404
+ await client.query("CREATE EXTENSION IF NOT EXISTS vector");
405
+ await client.query(`
406
+ CREATE TABLE IF NOT EXISTS ${indexName} (
407
+ id SERIAL PRIMARY KEY,
408
+ vector_id TEXT UNIQUE NOT NULL,
409
+ embedding vector(${dimension}),
410
+ metadata JSONB DEFAULT '{}'::jsonb
411
+ );
412
+ `);
413
+ if (defineIndex) {
414
+ await this.defineIndex(indexName, metric, indexConfig);
415
+ }
416
+ } catch (error) {
417
+ console.error("Failed to create vector table:", error);
418
+ throw error;
419
+ } finally {
420
+ client.release();
421
+ }
422
+ }
423
+ /**
424
+ * @deprecated This function is deprecated. Use buildIndex instead
425
+ */
426
+ async defineIndex(indexName, metric = "cosine", indexConfig) {
427
+ return this.buildIndex(indexName, metric, indexConfig);
428
+ }
429
+ async buildIndex(indexName, metric = "cosine", indexConfig) {
430
+ const client = await this.pool.connect();
431
+ try {
432
+ await client.query(`DROP INDEX IF EXISTS ${indexName}_vector_idx`);
433
+ if (indexConfig.type === "flat") return;
434
+ const metricOp = metric === "cosine" ? "vector_cosine_ops" : metric === "euclidean" ? "vector_l2_ops" : "vector_ip_ops";
435
+ let indexSQL;
436
+ if (indexConfig.type === "hnsw") {
437
+ const m = indexConfig.hnsw?.m ?? 8;
438
+ const efConstruction = indexConfig.hnsw?.efConstruction ?? 32;
439
+ indexSQL = `
440
+ CREATE INDEX ${indexName}_vector_idx
441
+ ON ${indexName}
442
+ USING hnsw (embedding ${metricOp})
443
+ WITH (
444
+ m = ${m},
445
+ ef_construction = ${efConstruction}
446
+ )
447
+ `;
448
+ } else {
449
+ let lists;
450
+ if (indexConfig.ivf?.lists) {
451
+ lists = indexConfig.ivf.lists;
452
+ } else {
453
+ const size = (await client.query(`SELECT COUNT(*) FROM ${indexName}`)).rows[0].count;
454
+ lists = Math.max(100, Math.min(4e3, Math.floor(Math.sqrt(size) * 2)));
455
+ }
456
+ indexSQL = `
457
+ CREATE INDEX ${indexName}_vector_idx
458
+ ON ${indexName}
459
+ USING ivfflat (embedding ${metricOp})
460
+ WITH (lists = ${lists});
461
+ `;
462
+ }
463
+ await client.query(indexSQL);
464
+ this.indexCache.delete(indexName);
465
+ } finally {
466
+ client.release();
467
+ }
468
+ }
469
+ async listIndexes() {
470
+ const client = await this.pool.connect();
471
+ try {
472
+ const vectorTablesQuery = `
473
+ SELECT DISTINCT table_name
474
+ FROM information_schema.columns
475
+ WHERE table_schema = 'public'
476
+ AND udt_name = 'vector';
477
+ `;
478
+ const vectorTables = await client.query(vectorTablesQuery);
479
+ return vectorTables.rows.map((row) => row.table_name);
480
+ } finally {
481
+ client.release();
482
+ }
483
+ }
484
+ async describeIndex(indexName) {
485
+ const client = await this.pool.connect();
486
+ try {
487
+ const dimensionQuery = `
488
+ SELECT atttypmod as dimension
489
+ FROM pg_attribute
490
+ WHERE attrelid = $1::regclass
491
+ AND attname = 'embedding';
492
+ `;
493
+ const countQuery = `
494
+ SELECT COUNT(*) as count
495
+ FROM ${indexName};
496
+ `;
497
+ const indexQuery = `
498
+ SELECT
499
+ am.amname as index_method,
500
+ pg_get_indexdef(i.indexrelid) as index_def,
501
+ opclass.opcname as operator_class
502
+ FROM pg_index i
503
+ JOIN pg_class c ON i.indexrelid = c.oid
504
+ JOIN pg_am am ON c.relam = am.oid
505
+ JOIN pg_opclass opclass ON i.indclass[0] = opclass.oid
506
+ WHERE c.relname = '${indexName}_vector_idx';
507
+ `;
508
+ const [dimResult, countResult, indexResult] = await Promise.all([
509
+ client.query(dimensionQuery, [indexName]),
510
+ client.query(countQuery),
511
+ client.query(indexQuery)
512
+ ]);
513
+ const { index_method, index_def, operator_class } = indexResult.rows[0] || {
514
+ index_method: "flat",
515
+ index_def: "",
516
+ operator_class: "cosine"
517
+ };
518
+ const metric = operator_class.includes("l2") ? "euclidean" : operator_class.includes("ip") ? "dotproduct" : "cosine";
519
+ const config = {};
520
+ if (index_method === "hnsw") {
521
+ const m = index_def.match(/m\s*=\s*'?(\d+)'?/)?.[1];
522
+ const efConstruction = index_def.match(/ef_construction\s*=\s*'?(\d+)'?/)?.[1];
523
+ if (m) config.m = parseInt(m);
524
+ if (efConstruction) config.efConstruction = parseInt(efConstruction);
525
+ } else if (index_method === "ivfflat") {
526
+ const lists = index_def.match(/lists\s*=\s*'?(\d+)'?/)?.[1];
527
+ if (lists) config.lists = parseInt(lists);
528
+ }
529
+ return {
530
+ dimension: dimResult.rows[0].dimension,
531
+ count: parseInt(countResult.rows[0].count),
532
+ metric,
533
+ type: index_method,
534
+ config
535
+ };
536
+ } catch (e) {
537
+ await client.query("ROLLBACK");
538
+ throw new Error(`Failed to describe vector table: ${e.message}`);
539
+ } finally {
540
+ client.release();
541
+ }
542
+ }
543
+ async deleteIndex(indexName) {
544
+ const client = await this.pool.connect();
545
+ try {
546
+ await client.query(`DROP TABLE IF EXISTS ${indexName} CASCADE`);
547
+ } catch (error) {
548
+ await client.query("ROLLBACK");
549
+ throw new Error(`Failed to delete vector table: ${error.message}`);
550
+ } finally {
551
+ client.release();
552
+ }
553
+ }
554
+ async truncateIndex(indexName) {
555
+ const client = await this.pool.connect();
556
+ try {
557
+ await client.query(`TRUNCATE ${indexName}`);
558
+ } catch (e) {
559
+ await client.query("ROLLBACK");
560
+ throw new Error(`Failed to truncate vector table: ${e.message}`);
561
+ } finally {
562
+ client.release();
563
+ }
564
+ }
565
+ async disconnect() {
566
+ await this.pool.end();
567
+ }
568
+ };
569
+ var PostgresStore = class extends MastraStorage {
570
+ db;
571
+ pgp;
572
+ constructor(config) {
573
+ super({ name: "PostgresStore" });
574
+ this.pgp = pgPromise();
575
+ this.db = this.pgp(
576
+ `connectionString` in config ? { connectionString: config.connectionString } : {
577
+ host: config.host,
578
+ port: config.port,
579
+ database: config.database,
580
+ user: config.user,
581
+ password: config.password
582
+ }
583
+ );
584
+ }
585
+ getEvalsByAgentName(_agentName, _type) {
586
+ throw new Error("Method not implemented.");
587
+ }
588
+ async batchInsert({ tableName, records }) {
589
+ try {
590
+ await this.db.query("BEGIN");
591
+ for (const record of records) {
592
+ await this.insert({ tableName, record });
593
+ }
594
+ await this.db.query("COMMIT");
595
+ } catch (error) {
596
+ console.error(`Error inserting into ${tableName}:`, error);
597
+ await this.db.query("ROLLBACK");
598
+ throw error;
599
+ }
600
+ }
601
+ async getTraces({
602
+ name,
603
+ scope,
604
+ page,
605
+ perPage,
606
+ attributes
607
+ }) {
608
+ let idx = 1;
609
+ const limit = perPage;
610
+ const offset = page * perPage;
611
+ const args = [];
612
+ const conditions = [];
613
+ if (name) {
614
+ conditions.push(`name LIKE CONCAT($${idx++}, '%')`);
615
+ }
616
+ if (scope) {
617
+ conditions.push(`scope = $${idx++}`);
618
+ }
619
+ if (attributes) {
620
+ Object.keys(attributes).forEach((key) => {
621
+ conditions.push(`attributes->>'${key}' = $${idx++}`);
622
+ });
623
+ }
624
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
625
+ if (name) {
626
+ args.push(name);
627
+ }
628
+ if (scope) {
629
+ args.push(scope);
630
+ }
631
+ if (attributes) {
632
+ for (const [_key, value] of Object.entries(attributes)) {
633
+ args.push(value);
634
+ }
635
+ }
636
+ console.log(
637
+ "QUERY",
638
+ `SELECT * FROM ${MastraStorage.TABLE_TRACES} ${whereClause} ORDER BY "createdAt" DESC LIMIT ${limit} OFFSET ${offset}`,
639
+ args
640
+ );
641
+ const result = await this.db.manyOrNone(
642
+ `SELECT * FROM ${MastraStorage.TABLE_TRACES} ${whereClause} ORDER BY "createdAt" DESC LIMIT ${limit} OFFSET ${offset}`,
643
+ args
644
+ );
645
+ if (!result) {
646
+ return [];
647
+ }
648
+ return result.map((row) => ({
649
+ id: row.id,
650
+ parentSpanId: row.parentSpanId,
651
+ traceId: row.traceId,
652
+ name: row.name,
653
+ scope: row.scope,
654
+ kind: row.kind,
655
+ status: row.status,
656
+ events: row.events,
657
+ links: row.links,
658
+ attributes: row.attributes,
659
+ startTime: row.startTime,
660
+ endTime: row.endTime,
661
+ other: row.other,
662
+ createdAt: row.createdAt
663
+ }));
664
+ }
665
+ async createTable({
666
+ tableName,
667
+ schema
668
+ }) {
669
+ try {
670
+ const columns = Object.entries(schema).map(([name, def]) => {
671
+ const constraints = [];
672
+ if (def.primaryKey) constraints.push("PRIMARY KEY");
673
+ if (!def.nullable) constraints.push("NOT NULL");
674
+ return `"${name}" ${def.type.toUpperCase()} ${constraints.join(" ")}`;
675
+ }).join(",\n");
676
+ const sql = `
677
+ CREATE TABLE IF NOT EXISTS ${tableName} (
678
+ ${columns}
679
+ );
680
+ ${tableName === MastraStorage.TABLE_WORKFLOW_SNAPSHOT ? `
681
+ DO $$ BEGIN
682
+ IF NOT EXISTS (
683
+ SELECT 1 FROM pg_constraint WHERE conname = 'mastra_workflow_snapshot_workflow_name_run_id_key'
684
+ ) THEN
685
+ ALTER TABLE ${tableName}
686
+ ADD CONSTRAINT mastra_workflow_snapshot_workflow_name_run_id_key
687
+ UNIQUE (workflow_name, run_id);
688
+ END IF;
689
+ END $$;
690
+ ` : ""}
691
+ `;
692
+ await this.db.none(sql);
693
+ } catch (error) {
694
+ console.error(`Error creating table ${tableName}:`, error);
695
+ throw error;
696
+ }
697
+ }
698
+ async clearTable({ tableName }) {
699
+ try {
700
+ await this.db.none(`TRUNCATE TABLE ${tableName} CASCADE`);
701
+ } catch (error) {
702
+ console.error(`Error clearing table ${tableName}:`, error);
703
+ throw error;
704
+ }
705
+ }
706
+ async insert({ tableName, record }) {
707
+ try {
708
+ const columns = Object.keys(record);
709
+ const values = Object.values(record);
710
+ const placeholders = values.map((_, i) => `$${i + 1}`).join(", ");
711
+ await this.db.none(
712
+ `INSERT INTO ${tableName} (${columns.map((c) => `"${c}"`).join(", ")}) VALUES (${placeholders})`,
713
+ values
714
+ );
715
+ } catch (error) {
716
+ console.error(`Error inserting into ${tableName}:`, error);
717
+ throw error;
718
+ }
719
+ }
720
+ async load({ tableName, keys }) {
721
+ try {
722
+ const keyEntries = Object.entries(keys);
723
+ const conditions = keyEntries.map(([key], index) => `"${key}" = $${index + 1}`).join(" AND ");
724
+ const values = keyEntries.map(([_, value]) => value);
725
+ const result = await this.db.oneOrNone(`SELECT * FROM ${tableName} WHERE ${conditions}`, values);
726
+ if (!result) {
727
+ return null;
728
+ }
729
+ if (tableName === MastraStorage.TABLE_WORKFLOW_SNAPSHOT) {
730
+ const snapshot = result;
731
+ if (typeof snapshot.snapshot === "string") {
732
+ snapshot.snapshot = JSON.parse(snapshot.snapshot);
733
+ }
734
+ return snapshot;
735
+ }
736
+ return result;
737
+ } catch (error) {
738
+ console.error(`Error loading from ${tableName}:`, error);
739
+ throw error;
740
+ }
741
+ }
742
+ async getThreadById({ threadId }) {
743
+ try {
744
+ const thread = await this.db.oneOrNone(
745
+ `SELECT
746
+ id,
747
+ "resourceId",
748
+ title,
749
+ metadata,
750
+ "createdAt",
751
+ "updatedAt"
752
+ FROM "${MastraStorage.TABLE_THREADS}"
753
+ WHERE id = $1`,
754
+ [threadId]
755
+ );
756
+ if (!thread) {
757
+ return null;
758
+ }
759
+ return {
760
+ ...thread,
761
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
762
+ createdAt: thread.createdAt,
763
+ updatedAt: thread.updatedAt
764
+ };
765
+ } catch (error) {
766
+ console.error(`Error getting thread ${threadId}:`, error);
767
+ throw error;
768
+ }
769
+ }
770
+ async getThreadsByResourceId({ resourceId }) {
771
+ try {
772
+ const threads = await this.db.manyOrNone(
773
+ `SELECT
774
+ id,
775
+ "resourceId",
776
+ title,
777
+ metadata,
778
+ "createdAt",
779
+ "updatedAt"
780
+ FROM "${MastraStorage.TABLE_THREADS}"
781
+ WHERE "resourceId" = $1`,
782
+ [resourceId]
783
+ );
784
+ return threads.map((thread) => ({
785
+ ...thread,
786
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
787
+ createdAt: thread.createdAt,
788
+ updatedAt: thread.updatedAt
789
+ }));
790
+ } catch (error) {
791
+ console.error(`Error getting threads for resource ${resourceId}:`, error);
792
+ throw error;
793
+ }
794
+ }
795
+ async saveThread({ thread }) {
796
+ try {
797
+ await this.db.none(
798
+ `INSERT INTO "${MastraStorage.TABLE_THREADS}" (
799
+ id,
800
+ "resourceId",
801
+ title,
802
+ metadata,
803
+ "createdAt",
804
+ "updatedAt"
805
+ ) VALUES ($1, $2, $3, $4, $5, $6)
806
+ ON CONFLICT (id) DO UPDATE SET
807
+ "resourceId" = EXCLUDED."resourceId",
808
+ title = EXCLUDED.title,
809
+ metadata = EXCLUDED.metadata,
810
+ "createdAt" = EXCLUDED."createdAt",
811
+ "updatedAt" = EXCLUDED."updatedAt"`,
812
+ [
813
+ thread.id,
814
+ thread.resourceId,
815
+ thread.title,
816
+ thread.metadata ? JSON.stringify(thread.metadata) : null,
817
+ thread.createdAt,
818
+ thread.updatedAt
819
+ ]
820
+ );
821
+ return thread;
822
+ } catch (error) {
823
+ console.error("Error saving thread:", error);
824
+ throw error;
825
+ }
826
+ }
827
+ async updateThread({
828
+ id,
829
+ title,
830
+ metadata
831
+ }) {
832
+ try {
833
+ const existingThread = await this.getThreadById({ threadId: id });
834
+ if (!existingThread) {
835
+ throw new Error(`Thread ${id} not found`);
836
+ }
837
+ const mergedMetadata = {
838
+ ...existingThread.metadata,
839
+ ...metadata
840
+ };
841
+ const thread = await this.db.one(
842
+ `UPDATE "${MastraStorage.TABLE_THREADS}"
843
+ SET title = $1,
844
+ metadata = $2,
845
+ "updatedAt" = $3
846
+ WHERE id = $4
847
+ RETURNING *`,
848
+ [title, mergedMetadata, (/* @__PURE__ */ new Date()).toISOString(), id]
849
+ );
850
+ return {
851
+ ...thread,
852
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
853
+ createdAt: thread.createdAt,
854
+ updatedAt: thread.updatedAt
855
+ };
856
+ } catch (error) {
857
+ console.error("Error updating thread:", error);
858
+ throw error;
859
+ }
860
+ }
861
+ async deleteThread({ threadId }) {
862
+ try {
863
+ await this.db.tx(async (t) => {
864
+ await t.none(`DELETE FROM "${MastraStorage.TABLE_MESSAGES}" WHERE thread_id = $1`, [threadId]);
865
+ await t.none(`DELETE FROM "${MastraStorage.TABLE_THREADS}" WHERE id = $1`, [threadId]);
866
+ });
867
+ } catch (error) {
868
+ console.error("Error deleting thread:", error);
869
+ throw error;
870
+ }
871
+ }
872
+ async getMessages({ threadId, selectBy }) {
873
+ try {
874
+ const messages = [];
875
+ const limit = typeof selectBy?.last === `number` ? selectBy.last : 40;
876
+ const include = selectBy?.include || [];
877
+ if (include.length) {
878
+ const includeResult = await this.db.manyOrNone(
879
+ `
880
+ WITH ordered_messages AS (
881
+ SELECT
882
+ *,
883
+ ROW_NUMBER() OVER (ORDER BY "createdAt") as row_num
884
+ FROM "${MastraStorage.TABLE_MESSAGES}"
885
+ WHERE thread_id = $1
886
+ )
887
+ SELECT DISTINCT ON (m.id)
888
+ m.id,
889
+ m.content,
890
+ m.role,
891
+ m.type,
892
+ m."createdAt",
893
+ m.thread_id AS "threadId"
894
+ FROM ordered_messages m
895
+ WHERE m.id = ANY($2)
896
+ OR EXISTS (
897
+ SELECT 1 FROM ordered_messages target
898
+ WHERE target.id = ANY($2)
899
+ AND (
900
+ -- Get previous messages based on the max withPreviousMessages
901
+ (m.row_num >= target.row_num - $3 AND m.row_num < target.row_num)
902
+ OR
903
+ -- Get next messages based on the max withNextMessages
904
+ (m.row_num <= target.row_num + $4 AND m.row_num > target.row_num)
905
+ )
906
+ )
907
+ ORDER BY m.id, m."createdAt"
908
+ `,
909
+ [
910
+ threadId,
911
+ include.map((i) => i.id),
912
+ Math.max(...include.map((i) => i.withPreviousMessages || 0)),
913
+ Math.max(...include.map((i) => i.withNextMessages || 0))
914
+ ]
915
+ );
916
+ messages.push(...includeResult);
917
+ }
918
+ const result = await this.db.manyOrNone(
919
+ `
920
+ SELECT
921
+ id,
922
+ content,
923
+ role,
924
+ type,
925
+ "createdAt",
926
+ thread_id AS "threadId"
927
+ FROM "${MastraStorage.TABLE_MESSAGES}"
928
+ WHERE thread_id = $1
929
+ AND id != ALL($2)
930
+ ORDER BY "createdAt" DESC
931
+ LIMIT $3
932
+ `,
933
+ [threadId, messages.map((m) => m.id), limit]
934
+ );
935
+ messages.push(...result);
936
+ messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
937
+ messages.forEach((message) => {
938
+ if (typeof message.content === "string") {
939
+ try {
940
+ message.content = JSON.parse(message.content);
941
+ } catch {
942
+ }
943
+ }
944
+ });
945
+ return messages;
946
+ } catch (error) {
947
+ console.error("Error getting messages:", error);
948
+ throw error;
949
+ }
950
+ }
951
+ async saveMessages({ messages }) {
952
+ if (messages.length === 0) return messages;
953
+ try {
954
+ const threadId = messages[0]?.threadId;
955
+ if (!threadId) {
956
+ throw new Error("Thread ID is required");
957
+ }
958
+ const thread = await this.getThreadById({ threadId });
959
+ if (!thread) {
960
+ throw new Error(`Thread ${threadId} not found`);
961
+ }
962
+ await this.db.tx(async (t) => {
963
+ for (const message of messages) {
964
+ await t.none(
965
+ `INSERT INTO "${MastraStorage.TABLE_MESSAGES}" (id, thread_id, content, "createdAt", role, type)
966
+ VALUES ($1, $2, $3, $4, $5, $6)`,
967
+ [
968
+ message.id,
969
+ threadId,
970
+ typeof message.content === "string" ? message.content : JSON.stringify(message.content),
971
+ message.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
972
+ message.role,
973
+ message.type
974
+ ]
975
+ );
976
+ }
977
+ });
978
+ return messages;
979
+ } catch (error) {
980
+ console.error("Error saving messages:", error);
981
+ throw error;
982
+ }
983
+ }
984
+ async persistWorkflowSnapshot({
985
+ workflowName,
986
+ runId,
987
+ snapshot
988
+ }) {
989
+ try {
990
+ const now = (/* @__PURE__ */ new Date()).toISOString();
991
+ await this.db.none(
992
+ `INSERT INTO "${MastraStorage.TABLE_WORKFLOW_SNAPSHOT}" (
993
+ workflow_name,
994
+ run_id,
995
+ snapshot,
996
+ "createdAt",
997
+ "updatedAt"
998
+ ) VALUES ($1, $2, $3, $4, $5)
999
+ ON CONFLICT (workflow_name, run_id) DO UPDATE
1000
+ SET snapshot = EXCLUDED.snapshot,
1001
+ "updatedAt" = EXCLUDED."updatedAt"`,
1002
+ [workflowName, runId, JSON.stringify(snapshot), now, now]
1003
+ );
1004
+ } catch (error) {
1005
+ console.error("Error persisting workflow snapshot:", error);
1006
+ throw error;
1007
+ }
1008
+ }
1009
+ async loadWorkflowSnapshot({
1010
+ workflowName,
1011
+ runId
1012
+ }) {
1013
+ try {
1014
+ const result = await this.load({
1015
+ tableName: MastraStorage.TABLE_WORKFLOW_SNAPSHOT,
1016
+ keys: {
1017
+ workflow_name: workflowName,
1018
+ run_id: runId
1019
+ }
1020
+ });
1021
+ if (!result) {
1022
+ return null;
1023
+ }
1024
+ return result.snapshot;
1025
+ } catch (error) {
1026
+ console.error("Error loading workflow snapshot:", error);
1027
+ throw error;
1028
+ }
1029
+ }
1030
+ async close() {
1031
+ this.pgp.end();
1032
+ }
1033
+ };
1034
+
1035
+ export { PgVector, PostgresStore };