@mastra/pg 1.16.1-alpha.0 → 1.17.0-alpha.3

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 CHANGED
@@ -1,15 +1,15 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { BRANCH_SPAN_TYPES, createVectorErrorId, AgentsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, TABLE_SCHEMAS, createStorageErrorId, normalizePerPage, calculatePagination, BackgroundTasksStorage, TABLE_BACKGROUND_TASKS, BlobStore, TABLE_SKILL_BLOBS, ChannelsStorage, TABLE_CHANNEL_INSTALLATIONS, TABLE_CHANNEL_CONFIG, DatasetsStorage, TABLE_DATASETS, TABLE_DATASET_ITEMS, TABLE_DATASET_VERSIONS, DATASETS_SCHEMA, TABLE_CONFIGS, DATASET_ITEMS_SCHEMA, DATASET_VERSIONS_SCHEMA, ensureDate, safelyParseJSON, hasErrorCode, ExperimentsStorage, TABLE_EXPERIMENTS, TABLE_EXPERIMENT_RESULTS, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, FavoritesStorage, TABLE_FAVORITES, MCPClientsStorage, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, MCPServersStorage, TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS, MemoryStorage, TABLE_THREADS, TABLE_RESOURCES, TABLE_MESSAGES, OBSERVATIONAL_MEMORY_TABLE_SCHEMA, NotificationsStorage, TABLE_NOTIFICATIONS, ObservabilityStorage, TABLE_SPANS, listTracesArgsSchema, toTraceSpans, PromptBlocksStorage, TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS, SchedulesStorage, TABLE_SCHEDULES, TABLE_SCHEDULE_TRIGGERS, ScorerDefinitionsStorage, TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS, ScoresStorage, TABLE_SCORERS, SkillsStorage, TABLE_SKILLS, TABLE_SKILL_VERSIONS, ToolProviderConnectionsStorage, TABLE_TOOL_PROVIDER_CONNECTIONS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, mergeWorkflowStepResult, WorkspacesStorage, TABLE_WORKSPACES, TABLE_WORKSPACE_VERSIONS, MastraCompositeStore, TraceStatus, getDefaultValue, parseDuration, listBranchesArgsSchema, listLogsArgsSchema, listMetricsArgsSchema, listScoresArgsSchema, listFeedbackArgsSchema, normalizeScheduleTarget, transformScoreRow as transformScoreRow$1, getSqlType, EntityType, METRIC_DISTINCT_COLUMNS } from '@mastra/core/storage';
2
+ import { BRANCH_SPAN_TYPES, createVectorErrorId, AgentsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, TABLE_SCHEMAS, createStorageErrorId, normalizePerPage, calculatePagination, BackgroundTasksStorage, TABLE_BACKGROUND_TASKS, BlobStore, TABLE_SKILL_BLOBS, ChannelsStorage, TABLE_CHANNEL_INSTALLATIONS, TABLE_CHANNEL_CONFIG, DatasetsStorage, TABLE_DATASETS, TABLE_DATASET_ITEMS, TABLE_DATASET_VERSIONS, DATASETS_SCHEMA, TABLE_CONFIGS, DATASET_ITEMS_SCHEMA, DATASET_VERSIONS_SCHEMA, ensureDate, safelyParseJSON, hasErrorCode, ExperimentsStorage, TABLE_EXPERIMENTS, TABLE_EXPERIMENT_RESULTS, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, FavoritesStorage, TABLE_FAVORITES, MCPClientsStorage, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, MCPServersStorage, TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS, MemoryStorage, TABLE_THREADS, TABLE_RESOURCES, TABLE_MESSAGES, OBSERVATIONAL_MEMORY_TABLE_SCHEMA, NotificationsStorage, TABLE_NOTIFICATIONS, ObservabilityStorage, TABLE_SPANS, listTracesArgsSchema, toTraceSpans, PromptBlocksStorage, TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS, SchedulesStorage, TABLE_SCHEDULES, TABLE_SCHEDULE_TRIGGERS, ScorerDefinitionsStorage, TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS, ScoresStorage, TABLE_SCORERS, SkillsStorage, TABLE_SKILLS, TABLE_SKILL_VERSIONS, ToolProviderConnectionsStorage, TABLE_TOOL_PROVIDER_CONNECTIONS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, mergeWorkflowStepResult, WorkspacesStorage, TABLE_WORKSPACES, TABLE_WORKSPACE_VERSIONS, FactoryStorage, MastraCompositeStore, TraceStatus, getDefaultValue, parseDuration, listBranchesArgsSchema, listLogsArgsSchema, listMetricsArgsSchema, listScoresArgsSchema, listFeedbackArgsSchema, normalizeScheduleTarget, transformScoreRow as transformScoreRow$1, UniqueViolationError, getSqlType, EntityType, METRIC_DISTINCT_COLUMNS } from '@mastra/core/storage';
3
3
  import { parseSqlIdentifier, parseFieldKey } from '@mastra/core/utils';
