@mastra/pg 1.27.1-alpha.0 → 1.27.2-alpha.0

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.cjs CHANGED
@@ -118,6 +118,34 @@ function buildConnectionStringPoolConfig(config, defaults) {
118
118
  };
119
119
  }
120
120
  //#endregion
121
+ //#region src/shared/schema-name.ts
122
+ const POSTGRES_IDENTIFIER_MAX_BYTES = 63;
123
+ const UNSAFE_SCHEMA_NAME_CHARS = /["'\\$\u0000-\u001f\u007f]/;
124
+ /**
125
+ * Validates a PostgreSQL schema name.
126
+ *
127
+ * Schema names are always double-quoted in generated SQL, so PostgreSQL accepts any name
128
+ * that fits the identifier limit (for example `my-tenant`). Quotes, backslashes, `$` and
129
+ * control characters are rejected so the name can never break out of a quoted identifier,
130
+ * a string literal, or a dollar-quoted block.
131
+ */
132
+ function parseSchemaName(name, kind = "schema name") {
133
+ if (typeof name !== "string" || name.length === 0 || UNSAFE_SCHEMA_NAME_CHARS.test(name) || Buffer.byteLength(name, "utf-8") > POSTGRES_IDENTIFIER_MAX_BYTES) throw new Error(`Invalid ${kind}: ${name}. Must be 1-${POSTGRES_IDENTIFIER_MAX_BYTES} bytes long and must not contain quotes, backslashes, "$", or control characters.`);
134
+ return name;
135
+ }
136
+ /**
137
+ * Turns a schema name into a string that is safe to use as part of an unquoted identifier,
138
+ * such as the schema prefix of an index or constraint name.
139
+ *
140
+ * Names that are already plain identifiers (letters, digits, underscores) are returned
141
+ * unchanged, so existing index and constraint names keep working. Any other character
142
+ * becomes `_`, e.g. `my-tenant` -> `my_tenant`.
143
+ */
144
+ function schemaNamePrefix(name) {
145
+ const sanitized = parseSchemaName(name).replace(/[^A-Za-z0-9_]/g, "_");
146
+ return /^[0-9]/.test(sanitized) ? `_${sanitized}` : sanitized;
147
+ }
148
+ //#endregion
121
149
  //#region src/vector/filter.ts
122
150
  /**
123
151
  * Translates MongoDB-style filters to PG compatible filters.
@@ -742,7 +770,8 @@ var PgVector = class extends _mastra_core_vector.MastraVector {
742
770
  if (vectorType === "bit") return dimension ? `bit(${dimension})` : "bit";
743
771
  if (this.vectorExtensionSchema) {
744
772
  if (this.vectorExtensionSchema === "pg_catalog") return vectorType;
745
- return `${(0, _mastra_core_utils.parseSqlIdentifier)(this.vectorExtensionSchema, "vector extension schema")}.${vectorType}`;
773
+ const extensionSchema = parseSchemaName(this.vectorExtensionSchema, "vector extension schema");
774
+ return `${/^[A-Za-z_][A-Za-z0-9_]*$/.test(extensionSchema) ? extensionSchema : `"${extensionSchema}"`}.${vectorType}`;
746
775
  }
747
776
  return vectorType;
748
777
  }
@@ -820,7 +849,7 @@ var PgVector = class extends _mastra_core_vector.MastraVector {
820
849
  };
821
850
  }
822
851
  getSchemaName() {
823
- return this.schema ? `"${(0, _mastra_core_utils.parseSqlIdentifier)(this.schema, "schema name")}"` : void 0;
852
+ return this.schema ? `"${parseSchemaName(this.schema)}"` : void 0;
824
853
  }
825
854
  async ensureNamespaceSchema(indexName, client) {
826
855
  const { tableName, parsedIndexName } = this.getTableName(indexName);
@@ -2575,7 +2604,7 @@ function resolvePgConfig(config) {
2575
2604
  };
2576
2605
  }
2577
2606
  function getSchemaName$6(schema) {
2578
- return schema ? `"${(0, _mastra_core_utils.parseSqlIdentifier)(schema, "schema name")}"` : "\"public\"";
2607
+ return schema ? `"${parseSchemaName(schema)}"` : "\"public\"";
2579
2608
  }
2580
2609
  function getTableName$6({ indexName, schemaName }) {
2581
2610
  const quotedIndexName = `"${(0, _mastra_core_utils.parseSqlIdentifier)(indexName, "index name")}"`;
@@ -2614,7 +2643,7 @@ function generateTableSQL({ tableName, schema, schemaName, compositePrimaryKey,
2614
2643
  ...timeZColumns,
2615
2644
  ...tableConstraints
2616
2645
  ].join(",\n");
2617
- const parsedSchemaName = schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name") : "";
2646
+ const parsedSchemaName = schemaName ? schemaNamePrefix(schemaName) : "";
2618
2647
  const workflowSnapshotConstraint = buildConstraintName({
2619
2648
  baseName: "mastra_workflow_snapshot_workflow_name_run_id_key",
2620
2649
  schemaName: parsedSchemaName || void 0
@@ -2624,7 +2653,7 @@ function generateTableSQL({ tableName, schema, schemaName, compositePrimaryKey,
2624
2653
  schemaName: parsedSchemaName || void 0
2625
2654
  });
2626
2655
  const quotedSchemaName = getSchemaName$6(schemaName);
2627
- const schemaFilter = parsedSchemaName || "public";
2656
+ const schemaFilter = schemaName ? parseSchemaName(schemaName) : "public";
2628
2657
  return `
2629
2658
  CREATE TABLE IF NOT EXISTS ${getTableName$6({
2630
2659
  indexName: tableName,
@@ -2750,7 +2779,7 @@ BEGIN
2750
2779
  JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2751
2780
  WHERE tg.tgname = ${`'${parsedTriggerName}'`}
2752
2781
  AND c.relname = ${`'${(0, _mastra_core_utils.parseSqlIdentifier)(tableName, "table name")}'`}
2753
- AND n.nspname = ${schemaName ? `'${(0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name")}'` : `'public'`}
2782
+ AND n.nspname = ${schemaName ? `'${parseSchemaName(schemaName)}'` : `'public'`}
2754
2783
  AND NOT tg.tgisinternal
2755
2784
  AND tg.tgtype = 23
2756
2785
  AND tg.tgfoid = '${functionName}()'::regprocedure
@@ -2819,7 +2848,7 @@ var PgDB = class extends _mastra_core_base.MastraBase {
2819
2848
  if (tableName === _mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT) {
2820
2849
  const constraintName = buildConstraintName({
2821
2850
  baseName: "mastra_workflow_snapshot_workflow_name_run_id_key",
2822
- schemaName: this.schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(this.schemaName, "schema name") : void 0
2851
+ schemaName: this.schemaName ? schemaNamePrefix(this.schemaName) : void 0
2823
2852
  }).toLowerCase();
2824
2853
  return snapshot.indexes.has(constraintName) && snapshot.replicaIdentityIndexes.has(constraintName);
2825
2854
  }
@@ -3424,7 +3453,7 @@ MIGRATION REQUIRED: Duplicate spans detected in ${duplicateInfo.tableName}\n====
3424
3453
  async spansPrimaryKeyExists() {
3425
3454
  const constraintName = buildConstraintName({
3426
3455
  baseName: "mastra_ai_spans_traceid_spanid_pk",
3427
- schemaName: (this.schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(this.schemaName, "schema name") : "") || void 0
3456
+ schemaName: (this.schemaName ? schemaNamePrefix(this.schemaName) : "") || void 0
3428
3457
  });
3429
3458
  const schemaFilter = this.schemaName || "public";
3430
3459
  const snapshot = this.schemaSnapshot;
@@ -3446,7 +3475,7 @@ MIGRATION REQUIRED: Duplicate spans detected in ${duplicateInfo.tableName}\n====
3446
3475
  });
3447
3476
  const constraintName = buildConstraintName({
3448
3477
  baseName: "mastra_ai_spans_traceid_spanid_pk",
3449
- schemaName: (this.schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(this.schemaName, "schema name") : "") || void 0
3478
+ schemaName: (this.schemaName ? schemaNamePrefix(this.schemaName) : "") || void 0
3450
3479
  });
3451
3480
  const schemaFilter = this.schemaName || "public";
3452
3481
  try {
@@ -4039,7 +4068,7 @@ MIGRATION REQUIRED: Duplicate spans detected in ${duplicateInfo.tableName}\n====
4039
4068
  //#endregion
4040
4069
  //#region src/storage/domains/utils.ts
4041
4070
  function getSchemaName$5(schema) {
4042
- return schema ? `"${(0, _mastra_core_utils.parseSqlIdentifier)(schema, "schema name")}"` : void 0;
4071
+ return schema ? `"${parseSchemaName(schema)}"` : void 0;
4043
4072
  }
4044
4073
  function getTableName$5({ indexName, schemaName }) {
4045
4074
  const quotedIndexName = `"${(0, _mastra_core_utils.parseSqlIdentifier)(indexName, "index name")}"`;
@@ -5093,7 +5122,7 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
5093
5122
  * so its supporting index is not part of the default index set.
5094
5123
  */
5095
5124
  async ensureRetentionIndexes(policies) {
5096
- const prefix = this.#schema !== "public" ? `${this.#schema}_` : "";
5125
+ const prefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
5097
5126
  for (const [key, entry] of Object.entries(BackgroundTasksPG.retentionTables)) {
5098
5127
  if (!entry.indexed || !policies[key]) continue;
5099
5128
  try {
@@ -5148,7 +5177,7 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
5148
5177
  }
5149
5178
  static getExportDDL(schemaName) {
5150
5179
  const statements = [];
5151
- const parsedSchema = schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name") : "";
5180
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
5152
5181
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
5153
5182
  statements.push(generateTableSQL({
5154
5183
  tableName: _mastra_core_storage.TABLE_BACKGROUND_TASKS,
@@ -5160,7 +5189,7 @@ var BackgroundTasksPG = class BackgroundTasksPG extends _mastra_core_storage.Bac
5160
5189
  return statements;
5161
5190
  }
5162
5191
  getDefaultIndexDefinitions() {
5163
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
5192
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
5164
5193
  return BackgroundTasksPG.getDefaultIndexDefs(schemaPrefix);
5165
5194
  }
5166
5195
  async createDefaultIndexes() {
@@ -5522,7 +5551,7 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5522
5551
  }
5523
5552
  static getExportDDL(schemaName) {
5524
5553
  const statements = [];
5525
- const parsedSchema = schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name") : "";
5554
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
5526
5555
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
5527
5556
  for (const tableName of ChannelsPG.MANAGED_TABLES) statements.push(generateTableSQL({
5528
5557
  tableName,
@@ -5534,7 +5563,7 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5534
5563
  return statements;
5535
5564
  }
5536
5565
  getDefaultIndexDefinitions() {
5537
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
5566
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
5538
5567
  return ChannelsPG.getDefaultIndexDefs(schemaPrefix);
5539
5568
  }
5540
5569
  async createDefaultIndexes() {
@@ -7046,7 +7075,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7046
7075
  * so its supporting index is not part of the default index set.
7047
7076
  */
7048
7077
  async ensureRetentionIndexes(policies) {
7049
- const prefix = this.#schema !== "public" ? `${this.#schema}_` : "";
7078
+ const prefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
7050
7079
  for (const [key, entry] of Object.entries(ExperimentsPG.retentionTables)) {
7051
7080
  if (!entry.indexed || !policies[key]) continue;
7052
7081
  try {
@@ -8214,7 +8243,7 @@ function postgresSql(sql, schemaName) {
8214
8243
  return transformed;
8215
8244
  });
8216
8245
  if (schemaName) {
8217
- const quotedSchema = `"${(0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name")}"`;
8246
+ const quotedSchema = `"${parseSchemaName(schemaName)}"`;
8218
8247
  normalized = transformSqlCode(normalized, (code) => {
8219
8248
  let transformed = code;
8220
8249
  for (const table of [
@@ -8327,7 +8356,7 @@ function parseOutbox(row) {
8327
8356
  function knowledgeIndexes(schemaName) {
8328
8357
  const table = (name) => {
8329
8358
  const quotedName = `"${(0, _mastra_core_utils.parseSqlIdentifier)(name, "table name")}"`;
8330
- return schemaName ? `"${(0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name")}".${quotedName}` : quotedName;
8359
+ return schemaName ? `"${parseSchemaName(schemaName)}".${quotedName}` : quotedName;
8331
8360
  };
8332
8361
  return [
8333
8362
  {
@@ -9231,7 +9260,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9231
9260
  }
9232
9261
  static getExportDDL(schemaName) {
9233
9262
  const statements = [];
9234
- const parsedSchema = schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name") : "";
9263
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
9235
9264
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
9236
9265
  for (const tableName of MCPClientsPG.MANAGED_TABLES) statements.push(generateTableSQL({
9237
9266
  tableName,
@@ -9243,7 +9272,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9243
9272
  return statements;
9244
9273
  }
9245
9274
  getDefaultIndexDefinitions() {
9246
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
9275
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
9247
9276
  return MCPClientsPG.getDefaultIndexDefs(schemaPrefix);
9248
9277
  }
9249
9278
  async createDefaultIndexes() {
@@ -9799,7 +9828,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9799
9828
  }
9800
9829
  static getExportDDL(schemaName) {
9801
9830
  const statements = [];
9802
- const parsedSchema = schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name") : "";
9831
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
9803
9832
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
9804
9833
  for (const tableName of MCPServersPG.MANAGED_TABLES) statements.push(generateTableSQL({
9805
9834
  tableName,
@@ -9811,7 +9840,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9811
9840
  return statements;
9812
9841
  }
9813
9842
  getDefaultIndexDefinitions() {
9814
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
9843
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
9815
9844
  return MCPServersPG.getDefaultIndexDefs(schemaPrefix);
9816
9845
  }
9817
9846
  async createDefaultIndexes() {
@@ -10344,6 +10373,12 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
10344
10373
  * versions that don't export TABLE_OBSERVATIONAL_MEMORY.
10345
10374
  */
10346
10375
  const OM_TABLE = "mastra_observational_memory";
10376
+ /**
10377
+ * Newest generation first. Databases written before generation creation was
10378
+ * serialized can hold several rows with the same generation; the earliest-created
10379
+ * one wins so the active record stays stable across reads.
10380
+ */
10381
+ const OM_GENERATION_ORDER = `"generationCount" DESC, "createdAt" ASC, id ASC`;
10347
10382
  const POSTGRES_MAX_BIND_PARAMETERS = 65535;
10348
10383
  const MESSAGE_INSERT_BIND_PARAMETERS = 8;
10349
10384
  const MAX_MESSAGES_PER_INSERT = Math.floor(POSTGRES_MAX_BIND_PARAMETERS / MESSAGE_INSERT_BIND_PARAMETERS);
@@ -10521,7 +10556,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10521
10556
  * so its supporting index is not part of the default index set.
10522
10557
  */
10523
10558
  async ensureRetentionIndexes(policies) {
10524
- const prefix = this.#schema && this.#schema !== "public" ? `${this.#schema}_` : "";
10559
+ const prefix = this.#schema && this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
10525
10560
  for (const [key, entry] of Object.entries(MemoryPG.retentionTables)) {
10526
10561
  if (!entry.indexed || !policies[key]) continue;
10527
10562
  try {
@@ -10556,7 +10591,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10556
10591
  */
10557
10592
  static getExportDDL(schemaName) {
10558
10593
  const statements = [];
10559
- const parsedSchema = schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name") : "";
10594
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
10560
10595
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
10561
10596
  const quotedSchemaName = getSchemaName$6(schemaName);
10562
10597
  for (const tableName of [
@@ -10591,7 +10626,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10591
10626
  * Returns default index definitions for this instance's schema.
10592
10627
  */
10593
10628
  getDefaultIndexDefinitions() {
10594
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
10629
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
10595
10630
  return MemoryPG.getDefaultIndexDefs(schemaPrefix);
10596
10631
  }
10597
10632
  /**
@@ -11945,6 +11980,23 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11945
11980
  getOMKey(threadId, resourceId) {
11946
11981
  return threadId ? `thread:${threadId}` : `resource:${resourceId}`;
11947
11982
  }
11983
+ /**
11984
+ * Runs `fn` in a transaction that holds an advisory lock for one OM lookup key.
11985
+ *
11986
+ * The table has no unique constraint on ("lookupKey", "generationCount"), and
11987
+ * adding one would fail on databases that already contain duplicates. The lock
11988
+ * serializes generation creation across processes instead. It is
11989
+ * transaction-scoped so it also works behind transaction-pooling proxies.
11990
+ */
11991
+ async #withOMLookupKeyLock(tableName, lookupKey, fn) {
11992
+ return this.#db.client.tx(async (t) => {
11993
+ await t.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", [`${tableName}:${lookupKey}`]);
11994
+ return fn(t);
11995
+ });
11996
+ }
11997
+ async #getLatestOMRow(client, tableName, lookupKey) {
11998
+ return client.oneOrNone(`SELECT * FROM ${tableName} WHERE "lookupKey" = $1 ORDER BY ${OM_GENERATION_ORDER} LIMIT 1`, [lookupKey]);
11999
+ }
11948
12000
  parseOMRow(row) {
11949
12001
  return {
11950
12002
  id: row.id,
@@ -11987,7 +12039,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11987
12039
  indexName: OM_TABLE,
11988
12040
  schemaName: getSchemaName$3(this.#schema)
11989
12041
  });
11990
- const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "lookupKey" = $1 ORDER BY "generationCount" DESC LIMIT 1`, [lookupKey]);
12042
+ const result = await this.#getLatestOMRow(this.#db.readClient, tableName, lookupKey);
11991
12043
  if (!result) return null;
11992
12044
  return this.parseOMRow(result);
11993
12045
  } catch (error) {
@@ -12023,7 +12075,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12023
12075
  paramIndex++;
12024
12076
  }
12025
12077
  params.push(limit);
12026
- let sql = `SELECT * FROM ${tableName} WHERE ${conditions.join(" AND ")} ORDER BY "generationCount" DESC LIMIT $${paramIndex}`;
12078
+ let sql = `SELECT * FROM ${tableName} WHERE ${conditions.join(" AND ")} ORDER BY ${OM_GENERATION_ORDER} LIMIT $${paramIndex}`;
12027
12079
  paramIndex++;
12028
12080
  if (options?.offset != null) {
12029
12081
  params.push(options.offset);
@@ -12078,7 +12130,10 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12078
12130
  schemaName: getSchemaName$3(this.#schema)
12079
12131
  });
12080
12132
  const nowStr = now.toISOString();
12081
- await this.#db.client.none(`INSERT INTO ${tableName} (
12133
+ return await this.#withOMLookupKeyLock(tableName, lookupKey, async (t) => {
12134
+ const existing = await this.#getLatestOMRow(t, tableName, lookupKey);
12135
+ if (existing) return this.parseOMRow(existing);
12136
+ await t.none(`INSERT INTO ${tableName} (
12082
12137
  id, "lookupKey", scope, "resourceId", "threadId",
12083
12138
  "activeObservations", "activeObservationsPendingUpdate",
12084
12139
  "originType", config, "generationCount", "lastObservedAt", "lastObservedAtZ", "lastReflectionAt", "lastReflectionAtZ",
@@ -12086,36 +12141,37 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12086
12141
  "isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
12087
12142
  "observedTimezone", "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
12088
12143
  ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28)`, [
12089
- id,
12090
- lookupKey,
12091
- input.scope,
12092
- input.resourceId,
12093
- input.threadId || null,
12094
- "",
12095
- null,
12096
- "initial",
12097
- toPgJson(input.config),
12098
- 0,
12099
- null,
12100
- null,
12101
- null,
12102
- null,
12103
- 0,
12104
- 0,
12105
- 0,
12106
- false,
12107
- false,
12108
- false,
12109
- false,
12110
- 0,
12111
- null,
12112
- input.observedTimezone || null,
12113
- nowStr,
12114
- nowStr,
12115
- nowStr,
12116
- nowStr
12117
- ]);
12118
- return record;
12144
+ id,
12145
+ lookupKey,
12146
+ input.scope,
12147
+ input.resourceId,
12148
+ input.threadId || null,
12149
+ "",
12150
+ null,
12151
+ "initial",
12152
+ toPgJson(input.config),
12153
+ 0,
12154
+ null,
12155
+ null,
12156
+ null,
12157
+ null,
12158
+ 0,
12159
+ 0,
12160
+ 0,
12161
+ false,
12162
+ false,
12163
+ false,
12164
+ false,
12165
+ 0,
12166
+ null,
12167
+ input.observedTimezone || null,
12168
+ nowStr,
12169
+ nowStr,
12170
+ nowStr,
12171
+ nowStr
12172
+ ]);
12173
+ return record;
12174
+ });
12119
12175
  } catch (error) {
12120
12176
  throw new _mastra_core_error.MastraError({
12121
12177
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "INITIALIZE_OBSERVATIONAL_MEMORY", "FAILED"),
@@ -12247,78 +12303,16 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12247
12303
  }
12248
12304
  async createReflectionGeneration(input) {
12249
12305
  try {
12250
- const id = crypto.randomUUID();
12251
- const now = /* @__PURE__ */ new Date();
12252
12306
  const lookupKey = this.getOMKey(input.currentRecord.threadId, input.currentRecord.resourceId);
12253
- const record = {
12254
- id,
12255
- scope: input.currentRecord.scope,
12256
- threadId: input.currentRecord.threadId,
12257
- resourceId: input.currentRecord.resourceId,
12258
- createdAt: now,
12259
- updatedAt: now,
12260
- lastObservedAt: input.currentRecord.lastObservedAt,
12261
- originType: "reflection",
12262
- generationCount: input.currentRecord.generationCount + 1,
12263
- activeObservations: input.reflection,
12264
- totalTokensObserved: input.currentRecord.totalTokensObserved,
12265
- observationTokenCount: input.tokenCount,
12266
- pendingMessageTokens: 0,
12267
- isReflecting: false,
12268
- isObserving: false,
12269
- isBufferingObservation: false,
12270
- isBufferingReflection: false,
12271
- lastBufferedAtTokens: 0,
12272
- lastBufferedAtTime: null,
12273
- config: input.currentRecord.config,
12274
- metadata: input.currentRecord.metadata,
12275
- observedTimezone: input.currentRecord.observedTimezone
12276
- };
12277
12307
  const tableName = getTableName$3({
12278
12308
  indexName: OM_TABLE,
12279
12309
  schemaName: getSchemaName$3(this.#schema)
12280
12310
  });
12281
- const nowStr = now.toISOString();
12282
- const lastObservedAtStr = record.lastObservedAt?.toISOString() || null;
12283
- await this.#db.client.none(`INSERT INTO ${tableName} (
12284
- id, "lookupKey", scope, "resourceId", "threadId",
12285
- "activeObservations", "activeObservationsPendingUpdate",
12286
- "originType", config, "generationCount", "lastObservedAt", "lastObservedAtZ", "lastReflectionAt", "lastReflectionAtZ",
12287
- "pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
12288
- "isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
12289
- "observedTimezone", metadata, "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
12290
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29)`, [
12291
- id,
12292
- lookupKey,
12293
- record.scope,
12294
- record.resourceId,
12295
- record.threadId || null,
12296
- input.reflection,
12297
- null,
12298
- "reflection",
12299
- toPgJson(record.config),
12300
- input.currentRecord.generationCount + 1,
12301
- lastObservedAtStr,
12302
- lastObservedAtStr,
12303
- nowStr,
12304
- nowStr,
12305
- record.pendingMessageTokens,
12306
- Math.round(record.totalTokensObserved),
12307
- Math.round(record.observationTokenCount),
12308
- false,
12309
- false,
12310
- false,
12311
- false,
12312
- 0,
12313
- null,
12314
- record.observedTimezone || null,
12315
- record.metadata ? toPgJson(record.metadata) : null,
12316
- nowStr,
12317
- nowStr,
12318
- nowStr,
12319
- nowStr
12320
- ]);
12321
- return record;
12311
+ return await this.#withOMLookupKeyLock(tableName, lookupKey, async (t) => {
12312
+ const newer = await this.#getNewerOMGeneration(t, tableName, lookupKey, input.currentRecord.generationCount);
12313
+ if (newer) return newer;
12314
+ return this.#insertReflectionGeneration(t, tableName, lookupKey, input);
12315
+ });
12322
12316
  } catch (error) {
12323
12317
  throw new _mastra_core_error.MastraError({
12324
12318
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "CREATE_REFLECTION_GENERATION", "FAILED"),
@@ -12328,6 +12322,84 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12328
12322
  }, error);
12329
12323
  }
12330
12324
  }
12325
+ /**
12326
+ * Returns the active record when another writer already created a generation
12327
+ * after `generationCount`. Reflecting from the older generation again would
12328
+ * add a second record with the same generation.
12329
+ */
12330
+ async #getNewerOMGeneration(t, tableName, lookupKey, generationCount) {
12331
+ const latest = await this.#getLatestOMRow(t, tableName, lookupKey);
12332
+ return latest && Number(latest.generationCount) > generationCount ? this.parseOMRow(latest) : null;
12333
+ }
12334
+ async #insertReflectionGeneration(t, tableName, lookupKey, input) {
12335
+ const id = crypto.randomUUID();
12336
+ const now = /* @__PURE__ */ new Date();
12337
+ const record = {
12338
+ id,
12339
+ scope: input.currentRecord.scope,
12340
+ threadId: input.currentRecord.threadId,
12341
+ resourceId: input.currentRecord.resourceId,
12342
+ createdAt: now,
12343
+ updatedAt: now,
12344
+ lastObservedAt: input.currentRecord.lastObservedAt,
12345
+ originType: "reflection",
12346
+ generationCount: input.currentRecord.generationCount + 1,
12347
+ activeObservations: input.reflection,
12348
+ totalTokensObserved: input.currentRecord.totalTokensObserved,
12349
+ observationTokenCount: input.tokenCount,
12350
+ pendingMessageTokens: 0,
12351
+ isReflecting: false,
12352
+ isObserving: false,
12353
+ isBufferingObservation: false,
12354
+ isBufferingReflection: false,
12355
+ lastBufferedAtTokens: 0,
12356
+ lastBufferedAtTime: null,
12357
+ config: input.currentRecord.config,
12358
+ metadata: input.currentRecord.metadata,
12359
+ observedTimezone: input.currentRecord.observedTimezone
12360
+ };
12361
+ const nowStr = now.toISOString();
12362
+ const lastObservedAtStr = record.lastObservedAt?.toISOString() || null;
12363
+ await t.none(`INSERT INTO ${tableName} (
12364
+ id, "lookupKey", scope, "resourceId", "threadId",
12365
+ "activeObservations", "activeObservationsPendingUpdate",
12366
+ "originType", config, "generationCount", "lastObservedAt", "lastObservedAtZ", "lastReflectionAt", "lastReflectionAtZ",
12367
+ "pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
12368
+ "isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
12369
+ "observedTimezone", metadata, "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
12370
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29)`, [
12371
+ id,
12372
+ lookupKey,
12373
+ record.scope,
12374
+ record.resourceId,
12375
+ record.threadId || null,
12376
+ input.reflection,
12377
+ null,
12378
+ "reflection",
12379
+ toPgJson(record.config),
12380
+ input.currentRecord.generationCount + 1,
12381
+ lastObservedAtStr,
12382
+ lastObservedAtStr,
12383
+ nowStr,
12384
+ nowStr,
12385
+ record.pendingMessageTokens,
12386
+ Math.round(record.totalTokensObserved),
12387
+ Math.round(record.observationTokenCount),
12388
+ false,
12389
+ false,
12390
+ false,
12391
+ false,
12392
+ 0,
12393
+ null,
12394
+ record.observedTimezone || null,
12395
+ record.metadata ? toPgJson(record.metadata) : null,
12396
+ nowStr,
12397
+ nowStr,
12398
+ nowStr,
12399
+ nowStr
12400
+ ]);
12401
+ return record;
12402
+ }
12331
12403
  async setReflectingFlag(id, isReflecting) {
12332
12404
  try {
12333
12405
  const tableName = getTableName$3({
@@ -12822,32 +12894,36 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12822
12894
  indexName: OM_TABLE,
12823
12895
  schemaName: getSchemaName$3(this.#schema)
12824
12896
  });
12825
- const record = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [input.currentRecord.id]);
12826
- if (!record) throw new _mastra_core_error.MastraError({
12827
- id: (0, _mastra_core_storage.createStorageErrorId)("PG", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NOT_FOUND"),
12828
- text: `Observational memory record not found: ${input.currentRecord.id}`,
12829
- domain: _mastra_core_error.ErrorDomain.STORAGE,
12830
- category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
12831
- details: { id: input.currentRecord.id }
12832
- });
12833
- const bufferedReflection = record.bufferedReflection || "";
12834
- const reflectedLineCount = Number(record.reflectedObservationLineCount || 0);
12835
- if (!bufferedReflection) throw new _mastra_core_error.MastraError({
12836
- id: (0, _mastra_core_storage.createStorageErrorId)("PG", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NO_CONTENT"),
12837
- text: "No buffered reflection to swap",
12838
- domain: _mastra_core_error.ErrorDomain.STORAGE,
12839
- category: _mastra_core_error.ErrorCategory.USER,
12840
- details: { id: input.currentRecord.id }
12841
- });
12842
- const unreflectedContent = (record.activeObservations || "").split("\n").slice(reflectedLineCount).join("\n").trim();
12843
- const newObservations = unreflectedContent ? `${bufferedReflection}\n\n${unreflectedContent}` : bufferedReflection;
12844
- const newRecord = await this.createReflectionGeneration({
12845
- currentRecord: input.currentRecord,
12846
- reflection: newObservations,
12847
- tokenCount: input.tokenCount
12848
- });
12849
- const nowStr = (/* @__PURE__ */ new Date()).toISOString();
12850
- await this.#db.client.query(`UPDATE ${tableName} SET
12897
+ const lookupKey = this.getOMKey(input.currentRecord.threadId, input.currentRecord.resourceId);
12898
+ return await this.#withOMLookupKeyLock(tableName, lookupKey, async (t) => {
12899
+ const newer = await this.#getNewerOMGeneration(t, tableName, lookupKey, input.currentRecord.generationCount);
12900
+ if (newer) return newer;
12901
+ const record = await t.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [input.currentRecord.id]);
12902
+ if (!record) throw new _mastra_core_error.MastraError({
12903
+ id: (0, _mastra_core_storage.createStorageErrorId)("PG", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NOT_FOUND"),
12904
+ text: `Observational memory record not found: ${input.currentRecord.id}`,
12905
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
12906
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
12907
+ details: { id: input.currentRecord.id }
12908
+ });
12909
+ const bufferedReflection = record.bufferedReflection || "";
12910
+ const reflectedLineCount = Number(record.reflectedObservationLineCount || 0);
12911
+ if (!bufferedReflection) throw new _mastra_core_error.MastraError({
12912
+ id: (0, _mastra_core_storage.createStorageErrorId)("PG", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NO_CONTENT"),
12913
+ text: "No buffered reflection to swap",
12914
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
12915
+ category: _mastra_core_error.ErrorCategory.USER,
12916
+ details: { id: input.currentRecord.id }
12917
+ });
12918
+ const unreflectedContent = (record.activeObservations || "").split("\n").slice(reflectedLineCount).join("\n").trim();
12919
+ const newObservations = unreflectedContent ? `${bufferedReflection}\n\n${unreflectedContent}` : bufferedReflection;
12920
+ const newRecord = await this.#insertReflectionGeneration(t, tableName, lookupKey, {
12921
+ currentRecord: input.currentRecord,
12922
+ reflection: newObservations,
12923
+ tokenCount: input.tokenCount
12924
+ });
12925
+ const nowStr = (/* @__PURE__ */ new Date()).toISOString();
12926
+ await t.query(`UPDATE ${tableName} SET
12851
12927
  "bufferedReflection" = NULL,
12852
12928
  "bufferedReflectionTokens" = NULL,
12853
12929
  "bufferedReflectionInputTokens" = NULL,
@@ -12855,11 +12931,12 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12855
12931
  "updatedAt" = $1,
12856
12932
  "updatedAtZ" = $2
12857
12933
  WHERE id = $3`, [
12858
- nowStr,
12859
- nowStr,
12860
- input.currentRecord.id
12861
- ]);
12862
- return newRecord;
12934
+ nowStr,
12935
+ nowStr,
12936
+ input.currentRecord.id
12937
+ ]);
12938
+ return newRecord;
12939
+ });
12863
12940
  } catch (error) {
12864
12941
  if (error instanceof _mastra_core_error.MastraError) throw error;
12865
12942
  throw new _mastra_core_error.MastraError({
@@ -12999,7 +13076,7 @@ var NotificationsPG = class NotificationsPG extends _mastra_core_storage.Notific
12999
13076
  * so its supporting index is not part of the default index set.
13000
13077
  */
13001
13078
  async ensureRetentionIndexes(policies) {
13002
- const prefix = this.#schema && this.#schema !== "public" ? `${this.#schema}_` : "";
13079
+ const prefix = this.#schema && this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
13003
13080
  for (const [key, entry] of Object.entries(NotificationsPG.retentionTables)) {
13004
13081
  if (!entry.indexed || !policies[key]) continue;
13005
13082
  try {
@@ -13066,7 +13143,7 @@ var NotificationsPG = class NotificationsPG extends _mastra_core_storage.Notific
13066
13143
  }
13067
13144
  static getExportDDL(schemaName) {
13068
13145
  const statements = [];
13069
- const parsedSchema = schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name") : "";
13146
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
13070
13147
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
13071
13148
  statements.push(generateTableSQL({
13072
13149
  tableName: _mastra_core_storage.TABLE_NOTIFICATIONS,
@@ -13078,7 +13155,7 @@ var NotificationsPG = class NotificationsPG extends _mastra_core_storage.Notific
13078
13155
  return statements;
13079
13156
  }
13080
13157
  getDefaultIndexDefinitions() {
13081
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
13158
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
13082
13159
  return NotificationsPG.getDefaultIndexDefs(schemaPrefix);
13083
13160
  }
13084
13161
  async createDefaultIndexes() {
@@ -13375,7 +13452,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13375
13452
  * so its supporting index is not part of the default index set.
13376
13453
  */
13377
13454
  async ensureRetentionIndexes(policies) {
13378
- const prefix = this.#schema !== "public" ? `${this.#schema}_` : "";
13455
+ const prefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
13379
13456
  for (const [key, entry] of Object.entries(ObservabilityPG.retentionTables)) {
13380
13457
  if (!entry.indexed || !policies[key]) continue;
13381
13458
  try {
@@ -13456,7 +13533,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13456
13533
  */
13457
13534
  static getExportDDL(schemaName) {
13458
13535
  const statements = [];
13459
- const parsedSchema = schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name") : "";
13536
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
13460
13537
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
13461
13538
  statements.push(generateTableSQL({
13462
13539
  tableName: _mastra_core_storage.TABLE_SPANS,
@@ -13472,7 +13549,7 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13472
13549
  * Returns default index definitions for this instance's schema.
13473
13550
  */
13474
13551
  getDefaultIndexDefinitions() {
13475
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
13552
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
13476
13553
  return ObservabilityPG.getDefaultIndexDefs(schemaPrefix);
13477
13554
  }
13478
13555
  /**
@@ -14683,15 +14760,15 @@ const SIGNAL_TIME_COLUMN = {
14683
14760
  };
14684
14761
  /** Returns a fully-qualified, double-quoted table name. */
14685
14762
  function qualifiedTable(schema, table) {
14686
- return `"${(0, _mastra_core_utils.parseSqlIdentifier)(schema, "schema name")}"."${(0, _mastra_core_utils.parseSqlIdentifier)(table, "table name")}"`;
14763
+ return `"${parseSchemaName(schema)}"."${(0, _mastra_core_utils.parseSqlIdentifier)(table, "table name")}"`;
14687
14764
  }
14688
14765
  /** Returns a parsed, quoted, schema-prefixed object name (constraint, index, etc.). */
14689
14766
  function qualifiedName(schema, name) {
14690
- return `"${(0, _mastra_core_utils.parseSqlIdentifier)(schema, "schema name")}"."${(0, _mastra_core_utils.parseSqlIdentifier)(name, "object name")}"`;
14767
+ return `"${parseSchemaName(schema)}"."${(0, _mastra_core_utils.parseSqlIdentifier)(name, "object name")}"`;
14691
14768
  }
14692
14769
  /** Schema CREATE. Safe to run repeatedly before table DDL. */
14693
14770
  function schemaDDL(schema) {
14694
- return `CREATE SCHEMA IF NOT EXISTS "${(0, _mastra_core_utils.parseSqlIdentifier)(schema, "schema name")}"`;
14771
+ return `CREATE SCHEMA IF NOT EXISTS "${parseSchemaName(schema)}"`;
14695
14772
  }
14696
14773
  /**
14697
14774
  * Postgres declarative partitioning and Timescale hypertables are mutually
@@ -19231,7 +19308,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
19231
19308
  */
19232
19309
  static getExportDDL(schemaName) {
19233
19310
  const statements = [];
19234
- const parsedSchema = schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name") : "";
19311
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
19235
19312
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
19236
19313
  for (const tableName of PromptBlocksPG.MANAGED_TABLES) statements.push(generateTableSQL({
19237
19314
  tableName,
@@ -19243,7 +19320,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
19243
19320
  return statements;
19244
19321
  }
19245
19322
  getDefaultIndexDefinitions() {
19246
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
19323
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
19247
19324
  return PromptBlocksPG.getDefaultIndexDefs(schemaPrefix);
19248
19325
  }
19249
19326
  async createDefaultIndexes() {
@@ -19878,7 +19955,7 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
19878
19955
  * so its supporting index is not part of the default index set.
19879
19956
  */
19880
19957
  async ensureRetentionIndexes(policies) {
19881
- const prefix = this.#schema !== "public" ? `${this.#schema}_` : "";
19958
+ const prefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
19882
19959
  for (const [key, entry] of Object.entries(SchedulesPG.retentionTables)) {
19883
19960
  if (!entry.indexed || !policies[key]) continue;
19884
19961
  try {
@@ -19926,7 +20003,7 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
19926
20003
  }];
19927
20004
  }
19928
20005
  getDefaultIndexDefinitions() {
19929
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
20006
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
19930
20007
  return SchedulesPG.getDefaultIndexDefs(schemaPrefix);
19931
20008
  }
19932
20009
  async createDefaultIndexes() {
@@ -19947,7 +20024,7 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
19947
20024
  }
19948
20025
  static getExportDDL(schemaName) {
19949
20026
  const statements = [];
19950
- const parsedSchema = schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name") : "";
20027
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
19951
20028
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
19952
20029
  statements.push(generateTableSQL({
19953
20030
  tableName: _mastra_core_storage.TABLE_SCHEDULES,
@@ -19969,7 +20046,7 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
19969
20046
  await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_SCHEDULES });
19970
20047
  }
19971
20048
  #table(tableName) {
19972
- return getTableName$2(tableName, getSchemaName$2((0, _mastra_core_utils.parseSqlIdentifier)(this.#schema, "schema name")));
20049
+ return getTableName$2(tableName, getSchemaName$2(parseSchemaName(this.#schema)));
19973
20050
  }
19974
20051
  async createSchedule(schedule) {
19975
20052
  if (await this.#getSchedule(this.#client, schedule.id)) throw new Error(`Schedule with id "${schedule.id}" already exists`);
@@ -20174,7 +20251,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
20174
20251
  */
20175
20252
  static getExportDDL(schemaName) {
20176
20253
  const statements = [];
20177
- const parsedSchema = schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name") : "";
20254
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
20178
20255
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
20179
20256
  for (const tableName of ScorerDefinitionsPG.MANAGED_TABLES) statements.push(generateTableSQL({
20180
20257
  tableName,
@@ -20186,7 +20263,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
20186
20263
  return statements;
20187
20264
  }
20188
20265
  getDefaultIndexDefinitions() {
20189
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
20266
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
20190
20267
  return ScorerDefinitionsPG.getDefaultIndexDefs(schemaPrefix);
20191
20268
  }
20192
20269
  async createDefaultIndexes() {
@@ -20819,7 +20896,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
20819
20896
  * so its supporting index is not part of the default index set.
20820
20897
  */
20821
20898
  async ensureRetentionIndexes(policies) {
20822
- const prefix = this.#schema && this.#schema !== "public" ? `${this.#schema}_` : "";
20899
+ const prefix = this.#schema && this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
20823
20900
  for (const [key, entry] of Object.entries(ScoresPG.retentionTables)) {
20824
20901
  if (!entry.indexed || !policies[key]) continue;
20825
20902
  try {
@@ -20854,7 +20931,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
20854
20931
  */
20855
20932
  static getExportDDL(schemaName) {
20856
20933
  const statements = [];
20857
- const parsedSchema = schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name") : "";
20934
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
20858
20935
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
20859
20936
  statements.push(generateTableSQL({
20860
20937
  tableName: _mastra_core_storage.TABLE_SCORERS,
@@ -20869,7 +20946,7 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
20869
20946
  * Returns default index definitions for this instance's schema.
20870
20947
  */
20871
20948
  getDefaultIndexDefinitions() {
20872
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
20949
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
20873
20950
  return ScoresPG.getDefaultIndexDefs(schemaPrefix);
20874
20951
  }
20875
20952
  /**
@@ -21232,7 +21309,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
21232
21309
  }
21233
21310
  static getExportDDL(schemaName) {
21234
21311
  const statements = [];
21235
- const parsedSchema = schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name") : "";
21312
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
21236
21313
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
21237
21314
  for (const tableName of SkillsPG.MANAGED_TABLES) statements.push(generateTableSQL({
21238
21315
  tableName,
@@ -21244,7 +21321,7 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
21244
21321
  return statements;
21245
21322
  }
21246
21323
  getDefaultIndexDefinitions() {
21247
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
21324
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
21248
21325
  return SkillsPG.getDefaultIndexDefs(schemaPrefix);
21249
21326
  }
21250
21327
  async createDefaultIndexes() {
@@ -21939,7 +22016,7 @@ var ThreadStatePG = class ThreadStatePG extends _mastra_core_storage.ThreadState
21939
22016
  * a failure here leaves pruning correct, just slower.
21940
22017
  */
21941
22018
  async #ensureRetentionIndexes(policies) {
21942
- const prefix = this.#schema && this.#schema !== "public" ? `${this.#schema}_` : "";
22019
+ const prefix = this.#schema && this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
21943
22020
  for (const [key, entry] of Object.entries(ThreadStatePG.retentionTables)) {
21944
22021
  if (!entry.indexed || !policies[key]) continue;
21945
22022
  try {
@@ -22105,7 +22182,7 @@ var ToolProviderConnectionsPG = class ToolProviderConnectionsPG extends _mastra_
22105
22182
  }
22106
22183
  static getExportDDL(schemaName) {
22107
22184
  const statements = [];
22108
- const parsedSchema = schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name") : "";
22185
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
22109
22186
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
22110
22187
  statements.push(generateTableSQL({
22111
22188
  tableName: _mastra_core_storage.TABLE_TOOL_PROVIDER_CONNECTIONS,
@@ -22122,7 +22199,7 @@ var ToolProviderConnectionsPG = class ToolProviderConnectionsPG extends _mastra_
22122
22199
  return statements;
22123
22200
  }
22124
22201
  getDefaultIndexDefinitions() {
22125
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
22202
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
22126
22203
  return ToolProviderConnectionsPG.getDefaultIndexDefs(schemaPrefix);
22127
22204
  }
22128
22205
  async createDefaultIndexes() {
@@ -22354,7 +22431,7 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_sto
22354
22431
  }
22355
22432
  getDefaultIndexDefinitions() {
22356
22433
  return [{
22357
- name: `${this.#schema !== "public" ? `${this.#schema}_` : ""}idx_workflow_definitions_status`,
22434
+ name: `${this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : ""}idx_workflow_definitions_status`,
22358
22435
  table: _mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS,
22359
22436
  columns: ["status"]
22360
22437
  }];
@@ -22631,7 +22708,7 @@ var WorkflowsPG = class WorkflowsPG extends _mastra_core_storage.WorkflowsStorag
22631
22708
  */
22632
22709
  static getExportDDL(schemaName) {
22633
22710
  const statements = [];
22634
- const parsedSchema = schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name") : "";
22711
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
22635
22712
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
22636
22713
  statements.push(generateTableSQL({
22637
22714
  tableName: _mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT,
@@ -22648,7 +22725,7 @@ var WorkflowsPG = class WorkflowsPG extends _mastra_core_storage.WorkflowsStorag
22648
22725
  * Returns default index definitions for the workflows domain tables.
22649
22726
  */
22650
22727
  getDefaultIndexDefinitions() {
22651
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
22728
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
22652
22729
  return WorkflowsPG.getDefaultIndexDefs(schemaPrefix);
22653
22730
  }
22654
22731
  /**
@@ -22698,7 +22775,7 @@ var WorkflowsPG = class WorkflowsPG extends _mastra_core_storage.WorkflowsStorag
22698
22775
  * so its supporting index is not part of the default index set.
22699
22776
  */
22700
22777
  async ensureRetentionIndexes(policies) {
22701
- const prefix = this.#schema && this.#schema !== "public" ? `${this.#schema}_` : "";
22778
+ const prefix = this.#schema && this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
22702
22779
  for (const [key, entry] of Object.entries(WorkflowsPG.retentionTables)) {
22703
22780
  if (!entry.indexed || !policies[key]) continue;
22704
22781
  try {
@@ -23076,7 +23153,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
23076
23153
  }
23077
23154
  static getExportDDL(schemaName) {
23078
23155
  const statements = [];
23079
- const parsedSchema = schemaName ? (0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name") : "";
23156
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
23080
23157
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
23081
23158
  for (const tableName of WorkspacesPG.MANAGED_TABLES) statements.push(generateTableSQL({
23082
23159
  tableName,
@@ -23088,7 +23165,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
23088
23165
  return statements;
23089
23166
  }
23090
23167
  getDefaultIndexDefinitions() {
23091
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
23168
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
23092
23169
  return WorkspacesPG.getDefaultIndexDefs(schemaPrefix);
23093
23170
  }
23094
23171
  async createDefaultIndexes() {
@@ -24216,7 +24293,7 @@ var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
24216
24293
  disableInit: config.disableInit,
24217
24294
  retention: config.retention
24218
24295
  });
24219
- this.schema = (0, _mastra_core_utils.parseSqlIdentifier)(config.schemaName || "public", "schema name");
24296
+ this.schema = parseSchemaName(config.schemaName || "public");
24220
24297
  if (isPoolConfig(config)) {
24221
24298
  this.#writePool = config.pool;
24222
24299
  this.#ownsWritePool = false;