Repository: mastra-ai/mastra
File: stores/pg/src/storage/db/index.ts (TypeScript)

Code before:
      return `"${parsedName}Z" TIMESTAMPTZ DEFAULT NOW()`;
    });

  const columns = Object.entries(schema).map(([name, def]) => {
    const parsedName = parseSqlIdentifier(name, 'column name');
    const constraints = [];
    if (def.primaryKey) constraints.push('PRIMARY KEY');
    if (!def.nullable) constraints.push('NOT NULL');
    return `"${parsedName}" ${mapToSqlType(def.type)} ${constraints.join(' ')}`;
  });

  const finalColumns = [...columns, ...timeZColumns].join(',\n');
  // Sanitize schema name before using it in constraint names to ensure valid SQL identifiers
  const parsedSchemaName = schemaName ? parseSqlIdentifier(schemaName, 'schema name') : '';
  const workflowSnapshotConstraint = buildConstraintName({
    baseName: 'mastra_workflow_snapshot_workflow_name_run_id_key',
    schemaName: parsedSchemaName || undefined,
  });
  const spansPrimaryKeyConstraint = buildConstraintName({
    baseName: 'mastra_ai_spans_traceid_spanid_pk',
    schemaName: parsedSchemaName || undefined,
  });
  const quotedSchemaName = getSchemaName(schemaName);

  const sql = `
            CREATE TABLE IF NOT EXISTS ${getTableName({ indexName: tableName, schemaName: quotedSchemaName })} (
              ${finalColumns}
            );
            ${
              tableName === TABLE_WORKFLOW_SNAPSHOT
                ? `
            DO $$ BEGIN
              IF NOT EXISTS (
                SELECT 1 FROM pg_constraint WHERE conname = lower('${workflowSnapshotConstraint}')
              ) AND NOT EXISTS (
                SELECT 1 FROM pg_indexes WHERE indexname = lower('${workflowSnapshotConstraint}')
              ) THEN
                ALTER TABLE ${getTableName({ indexName: tableName, schemaName: quotedSchemaName })}
                ADD CONSTRAINT ${workflowSnapshotConstraint}
                UNIQUE (workflow_name, run_id);
              END IF;
            END $$;
            `
                : ''
            }
          ${
            // For spans table: Include PRIMARY KEY in exports, but not in runtime (handled after deduplication)
            tableName === TABLE_SPANS && includeAllConstraints
              ? `
            DO $$ BEGIN
              IF NOT EXISTS (

Review comment (suggestion):
```suggestion
  const workflowSnapshotConstraint = buildConstraintName({
    baseName: 'mastra_wf_snapshot_wf_name_run_id_key',
    schemaName: parsedSchemaName || undefined,
  });
  const spansPrimaryKeyConstraint = buildConstraintName({
    baseName: 'mastra_ai_spans_traceid_spanid_pk',
    schemaName: parsedSchemaName || undefined,
  });
```

Code after:
      return `"${parsedName}Z" TIMESTAMPTZ DEFAULT NOW()`;
    });

  const columns = Object.entries(schema).map(([name, def]) => {
    const parsedName = parseSqlIdentifier(name, 'column name');
    const constraints = [];
    if (def.primaryKey) constraints.push('PRIMARY KEY');
    if (!def.nullable) constraints.push('NOT NULL');
    return `"${parsedName}" ${mapToSqlType(def.type)} ${constraints.join(' ')}`;
  });

  const finalColumns = [...columns, ...timeZColumns].join(',\n');
  // Sanitize schema name before using it in constraint names to ensure valid SQL identifiers
  const parsedSchemaName = schemaName ? parseSqlIdentifier(schemaName, 'schema name') : '';
  // Use the original (long) base name so existing databases that already have
  // the constraint under this name are detected by the IF NOT EXISTS check.
  // buildConstraintName will truncate only when a schema prefix pushes the
  // combined name past the 63-byte Postgres limit.
  const workflowSnapshotConstraint = buildConstraintName({
    baseName: 'mastra_workflow_snapshot_workflow_name_run_id_key',
    schemaName: parsedSchemaName || undefined,
  });
  const spansPrimaryKeyConstraint = buildConstraintName({
    baseName: 'mastra_ai_spans_traceid_spanid_pk',
    schemaName: parsedSchemaName || undefined,
  });
  const quotedSchemaName = getSchemaName(schemaName);

  const sql = `
            CREATE TABLE IF NOT EXISTS ${getTableName({ indexName: tableName, schemaName: quotedSchemaName })} (
              ${finalColumns}
            );
            ${
              tableName === TABLE_WORKFLOW_SNAPSHOT
                ? `
            DO $$ BEGIN
              IF NOT EXISTS (
                SELECT 1 FROM pg_constraint WHERE conname = lower('${workflowSnapshotConstraint}')
              ) AND NOT EXISTS (
                SELECT 1 FROM pg_indexes WHERE indexname = lower('${workflowSnapshotConstraint}')
              ) THEN
                ALTER TABLE ${getTableName({ indexName: tableName, schemaName: quotedSchemaName })}
                ADD CONSTRAINT ${workflowSnapshotConstraint}
                UNIQUE (workflow_name, run_id);
              END IF;
            END $$;
            `
                : ''
            }
          ${
            // For spans table: Include PRIMARY KEY in exports, but not in runtime (handled after deduplication)