@mastra/mysql 0.3.4 → 0.4.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
@@ -1,5 +1,5 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { StoreOperations, TABLE_CONFIGS, TABLE_WORKFLOW_SNAPSHOT, TABLE_SPANS, AgentsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, AGENTS_SCHEMA, AGENT_VERSIONS_SCHEMA, createStorageErrorId, normalizePerPage, calculatePagination, BlobStore, SKILL_BLOBS_SCHEMA, TABLE_SKILL_BLOBS, DatasetsStorage, TABLE_DATASETS, TABLE_DATASET_ITEMS, TABLE_DATASET_VERSIONS, DATASETS_SCHEMA, DATASET_ITEMS_SCHEMA, DATASET_VERSIONS_SCHEMA, TABLE_EXPERIMENTS, TABLE_EXPERIMENT_RESULTS, ExperimentsStorage, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, MCPClientsStorage, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, MCP_CLIENTS_SCHEMA, MCP_CLIENT_VERSIONS_SCHEMA, MCPServersStorage, TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS, MCP_SERVERS_SCHEMA, MCP_SERVER_VERSIONS_SCHEMA, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, TABLE_SCHEMAS, OBSERVATIONAL_MEMORY_TABLE_SCHEMA, ObservabilityStorage, SPAN_SCHEMA, listTracesArgsSchema, TraceStatus, toTraceSpans, PromptBlocksStorage, TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS, PROMPT_BLOCKS_SCHEMA, PROMPT_BLOCK_VERSIONS_SCHEMA, ScorerDefinitionsStorage, TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS, SCORER_DEFINITIONS_SCHEMA, SCORER_DEFINITION_VERSIONS_SCHEMA, ScoresStorage, TABLE_SCORERS, SCORERS_SCHEMA, SkillsStorage, TABLE_SKILLS, TABLE_SKILL_VERSIONS, SKILLS_SCHEMA, SKILL_VERSIONS_SCHEMA, WorkflowsStorage, WorkspacesStorage, TABLE_WORKSPACES, TABLE_WORKSPACE_VERSIONS, WORKSPACES_SCHEMA, WORKSPACE_VERSIONS_SCHEMA, MastraCompositeStore, TABLE_FAVORITES, BackgroundTasksStorage, TABLE_BACKGROUND_TASKS, ChannelsStorage, TABLE_CHANNEL_INSTALLATIONS, TABLE_CHANNEL_CONFIG, FavoritesStorage, FAVORITES_SCHEMA, SchedulesStorage, TABLE_SCHEDULES, TABLE_SCHEDULE_TRIGGERS, ToolProviderConnectionsStorage, TABLE_TOOL_PROVIDER_CONNECTIONS, TOOL_PROVIDER_CONNECTIONS_SCHEMA, normalizeScheduleTarget } from '@mastra/core/storage';
2
+ import { StoreOperations, TABLE_CONFIGS, TABLE_WORKFLOW_SNAPSHOT, TABLE_SPANS, AgentsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, AGENTS_SCHEMA, AGENT_VERSIONS_SCHEMA, createStorageErrorId, normalizePerPage, calculatePagination, BlobStore, SKILL_BLOBS_SCHEMA, TABLE_SKILL_BLOBS, DatasetsStorage, TABLE_DATASETS, TABLE_DATASET_ITEMS, TABLE_DATASET_VERSIONS, DATASETS_SCHEMA, DATASET_ITEMS_SCHEMA, DATASET_VERSIONS_SCHEMA, TABLE_EXPERIMENTS, TABLE_EXPERIMENT_RESULTS, hasErrorCode, ExperimentsStorage, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, MCPClientsStorage, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, MCP_CLIENTS_SCHEMA, MCP_CLIENT_VERSIONS_SCHEMA, MCPServersStorage, TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS, MCP_SERVERS_SCHEMA, MCP_SERVER_VERSIONS_SCHEMA, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, TABLE_SCHEMAS, OBSERVATIONAL_MEMORY_TABLE_SCHEMA, ObservabilityStorage, SPAN_SCHEMA, listTracesArgsSchema, TraceStatus, toTraceSpans, PromptBlocksStorage, TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS, PROMPT_BLOCKS_SCHEMA, PROMPT_BLOCK_VERSIONS_SCHEMA, ScorerDefinitionsStorage, TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS, SCORER_DEFINITIONS_SCHEMA, SCORER_DEFINITION_VERSIONS_SCHEMA, ScoresStorage, TABLE_SCORERS, SCORERS_SCHEMA, SkillsStorage, TABLE_SKILLS, TABLE_SKILL_VERSIONS, SKILLS_SCHEMA, SKILL_VERSIONS_SCHEMA, WorkflowsStorage, WorkspacesStorage, TABLE_WORKSPACES, TABLE_WORKSPACE_VERSIONS, WORKSPACES_SCHEMA, WORKSPACE_VERSIONS_SCHEMA, MastraCompositeStore, TABLE_FAVORITES, BackgroundTasksStorage, TABLE_BACKGROUND_TASKS, ChannelsStorage, TABLE_CHANNEL_INSTALLATIONS, TABLE_CHANNEL_CONFIG, FavoritesStorage, FAVORITES_SCHEMA, SchedulesStorage, TABLE_SCHEDULES, TABLE_SCHEDULE_TRIGGERS, ToolProviderConnectionsStorage, TABLE_TOOL_PROVIDER_CONNECTIONS, TOOL_PROVIDER_CONNECTIONS_SCHEMA, normalizeScheduleTarget } from '@mastra/core/storage';
3
3
  import { createPool } from 'mysql2/promise';