4
4
  import { MastraVector, validateTopK, validateUpsertInput } from '@mastra/core/vector';
5
5
  import { Mutex } from 'async-mutex';
6
6
  import * as pg from 'pg';
7
- import { Pool } from 'pg';
7
+ import pg__default, { Pool } from 'pg';
8
8
  import xxhash from 'xxhash-wasm';
9
9
  import { parse } from 'pg-connection-string';
10
10
  import { BaseFilterTranslator } from '@mastra/core/vector/filter';
11
11
  import { MastraBase } from '@mastra/core/base';
12
- import { randomUUID } from 'crypto';
12
+ import { randomUUID, createHash } from 'crypto';
13
13
  import { MessageList } from '@mastra/core/agent';
14
14
  import { coreFeatures } from '@mastra/core/features';
15
15
  import { saveScorePayloadSchema } from '@mastra/core/evals';
@@ -7302,7 +7302,7 @@ var FavoritesPG = class _FavoritesPG extends FavoritesStorage {
7302
7302
  }
7303
7303
  const fullFavoritesTable = getTableName2({ indexName: TABLE_FAVORITES, schemaName: getSchemaName2(schemaName) });
7304
7304
  statements.push(
7305
- `CREATE INDEX IF NOT EXISTS idx_favorites_entity ON ${fullFavoritesTable} ("entityType", "entityId")`
7305
+ `CREATE INDEX IF NOT EXISTS idx_favorites_entity ON ${fullFavoritesTable} ("entityType", "entityId");`
7306
7306
  );
7307
7307
  return statements;
7308
7308
  }
@@ -20173,6 +20173,453 @@ var WorkspacesPG = class _WorkspacesPG extends WorkspacesStorage {
20173
20173
  };
20174
20174
  }
20175
20175
  };
