@mastra/pg 0.1.0-alpha.11 → 0.1.0-alpha.12

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/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # @mastra/pg
2
2
 
3
+ ## 0.1.0-alpha.12
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [a9345f9]
8
+ - @mastra/core@0.2.0-alpha.102
9
+
3
10
  ## 0.1.0-alpha.11
4
11
 
5
12
  ### Patch Changes
@@ -0,0 +1,141 @@
1
+ import { ArrayOperator } from '@mastra/core/filter';
2
+ import { BaseFilterTranslator } from '@mastra/core/filter';
3
+ import { BasicOperator } from '@mastra/core/filter';
4
+ import { ElementOperator } from '@mastra/core/filter';
5
+ import { Filter } from '@mastra/core/filter';
6
+ import { IndexStats } from '@mastra/core/vector';
7
+ import { LogicalOperator } from '@mastra/core/filter';
8
+ import { MastraStorage } from '@mastra/core/storage';
9
+ import { MastraVector } from '@mastra/core/vector';
10
+ import { MessageType } from '@mastra/core/memory';
11
+ import { NumericOperator } from '@mastra/core/filter';
12
+ import { OperatorSupport } from '@mastra/core/filter';
13
+ import { QueryResult } from '@mastra/core/vector';
14
+ import { RegexOperator } from '@mastra/core/filter';
15
+ import { StorageColumn } from '@mastra/core/storage';
16
+ import { StorageGetMessagesArg } from '@mastra/core/storage';
17
+ import { StorageThreadType } from '@mastra/core/memory';
18
+ import { TABLE_NAMES } from '@mastra/core/storage';
19
+ import { WorkflowRunState } from '@mastra/core/workflows';
20
+
21
+ export declare function buildFilterQuery(filter: Filter, minScore: number): FilterResult;
22
+
23
+ export declare const FILTER_OPERATORS: Record<string, OperatorFn>;
24
+
25
+ declare type FilterOperator = {
26
+ sql: string;
27
+ needsValue: boolean;
28
+ transformValue?: (value: any) => any;
29
+ };
30
+
31
+ export declare interface FilterResult {
32
+ sql: string;
33
+ values: any[];
34
+ }
35
+
36
+ export declare const handleKey: (key: string) => string;
37
+
38
+ declare type OperatorFn = (key: string, paramIndex: number, value?: any) => FilterOperator;
39
+
40
+ export declare type OperatorType = BasicOperator | NumericOperator | ArrayOperator | ElementOperator | LogicalOperator | '$contains' | Exclude<RegexOperator, '$options'>;
41
+
42
+ /**
43
+ * Translates MongoDB-style filters to PG compatible filters.
44
+ *
45
+ * Key differences from MongoDB:
46
+ *
47
+ * Logical Operators ($and, $or, $nor):
48
+ * - Can be used at the top level or nested within fields
49
+ * - Can take either a single condition or an array of conditions
50
+ *
51
+ */
52
+ export declare class PGFilterTranslator extends BaseFilterTranslator {
53
+ protected getSupportedOperators(): OperatorSupport;
54
+ translate(filter: Filter): Filter;
55
+ private translateNode;
56
+ private translateRegexPattern;
57
+ }
58
+
59
+ declare class PgVector extends MastraVector {
60
+ private pool;
61
+ constructor(connectionString: string);
62
+ transformFilter(filter?: Filter): Filter;
63
+ query(indexName: string, queryVector: number[], topK?: number, filter?: Filter, includeVector?: boolean, minScore?: number): Promise<QueryResult[]>;
64
+ upsert(indexName: string, vectors: number[][], metadata?: Record<string, any>[], ids?: string[]): Promise<string[]>;
65
+ createIndex(indexName: string, dimension: number, metric?: 'cosine' | 'euclidean' | 'dotproduct'): Promise<void>;
66
+ listIndexes(): Promise<string[]>;
67
+ describeIndex(indexName: string): Promise<IndexStats>;
68
+ deleteIndex(indexName: string): Promise<void>;
69
+ truncateIndex(indexName: string): Promise<void>;
70
+ disconnect(): Promise<void>;
71
+ }
72
+ export { PgVector }
73
+ export { PgVector as PgVector_alias_1 }
74
+
75
+ declare type PostgresConfig = {
76
+ host: string;
77
+ port: number;
78
+ database: string;
79
+ user: string;
80
+ password: string;
81
+ } | {
82
+ connectionString: string;
83
+ };
84
+ export { PostgresConfig }
85
+ export { PostgresConfig as PostgresConfig_alias_1 }
86
+
87
+ declare class PostgresStore extends MastraStorage {
88
+ private db;
89
+ private pgp;
90
+ constructor(config: PostgresConfig);
91
+ createTable({ tableName, schema, }: {
92
+ tableName: TABLE_NAMES;
93
+ schema: Record<string, StorageColumn>;
94
+ }): Promise<void>;
95
+ clearTable({ tableName }: {
96
+ tableName: TABLE_NAMES;
97
+ }): Promise<void>;
98
+ insert({ tableName, record }: {
99
+ tableName: TABLE_NAMES;
100
+ record: Record<string, any>;
101
+ }): Promise<void>;
102
+ load<R>({ tableName, keys }: {
103
+ tableName: TABLE_NAMES;
104
+ keys: Record<string, string>;
105
+ }): Promise<R | null>;
106
+ getThreadById({ threadId }: {
107
+ threadId: string;
108
+ }): Promise<StorageThreadType | null>;
109
+ getThreadsByResourceId({ resourceId }: {
110
+ resourceId: string;
111
+ }): Promise<StorageThreadType[]>;
112
+ saveThread({ thread }: {
113
+ thread: StorageThreadType;
114
+ }): Promise<StorageThreadType>;
115
+ updateThread({ id, title, metadata, }: {
116
+ id: string;
117
+ title: string;
118
+ metadata: Record<string, unknown>;
119
+ }): Promise<StorageThreadType>;
120
+ deleteThread({ threadId }: {
121
+ threadId: string;
122
+ }): Promise<void>;
123
+ getMessages<T = unknown>({ threadId, selectBy }: StorageGetMessagesArg): Promise<T>;
124
+ saveMessages({ messages }: {
125
+ messages: MessageType[];
126
+ }): Promise<MessageType[]>;
127
+ persistWorkflowSnapshot({ workflowName, runId, snapshot, }: {
128
+ workflowName: string;
129
+ runId: string;
130
+ snapshot: WorkflowRunState;
131
+ }): Promise<void>;
132
+ loadWorkflowSnapshot({ workflowName, runId, }: {
133
+ workflowName: string;
134
+ runId: string;
135
+ }): Promise<WorkflowRunState | null>;
136
+ close(): Promise<void>;
137
+ }
138
+ export { PostgresStore }
139
+ export { PostgresStore as PostgresStore_alias_1 }
140
+
141
+ export { }
@@ -0,0 +1,3 @@
1
+ export { PgVector } from './_tsup-dts-rollup.js';
2
+ export { PostgresConfig } from './_tsup-dts-rollup.js';
3
+ export { PostgresStore } from './_tsup-dts-rollup.js';
package/dist/index.js ADDED
@@ -0,0 +1,889 @@
1
+ import { MastraVector } from '@mastra/core/vector';
2
+ import pg from 'pg';
3
+ import { BaseFilterTranslator } from '@mastra/core/filter';
4
+ import '@mastra/core/memory';
5
+ import { MastraStorage } from '@mastra/core/storage';
6
+ import '@mastra/core/workflows';
7
+ import pgPromise from 'pg-promise';
8
+
9
+ // src/vector/index.ts
10
+ var PGFilterTranslator = class extends BaseFilterTranslator {
11
+ getSupportedOperators() {
12
+ return {
13
+ ...BaseFilterTranslator.DEFAULT_OPERATORS,
14
+ custom: ["$contains", "$size"]
15
+ };
16
+ }
17
+ translate(filter) {
18
+ if (this.isEmpty(filter)) {
19
+ return filter;
20
+ }
21
+ this.validateFilter(filter);
22
+ return this.translateNode(filter);
23
+ }
24
+ translateNode(node, currentPath = "") {
25
+ const withPath = (result2) => currentPath ? { [currentPath]: result2 } : result2;
26
+ if (this.isPrimitive(node)) {
27
+ return withPath({ $eq: this.normalizeComparisonValue(node) });
28
+ }
29
+ if (Array.isArray(node)) {
30
+ return withPath({ $in: this.normalizeArrayValues(node) });
31
+ }
32
+ if (node instanceof RegExp) {
33
+ return withPath(this.translateRegexPattern(node.source, node.flags));
34
+ }
35
+ const entries = Object.entries(node);
36
+ const result = {};
37
+ if ("$options" in node && !("$regex" in node)) {
38
+ throw new Error("$options is not valid without $regex");
39
+ }
40
+ if ("$regex" in node) {
41
+ const options = node.$options || "";
42
+ return withPath(this.translateRegexPattern(node.$regex, options));
43
+ }
44
+ for (const [key, value] of entries) {
45
+ if (key === "$options") continue;
46
+ const newPath = currentPath ? `${currentPath}.${key}` : key;
47
+ if (this.isLogicalOperator(key)) {
48
+ result[key] = Array.isArray(value) ? value.map((filter) => this.translateNode(filter)) : this.translateNode(value);
49
+ } else if (this.isOperator(key)) {
50
+ if (this.isArrayOperator(key) && !Array.isArray(value) && key !== "$elemMatch") {
51
+ result[key] = [value];
52
+ } else if (this.isBasicOperator(key) && Array.isArray(value)) {
53
+ result[key] = JSON.stringify(value);
54
+ } else {
55
+ result[key] = value;
56
+ }
57
+ } else if (typeof value === "object" && value !== null) {
58
+ const hasOperators = Object.keys(value).some((k) => this.isOperator(k));
59
+ if (hasOperators) {
60
+ result[newPath] = this.translateNode(value);
61
+ } else {
62
+ Object.assign(result, this.translateNode(value, newPath));
63
+ }
64
+ } else {
65
+ result[newPath] = this.translateNode(value);
66
+ }
67
+ }
68
+ return result;
69
+ }
70
+ translateRegexPattern(pattern, options = "") {
71
+ if (!options) return { $regex: pattern };
72
+ const flags = options.split("").filter((f) => "imsux".includes(f)).join("");
73
+ return { $regex: flags ? `(?${flags})${pattern}` : pattern };
74
+ }
75
+ };
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
+ constructor(connectionString) {
290
+ super();
291
+ const basePool = new pg.Pool({
292
+ connectionString,
293
+ max: 20,
294
+ // Maximum number of clients in the pool
295
+ idleTimeoutMillis: 3e4,
296
+ // Close idle connections after 30 seconds
297
+ connectionTimeoutMillis: 2e3
298
+ // Fail fast if can't connect
299
+ });
300
+ const telemetry = this.__getTelemetry();
301
+ this.pool = telemetry?.traceClass(basePool, {
302
+ spanNamePrefix: "pg-vector",
303
+ attributes: {
304
+ "vector.type": "postgres"
305
+ }
306
+ }) ?? basePool;
307
+ }
308
+ transformFilter(filter) {
309
+ const pgFilter = new PGFilterTranslator();
310
+ const translatedFilter = pgFilter.translate(filter ?? {});
311
+ return translatedFilter;
312
+ }
313
+ async query(indexName, queryVector, topK = 10, filter, includeVector = false, minScore = 0) {
314
+ const client = await this.pool.connect();
315
+ try {
316
+ const vectorStr = `[${queryVector.join(",")}]`;
317
+ const translatedFilter = this.transformFilter(filter);
318
+ const { sql: filterQuery, values: filterValues } = buildFilterQuery(translatedFilter, minScore);
319
+ const query = `
320
+ WITH vector_scores AS (
321
+ SELECT
322
+ vector_id as id,
323
+ 1 - (embedding <=> '${vectorStr}'::vector) as score,
324
+ metadata
325
+ ${includeVector ? ", embedding" : ""}
326
+ FROM ${indexName}
327
+ ${filterQuery}
328
+ )
329
+ SELECT *
330
+ FROM vector_scores
331
+ WHERE score > $1
332
+ ORDER BY score DESC
333
+ LIMIT ${topK}`;
334
+ const result = await client.query(query, filterValues);
335
+ return result.rows.map(({ id, score, metadata, embedding }) => ({
336
+ id,
337
+ score,
338
+ metadata,
339
+ ...includeVector && embedding && { vector: JSON.parse(embedding) }
340
+ }));
341
+ } finally {
342
+ client.release();
343
+ }
344
+ }
345
+ async upsert(indexName, vectors, metadata, ids) {
346
+ const client = await this.pool.connect();
347
+ try {
348
+ await client.query("BEGIN");
349
+ const vectorIds = ids || vectors.map(() => crypto.randomUUID());
350
+ for (let i = 0; i < vectors.length; i++) {
351
+ const query = `
352
+ INSERT INTO ${indexName} (vector_id, embedding, metadata)
353
+ VALUES ($1, $2::vector, $3::jsonb)
354
+ ON CONFLICT (vector_id)
355
+ DO UPDATE SET
356
+ embedding = $2::vector,
357
+ metadata = $3::jsonb
358
+ RETURNING embedding::text
359
+ `;
360
+ await client.query(query, [vectorIds[i], `[${vectors[i]?.join(",")}]`, JSON.stringify(metadata?.[i] || {})]);
361
+ }
362
+ await client.query("COMMIT");
363
+ return vectorIds;
364
+ } catch (error) {
365
+ await client.query("ROLLBACK");
366
+ throw error;
367
+ } finally {
368
+ client.release();
369
+ }
370
+ }
371
+ async createIndex(indexName, dimension, metric = "cosine") {
372
+ const client = await this.pool.connect();
373
+ try {
374
+ if (!indexName.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) {
375
+ throw new Error("Invalid index name format");
376
+ }
377
+ if (!Number.isInteger(dimension) || dimension <= 0) {
378
+ throw new Error("Dimension must be a positive integer");
379
+ }
380
+ const extensionCheck = await client.query(`
381
+ SELECT EXISTS (
382
+ SELECT 1 FROM pg_available_extensions WHERE name = 'vector'
383
+ );
384
+ `);
385
+ if (!extensionCheck.rows[0].exists) {
386
+ throw new Error("PostgreSQL vector extension is not available. Please install it first.");
387
+ }
388
+ await client.query("CREATE EXTENSION IF NOT EXISTS vector");
389
+ await client.query(`
390
+ CREATE TABLE IF NOT EXISTS ${indexName} (
391
+ id SERIAL PRIMARY KEY,
392
+ vector_id TEXT UNIQUE NOT NULL,
393
+ embedding vector(${dimension}),
394
+ metadata JSONB DEFAULT '{}'::jsonb
395
+ );
396
+ `);
397
+ const indexMethod = metric === "cosine" ? "vector_cosine_ops" : metric === "euclidean" ? "vector_l2_ops" : "vector_ip_ops";
398
+ await client.query(`
399
+ CREATE INDEX IF NOT EXISTS ${indexName}_vector_idx
400
+ ON public.${indexName}
401
+ USING ivfflat (embedding ${indexMethod})
402
+ WITH (lists = 100);
403
+ `);
404
+ } catch (error) {
405
+ console.error("Failed to create vector table:", error);
406
+ throw error;
407
+ } finally {
408
+ client.release();
409
+ }
410
+ }
411
+ async listIndexes() {
412
+ const client = await this.pool.connect();
413
+ try {
414
+ const vectorTablesQuery = `
415
+ SELECT DISTINCT table_name
416
+ FROM information_schema.columns
417
+ WHERE table_schema = 'public'
418
+ AND udt_name = 'vector';
419
+ `;
420
+ const vectorTables = await client.query(vectorTablesQuery);
421
+ return vectorTables.rows.map((row) => row.table_name);
422
+ } finally {
423
+ client.release();
424
+ }
425
+ }
426
+ async describeIndex(indexName) {
427
+ const client = await this.pool.connect();
428
+ try {
429
+ const dimensionQuery = `
430
+ SELECT atttypmod as dimension
431
+ FROM pg_attribute
432
+ WHERE attrelid = $1::regclass
433
+ AND attname = 'embedding';
434
+ `;
435
+ const countQuery = `
436
+ SELECT COUNT(*) as count
437
+ FROM ${indexName};
438
+ `;
439
+ const metricQuery = `
440
+ SELECT
441
+ am.amname as index_method,
442
+ opclass.opcname as operator_class
443
+ FROM pg_index i
444
+ JOIN pg_class c ON i.indexrelid = c.oid
445
+ JOIN pg_am am ON c.relam = am.oid
446
+ JOIN pg_opclass opclass ON i.indclass[0] = opclass.oid
447
+ WHERE c.relname = '${indexName}_vector_idx';
448
+ `;
449
+ const [dimResult, countResult, metricResult] = await Promise.all([
450
+ client.query(dimensionQuery, [indexName]),
451
+ client.query(countQuery),
452
+ client.query(metricQuery)
453
+ ]);
454
+ let metric = "cosine";
455
+ if (metricResult.rows.length > 0) {
456
+ const operatorClass = metricResult.rows[0].operator_class;
457
+ if (operatorClass.includes("l2")) {
458
+ metric = "euclidean";
459
+ } else if (operatorClass.includes("ip")) {
460
+ metric = "dotproduct";
461
+ } else if (operatorClass.includes("cosine")) {
462
+ metric = "cosine";
463
+ }
464
+ }
465
+ return {
466
+ dimension: dimResult.rows[0].dimension,
467
+ count: parseInt(countResult.rows[0].count),
468
+ metric
469
+ };
470
+ } catch (e) {
471
+ await client.query("ROLLBACK");
472
+ throw new Error(`Failed to describe vector table: ${e.message}`);
473
+ } finally {
474
+ client.release();
475
+ }
476
+ }
477
+ async deleteIndex(indexName) {
478
+ const client = await this.pool.connect();
479
+ try {
480
+ await client.query(`DROP TABLE IF EXISTS ${indexName} CASCADE`);
481
+ } catch (error) {
482
+ await client.query("ROLLBACK");
483
+ throw new Error(`Failed to delete vector table: ${error.message}`);
484
+ } finally {
485
+ client.release();
486
+ }
487
+ }
488
+ async truncateIndex(indexName) {
489
+ const client = await this.pool.connect();
490
+ try {
491
+ await client.query(`TRUNCATE ${indexName}`);
492
+ } catch (e) {
493
+ await client.query("ROLLBACK");
494
+ throw new Error(`Failed to truncate vector table: ${e.message}`);
495
+ } finally {
496
+ client.release();
497
+ }
498
+ }
499
+ async disconnect() {
500
+ await this.pool.end();
501
+ }
502
+ };
503
+ var PostgresStore = class extends MastraStorage {
504
+ db;
505
+ pgp;
506
+ constructor(config) {
507
+ super({ name: "PostgresStore" });
508
+ this.pgp = pgPromise();
509
+ this.db = this.pgp(
510
+ `connectionString` in config ? { connectionString: config.connectionString } : {
511
+ host: config.host,
512
+ port: config.port,
513
+ database: config.database,
514
+ user: config.user,
515
+ password: config.password
516
+ }
517
+ );
518
+ }
519
+ async createTable({
520
+ tableName,
521
+ schema
522
+ }) {
523
+ try {
524
+ const columns = Object.entries(schema).map(([name, def]) => {
525
+ const constraints = [];
526
+ if (def.primaryKey) constraints.push("PRIMARY KEY");
527
+ if (!def.nullable) constraints.push("NOT NULL");
528
+ return `"${name}" ${def.type.toUpperCase()} ${constraints.join(" ")}`;
529
+ }).join(",\n");
530
+ const sql = `
531
+ CREATE TABLE IF NOT EXISTS ${tableName} (
532
+ ${columns}
533
+ );
534
+ ${tableName === MastraStorage.TABLE_WORKFLOW_SNAPSHOT ? `
535
+ DO $$ BEGIN
536
+ IF NOT EXISTS (
537
+ SELECT 1 FROM pg_constraint WHERE conname = 'mastra_workflow_snapshot_workflow_name_run_id_key'
538
+ ) THEN
539
+ ALTER TABLE ${tableName}
540
+ ADD CONSTRAINT mastra_workflow_snapshot_workflow_name_run_id_key
541
+ UNIQUE (workflow_name, run_id);
542
+ END IF;
543
+ END $$;
544
+ ` : ""}
545
+ `;
546
+ await this.db.none(sql);
547
+ } catch (error) {
548
+ console.error(`Error creating table ${tableName}:`, error);
549
+ throw error;
550
+ }
551
+ }
552
+ async clearTable({ tableName }) {
553
+ try {
554
+ await this.db.none(`TRUNCATE TABLE ${tableName} CASCADE`);
555
+ } catch (error) {
556
+ console.error(`Error clearing table ${tableName}:`, error);
557
+ throw error;
558
+ }
559
+ }
560
+ async insert({ tableName, record }) {
561
+ try {
562
+ const columns = Object.keys(record);
563
+ const values = Object.values(record);
564
+ const placeholders = values.map((_, i) => `$${i + 1}`).join(", ");
565
+ await this.db.none(
566
+ `INSERT INTO ${tableName} (${columns.map((c) => `"${c}"`).join(", ")}) VALUES (${placeholders})`,
567
+ values
568
+ );
569
+ } catch (error) {
570
+ console.error(`Error inserting into ${tableName}:`, error);
571
+ throw error;
572
+ }
573
+ }
574
+ async load({ tableName, keys }) {
575
+ try {
576
+ const keyEntries = Object.entries(keys);
577
+ const conditions = keyEntries.map(([key], index) => `"${key}" = $${index + 1}`).join(" AND ");
578
+ const values = keyEntries.map(([_, value]) => value);
579
+ const result = await this.db.oneOrNone(`SELECT * FROM ${tableName} WHERE ${conditions}`, values);
580
+ if (!result) {
581
+ return null;
582
+ }
583
+ if (tableName === MastraStorage.TABLE_WORKFLOW_SNAPSHOT) {
584
+ const snapshot = result;
585
+ if (typeof snapshot.snapshot === "string") {
586
+ snapshot.snapshot = JSON.parse(snapshot.snapshot);
587
+ }
588
+ return snapshot;
589
+ }
590
+ return result;
591
+ } catch (error) {
592
+ console.error(`Error loading from ${tableName}:`, error);
593
+ throw error;
594
+ }
595
+ }
596
+ async getThreadById({ threadId }) {
597
+ try {
598
+ const thread = await this.db.oneOrNone(
599
+ `SELECT
600
+ id,
601
+ "resourceId",
602
+ title,
603
+ metadata,
604
+ "createdAt",
605
+ "updatedAt"
606
+ FROM "${MastraStorage.TABLE_THREADS}"
607
+ WHERE id = $1`,
608
+ [threadId]
609
+ );
610
+ if (!thread) {
611
+ return null;
612
+ }
613
+ return {
614
+ ...thread,
615
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
616
+ createdAt: thread.createdAt,
617
+ updatedAt: thread.updatedAt
618
+ };
619
+ } catch (error) {
620
+ console.error(`Error getting thread ${threadId}:`, error);
621
+ throw error;
622
+ }
623
+ }
624
+ async getThreadsByResourceId({ resourceId }) {
625
+ try {
626
+ const threads = await this.db.manyOrNone(
627
+ `SELECT
628
+ id,
629
+ "resourceId",
630
+ title,
631
+ metadata,
632
+ "createdAt",
633
+ "updatedAt"
634
+ FROM "${MastraStorage.TABLE_THREADS}"
635
+ WHERE "resourceId" = $1`,
636
+ [resourceId]
637
+ );
638
+ return threads.map((thread) => ({
639
+ ...thread,
640
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
641
+ createdAt: thread.createdAt,
642
+ updatedAt: thread.updatedAt
643
+ }));
644
+ } catch (error) {
645
+ console.error(`Error getting threads for resource ${resourceId}:`, error);
646
+ throw error;
647
+ }
648
+ }
649
+ async saveThread({ thread }) {
650
+ try {
651
+ await this.db.none(
652
+ `INSERT INTO "${MastraStorage.TABLE_THREADS}" (
653
+ id,
654
+ "resourceId",
655
+ title,
656
+ metadata,
657
+ "createdAt",
658
+ "updatedAt"
659
+ ) VALUES ($1, $2, $3, $4, $5, $6)
660
+ ON CONFLICT (id) DO UPDATE SET
661
+ "resourceId" = EXCLUDED."resourceId",
662
+ title = EXCLUDED.title,
663
+ metadata = EXCLUDED.metadata,
664
+ "createdAt" = EXCLUDED."createdAt",
665
+ "updatedAt" = EXCLUDED."updatedAt"`,
666
+ [
667
+ thread.id,
668
+ thread.resourceId,
669
+ thread.title,
670
+ thread.metadata ? JSON.stringify(thread.metadata) : null,
671
+ thread.createdAt,
672
+ thread.updatedAt
673
+ ]
674
+ );
675
+ return thread;
676
+ } catch (error) {
677
+ console.error("Error saving thread:", error);
678
+ throw error;
679
+ }
680
+ }
681
+ async updateThread({
682
+ id,
683
+ title,
684
+ metadata
685
+ }) {
686
+ try {
687
+ const existingThread = await this.getThreadById({ threadId: id });
688
+ if (!existingThread) {
689
+ throw new Error(`Thread ${id} not found`);
690
+ }
691
+ const mergedMetadata = {
692
+ ...existingThread.metadata,
693
+ ...metadata
694
+ };
695
+ const thread = await this.db.one(
696
+ `UPDATE "${MastraStorage.TABLE_THREADS}"
697
+ SET title = $1,
698
+ metadata = $2,
699
+ "updatedAt" = $3
700
+ WHERE id = $4
701
+ RETURNING *`,
702
+ [title, mergedMetadata, (/* @__PURE__ */ new Date()).toISOString(), id]
703
+ );
704
+ return {
705
+ ...thread,
706
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
707
+ createdAt: thread.createdAt,
708
+ updatedAt: thread.updatedAt
709
+ };
710
+ } catch (error) {
711
+ console.error("Error updating thread:", error);
712
+ throw error;
713
+ }
714
+ }
715
+ async deleteThread({ threadId }) {
716
+ try {
717
+ await this.db.tx(async (t) => {
718
+ await t.none(`DELETE FROM "${MastraStorage.TABLE_MESSAGES}" WHERE thread_id = $1`, [threadId]);
719
+ await t.none(`DELETE FROM "${MastraStorage.TABLE_THREADS}" WHERE id = $1`, [threadId]);
720
+ });
721
+ } catch (error) {
722
+ console.error("Error deleting thread:", error);
723
+ throw error;
724
+ }
725
+ }
726
+ async getMessages({ threadId, selectBy }) {
727
+ try {
728
+ const messages = [];
729
+ const limit = typeof selectBy?.last === `number` ? selectBy.last : 40;
730
+ const include = selectBy?.include || [];
731
+ if (include.length) {
732
+ const includeResult = await this.db.manyOrNone(
733
+ `
734
+ WITH ordered_messages AS (
735
+ SELECT
736
+ *,
737
+ ROW_NUMBER() OVER (ORDER BY "createdAt") as row_num
738
+ FROM "${MastraStorage.TABLE_MESSAGES}"
739
+ WHERE thread_id = $1
740
+ )
741
+ SELECT DISTINCT ON (m.id)
742
+ m.id,
743
+ m.content,
744
+ m.role,
745
+ m.type,
746
+ m."createdAt",
747
+ m.thread_id AS "threadId"
748
+ FROM ordered_messages m
749
+ WHERE m.id = ANY($2)
750
+ OR EXISTS (
751
+ SELECT 1 FROM ordered_messages target
752
+ WHERE target.id = ANY($2)
753
+ AND (
754
+ -- Get previous messages based on the max withPreviousMessages
755
+ (m.row_num >= target.row_num - $3 AND m.row_num < target.row_num)
756
+ OR
757
+ -- Get next messages based on the max withNextMessages
758
+ (m.row_num <= target.row_num + $4 AND m.row_num > target.row_num)
759
+ )
760
+ )
761
+ ORDER BY m.id, m."createdAt"
762
+ `,
763
+ [
764
+ threadId,
765
+ include.map((i) => i.id),
766
+ Math.max(...include.map((i) => i.withPreviousMessages || 0)),
767
+ Math.max(...include.map((i) => i.withNextMessages || 0))
768
+ ]
769
+ );
770
+ messages.push(...includeResult);
771
+ }
772
+ const result = await this.db.manyOrNone(
773
+ `
774
+ SELECT
775
+ id,
776
+ content,
777
+ role,
778
+ type,
779
+ "createdAt",
780
+ thread_id AS "threadId"
781
+ FROM "${MastraStorage.TABLE_MESSAGES}"
782
+ WHERE thread_id = $1
783
+ AND id != ALL($2)
784
+ ORDER BY "createdAt" DESC
785
+ LIMIT $3
786
+ `,
787
+ [threadId, messages.map((m) => m.id), limit]
788
+ );
789
+ messages.push(...result);
790
+ messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
791
+ messages.forEach((message) => {
792
+ if (typeof message.content === "string") {
793
+ try {
794
+ message.content = JSON.parse(message.content);
795
+ } catch (e) {
796
+ }
797
+ }
798
+ });
799
+ return messages;
800
+ } catch (error) {
801
+ console.error("Error getting messages:", error);
802
+ throw error;
803
+ }
804
+ }
805
+ async saveMessages({ messages }) {
806
+ if (messages.length === 0) return messages;
807
+ try {
808
+ const threadId = messages[0]?.threadId;
809
+ if (!threadId) {
810
+ throw new Error("Thread ID is required");
811
+ }
812
+ const thread = await this.getThreadById({ threadId });
813
+ if (!thread) {
814
+ throw new Error(`Thread ${threadId} not found`);
815
+ }
816
+ await this.db.tx(async (t) => {
817
+ for (const message of messages) {
818
+ await t.none(
819
+ `INSERT INTO "${MastraStorage.TABLE_MESSAGES}" (id, thread_id, content, "createdAt", role, type)
820
+ VALUES ($1, $2, $3, $4, $5, $6)`,
821
+ [
822
+ message.id,
823
+ threadId,
824
+ typeof message.content === "string" ? message.content : JSON.stringify(message.content),
825
+ message.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
826
+ message.role,
827
+ message.type
828
+ ]
829
+ );
830
+ }
831
+ });
832
+ return messages;
833
+ } catch (error) {
834
+ console.error("Error saving messages:", error);
835
+ throw error;
836
+ }
837
+ }
838
+ async persistWorkflowSnapshot({
839
+ workflowName,
840
+ runId,
841
+ snapshot
842
+ }) {
843
+ try {
844
+ const now = (/* @__PURE__ */ new Date()).toISOString();
845
+ await this.db.none(
846
+ `INSERT INTO "${MastraStorage.TABLE_WORKFLOW_SNAPSHOT}" (
847
+ workflow_name,
848
+ run_id,
849
+ snapshot,
850
+ "createdAt",
851
+ "updatedAt"
852
+ ) VALUES ($1, $2, $3, $4, $5)
853
+ ON CONFLICT (workflow_name, run_id) DO UPDATE
854
+ SET snapshot = EXCLUDED.snapshot,
855
+ "updatedAt" = EXCLUDED."updatedAt"`,
856
+ [workflowName, runId, JSON.stringify(snapshot), now, now]
857
+ );
858
+ } catch (error) {
859
+ console.error("Error persisting workflow snapshot:", error);
860
+ throw error;
861
+ }
862
+ }
863
+ async loadWorkflowSnapshot({
864
+ workflowName,
865
+ runId
866
+ }) {
867
+ try {
868
+ const result = await this.load({
869
+ tableName: MastraStorage.TABLE_WORKFLOW_SNAPSHOT,
870
+ keys: {
871
+ workflow_name: workflowName,
872
+ run_id: runId
873
+ }
874
+ });
875
+ if (!result) {
876
+ return null;
877
+ }
878
+ return result.snapshot;
879
+ } catch (error) {
880
+ console.error("Error loading workflow snapshot:", error);
881
+ throw error;
882
+ }
883
+ }
884
+ async close() {
885
+ this.pgp.end();
886
+ }
887
+ };
888
+
889
+ export { PgVector, PostgresStore };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/pg",
3
- "version": "0.1.0-alpha.11",
3
+ "version": "0.1.0-alpha.12",
4
4
  "description": "Postgres provider for Mastra - includes both vector and db storage capabilities",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -17,7 +17,7 @@
17
17
  "dependencies": {
18
18
  "pg": "^8.13.1",
19
19
  "pg-promise": "^11.5.4",
20
- "@mastra/core": "^0.2.0-alpha.101"
20
+ "@mastra/core": "^0.2.0-alpha.102"
21
21
  },
22
22
  "devDependencies": {
23
23
  "@microsoft/api-extractor": "^7.49.2",