4
4
  import { parseSqlIdentifier } from '@mastra/core/utils';
5
5
  import { randomUUID } from 'crypto';
@@ -83,7 +83,7 @@ function transformToSqlValue(value) {
83
83
  }
84
84
  return value;
85
85
  }
86
- function prepareStatement({
86
+ function prepareInsertOnlyStatement({
87
87
  tableName,
88
88
  record,
89
89
  database
@@ -96,11 +96,22 @@ function prepareStatement({
96
96
  const columnIdentifiers = columns.map((column) => quoteIdentifier(column, "column name"));
97
97
  const values = columns.map((column) => transformToSqlValue(record[column]));
98
98
  const placeholders = columns.map(() => "?").join(", ");
99
- const updateAssignments = columnIdentifiers.map((column) => `${column} = ?`).join(", ");
100
- const sql = `INSERT INTO ${tableIdent} (${columnIdentifiers.join(", ")}) VALUES (${placeholders}) ON DUPLICATE KEY UPDATE ${updateAssignments}`;
101
99
  return {
102
- sql,
103
- args: [...values, ...values]
100
+ sql: `INSERT INTO ${tableIdent} (${columnIdentifiers.join(", ")}) VALUES (${placeholders})`,
101
+ args: values
102
+ };
103
+ }
104
+ function prepareStatement({
105
+ tableName,
106
+ record,
107
+ database
108
+ }) {
109
+ const statement = prepareInsertOnlyStatement({ tableName, record, database });
110
+ const columns = Object.keys(record).map((column) => quoteIdentifier(column, "column name"));
111
+ const updateAssignments = columns.map((column) => `${column} = ?`).join(", ");
112
+ return {
113
+ sql: `${statement.sql} ON DUPLICATE KEY UPDATE ${updateAssignments}`,
114
+ args: [...statement.args, ...statement.args]
104
115
  };
105
116
  }
106
117
  function prepareUpdateStatement({
@@ -468,6 +479,22 @@ var StoreOperationsMySQL = class extends StoreOperations {
468
479
  );
469
480
  }
470
481
  }
482
+ async insertOnly({ tableName, record }) {
483
+ try {
484
+ const statement = prepareInsertOnlyStatement({ tableName, record, database: this.database });
485
+ await this.pool.execute(statement.sql, statement.args);
486
+ } catch (error) {
487
+ throw new MastraError(
488
+ {
489
+ id: "MYSQL_STORE_INSERT_FAILED",
490
+ domain: ErrorDomain.STORAGE,
491
+ category: ErrorCategory.THIRD_PARTY,
492
+ details: { tableName }
493
+ },
494
+ error
495
+ );
496
+ }
497
+ }
471
498
  async batchInsert({ tableName, records }) {
472
499
  if (records.length === 0) return;
473
500
  try {
@@ -2085,8 +2112,14 @@ var DatasetsMySQL = class _DatasetsMySQL extends DatasetsStorage {
2085
2112
  * Returns default index definitions for the datasets domain tables.
2086
2113
  * Currently no default indexes are defined for datasets.
2087
2114
  */
2088
- static getDefaultIndexDefs(_prefix = "") {
2089
- return [];
2115
+ static getDefaultIndexDefs(prefix = "") {
2116
+ return [
2117
+ {
2118
+ name: `${prefix}idx_dataset_items_dataset_externalid_version`,
2119
+ table: TABLE_DATASET_ITEMS,
2120
+ columns: ["datasetId", "externalId", "datasetVersion"]
2121
+ }
2122
+ ];
2090
2123
  }
2091
2124
  /**
2092
2125
  * Exports DDL statements for all managed tables.
@@ -2126,6 +2159,9 @@ var DatasetsMySQL = class _DatasetsMySQL extends DatasetsStorage {
2126
2159
  */
2127
2160
  async createDefaultIndexes() {
2128
2161
  if (this.#skipDefaultIndexes) return;
2162
+ for (const indexDef of this.getDefaultIndexDefinitions()) {
2163
+ await this.operations.createIndex(indexDef);
2164
+ }
2129
2165
  }
2130
2166
  /**
2131
2167
  * Creates custom user-defined indexes for this domain's tables.
@@ -2158,7 +2194,15 @@ var DatasetsMySQL = class _DatasetsMySQL extends DatasetsStorage {
2158
2194
  await this.operations.alterTable({
2159
2195
  tableName: TABLE_DATASET_ITEMS,
2160
2196
  schema: DATASET_ITEMS_SCHEMA,
2161
- ifNotExists: ["organizationId", "projectId"]
2197
+ ifNotExists: [
2198
+ "organizationId",
2199
+ "projectId",
2200
+ "requestContext",
2201
+ "source",
2202
+ "expectedTrajectory",
2203
+ "toolMocks",
2204
+ "externalId"
2205
+ ]
2162
2206
  });
2163
2207
  await this.createDefaultIndexes();
2164
2208
  await this.createCustomIndexes();
@@ -2209,11 +2253,16 @@ var DatasetsMySQL = class _DatasetsMySQL extends DatasetsStorage {
2209
2253
  id: row.id,
2210
2254
  datasetId: row.datasetId,
2211
2255
  datasetVersion: row.datasetVersion,
2256
+ externalId: row.externalId ?? null,
2212
2257
  organizationId: row.organizationId ?? null,
2213
2258
  projectId: row.projectId ?? null,
2214
2259
  input: parseJSON(row.input),
2215
2260
  groundTruth: row.groundTruth ? parseJSON(row.groundTruth) : void 0,
2261
+ expectedTrajectory: row.expectedTrajectory ? parseJSON(row.expectedTrajectory) : void 0,
2262
+ toolMocks: row.toolMocks ? parseJSON(row.toolMocks) : void 0,
2263
+ requestContext: row.requestContext ? parseJSON(row.requestContext) : void 0,
2216
2264
  metadata: row.metadata ? parseJSON(row.metadata) : void 0,
2265
+ source: row.source ? parseJSON(row.source) : void 0,
2217
2266
  createdAt: parseDateTime(row.createdAt) ?? /* @__PURE__ */ new Date(),
2218
2267
  updatedAt: parseDateTime(row.updatedAt) ?? /* @__PURE__ */ new Date()
2219
2268
  };
@@ -2223,13 +2272,18 @@ var DatasetsMySQL = class _DatasetsMySQL extends DatasetsStorage {
2223
2272
  id: row.id,
2224
2273
  datasetId: row.datasetId,
2225
2274
  datasetVersion: row.datasetVersion,
2275
+ externalId: row.externalId ?? null,
2226
2276
  organizationId: row.organizationId ?? null,
2227
2277
  projectId: row.projectId ?? null,
2228
2278
  validTo: row.validTo,
2229
2279
  isDeleted: Boolean(row.isDeleted),
2230
2280
  input: parseJSON(row.input),
2231
2281
  groundTruth: row.groundTruth ? parseJSON(row.groundTruth) : void 0,
2282
+ expectedTrajectory: row.expectedTrajectory ? parseJSON(row.expectedTrajectory) : void 0,
2283
+ toolMocks: row.toolMocks ? parseJSON(row.toolMocks) : void 0,
2284
+ requestContext: row.requestContext ? parseJSON(row.requestContext) : void 0,
2232
2285
  metadata: row.metadata ? parseJSON(row.metadata) : void 0,
2286
+ source: row.source ? parseJSON(row.source) : void 0,
2233
2287
  createdAt: parseDateTime(row.createdAt) ?? /* @__PURE__ */ new Date(),
2234
2288
  updatedAt: parseDateTime(row.updatedAt) ?? /* @__PURE__ */ new Date()
2235
2289
  };
@@ -2245,9 +2299,11 @@ var DatasetsMySQL = class _DatasetsMySQL extends DatasetsStorage {
2245
2299
  // --- Dataset CRUD ---
2246
2300
  async createDataset(input) {
2247
2301
  try {
2248
- const id = randomUUID();
2302
+ const id = input.id ?? randomUUID();
2303
+ if (input.id !== void 0) this.validateCallerDefinedDatasetId(input.id);
2249
2304
  const now = /* @__PURE__ */ new Date();
2250
- await this.operations.insert({
2305
+ const insert = input.id === void 0 ? this.operations.insert.bind(this.operations) : this.operations.insertOnly.bind(this.operations);
2306
+ await insert({
2251
2307
  tableName: TABLE_DATASETS,
2252
2308
  record: {
2253
2309
  id,
@@ -2289,6 +2345,11 @@ var DatasetsMySQL = class _DatasetsMySQL extends DatasetsStorage {
2289
2345
  updatedAt: now
2290
2346
  };
2291
2347
  } catch (error) {
2348
+ if (input.id !== void 0 && hasErrorCode(error, /* @__PURE__ */ new Set([1062, "ER_DUP_ENTRY"]))) {
2349
+ const existing = await this.getDatasetById({ id: input.id });
2350
+ if (existing) return this.resolveExistingDataset(existing, { ...input, id: input.id });
2351
+ }
2352
+ if (error instanceof MastraError) throw error;
2292
2353
  throw new MastraError(
2293
2354
  {
2294
2355
  id: "MYSQL_CREATE_DATASET_FAILED",
@@ -2617,7 +2678,11 @@ var DatasetsMySQL = class _DatasetsMySQL extends DatasetsStorage {
2617
2678
  const tableVersionsName = formatTableName(TABLE_DATASET_VERSIONS);
2618
2679
  const mergedInput = args.input ?? existing.input;
2619
2680
  const mergedGroundTruth = args.groundTruth ?? existing.groundTruth;
2681
+ const mergedExpectedTrajectory = args.expectedTrajectory ?? existing.expectedTrajectory;
2682
+ const mergedToolMocks = args.toolMocks ?? existing.toolMocks;
2683
+ const mergedRequestContext = args.requestContext ?? existing.requestContext;
2620
2684
  const mergedMetadata = args.metadata ?? existing.metadata;
2685
+ const mergedSource = args.source ?? existing.source;
2621
2686
  await connection.execute(`UPDATE ${tableDatasetsName} SET \`version\` = \`version\` + 1 WHERE id = ?`, [
2622
2687
  args.datasetId
2623
2688
  ]);
@@ -2634,16 +2699,21 @@ var DatasetsMySQL = class _DatasetsMySQL extends DatasetsStorage {
2634
2699
  [newVersion, args.id]
2635
2700
  );
2636
2701
  await connection.execute(
2637
- `INSERT INTO ${tableItemsName} (\`id\`, \`datasetId\`, \`datasetVersion\`, \`organizationId\`, \`projectId\`, \`validTo\`, \`isDeleted\`, \`input\`, \`groundTruth\`, \`metadata\`, \`createdAt\`, \`updatedAt\`) VALUES (?, ?, ?, ?, ?, NULL, 0, ?, ?, ?, ?, ?)`,
2702
+ `INSERT INTO ${tableItemsName} (\`id\`, \`datasetId\`, \`datasetVersion\`, \`externalId\`, \`organizationId\`, \`projectId\`, \`validTo\`, \`isDeleted\`, \`input\`, \`groundTruth\`, \`expectedTrajectory\`, \`toolMocks\`, \`requestContext\`, \`metadata\`, \`source\`, \`createdAt\`, \`updatedAt\`) VALUES (?, ?, ?, ?, ?, ?, NULL, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2638
2703
  [
2639
2704
  args.id,
2640
2705
  args.datasetId,
2641
2706
  newVersion,
2707
+ existing.externalId ?? null,
2642
2708
  parentOrganizationId,
2643
2709
  parentProjectId,
2644
2710
  jsonArg(mergedInput),
2645
2711
  jsonArg(mergedGroundTruth),
2712
+ jsonArg(mergedExpectedTrajectory),
2713
+ jsonArg(mergedToolMocks),
2714
+ jsonArg(mergedRequestContext),
2646
2715
  jsonArg(mergedMetadata),
2716
+ jsonArg(mergedSource),
2647
2717
  transformToSqlValue(existing.createdAt),
2648
2718
  transformToSqlValue(now)
2649
2719
  ]
@@ -2660,7 +2730,11 @@ var DatasetsMySQL = class _DatasetsMySQL extends DatasetsStorage {
2660
2730
  projectId: parentProjectId,
2661
2731
  input: mergedInput,
2662
2732
  groundTruth: mergedGroundTruth,
2733
+ expectedTrajectory: mergedExpectedTrajectory,
2734
+ toolMocks: mergedToolMocks,
2735
+ requestContext: mergedRequestContext,
2663
2736
  metadata: mergedMetadata,
2737
+ source: mergedSource,
2664
2738
  updatedAt: now
2665
2739
  };
2666
2740
  } catch (error) {
@@ -2713,16 +2787,21 @@ var DatasetsMySQL = class _DatasetsMySQL extends DatasetsStorage {
2713
2787
  [newVersion, id]
2714
2788
  );
2715
2789
  await connection.execute(
2716
- `INSERT INTO ${tableItemsName} (\`id\`, \`datasetId\`, \`datasetVersion\`, \`organizationId\`, \`projectId\`, \`validTo\`, \`isDeleted\`, \`input\`, \`groundTruth\`, \`metadata\`, \`createdAt\`, \`updatedAt\`) VALUES (?, ?, ?, ?, ?, NULL, 1, ?, ?, ?, ?, ?)`,
2790
+ `INSERT INTO ${tableItemsName} (\`id\`, \`datasetId\`, \`datasetVersion\`, \`externalId\`, \`organizationId\`, \`projectId\`, \`validTo\`, \`isDeleted\`, \`input\`, \`groundTruth\`, \`expectedTrajectory\`, \`toolMocks\`, \`requestContext\`, \`metadata\`, \`source\`, \`createdAt\`, \`updatedAt\`) VALUES (?, ?, ?, ?, ?, ?, NULL, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2717
2791
  [
2718
2792
  id,
2719
2793
  datasetId,
2720
2794
  newVersion,
2795
+ existing.externalId ?? null,
2721
2796
  parentOrganizationId,
2722
2797
  parentProjectId,
2723
2798
  jsonArg(existing.input),
2724
2799
  jsonArg(existing.groundTruth),
2800
+ jsonArg(existing.expectedTrajectory),
2801
+ jsonArg(existing.toolMocks),
2802
+ jsonArg(existing.requestContext),
2725
2803
  jsonArg(existing.metadata),
2804
+ jsonArg(existing.source),
2726
2805
  transformToSqlValue(existing.createdAt),
2727
2806
  transformToSqlValue(now)
2728
2807
  ]
@@ -2955,70 +3034,89 @@ var DatasetsMySQL = class _DatasetsMySQL extends DatasetsStorage {
2955
3034
  for (const item of input.items) {
2956
3035
  this.#rejectToolMocks(item.toolMocks);
2957
3036
  }
2958
- const dataset = await this.getDatasetById({ id: input.datasetId });
2959
- if (!dataset) {
2960
- throw new MastraError({
2961
- id: "MYSQL_BULK_ADD_ITEMS_DATASET_NOT_FOUND",
2962
- domain: ErrorDomain.STORAGE,
2963
- category: ErrorCategory.USER,
2964
- details: { datasetId: input.datasetId }
2965
- });
2966
- }
2967
3037
  const connection = await this.pool.getConnection();
2968
3038
  try {
2969
3039
  await connection.beginTransaction();
2970
- const now = /* @__PURE__ */ new Date();
2971
- const versionId = randomUUID();
2972
3040
  const tableDatasetsName = formatTableName(TABLE_DATASETS);
2973
3041
  const tableItemsName = formatTableName(TABLE_DATASET_ITEMS);
2974
3042
  const tableVersionsName = formatTableName(TABLE_DATASET_VERSIONS);
2975
- await connection.execute(`UPDATE ${tableDatasetsName} SET \`version\` = \`version\` + 1 WHERE id = ?`, [
2976
- input.datasetId
2977
- ]);
2978
- const [versionRows] = await connection.execute(
2979
- `SELECT \`version\` FROM ${tableDatasetsName} WHERE id = ?`,
3043
+ const [datasetRows] = await connection.execute(
3044
+ `SELECT \`version\`, \`organizationId\`, \`projectId\` FROM ${tableDatasetsName} WHERE id = ? FOR UPDATE`,
2980
3045
  [input.datasetId]
2981
3046
  );
2982
- const newVersion = versionRows[0]?.version;
2983
- const parentOrganizationId = dataset.organizationId ?? null;
2984
- const parentProjectId = dataset.projectId ?? null;
2985
- const items = [];
2986
- for (const itemInput of input.items) {
2987
- const id = randomUUID();
2988
- items.push({ id, itemInput });
3047
+ const dataset = datasetRows[0];
3048
+ if (!dataset) {
3049
+ throw new MastraError({
3050
+ id: "MYSQL_BULK_ADD_ITEMS_DATASET_NOT_FOUND",
3051
+ domain: ErrorDomain.STORAGE,
3052
+ category: ErrorCategory.USER,
3053
+ details: { datasetId: input.datasetId }
3054
+ });
3055
+ }
3056
+ const externalIds = [...new Set(input.items.flatMap((item) => item.externalId ? [item.externalId] : []))];
3057
+ let historyRows = [];
3058
+ if (externalIds.length > 0) {
3059
+ const placeholders = externalIds.map(() => "?").join(", ");
3060
+ const [rows] = await connection.execute(
3061
+ `SELECT * FROM ${tableItemsName} WHERE \`datasetId\` = ? AND \`externalId\` IN (${placeholders}) ORDER BY \`datasetVersion\` ASC`,
3062
+ [input.datasetId, ...externalIds]
3063
+ );
3064
+ historyRows = rows.map((row) => this.mapItemFull(row));
3065
+ }
3066
+ const plan = this.planDatasetItemBatch(input.items, historyRows, randomUUID);
3067
+ const existingItems = new Map(
3068
+ [...plan.existingCurrentItems].map(([id, row]) => [id, this.datasetItemFromRow(row)])
3069
+ );
3070
+ if (plan.inserts.length === 0) {
3071
+ await connection.commit();
3072
+ return plan.resolvedIds.map((id) => existingItems.get(id));
3073
+ }
3074
+ const now = /* @__PURE__ */ new Date();
3075
+ const newVersion = Number(dataset.version) + 1;
3076
+ await connection.execute(`UPDATE ${tableDatasetsName} SET \`version\` = ? WHERE id = ?`, [
3077
+ newVersion,
3078
+ input.datasetId
3079
+ ]);
3080
+ const inserted = /* @__PURE__ */ new Map();
3081
+ for (const { id, item } of plan.inserts) {
2989
3082
  await connection.execute(
2990
- `INSERT INTO ${tableItemsName} (\`id\`, \`datasetId\`, \`datasetVersion\`, \`organizationId\`, \`projectId\`, \`validTo\`, \`isDeleted\`, \`input\`, \`groundTruth\`, \`metadata\`, \`createdAt\`, \`updatedAt\`) VALUES (?, ?, ?, ?, ?, NULL, 0, ?, ?, ?, ?, ?)`,
3083
+ `INSERT INTO ${tableItemsName} (\`id\`, \`datasetId\`, \`datasetVersion\`, \`externalId\`, \`organizationId\`, \`projectId\`, \`validTo\`, \`isDeleted\`, \`input\`, \`groundTruth\`, \`expectedTrajectory\`, \`toolMocks\`, \`requestContext\`, \`metadata\`, \`source\`, \`createdAt\`, \`updatedAt\`) VALUES (?, ?, ?, ?, ?, ?, NULL, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2991
3084
  [
2992
3085
  id,
2993
3086
  input.datasetId,
2994
3087
  newVersion,
2995
- parentOrganizationId,
2996
- parentProjectId,
2997
- jsonArg(itemInput.input),
2998
- jsonArg(itemInput.groundTruth),
2999
- jsonArg(itemInput.metadata),
3088
+ item.externalId ?? null,
3089
+ dataset.organizationId ?? null,
3090
+ dataset.projectId ?? null,
3091
+ jsonArg(item.input),
3092
+ jsonArg(item.groundTruth),
3093
+ jsonArg(item.expectedTrajectory),
3094
+ jsonArg(item.toolMocks),
3095
+ jsonArg(item.requestContext),
3096
+ jsonArg(item.metadata),
3097
+ jsonArg(item.source),
3000
3098
  transformToSqlValue(now),
3001
3099
  transformToSqlValue(now)
3002
3100
  ]
3003
3101
  );
3102
+ inserted.set(id, {
3103
+ id,
3104
+ datasetId: input.datasetId,
3105
+ datasetVersion: newVersion,
3106
+ externalId: item.externalId ?? null,
3107
+ organizationId: dataset.organizationId ?? null,
3108
+ projectId: dataset.projectId ?? null,
3109
+ ...item,
3110
+ createdAt: now,
3111
+ updatedAt: now
3112
+ });
3004
3113
  }
3005
3114
  await connection.execute(
3006
3115
  `INSERT INTO ${tableVersionsName} (\`id\`, \`datasetId\`, \`version\`, \`createdAt\`) VALUES (?, ?, ?, ?)`,
3007
- [versionId, input.datasetId, newVersion, transformToSqlValue(now)]
3116
+ [randomUUID(), input.datasetId, newVersion, transformToSqlValue(now)]
3008
3117
  );
3009
3118
  await connection.commit();
3010
- return items.map(({ id, itemInput }) => ({
3011
- id,
3012
- datasetId: input.datasetId,
3013
- datasetVersion: newVersion,
3014
- organizationId: parentOrganizationId,
3015
- projectId: parentProjectId,
3016
- input: itemInput.input,
3017
- groundTruth: itemInput.groundTruth,
3018
- metadata: itemInput.metadata,
3019
- createdAt: now,
3020
- updatedAt: now
3021
- }));
3119
+ return plan.resolvedIds.map((id) => inserted.get(id) ?? existingItems.get(id));
3022
3120
  } catch (error) {
3023
3121
  await connection.rollback();
3024
3122
  if (error instanceof MastraError) throw error;
@@ -3076,16 +3174,21 @@ var DatasetsMySQL = class _DatasetsMySQL extends DatasetsStorage {
3076
3174
  [newVersion, item.id]
3077
3175
  );
3078
3176
  await connection.execute(
3079
- `INSERT INTO ${tableItemsName} (\`id\`, \`datasetId\`, \`datasetVersion\`, \`organizationId\`, \`projectId\`, \`validTo\`, \`isDeleted\`, \`input\`, \`groundTruth\`, \`metadata\`, \`createdAt\`, \`updatedAt\`) VALUES (?, ?, ?, ?, ?, NULL, 1, ?, ?, ?, ?, ?)`,
3177
+ `INSERT INTO ${tableItemsName} (\`id\`, \`datasetId\`, \`datasetVersion\`, \`externalId\`, \`organizationId\`, \`projectId\`, \`validTo\`, \`isDeleted\`, \`input\`, \`groundTruth\`, \`expectedTrajectory\`, \`toolMocks\`, \`requestContext\`, \`metadata\`, \`source\`, \`createdAt\`, \`updatedAt\`) VALUES (?, ?, ?, ?, ?, ?, NULL, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3080
3178
  [
3081
3179
  item.id,
3082
3180
  input.datasetId,
3083
3181
  newVersion,
3182
+ item.externalId ?? null,
3084
3183
  parentOrganizationId,
3085
3184
  parentProjectId,
3086
3185
  jsonArg(item.input),
3087
3186
  jsonArg(item.groundTruth),
3187
+ jsonArg(item.expectedTrajectory),
3188
+ jsonArg(item.toolMocks),
3189
+ jsonArg(item.requestContext),
3088
3190
  jsonArg(item.metadata),
3191
+ jsonArg(item.source),
3089
3192
  transformToSqlValue(item.createdAt),
3090
3193
  transformToSqlValue(now)
3091
3194
  ]