@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.js CHANGED
@@ -94,6 +94,34 @@ function buildConnectionStringPoolConfig(config, defaults) {
94
94
  };
95
95
  }
96
96
  //#endregion
97
+ //#region src/shared/schema-name.ts
98
+ const POSTGRES_IDENTIFIER_MAX_BYTES = 63;
99
+ const UNSAFE_SCHEMA_NAME_CHARS = /["'\\$\u0000-\u001f\u007f]/;
100
+ /**
101
+ * Validates a PostgreSQL schema name.
102
+ *
103
+ * Schema names are always double-quoted in generated SQL, so PostgreSQL accepts any name
104
+ * that fits the identifier limit (for example `my-tenant`). Quotes, backslashes, `$` and
105
+ * control characters are rejected so the name can never break out of a quoted identifier,
106
+ * a string literal, or a dollar-quoted block.
107
+ */
108
+ function parseSchemaName(name, kind = "schema name") {
109
+ 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.`);
110
+ return name;
111
+ }
112
+ /**
113
+ * Turns a schema name into a string that is safe to use as part of an unquoted identifier,
114
+ * such as the schema prefix of an index or constraint name.
115
+ *
116
+ * Names that are already plain identifiers (letters, digits, underscores) are returned
117
+ * unchanged, so existing index and constraint names keep working. Any other character
118
+ * becomes `_`, e.g. `my-tenant` -> `my_tenant`.
119
+ */
120
+ function schemaNamePrefix(name) {
121
+ const sanitized = parseSchemaName(name).replace(/[^A-Za-z0-9_]/g, "_");
122
+ return /^[0-9]/.test(sanitized) ? `_${sanitized}` : sanitized;
123
+ }
124
+ //#endregion
97
125
  //#region src/vector/filter.ts
98
126
  /**
99
127
  * Translates MongoDB-style filters to PG compatible filters.
@@ -718,7 +746,8 @@ var PgVector = class extends MastraVector {
718
746
  if (vectorType === "bit") return dimension ? `bit(${dimension})` : "bit";
719
747
  if (this.vectorExtensionSchema) {
720
748
  if (this.vectorExtensionSchema === "pg_catalog") return vectorType;
721
- return `${parseSqlIdentifier(this.vectorExtensionSchema, "vector extension schema")}.${vectorType}`;
749
+ const extensionSchema = parseSchemaName(this.vectorExtensionSchema, "vector extension schema");
750
+ return `${/^[A-Za-z_][A-Za-z0-9_]*$/.test(extensionSchema) ? extensionSchema : `"${extensionSchema}"`}.${vectorType}`;
722
751
  }
723
752
  return vectorType;
724
753
  }
@@ -796,7 +825,7 @@ var PgVector = class extends MastraVector {
796
825
  };
797
826
  }
798
827
  getSchemaName() {
799
- return this.schema ? `"${parseSqlIdentifier(this.schema, "schema name")}"` : void 0;
828
+ return this.schema ? `"${parseSchemaName(this.schema)}"` : void 0;
800
829
  }
801
830
  async ensureNamespaceSchema(indexName, client) {
802
831
  const { tableName, parsedIndexName } = this.getTableName(indexName);
@@ -2551,7 +2580,7 @@ function resolvePgConfig(config) {
2551
2580
  };
2552
2581
  }
2553
2582
  function getSchemaName$6(schema) {
2554
- return schema ? `"${parseSqlIdentifier(schema, "schema name")}"` : "\"public\"";
2583
+ return schema ? `"${parseSchemaName(schema)}"` : "\"public\"";
2555
2584
  }
2556
2585
  function getTableName$6({ indexName, schemaName }) {
2557
2586
  const quotedIndexName = `"${parseSqlIdentifier(indexName, "index name")}"`;
@@ -2590,7 +2619,7 @@ function generateTableSQL({ tableName, schema, schemaName, compositePrimaryKey,
2590
2619
  ...timeZColumns,
2591
2620
  ...tableConstraints
2592
2621
  ].join(",\n");
2593
- const parsedSchemaName = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
2622
+ const parsedSchemaName = schemaName ? schemaNamePrefix(schemaName) : "";
2594
2623
  const workflowSnapshotConstraint = buildConstraintName({
2595
2624
  baseName: "mastra_workflow_snapshot_workflow_name_run_id_key",
2596
2625
  schemaName: parsedSchemaName || void 0
@@ -2600,7 +2629,7 @@ function generateTableSQL({ tableName, schema, schemaName, compositePrimaryKey,
2600
2629
  schemaName: parsedSchemaName || void 0
2601
2630
  });
2602
2631
  const quotedSchemaName = getSchemaName$6(schemaName);
2603
- const schemaFilter = parsedSchemaName || "public";
2632
+ const schemaFilter = schemaName ? parseSchemaName(schemaName) : "public";
2604
2633
  return `
2605
2634
  CREATE TABLE IF NOT EXISTS ${getTableName$6({
2606
2635
  indexName: tableName,
@@ -2726,7 +2755,7 @@ BEGIN
2726
2755
  JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2727
2756
  WHERE tg.tgname = ${`'${parsedTriggerName}'`}
2728
2757
  AND c.relname = ${`'${parseSqlIdentifier(tableName, "table name")}'`}
2729
- AND n.nspname = ${schemaName ? `'${parseSqlIdentifier(schemaName, "schema name")}'` : `'public'`}
2758
+ AND n.nspname = ${schemaName ? `'${parseSchemaName(schemaName)}'` : `'public'`}
2730
2759
  AND NOT tg.tgisinternal
2731
2760
  AND tg.tgtype = 23
2732
2761
  AND tg.tgfoid = '${functionName}()'::regprocedure
@@ -2795,7 +2824,7 @@ var PgDB = class extends MastraBase {
2795
2824
  if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
2796
2825
  const constraintName = buildConstraintName({
2797
2826
  baseName: "mastra_workflow_snapshot_workflow_name_run_id_key",
2798
- schemaName: this.schemaName ? parseSqlIdentifier(this.schemaName, "schema name") : void 0
2827
+ schemaName: this.schemaName ? schemaNamePrefix(this.schemaName) : void 0
2799
2828
  }).toLowerCase();
2800
2829
  return snapshot.indexes.has(constraintName) && snapshot.replicaIdentityIndexes.has(constraintName);
2801
2830
  }
@@ -3400,7 +3429,7 @@ MIGRATION REQUIRED: Duplicate spans detected in ${duplicateInfo.tableName}\n====
3400
3429
  async spansPrimaryKeyExists() {
3401
3430
  const constraintName = buildConstraintName({
3402
3431
  baseName: "mastra_ai_spans_traceid_spanid_pk",
3403
- schemaName: (this.schemaName ? parseSqlIdentifier(this.schemaName, "schema name") : "") || void 0
3432
+ schemaName: (this.schemaName ? schemaNamePrefix(this.schemaName) : "") || void 0
3404
3433
  });
3405
3434
  const schemaFilter = this.schemaName || "public";
3406
3435
  const snapshot = this.schemaSnapshot;
@@ -3422,7 +3451,7 @@ MIGRATION REQUIRED: Duplicate spans detected in ${duplicateInfo.tableName}\n====
3422
3451
  });
3423
3452
  const constraintName = buildConstraintName({
3424
3453
  baseName: "mastra_ai_spans_traceid_spanid_pk",
3425
- schemaName: (this.schemaName ? parseSqlIdentifier(this.schemaName, "schema name") : "") || void 0
3454
+ schemaName: (this.schemaName ? schemaNamePrefix(this.schemaName) : "") || void 0
3426
3455
  });
3427
3456
  const schemaFilter = this.schemaName || "public";
3428
3457
  try {
@@ -4015,7 +4044,7 @@ MIGRATION REQUIRED: Duplicate spans detected in ${duplicateInfo.tableName}\n====
4015
4044
  //#endregion
4016
4045
  //#region src/storage/domains/utils.ts
4017
4046
  function getSchemaName$5(schema) {
4018
- return schema ? `"${parseSqlIdentifier(schema, "schema name")}"` : void 0;
4047
+ return schema ? `"${parseSchemaName(schema)}"` : void 0;
4019
4048
  }
4020
4049
  function getTableName$5({ indexName, schemaName }) {
4021
4050
  const quotedIndexName = `"${parseSqlIdentifier(indexName, "index name")}"`;
@@ -5069,7 +5098,7 @@ var BackgroundTasksPG = class BackgroundTasksPG extends BackgroundTasksStorage {
5069
5098
  * so its supporting index is not part of the default index set.
5070
5099
  */
5071
5100
  async ensureRetentionIndexes(policies) {
5072
- const prefix = this.#schema !== "public" ? `${this.#schema}_` : "";
5101
+ const prefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
5073
5102
  for (const [key, entry] of Object.entries(BackgroundTasksPG.retentionTables)) {
5074
5103
  if (!entry.indexed || !policies[key]) continue;
5075
5104
  try {
@@ -5124,7 +5153,7 @@ var BackgroundTasksPG = class BackgroundTasksPG extends BackgroundTasksStorage {
5124
5153
  }
5125
5154
  static getExportDDL(schemaName) {
5126
5155
  const statements = [];
5127
- const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
5156
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
5128
5157
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
5129
5158
  statements.push(generateTableSQL({
5130
5159
  tableName: TABLE_BACKGROUND_TASKS,
@@ -5136,7 +5165,7 @@ var BackgroundTasksPG = class BackgroundTasksPG extends BackgroundTasksStorage {
5136
5165
  return statements;
5137
5166
  }
5138
5167
  getDefaultIndexDefinitions() {
5139
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
5168
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
5140
5169
  return BackgroundTasksPG.getDefaultIndexDefs(schemaPrefix);
5141
5170
  }
5142
5171
  async createDefaultIndexes() {
@@ -5498,7 +5527,7 @@ var ChannelsPG = class ChannelsPG extends ChannelsStorage {
5498
5527
  }
5499
5528
  static getExportDDL(schemaName) {
5500
5529
  const statements = [];
5501
- const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
5530
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
5502
5531
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
5503
5532
  for (const tableName of ChannelsPG.MANAGED_TABLES) statements.push(generateTableSQL({
5504
5533
  tableName,
@@ -5510,7 +5539,7 @@ var ChannelsPG = class ChannelsPG extends ChannelsStorage {
5510
5539
  return statements;
5511
5540
  }
5512
5541
  getDefaultIndexDefinitions() {
5513
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
5542
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
5514
5543
  return ChannelsPG.getDefaultIndexDefs(schemaPrefix);
5515
5544
  }
5516
5545
  async createDefaultIndexes() {
@@ -7022,7 +7051,7 @@ var ExperimentsPG = class ExperimentsPG extends ExperimentsStorage {
7022
7051
  * so its supporting index is not part of the default index set.
7023
7052
  */
7024
7053
  async ensureRetentionIndexes(policies) {
7025
- const prefix = this.#schema !== "public" ? `${this.#schema}_` : "";
7054
+ const prefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
7026
7055
  for (const [key, entry] of Object.entries(ExperimentsPG.retentionTables)) {
7027
7056
  if (!entry.indexed || !policies[key]) continue;
7028
7057
  try {
@@ -8190,7 +8219,7 @@ function postgresSql(sql, schemaName) {
8190
8219
  return transformed;
8191
8220
  });
8192
8221
  if (schemaName) {
8193
- const quotedSchema = `"${parseSqlIdentifier(schemaName, "schema name")}"`;
8222
+ const quotedSchema = `"${parseSchemaName(schemaName)}"`;
8194
8223
  normalized = transformSqlCode(normalized, (code) => {
8195
8224
  let transformed = code;
8196
8225
  for (const table of [
@@ -8303,7 +8332,7 @@ function parseOutbox(row) {
8303
8332
  function knowledgeIndexes(schemaName) {
8304
8333
  const table = (name) => {
8305
8334
  const quotedName = `"${parseSqlIdentifier(name, "table name")}"`;
8306
- return schemaName ? `"${parseSqlIdentifier(schemaName, "schema name")}".${quotedName}` : quotedName;
8335
+ return schemaName ? `"${parseSchemaName(schemaName)}".${quotedName}` : quotedName;
8307
8336
  };
8308
8337
  return [
8309
8338
  {
@@ -9207,7 +9236,7 @@ var MCPClientsPG = class MCPClientsPG extends MCPClientsStorage {
9207
9236
  }
9208
9237
  static getExportDDL(schemaName) {
9209
9238
  const statements = [];
9210
- const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
9239
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
9211
9240
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
9212
9241
  for (const tableName of MCPClientsPG.MANAGED_TABLES) statements.push(generateTableSQL({
9213
9242
  tableName,
@@ -9219,7 +9248,7 @@ var MCPClientsPG = class MCPClientsPG extends MCPClientsStorage {
9219
9248
  return statements;
9220
9249
  }
9221
9250
  getDefaultIndexDefinitions() {
9222
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
9251
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
9223
9252
  return MCPClientsPG.getDefaultIndexDefs(schemaPrefix);
9224
9253
  }
9225
9254
  async createDefaultIndexes() {
@@ -9775,7 +9804,7 @@ var MCPServersPG = class MCPServersPG extends MCPServersStorage {
9775
9804
  }
9776
9805
  static getExportDDL(schemaName) {
9777
9806
  const statements = [];
9778
- const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
9807
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
9779
9808
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
9780
9809
  for (const tableName of MCPServersPG.MANAGED_TABLES) statements.push(generateTableSQL({
9781
9810
  tableName,
@@ -9787,7 +9816,7 @@ var MCPServersPG = class MCPServersPG extends MCPServersStorage {
9787
9816
  return statements;
9788
9817
  }
9789
9818
  getDefaultIndexDefinitions() {
9790
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
9819
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
9791
9820
  return MCPServersPG.getDefaultIndexDefs(schemaPrefix);
9792
9821
  }
9793
9822
  async createDefaultIndexes() {
@@ -10320,6 +10349,12 @@ var MCPServersPG = class MCPServersPG extends MCPServersStorage {
10320
10349
  * versions that don't export TABLE_OBSERVATIONAL_MEMORY.
10321
10350
  */
10322
10351
  const OM_TABLE = "mastra_observational_memory";
10352
+ /**
10353
+ * Newest generation first. Databases written before generation creation was
10354
+ * serialized can hold several rows with the same generation; the earliest-created
10355
+ * one wins so the active record stays stable across reads.
10356
+ */
10357
+ const OM_GENERATION_ORDER = `"generationCount" DESC, "createdAt" ASC, id ASC`;
10323
10358
  const POSTGRES_MAX_BIND_PARAMETERS = 65535;
10324
10359
  const MESSAGE_INSERT_BIND_PARAMETERS = 8;
10325
10360
  const MAX_MESSAGES_PER_INSERT = Math.floor(POSTGRES_MAX_BIND_PARAMETERS / MESSAGE_INSERT_BIND_PARAMETERS);
@@ -10497,7 +10532,7 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
10497
10532
  * so its supporting index is not part of the default index set.
10498
10533
  */
10499
10534
  async ensureRetentionIndexes(policies) {
10500
- const prefix = this.#schema && this.#schema !== "public" ? `${this.#schema}_` : "";
10535
+ const prefix = this.#schema && this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
10501
10536
  for (const [key, entry] of Object.entries(MemoryPG.retentionTables)) {
10502
10537
  if (!entry.indexed || !policies[key]) continue;
10503
10538
  try {
@@ -10532,7 +10567,7 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
10532
10567
  */
10533
10568
  static getExportDDL(schemaName) {
10534
10569
  const statements = [];
10535
- const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
10570
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
10536
10571
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
10537
10572
  const quotedSchemaName = getSchemaName$6(schemaName);
10538
10573
  for (const tableName of [
@@ -10567,7 +10602,7 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
10567
10602
  * Returns default index definitions for this instance's schema.
10568
10603
  */
10569
10604
  getDefaultIndexDefinitions() {
10570
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
10605
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
10571
10606
  return MemoryPG.getDefaultIndexDefs(schemaPrefix);
10572
10607
  }
10573
10608
  /**
@@ -11921,6 +11956,23 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
11921
11956
  getOMKey(threadId, resourceId) {
11922
11957
  return threadId ? `thread:${threadId}` : `resource:${resourceId}`;
11923
11958
  }
11959
+ /**
11960
+ * Runs `fn` in a transaction that holds an advisory lock for one OM lookup key.
11961
+ *
11962
+ * The table has no unique constraint on ("lookupKey", "generationCount"), and
11963
+ * adding one would fail on databases that already contain duplicates. The lock
11964
+ * serializes generation creation across processes instead. It is
11965
+ * transaction-scoped so it also works behind transaction-pooling proxies.
11966
+ */
11967
+ async #withOMLookupKeyLock(tableName, lookupKey, fn) {
11968
+ return this.#db.client.tx(async (t) => {
11969
+ await t.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", [`${tableName}:${lookupKey}`]);
11970
+ return fn(t);
11971
+ });
11972
+ }
11973
+ async #getLatestOMRow(client, tableName, lookupKey) {
11974
+ return client.oneOrNone(`SELECT * FROM ${tableName} WHERE "lookupKey" = $1 ORDER BY ${OM_GENERATION_ORDER} LIMIT 1`, [lookupKey]);
11975
+ }
11924
11976
  parseOMRow(row) {
11925
11977
  return {
11926
11978
  id: row.id,
@@ -11963,7 +12015,7 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
11963
12015
  indexName: OM_TABLE,
11964
12016
  schemaName: getSchemaName$3(this.#schema)
11965
12017
  });
11966
- const result = await this.#db.readClient.oneOrNone(`SELECT * FROM ${tableName} WHERE "lookupKey" = $1 ORDER BY "generationCount" DESC LIMIT 1`, [lookupKey]);
12018
+ const result = await this.#getLatestOMRow(this.#db.readClient, tableName, lookupKey);
11967
12019
  if (!result) return null;
11968
12020
  return this.parseOMRow(result);
11969
12021
  } catch (error) {
@@ -11999,7 +12051,7 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
11999
12051
  paramIndex++;
12000
12052
  }
12001
12053
  params.push(limit);
12002
- let sql = `SELECT * FROM ${tableName} WHERE ${conditions.join(" AND ")} ORDER BY "generationCount" DESC LIMIT $${paramIndex}`;
12054
+ let sql = `SELECT * FROM ${tableName} WHERE ${conditions.join(" AND ")} ORDER BY ${OM_GENERATION_ORDER} LIMIT $${paramIndex}`;
12003
12055
  paramIndex++;
12004
12056
  if (options?.offset != null) {
12005
12057
  params.push(options.offset);
@@ -12054,7 +12106,10 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
12054
12106
  schemaName: getSchemaName$3(this.#schema)
12055
12107
  });
12056
12108
  const nowStr = now.toISOString();
12057
- await this.#db.client.none(`INSERT INTO ${tableName} (
12109
+ return await this.#withOMLookupKeyLock(tableName, lookupKey, async (t) => {
12110
+ const existing = await this.#getLatestOMRow(t, tableName, lookupKey);
12111
+ if (existing) return this.parseOMRow(existing);
12112
+ await t.none(`INSERT INTO ${tableName} (
12058
12113
  id, "lookupKey", scope, "resourceId", "threadId",
12059
12114
  "activeObservations", "activeObservationsPendingUpdate",
12060
12115
  "originType", config, "generationCount", "lastObservedAt", "lastObservedAtZ", "lastReflectionAt", "lastReflectionAtZ",
@@ -12062,36 +12117,37 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
12062
12117
  "isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
12063
12118
  "observedTimezone", "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
12064
12119
  ) 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)`, [
12065
- id,
12066
- lookupKey,
12067
- input.scope,
12068
- input.resourceId,
12069
- input.threadId || null,
12070
- "",
12071
- null,
12072
- "initial",
12073
- toPgJson(input.config),
12074
- 0,
12075
- null,
12076
- null,
12077
- null,
12078
- null,
12079
- 0,
12080
- 0,
12081
- 0,
12082
- false,
12083
- false,
12084
- false,
12085
- false,
12086
- 0,
12087
- null,
12088
- input.observedTimezone || null,
12089
- nowStr,
12090
- nowStr,
12091
- nowStr,
12092
- nowStr
12093
- ]);
12094
- return record;
12120
+ id,
12121
+ lookupKey,
12122
+ input.scope,
12123
+ input.resourceId,
12124
+ input.threadId || null,
12125
+ "",
12126
+ null,
12127
+ "initial",
12128
+ toPgJson(input.config),
12129
+ 0,
12130
+ null,
12131
+ null,
12132
+ null,
12133
+ null,
12134
+ 0,
12135
+ 0,
12136
+ 0,
12137
+ false,
12138
+ false,
12139
+ false,
12140
+ false,
12141
+ 0,
12142
+ null,
12143
+ input.observedTimezone || null,
12144
+ nowStr,
12145
+ nowStr,
12146
+ nowStr,
12147
+ nowStr
12148
+ ]);
12149
+ return record;
12150
+ });
12095
12151
  } catch (error) {
12096
12152
  throw new MastraError({
12097
12153
  id: createStorageErrorId("PG", "INITIALIZE_OBSERVATIONAL_MEMORY", "FAILED"),
@@ -12223,78 +12279,16 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
12223
12279
  }
12224
12280
  async createReflectionGeneration(input) {
12225
12281
  try {
12226
- const id = crypto.randomUUID();
12227
- const now = /* @__PURE__ */ new Date();
12228
12282
  const lookupKey = this.getOMKey(input.currentRecord.threadId, input.currentRecord.resourceId);
12229
- const record = {
12230
- id,
12231
- scope: input.currentRecord.scope,
12232
- threadId: input.currentRecord.threadId,
12233
- resourceId: input.currentRecord.resourceId,
12234
- createdAt: now,
12235
- updatedAt: now,
12236
- lastObservedAt: input.currentRecord.lastObservedAt,
12237
- originType: "reflection",
12238
- generationCount: input.currentRecord.generationCount + 1,
12239
- activeObservations: input.reflection,
12240
- totalTokensObserved: input.currentRecord.totalTokensObserved,
12241
- observationTokenCount: input.tokenCount,
12242
- pendingMessageTokens: 0,
12243
- isReflecting: false,
12244
- isObserving: false,
12245
- isBufferingObservation: false,
12246
- isBufferingReflection: false,
12247
- lastBufferedAtTokens: 0,
12248
- lastBufferedAtTime: null,
12249
- config: input.currentRecord.config,
12250
- metadata: input.currentRecord.metadata,
12251
- observedTimezone: input.currentRecord.observedTimezone
12252
- };
12253
12283
  const tableName = getTableName$3({
12254
12284
  indexName: OM_TABLE,
12255
12285
  schemaName: getSchemaName$3(this.#schema)
12256
12286
  });
12257
- const nowStr = now.toISOString();
12258
- const lastObservedAtStr = record.lastObservedAt?.toISOString() || null;
12259
- await this.#db.client.none(`INSERT INTO ${tableName} (
12260
- id, "lookupKey", scope, "resourceId", "threadId",
12261
- "activeObservations", "activeObservationsPendingUpdate",
12262
- "originType", config, "generationCount", "lastObservedAt", "lastObservedAtZ", "lastReflectionAt", "lastReflectionAtZ",
12263
- "pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
12264
- "isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
12265
- "observedTimezone", metadata, "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
12266
- ) 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)`, [
12267
- id,
12268
- lookupKey,
12269
- record.scope,
12270
- record.resourceId,
12271
- record.threadId || null,
12272
- input.reflection,
12273
- null,
12274
- "reflection",
12275
- toPgJson(record.config),
12276
- input.currentRecord.generationCount + 1,
12277
- lastObservedAtStr,
12278
- lastObservedAtStr,
12279
- nowStr,
12280
- nowStr,
12281
- record.pendingMessageTokens,
12282
- Math.round(record.totalTokensObserved),
12283
- Math.round(record.observationTokenCount),
12284
- false,
12285
- false,
12286
- false,
12287
- false,
12288
- 0,
12289
- null,
12290
- record.observedTimezone || null,
12291
- record.metadata ? toPgJson(record.metadata) : null,
12292
- nowStr,
12293
- nowStr,
12294
- nowStr,
12295
- nowStr
12296
- ]);
12297
- return record;
12287
+ return await this.#withOMLookupKeyLock(tableName, lookupKey, async (t) => {
12288
+ const newer = await this.#getNewerOMGeneration(t, tableName, lookupKey, input.currentRecord.generationCount);
12289
+ if (newer) return newer;
12290
+ return this.#insertReflectionGeneration(t, tableName, lookupKey, input);
12291
+ });
12298
12292
  } catch (error) {
12299
12293
  throw new MastraError({
12300
12294
  id: createStorageErrorId("PG", "CREATE_REFLECTION_GENERATION", "FAILED"),
@@ -12304,6 +12298,84 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
12304
12298
  }, error);
12305
12299
  }
12306
12300
  }
12301
+ /**
12302
+ * Returns the active record when another writer already created a generation
12303
+ * after `generationCount`. Reflecting from the older generation again would
12304
+ * add a second record with the same generation.
12305
+ */
12306
+ async #getNewerOMGeneration(t, tableName, lookupKey, generationCount) {
12307
+ const latest = await this.#getLatestOMRow(t, tableName, lookupKey);
12308
+ return latest && Number(latest.generationCount) > generationCount ? this.parseOMRow(latest) : null;
12309
+ }
12310
+ async #insertReflectionGeneration(t, tableName, lookupKey, input) {
12311
+ const id = crypto.randomUUID();
12312
+ const now = /* @__PURE__ */ new Date();
12313
+ const record = {
12314
+ id,
12315
+ scope: input.currentRecord.scope,
12316
+ threadId: input.currentRecord.threadId,
12317
+ resourceId: input.currentRecord.resourceId,
12318
+ createdAt: now,
12319
+ updatedAt: now,
12320
+ lastObservedAt: input.currentRecord.lastObservedAt,
12321
+ originType: "reflection",
12322
+ generationCount: input.currentRecord.generationCount + 1,
12323
+ activeObservations: input.reflection,
12324
+ totalTokensObserved: input.currentRecord.totalTokensObserved,
12325
+ observationTokenCount: input.tokenCount,
12326
+ pendingMessageTokens: 0,
12327
+ isReflecting: false,
12328
+ isObserving: false,
12329
+ isBufferingObservation: false,
12330
+ isBufferingReflection: false,
12331
+ lastBufferedAtTokens: 0,
12332
+ lastBufferedAtTime: null,
12333
+ config: input.currentRecord.config,
12334
+ metadata: input.currentRecord.metadata,
12335
+ observedTimezone: input.currentRecord.observedTimezone
12336
+ };
12337
+ const nowStr = now.toISOString();
12338
+ const lastObservedAtStr = record.lastObservedAt?.toISOString() || null;
12339
+ await t.none(`INSERT INTO ${tableName} (
12340
+ id, "lookupKey", scope, "resourceId", "threadId",
12341
+ "activeObservations", "activeObservationsPendingUpdate",
12342
+ "originType", config, "generationCount", "lastObservedAt", "lastObservedAtZ", "lastReflectionAt", "lastReflectionAtZ",
12343
+ "pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
12344
+ "isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
12345
+ "observedTimezone", metadata, "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
12346
+ ) 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)`, [
12347
+ id,
12348
+ lookupKey,
12349
+ record.scope,
12350
+ record.resourceId,
12351
+ record.threadId || null,
12352
+ input.reflection,
12353
+ null,
12354
+ "reflection",
12355
+ toPgJson(record.config),
12356
+ input.currentRecord.generationCount + 1,
12357
+ lastObservedAtStr,
12358
+ lastObservedAtStr,
12359
+ nowStr,
12360
+ nowStr,
12361
+ record.pendingMessageTokens,
12362
+ Math.round(record.totalTokensObserved),
12363
+ Math.round(record.observationTokenCount),
12364
+ false,
12365
+ false,
12366
+ false,
12367
+ false,
12368
+ 0,
12369
+ null,
12370
+ record.observedTimezone || null,
12371
+ record.metadata ? toPgJson(record.metadata) : null,
12372
+ nowStr,
12373
+ nowStr,
12374
+ nowStr,
12375
+ nowStr
12376
+ ]);
12377
+ return record;
12378
+ }
12307
12379
  async setReflectingFlag(id, isReflecting) {
12308
12380
  try {
12309
12381
  const tableName = getTableName$3({
@@ -12798,32 +12870,36 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
12798
12870
  indexName: OM_TABLE,
12799
12871
  schemaName: getSchemaName$3(this.#schema)
12800
12872
  });
12801
- const record = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [input.currentRecord.id]);
12802
- if (!record) throw new MastraError({
12803
- id: createStorageErrorId("PG", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NOT_FOUND"),
12804
- text: `Observational memory record not found: ${input.currentRecord.id}`,
12805
- domain: ErrorDomain.STORAGE,
12806
- category: ErrorCategory.THIRD_PARTY,
12807
- details: { id: input.currentRecord.id }
12808
- });
12809
- const bufferedReflection = record.bufferedReflection || "";
12810
- const reflectedLineCount = Number(record.reflectedObservationLineCount || 0);
12811
- if (!bufferedReflection) throw new MastraError({
12812
- id: createStorageErrorId("PG", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NO_CONTENT"),
12813
- text: "No buffered reflection to swap",
12814
- domain: ErrorDomain.STORAGE,
12815
- category: ErrorCategory.USER,
12816
- details: { id: input.currentRecord.id }
12817
- });
12818
- const unreflectedContent = (record.activeObservations || "").split("\n").slice(reflectedLineCount).join("\n").trim();
12819
- const newObservations = unreflectedContent ? `${bufferedReflection}\n\n${unreflectedContent}` : bufferedReflection;
12820
- const newRecord = await this.createReflectionGeneration({
12821
- currentRecord: input.currentRecord,
12822
- reflection: newObservations,
12823
- tokenCount: input.tokenCount
12824
- });
12825
- const nowStr = (/* @__PURE__ */ new Date()).toISOString();
12826
- await this.#db.client.query(`UPDATE ${tableName} SET
12873
+ const lookupKey = this.getOMKey(input.currentRecord.threadId, input.currentRecord.resourceId);
12874
+ return await this.#withOMLookupKeyLock(tableName, lookupKey, async (t) => {
12875
+ const newer = await this.#getNewerOMGeneration(t, tableName, lookupKey, input.currentRecord.generationCount);
12876
+ if (newer) return newer;
12877
+ const record = await t.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [input.currentRecord.id]);
12878
+ if (!record) throw new MastraError({
12879
+ id: createStorageErrorId("PG", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NOT_FOUND"),
12880
+ text: `Observational memory record not found: ${input.currentRecord.id}`,
12881
+ domain: ErrorDomain.STORAGE,
12882
+ category: ErrorCategory.THIRD_PARTY,
12883
+ details: { id: input.currentRecord.id }
12884
+ });
12885
+ const bufferedReflection = record.bufferedReflection || "";
12886
+ const reflectedLineCount = Number(record.reflectedObservationLineCount || 0);
12887
+ if (!bufferedReflection) throw new MastraError({
12888
+ id: createStorageErrorId("PG", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NO_CONTENT"),
12889
+ text: "No buffered reflection to swap",
12890
+ domain: ErrorDomain.STORAGE,
12891
+ category: ErrorCategory.USER,
12892
+ details: { id: input.currentRecord.id }
12893
+ });
12894
+ const unreflectedContent = (record.activeObservations || "").split("\n").slice(reflectedLineCount).join("\n").trim();
12895
+ const newObservations = unreflectedContent ? `${bufferedReflection}\n\n${unreflectedContent}` : bufferedReflection;
12896
+ const newRecord = await this.#insertReflectionGeneration(t, tableName, lookupKey, {
12897
+ currentRecord: input.currentRecord,
12898
+ reflection: newObservations,
12899
+ tokenCount: input.tokenCount
12900
+ });
12901
+ const nowStr = (/* @__PURE__ */ new Date()).toISOString();
12902
+ await t.query(`UPDATE ${tableName} SET
12827
12903
  "bufferedReflection" = NULL,
12828
12904
  "bufferedReflectionTokens" = NULL,
12829
12905
  "bufferedReflectionInputTokens" = NULL,
@@ -12831,11 +12907,12 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
12831
12907
  "updatedAt" = $1,
12832
12908
  "updatedAtZ" = $2
12833
12909
  WHERE id = $3`, [
12834
- nowStr,
12835
- nowStr,
12836
- input.currentRecord.id
12837
- ]);
12838
- return newRecord;
12910
+ nowStr,
12911
+ nowStr,
12912
+ input.currentRecord.id
12913
+ ]);
12914
+ return newRecord;
12915
+ });
12839
12916
  } catch (error) {
12840
12917
  if (error instanceof MastraError) throw error;
12841
12918
  throw new MastraError({
@@ -12975,7 +13052,7 @@ var NotificationsPG = class NotificationsPG extends NotificationsStorage {
12975
13052
  * so its supporting index is not part of the default index set.
12976
13053
  */
12977
13054
  async ensureRetentionIndexes(policies) {
12978
- const prefix = this.#schema && this.#schema !== "public" ? `${this.#schema}_` : "";
13055
+ const prefix = this.#schema && this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
12979
13056
  for (const [key, entry] of Object.entries(NotificationsPG.retentionTables)) {
12980
13057
  if (!entry.indexed || !policies[key]) continue;
12981
13058
  try {
@@ -13042,7 +13119,7 @@ var NotificationsPG = class NotificationsPG extends NotificationsStorage {
13042
13119
  }
13043
13120
  static getExportDDL(schemaName) {
13044
13121
  const statements = [];
13045
- const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
13122
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
13046
13123
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
13047
13124
  statements.push(generateTableSQL({
13048
13125
  tableName: TABLE_NOTIFICATIONS,
@@ -13054,7 +13131,7 @@ var NotificationsPG = class NotificationsPG extends NotificationsStorage {
13054
13131
  return statements;
13055
13132
  }
13056
13133
  getDefaultIndexDefinitions() {
13057
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
13134
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
13058
13135
  return NotificationsPG.getDefaultIndexDefs(schemaPrefix);
13059
13136
  }
13060
13137
  async createDefaultIndexes() {
@@ -13351,7 +13428,7 @@ var ObservabilityPG = class ObservabilityPG extends ObservabilityStorage {
13351
13428
  * so its supporting index is not part of the default index set.
13352
13429
  */
13353
13430
  async ensureRetentionIndexes(policies) {
13354
- const prefix = this.#schema !== "public" ? `${this.#schema}_` : "";
13431
+ const prefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
13355
13432
  for (const [key, entry] of Object.entries(ObservabilityPG.retentionTables)) {
13356
13433
  if (!entry.indexed || !policies[key]) continue;
13357
13434
  try {
@@ -13432,7 +13509,7 @@ var ObservabilityPG = class ObservabilityPG extends ObservabilityStorage {
13432
13509
  */
13433
13510
  static getExportDDL(schemaName) {
13434
13511
  const statements = [];
13435
- const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
13512
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
13436
13513
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
13437
13514
  statements.push(generateTableSQL({
13438
13515
  tableName: TABLE_SPANS,
@@ -13448,7 +13525,7 @@ var ObservabilityPG = class ObservabilityPG extends ObservabilityStorage {
13448
13525
  * Returns default index definitions for this instance's schema.
13449
13526
  */
13450
13527
  getDefaultIndexDefinitions() {
13451
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
13528
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
13452
13529
  return ObservabilityPG.getDefaultIndexDefs(schemaPrefix);
13453
13530
  }
13454
13531
  /**
@@ -14659,15 +14736,15 @@ const SIGNAL_TIME_COLUMN = {
14659
14736
  };
14660
14737
  /** Returns a fully-qualified, double-quoted table name. */
14661
14738
  function qualifiedTable(schema, table) {
14662
- return `"${parseSqlIdentifier(schema, "schema name")}"."${parseSqlIdentifier(table, "table name")}"`;
14739
+ return `"${parseSchemaName(schema)}"."${parseSqlIdentifier(table, "table name")}"`;
14663
14740
  }
14664
14741
  /** Returns a parsed, quoted, schema-prefixed object name (constraint, index, etc.). */
14665
14742
  function qualifiedName(schema, name) {
14666
- return `"${parseSqlIdentifier(schema, "schema name")}"."${parseSqlIdentifier(name, "object name")}"`;
14743
+ return `"${parseSchemaName(schema)}"."${parseSqlIdentifier(name, "object name")}"`;
14667
14744
  }
14668
14745
  /** Schema CREATE. Safe to run repeatedly before table DDL. */
14669
14746
  function schemaDDL(schema) {
14670
- return `CREATE SCHEMA IF NOT EXISTS "${parseSqlIdentifier(schema, "schema name")}"`;
14747
+ return `CREATE SCHEMA IF NOT EXISTS "${parseSchemaName(schema)}"`;
14671
14748
  }
14672
14749
  /**
14673
14750
  * Postgres declarative partitioning and Timescale hypertables are mutually
@@ -19207,7 +19284,7 @@ var PromptBlocksPG = class PromptBlocksPG extends PromptBlocksStorage {
19207
19284
  */
19208
19285
  static getExportDDL(schemaName) {
19209
19286
  const statements = [];
19210
- const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
19287
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
19211
19288
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
19212
19289
  for (const tableName of PromptBlocksPG.MANAGED_TABLES) statements.push(generateTableSQL({
19213
19290
  tableName,
@@ -19219,7 +19296,7 @@ var PromptBlocksPG = class PromptBlocksPG extends PromptBlocksStorage {
19219
19296
  return statements;
19220
19297
  }
19221
19298
  getDefaultIndexDefinitions() {
19222
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
19299
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
19223
19300
  return PromptBlocksPG.getDefaultIndexDefs(schemaPrefix);
19224
19301
  }
19225
19302
  async createDefaultIndexes() {
@@ -19854,7 +19931,7 @@ var SchedulesPG = class SchedulesPG extends SchedulesStorage {
19854
19931
  * so its supporting index is not part of the default index set.
19855
19932
  */
19856
19933
  async ensureRetentionIndexes(policies) {
19857
- const prefix = this.#schema !== "public" ? `${this.#schema}_` : "";
19934
+ const prefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
19858
19935
  for (const [key, entry] of Object.entries(SchedulesPG.retentionTables)) {
19859
19936
  if (!entry.indexed || !policies[key]) continue;
19860
19937
  try {
@@ -19902,7 +19979,7 @@ var SchedulesPG = class SchedulesPG extends SchedulesStorage {
19902
19979
  }];
19903
19980
  }
19904
19981
  getDefaultIndexDefinitions() {
19905
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
19982
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
19906
19983
  return SchedulesPG.getDefaultIndexDefs(schemaPrefix);
19907
19984
  }
19908
19985
  async createDefaultIndexes() {
@@ -19923,7 +20000,7 @@ var SchedulesPG = class SchedulesPG extends SchedulesStorage {
19923
20000
  }
19924
20001
  static getExportDDL(schemaName) {
19925
20002
  const statements = [];
19926
- const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
20003
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
19927
20004
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
19928
20005
  statements.push(generateTableSQL({
19929
20006
  tableName: TABLE_SCHEDULES,
@@ -19945,7 +20022,7 @@ var SchedulesPG = class SchedulesPG extends SchedulesStorage {
19945
20022
  await this.#db.clearTable({ tableName: TABLE_SCHEDULES });
19946
20023
  }
19947
20024
  #table(tableName) {
19948
- return getTableName$2(tableName, getSchemaName$2(parseSqlIdentifier(this.#schema, "schema name")));
20025
+ return getTableName$2(tableName, getSchemaName$2(parseSchemaName(this.#schema)));
19949
20026
  }
19950
20027
  async createSchedule(schedule) {
19951
20028
  if (await this.#getSchedule(this.#client, schedule.id)) throw new Error(`Schedule with id "${schedule.id}" already exists`);
@@ -20150,7 +20227,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends ScorerDefinitionsSto
20150
20227
  */
20151
20228
  static getExportDDL(schemaName) {
20152
20229
  const statements = [];
20153
- const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
20230
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
20154
20231
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
20155
20232
  for (const tableName of ScorerDefinitionsPG.MANAGED_TABLES) statements.push(generateTableSQL({
20156
20233
  tableName,
@@ -20162,7 +20239,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends ScorerDefinitionsSto
20162
20239
  return statements;
20163
20240
  }
20164
20241
  getDefaultIndexDefinitions() {
20165
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
20242
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
20166
20243
  return ScorerDefinitionsPG.getDefaultIndexDefs(schemaPrefix);
20167
20244
  }
20168
20245
  async createDefaultIndexes() {
@@ -20795,7 +20872,7 @@ var ScoresPG = class ScoresPG extends ScoresStorage {
20795
20872
  * so its supporting index is not part of the default index set.
20796
20873
  */
20797
20874
  async ensureRetentionIndexes(policies) {
20798
- const prefix = this.#schema && this.#schema !== "public" ? `${this.#schema}_` : "";
20875
+ const prefix = this.#schema && this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
20799
20876
  for (const [key, entry] of Object.entries(ScoresPG.retentionTables)) {
20800
20877
  if (!entry.indexed || !policies[key]) continue;
20801
20878
  try {
@@ -20830,7 +20907,7 @@ var ScoresPG = class ScoresPG extends ScoresStorage {
20830
20907
  */
20831
20908
  static getExportDDL(schemaName) {
20832
20909
  const statements = [];
20833
- const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
20910
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
20834
20911
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
20835
20912
  statements.push(generateTableSQL({
20836
20913
  tableName: TABLE_SCORERS,
@@ -20845,7 +20922,7 @@ var ScoresPG = class ScoresPG extends ScoresStorage {
20845
20922
  * Returns default index definitions for this instance's schema.
20846
20923
  */
20847
20924
  getDefaultIndexDefinitions() {
20848
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
20925
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
20849
20926
  return ScoresPG.getDefaultIndexDefs(schemaPrefix);
20850
20927
  }
20851
20928
  /**
@@ -21208,7 +21285,7 @@ var SkillsPG = class SkillsPG extends SkillsStorage {
21208
21285
  }
21209
21286
  static getExportDDL(schemaName) {
21210
21287
  const statements = [];
21211
- const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
21288
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
21212
21289
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
21213
21290
  for (const tableName of SkillsPG.MANAGED_TABLES) statements.push(generateTableSQL({
21214
21291
  tableName,
@@ -21220,7 +21297,7 @@ var SkillsPG = class SkillsPG extends SkillsStorage {
21220
21297
  return statements;
21221
21298
  }
21222
21299
  getDefaultIndexDefinitions() {
21223
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
21300
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
21224
21301
  return SkillsPG.getDefaultIndexDefs(schemaPrefix);
21225
21302
  }
21226
21303
  async createDefaultIndexes() {
@@ -21915,7 +21992,7 @@ var ThreadStatePG = class ThreadStatePG extends ThreadStateStorage {
21915
21992
  * a failure here leaves pruning correct, just slower.
21916
21993
  */
21917
21994
  async #ensureRetentionIndexes(policies) {
21918
- const prefix = this.#schema && this.#schema !== "public" ? `${this.#schema}_` : "";
21995
+ const prefix = this.#schema && this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
21919
21996
  for (const [key, entry] of Object.entries(ThreadStatePG.retentionTables)) {
21920
21997
  if (!entry.indexed || !policies[key]) continue;
21921
21998
  try {
@@ -22081,7 +22158,7 @@ var ToolProviderConnectionsPG = class ToolProviderConnectionsPG extends ToolProv
22081
22158
  }
22082
22159
  static getExportDDL(schemaName) {
22083
22160
  const statements = [];
22084
- const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
22161
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
22085
22162
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
22086
22163
  statements.push(generateTableSQL({
22087
22164
  tableName: TABLE_TOOL_PROVIDER_CONNECTIONS,
@@ -22098,7 +22175,7 @@ var ToolProviderConnectionsPG = class ToolProviderConnectionsPG extends ToolProv
22098
22175
  return statements;
22099
22176
  }
22100
22177
  getDefaultIndexDefinitions() {
22101
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
22178
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
22102
22179
  return ToolProviderConnectionsPG.getDefaultIndexDefs(schemaPrefix);
22103
22180
  }
22104
22181
  async createDefaultIndexes() {
@@ -22330,7 +22407,7 @@ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends WorkflowDefiniti
22330
22407
  }
22331
22408
  getDefaultIndexDefinitions() {
22332
22409
  return [{
22333
- name: `${this.#schema !== "public" ? `${this.#schema}_` : ""}idx_workflow_definitions_status`,
22410
+ name: `${this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : ""}idx_workflow_definitions_status`,
22334
22411
  table: TABLE_WORKFLOW_DEFINITIONS,
22335
22412
  columns: ["status"]
22336
22413
  }];
@@ -22607,7 +22684,7 @@ var WorkflowsPG = class WorkflowsPG extends WorkflowsStorage {
22607
22684
  */
22608
22685
  static getExportDDL(schemaName) {
22609
22686
  const statements = [];
22610
- const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
22687
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
22611
22688
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
22612
22689
  statements.push(generateTableSQL({
22613
22690
  tableName: TABLE_WORKFLOW_SNAPSHOT,
@@ -22624,7 +22701,7 @@ var WorkflowsPG = class WorkflowsPG extends WorkflowsStorage {
22624
22701
  * Returns default index definitions for the workflows domain tables.
22625
22702
  */
22626
22703
  getDefaultIndexDefinitions() {
22627
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
22704
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
22628
22705
  return WorkflowsPG.getDefaultIndexDefs(schemaPrefix);
22629
22706
  }
22630
22707
  /**
@@ -22674,7 +22751,7 @@ var WorkflowsPG = class WorkflowsPG extends WorkflowsStorage {
22674
22751
  * so its supporting index is not part of the default index set.
22675
22752
  */
22676
22753
  async ensureRetentionIndexes(policies) {
22677
- const prefix = this.#schema && this.#schema !== "public" ? `${this.#schema}_` : "";
22754
+ const prefix = this.#schema && this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
22678
22755
  for (const [key, entry] of Object.entries(WorkflowsPG.retentionTables)) {
22679
22756
  if (!entry.indexed || !policies[key]) continue;
22680
22757
  try {
@@ -23052,7 +23129,7 @@ var WorkspacesPG = class WorkspacesPG extends WorkspacesStorage {
23052
23129
  }
23053
23130
  static getExportDDL(schemaName) {
23054
23131
  const statements = [];
23055
- const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
23132
+ const parsedSchema = schemaName ? schemaNamePrefix(schemaName) : "";
23056
23133
  const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
23057
23134
  for (const tableName of WorkspacesPG.MANAGED_TABLES) statements.push(generateTableSQL({
23058
23135
  tableName,
@@ -23064,7 +23141,7 @@ var WorkspacesPG = class WorkspacesPG extends WorkspacesStorage {
23064
23141
  return statements;
23065
23142
  }
23066
23143
  getDefaultIndexDefinitions() {
23067
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
23144
+ const schemaPrefix = this.#schema !== "public" ? `${schemaNamePrefix(this.#schema)}_` : "";
23068
23145
  return WorkspacesPG.getDefaultIndexDefs(schemaPrefix);
23069
23146
  }
23070
23147
  async createDefaultIndexes() {
@@ -24192,7 +24269,7 @@ var PostgresStore = class extends MastraCompositeStore {
24192
24269
  disableInit: config.disableInit,
24193
24270
  retention: config.retention
24194
24271
  });
24195
- this.schema = parseSqlIdentifier(config.schemaName || "public", "schema name");
24272
+ this.schema = parseSchemaName(config.schemaName || "public");
24196
24273
  if (isPoolConfig(config)) {
24197
24274
  this.#writePool = config.pool;
24198
24275
  this.#ownsWritePool = false;