20176
+ var IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
20177
+ var PG_UNIQUE_VIOLATION = "23505";
20178
+ var COLUMN_DDL = {
20179
+ text: "TEXT",
20180
+ bigint: "BIGINT",
20181
+ integer: "INTEGER",
20182
+ boolean: "BOOLEAN",
20183
+ json: "JSONB",
20184
+ timestamp: "TIMESTAMPTZ",
20185
+ "uuid-pk": "UUID"
20186
+ };
20187
+ function assertIdentifier(kind, name) {
20188
+ if (!IDENTIFIER_RE.test(name)) {
20189
+ throw new Error(`PgFactoryStorage: invalid ${kind} identifier '${name}'`);
20190
+ }
20191
+ }
20192
+ function isUniqueViolation(error) {
20193
+ return typeof error === "object" && error !== null && error.code === PG_UNIQUE_VIOLATION;
20194
+ }
20195
+ function primaryKeyOf(schema) {
20196
+ const pks = Object.entries(schema.columns).filter(([, spec]) => spec.type === "uuid-pk" || spec.primaryKey);
20197
+ if (pks.length !== 1) {
20198
+ throw new Error(
20199
+ `PgFactoryStorage: collection '${schema.name}' must declare exactly one primary key (found ${pks.length})`
20200
+ );
20201
+ }
20202
+ return pks[0][0];
20203
+ }
20204
+ function assertUpsertConflict(schema, conflictKeys, row) {
20205
+ const keys = new Set(conflictKeys);
20206
+ if (keys.size !== conflictKeys.length || conflictKeys.some((key) => row[key] === void 0)) {
20207
+ throw new Error(
20208
+ `PgFactoryStorage: upsert conflict keys for '${schema.name}' must be unique and present in the row`
20209
+ );
20210
+ }
20211
+ const primaryKey = primaryKeyOf(schema);
20212
+ const candidates = [{ columns: [primaryKey] }, ...schema.uniqueIndexes ?? []];
20213
+ const matches = candidates.some((candidate) => {
20214
+ if (candidate.columns.length !== keys.size || candidate.columns.some((column) => !keys.has(column))) return false;
20215
+ if ("whereNotNull" in candidate && candidate.whereNotNull && row[candidate.whereNotNull] == null) return false;
20216
+ if ("whereNull" in candidate && candidate.whereNull && row[candidate.whereNull] != null) return false;
20217
+ return true;
20218
+ });
20219
+ if (!matches) {
20220
+ throw new Error(
20221
+ `PgFactoryStorage: upsert conflict keys [${conflictKeys.join(", ")}] do not match an applicable primary key or unique index on '${schema.name}'`
20222
+ );
20223
+ }
20224
+ }
20225
+ function serializeDefault(value) {
20226
+ if (typeof value === "string") return `'${value.replace(/'/g, "''")}'`;
20227
+ return String(value);
20228
+ }
20229
+ function hashAdvisoryLockKey(key) {
20230
+ const digest = createHash("sha256").update(key).digest();
20231
+ return [digest.readInt32BE(0), digest.readInt32BE(4)];
20232
+ }
20233
+ var PgFactoryStorageOps = class {
20234
+ #queryable;
20235
+ #transactionClient;
20236
+ #schemas;
20237
+ constructor(queryable, schemas, transactionClient) {
20238
+ this.#queryable = queryable;
20239
+ this.#transactionClient = transactionClient;
20240
+ this.#schemas = schemas;
20241
+ }
20242
+ #schema(collection) {
20243
+ const schema = this.#schemas.get(collection);
20244
+ if (!schema) {
20245
+ throw new Error(
20246
+ `PgFactoryStorage: unknown collection '${collection}' \u2014 register it via ensureCollections() first`
20247
+ );
20248
+ }
20249
+ return schema;
20250
+ }
20251
+ #column(schema, column) {
20252
+ const spec = schema.columns[column];
20253
+ if (!spec) {
20254
+ throw new Error(`PgFactoryStorage: unknown column '${column}' on collection '${schema.name}'`);
20255
+ }
20256
+ return spec;
20257
+ }
20258
+ #serialize(spec, value) {
20259
+ if (value === null || value === void 0) return null;
20260
+ switch (spec.type) {
20261
+ case "timestamp":
20262
+ return value instanceof Date ? value : new Date(String(value));
20263
+ case "boolean":
20264
+ return Boolean(value);
20265
+ case "json":
20266
+ return JSON.stringify(value);
20267
+ case "bigint":
20268
+ case "integer":
20269
+ return Number(value);
20270
+ default:
20271
+ return String(value);
20272
+ }
20273
+ }
20274
+ #deserializeRow(schema, raw) {
20275
+ const row = {};
20276
+ for (const [name, spec] of Object.entries(schema.columns)) {
20277
+ const value = raw[name];
20278
+ if (value === null || value === void 0) {
20279
+ row[name] = null;
20280
+ continue;
20281
+ }
20282
+ switch (spec.type) {
20283
+ case "timestamp":
20284
+ row[name] = value instanceof Date ? value : new Date(String(value));
20285
+ break;
20286
+ case "boolean":
20287
+ row[name] = Boolean(value);
20288
+ break;
20289
+ case "json":
20290
+ row[name] = typeof value === "string" ? JSON.parse(value) : value;
20291
+ break;
20292
+ case "bigint":
20293
+ case "integer":
20294
+ row[name] = Number(value);
20295
+ break;
20296
+ default:
20297
+ row[name] = String(value);
20298
+ }
20299
+ }
20300
+ return row;
20301
+ }
20302
+ /** Builds `WHERE` SQL (without the keyword). `{}` yields a match-all clause. */
20303
+ #buildWhere(schema, where, startIndex = 1) {
20304
+ const clauses = [];
20305
+ const args = [];
20306
+ let index = startIndex;
20307
+ for (const [column, condition] of Object.entries(where)) {
20308
+ const spec = this.#column(schema, column);
20309
+ if (condition !== null && typeof condition === "object" && !(condition instanceof Date) && "in" in condition) {
20310
+ if (condition.in.length === 0) {
20311
+ clauses.push("FALSE");
20312
+ continue;
20313
+ }
20314
+ const nonNull = condition.in.filter((value) => value !== null);
20315
+ const includesNull = nonNull.length !== condition.in.length;
20316
+ const inClause = nonNull.length > 0 ? `"${column}" IN (${nonNull.map(() => `$${index++}`).join(", ")})` : void 0;
20317
+ clauses.push(
20318
+ inClause && includesNull ? `(${inClause} OR "${column}" IS NULL)` : inClause ?? `"${column}" IS NULL`
20319
+ );
20320
+ args.push(...nonNull.map((value) => this.#serialize(spec, value)));
20321
+ } else if (condition === null) {
20322
+ clauses.push(`"${column}" IS NULL`);
20323
+ } else {
20324
+ clauses.push(`"${column}" = $${index++}`);
20325
+ args.push(this.#serialize(spec, condition));
20326
+ }
20327
+ }
20328
+ return { sql: clauses.length > 0 ? clauses.join(" AND ") : "TRUE", args, nextIndex: index };
20329
+ }
20330
+ /** Keyset condition: rows strictly after `cursor.values` in the `orderBy` order. */
20331
+ #buildCursor(schema, orderBy, values, startIndex) {
20332
+ if (values.length !== orderBy.length) {
20333
+ throw new Error(`PgFactoryStorage: cursor has ${values.length} values but orderBy has ${orderBy.length} columns`);
20334
+ }
20335
+ const branches = [];
20336
+ const args = [];
20337
+ let index = startIndex;
20338
+ for (let i = 0; i < orderBy.length; i++) {
20339
+ const parts = [];
20340
+ for (let j = 0; j < i; j++) {
20341
+ const [column2] = orderBy[j];
20342
+ parts.push(`"${column2}" = $${index++}`);
20343
+ args.push(this.#serialize(this.#column(schema, column2), values[j]));
20344
+ }
20345
+ const [column, dir] = orderBy[i];
20346
+ parts.push(`"${column}" ${dir === "desc" ? "<" : ">"} $${index++}`);
20347
+ args.push(this.#serialize(this.#column(schema, column), values[i]));
20348
+ branches.push(`(${parts.join(" AND ")})`);
20349
+ }
20350
+ return { sql: `(${branches.join(" OR ")})`, args, nextIndex: index };
20351
+ }
20352
+ #buildSelect(schema, where, opts, forUpdate = false) {
20353
+ const filter = this.#buildWhere(schema, where);
20354
+ let sql = `SELECT * FROM "${schema.name}" WHERE ${filter.sql}`;
20355
+ const args = [...filter.args];
20356
+ let index = filter.nextIndex;
20357
+ if (opts?.cursor) {
20358
+ if (!opts.orderBy || opts.orderBy.length === 0) {
20359
+ throw new Error("PgFactoryStorage: cursor pagination requires orderBy");
20360
+ }
20361
+ const cursor = this.#buildCursor(schema, opts.orderBy, opts.cursor.values, index);
20362
+ sql += ` AND ${cursor.sql}`;
20363
+ args.push(...cursor.args);
20364
+ index = cursor.nextIndex;
20365
+ }
20366
+ if (opts?.orderBy && opts.orderBy.length > 0) {
20367
+ const order = opts.orderBy.map(([column, dir]) => {
20368
+ this.#column(schema, column);
20369
+ return `"${column}" ${dir === "desc" ? "DESC" : "ASC"}`;
20370
+ }).join(", ");
20371
+ sql += ` ORDER BY ${order}`;
20372
+ }
20373
+ if (opts?.limit !== void 0) {
20374
+ sql += ` LIMIT $${index++}`;
20375
+ args.push(opts.limit);
20376
+ }
20377
+ if (forUpdate) sql += " FOR UPDATE";
20378
+ return { sql, args };
20379
+ }
20380
+ async #select(queryable, collection, where, opts, forUpdate = false) {
20381
+ const schema = this.#schema(collection);
20382
+ const { sql, args } = this.#buildSelect(schema, where, opts, forUpdate);
20383
+ const result = await queryable.query(sql, args);
20384
+ return result.rows.map((raw) => this.#deserializeRow(schema, raw));
20385
+ }
20386
+ async findOne(collection, where) {
20387
+ const rows = await this.#select(this.#queryable, collection, where, { limit: 1 });
20388
+ return rows[0] ?? null;
20389
+ }
20390
+ async findMany(collection, where, opts) {
20391
+ return this.#select(this.#queryable, collection, where, opts);
20392
+ }
20393
+ async insertOne(collection, row) {
20394
+ const schema = this.#schema(collection);
20395
+ const pk = primaryKeyOf(schema);
20396
+ const values = { ...row };
20397
+ if (schema.columns[pk].type === "uuid-pk" && values[pk] === void 0) {
20398
+ values[pk] = randomUUID();
20399
+ }
20400
+ const columns = Object.keys(values).filter((column) => values[column] !== void 0);
20401
+ for (const column of columns) this.#column(schema, column);
20402
+ const sql = `INSERT INTO "${schema.name}" (${columns.map((c) => `"${c}"`).join(", ")}) VALUES (${columns.map((_, i) => `$${i + 1}`).join(", ")}) RETURNING *`;
20403
+ const args = columns.map((column) => this.#serialize(this.#column(schema, column), values[column]));
20404
+ try {
20405
+ const result = await this.#queryable.query(sql, args);
20406
+ return this.#deserializeRow(schema, result.rows[0]);
20407
+ } catch (error) {
20408
+ if (isUniqueViolation(error)) throw new UniqueViolationError(collection, { cause: error });
20409
+ throw error;
20410
+ }
20411
+ }
20412
+ async upsertOne(collection, conflictKeys, row) {
20413
+ const schema = this.#schema(collection);
20414
+ const pk = primaryKeyOf(schema);
20415
+ assertUpsertConflict(schema, conflictKeys, row);
20416
+ const keyWhere = Object.fromEntries(conflictKeys.map((key) => [key, row[key]]));
20417
+ let lastError;
20418
+ for (let attempt = 0; attempt < 2; attempt++) {
20419
+ const existing = await this.findOne(collection, keyWhere);
20420
+ if (existing) {
20421
+ const set = Object.fromEntries(
20422
+ Object.entries(row).filter(
20423
+ ([column, value]) => value !== void 0 && column !== pk && !conflictKeys.includes(column)
20424
+ )
20425
+ );
20426
+ if (Object.keys(set).length > 0) {
20427
+ await this.updateMany(collection, { [pk]: existing[pk] }, set);
20428
+ }
20429
+ const updated = await this.findOne(collection, { [pk]: existing[pk] });
20430
+ if (!updated) continue;
20431
+ return updated;
20432
+ }
20433
+ try {
20434
+ return await this.insertOne(collection, row);
20435
+ } catch (error) {
20436
+ if (!(error instanceof UniqueViolationError)) throw error;
20437
+ lastError = error;
20438
+ }
20439
+ }
20440
+ throw lastError ?? new Error(`PgFactoryStorage: upsert into '${collection}' did not converge`);
20441
+ }
20442
+ async updateMany(collection, where, set) {
20443
+ return this.#updateMany(this.#queryable, collection, where, set);
20444
+ }
20445
+ async #updateMany(queryable, collection, where, set) {
20446
+ const schema = this.#schema(collection);
20447
+ const columns = Object.keys(set).filter((column) => set[column] !== void 0);
20448
+ if (columns.length === 0) return 0;
20449
+ const assignments = columns.map((column, i) => `"${column}" = $${i + 1}`).join(", ");
20450
+ const filter = this.#buildWhere(schema, where, columns.length + 1);
20451
+ const args = [...columns.map((column) => this.#serialize(this.#column(schema, column), set[column])), ...filter.args];
20452
+ const result = await queryable.query(`UPDATE "${schema.name}" SET ${assignments} WHERE ${filter.sql}`, args);
20453
+ return result.rowCount ?? 0;
20454
+ }
20455
+ async deleteMany(collection, where) {
20456
+ const schema = this.#schema(collection);
20457
+ const filter = this.#buildWhere(schema, where);
20458
+ const result = await this.#queryable.query(`DELETE FROM "${schema.name}" WHERE ${filter.sql}`, filter.args);
20459
+ return result.rowCount ?? 0;
20460
+ }
20461
+ async updateAtomic(collection, where, fn) {
20462
+ const run = async (client2) => {
20463
+ const schema = this.#schema(collection);
20464
+ const pk = primaryKeyOf(schema);
20465
+ const rows = await this.#select(client2, collection, where, { limit: 1 }, true);
20466
+ const row = rows[0];
20467
+ if (!row) return null;
20468
+ const patch = await fn(row);
20469
+ if (patch === null) return row;
20470
+ const pkWhere = { [pk]: row[pk] };
20471
+ await this.#updateMany(client2, collection, pkWhere, patch);
20472
+ const updated = await this.#select(client2, collection, pkWhere, { limit: 1 });
20473
+ return updated[0] ?? null;
20474
+ };
20475
+ if (this.#transactionClient) return run(this.#transactionClient);
20476
+ const pool = this.#queryable;
20477
+ const client = await pool.connect();
20478
+ try {
20479
+ await client.query("BEGIN");
20480
+ try {
20481
+ const result = await run(client);
20482
+ await client.query("COMMIT");
20483
+ return result;
20484
+ } catch (error) {
20485
+ await client.query("ROLLBACK");
20486
+ throw error;
20487
+ }
20488
+ } finally {
20489
+ client.release();
20490
+ }
20491
+ }
20492
+ };
20493
+ var PgFactoryStorage = class extends FactoryStorage {
20494
+ ops;
20495
+ #pool;
20496
+ #ownsPool;
20497
+ #config;
20498
+ #schemas = /* @__PURE__ */ new Map();
20499
+ #mastraStorage;
20500
+ constructor(config) {
20501
+ super();
20502
+ this.#config = config;
20503
+ if ("store" in config) {
20504
+ this.#pool = config.store.pool;
20505
+ this.#ownsPool = false;
20506
+ this.#mastraStorage = config.store;
20507
+ } else {
20508
+ this.#pool = new pg__default.Pool({ connectionString: config.connectionString });
20509
+ this.#ownsPool = true;
20510
+ }
20511
+ this.ops = new PgFactoryStorageOps(this.#pool, this.#schemas);
20512
+ }
20513
+ getMastraStorage() {
20514
+ if (!this.#mastraStorage) {
20515
+ const config = this.#config;
20516
+ this.#mastraStorage = new PostgresStore({
20517
+ id: config.id ?? "pg-factory",
20518
+ pool: this.#pool,
20519
+ ...config.retention ? { retention: config.retention } : {}
20520
+ });
20521
+ }
20522
+ return this.#mastraStorage;
20523
+ }
20524
+ async initStorage() {
20525
+ await this.#pool.query("SELECT 1");
20526
+ }
20527
+ async withTransaction(fn) {
20528
+ const client = await this.#pool.connect();
20529
+ try {
20530
+ await client.query("BEGIN");
20531
+ try {
20532
+ const result = await fn(new PgFactoryStorageOps(client, this.#schemas, client));
20533
+ await client.query("COMMIT");
20534
+ return result;
20535
+ } catch (error) {
20536
+ await client.query("ROLLBACK");
20537
+ throw error;
20538
+ }
20539
+ } finally {
20540
+ client.release();
20541
+ }
20542
+ }
20543
+ async ensureCollections(schemas) {
20544
+ for (const schema of schemas) {
20545
+ await this.#ensureCollection(schema);
20546
+ this.#schemas.set(schema.name, schema);
20547
+ }
20548
+ }
20549
+ async close() {
20550
+ if (this.#ownsPool) {
20551
+ await this.#pool.end();
20552
+ } else {
20553
+ await this.#mastraStorage?.close();
20554
+ }
20555
+ }
20556
+ authDatabase() {
20557
+ return { dialect: "postgres", pool: this.#pool };
20558
+ }
20559
+ /**
20560
+ * Run `fn` while holding a Postgres transaction-scoped advisory lock for
20561
+ * `key`, serializing callers across replicas. The lock releases when the
20562
+ * transaction ends (commit, rollback, or connection loss), so a crashed
20563
+ * replica can never hold it forever.
20564
+ */
20565
+ async withDistributedLock(key, fn) {
20566
+ const [k1, k2] = hashAdvisoryLockKey(key);
20567
+ const client = await this.#pool.connect();
20568
+ try {
20569
+ await client.query("BEGIN");
20570
+ await client.query("SELECT pg_advisory_xact_lock($1, $2)", [k1, k2]);
20571
+ try {
20572
+ const result = await fn();
20573
+ await client.query("COMMIT");
20574
+ return result;
20575
+ } catch (error) {
20576
+ await client.query("ROLLBACK");
20577
+ throw error;
20578
+ }
20579
+ } finally {
20580
+ client.release();
20581
+ }
20582
+ }
20583
+ #columnDdl(name, spec) {
20584
+ assertIdentifier("column", name);
20585
+ let ddl = `"${name}" ${COLUMN_DDL[spec.type]}`;
20586
+ if (spec.type === "uuid-pk" || spec.primaryKey) ddl += " PRIMARY KEY";
20587
+ if (!spec.nullable && spec.type !== "uuid-pk" && !spec.primaryKey) ddl += " NOT NULL";
20588
+ if (spec.default !== void 0) ddl += ` DEFAULT ${serializeDefault(spec.default)}`;
20589
+ return ddl;
20590
+ }
20591
+ async #ensureCollection(schema) {
20592
+ assertIdentifier("collection", schema.name);
20593
+ primaryKeyOf(schema);
20594
+ const columns = Object.entries(schema.columns).map(([name, spec]) => this.#columnDdl(name, spec));
20595
+ await this.#pool.query(`CREATE TABLE IF NOT EXISTS "${schema.name}" (${columns.join(", ")})`);
20596
+ for (const [name, spec] of Object.entries(schema.columns)) {
20597
+ await this.#pool.query(`ALTER TABLE "${schema.name}" ADD COLUMN IF NOT EXISTS ${this.#columnDdl(name, spec)}`);
20598
+ }
20599
+ for (const index of schema.uniqueIndexes ?? []) {
20600
+ assertIdentifier("index", index.name);
20601
+ index.columns.forEach((column) => assertIdentifier("column", column));
20602
+ let where = "";
20603
+ if (index.whereNotNull) {
20604
+ assertIdentifier("column", index.whereNotNull);
20605
+ where = ` WHERE "${index.whereNotNull}" IS NOT NULL`;
20606
+ } else if (index.whereNull) {
20607
+ assertIdentifier("column", index.whereNull);
20608
+ where = ` WHERE "${index.whereNull}" IS NULL`;
20609
+ }
20610
+ await this.#pool.query(
20611
+ `CREATE UNIQUE INDEX IF NOT EXISTS "${index.name}" ON "${schema.name}" (${index.columns.map((c) => `"${c}"`).join(", ")})${where}`
20612
+ );
20613
+ }
20614
+ for (const index of schema.indexes ?? []) {
20615
+ assertIdentifier("index", index.name);
20616
+ index.columns.forEach((column) => assertIdentifier("column", column));
20617
+ await this.#pool.query(
20618
+ `CREATE INDEX IF NOT EXISTS "${index.name}" ON "${schema.name}" (${index.columns.map((c) => `"${c}"`).join(", ")})`
20619
+ );
20620
+ }
20621
+ }
20622
+ };
20176
20623
 
20177
20624
  // src/storage/index.ts
20178
20625
  var DEFAULT_MAX_CONNECTIONS = 20;
@@ -20564,6 +21011,6 @@ Example Complex Query:
20564
21011
  ]
20565
21012
  }`;
20566
21013
 
20567
- export { AgentsPG, BackgroundTasksPG, BlobsPG, ChannelsPG, DatasetsPG, ExperimentsPG, FavoritesPG, MCPClientsPG, MCPServersPG, MemoryPG, NotificationsPG, ObservabilityPG, ObservabilityStoragePostgresVNext, PGVECTOR_PROMPT, PgVector, PoolAdapter, PostgresStore, PostgresStoreVNext, PromptBlocksPG, SchedulesPG, ScorerDefinitionsPG, ScoresPG, SkillsPG, ToolProviderConnectionsPG, WorkflowsPG, WorkspacesPG, exportSchemas };
21014
+ export { AgentsPG, BackgroundTasksPG, BlobsPG, ChannelsPG, DatasetsPG, ExperimentsPG, FavoritesPG, MCPClientsPG, MCPServersPG, MemoryPG, NotificationsPG, ObservabilityPG, ObservabilityStoragePostgresVNext, PGVECTOR_PROMPT, PgFactoryStorage, PgVector, PoolAdapter, PostgresStore, PostgresStoreVNext, PromptBlocksPG, SchedulesPG, ScorerDefinitionsPG, ScoresPG, SkillsPG, ToolProviderConnectionsPG, WorkflowsPG, WorkspacesPG, exportSchemas, hashAdvisoryLockKey };
20568
21015
  //# sourceMappingURL=index.js.map
20569
21016
  //# sourceMappingURL=index.js.map