@mastra/mssql 0.3.5 → 0.3.6-alpha.1

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.
@@ -1,296 +0,0 @@
1
- import type { StepResult, WorkflowRun, WorkflowRuns, WorkflowRunState } from '@mastra/core';
2
- import { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';
3
- import { WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT } from '@mastra/core/storage';
4
- import sql from 'mssql';
5
- import type { StoreOperationsMSSQL } from '../operations';
6
- import { getSchemaName, getTableName } from '../utils';
7
-
8
- function parseWorkflowRun(row: any): WorkflowRun {
9
- let parsedSnapshot: WorkflowRunState | string = row.snapshot as string;
10
- if (typeof parsedSnapshot === 'string') {
11
- try {
12
- parsedSnapshot = JSON.parse(row.snapshot as string) as WorkflowRunState;
13
- } catch (e) {
14
- console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
15
- }
16
- }
17
- return {
18
- workflowName: row.workflow_name,
19
- runId: row.run_id,
20
- snapshot: parsedSnapshot,
21
- createdAt: row.createdAt,
22
- updatedAt: row.updatedAt,
23
- resourceId: row.resourceId,
24
- };
25
- }
26
-
27
- export class WorkflowsMSSQL extends WorkflowsStorage {
28
- public pool: sql.ConnectionPool;
29
- private operations: StoreOperationsMSSQL;
30
- private schema: string;
31
-
32
- constructor({
33
- pool,
34
- operations,
35
- schema,
36
- }: {
37
- pool: sql.ConnectionPool;
38
- operations: StoreOperationsMSSQL;
39
- schema: string;
40
- }) {
41
- super();
42
- this.pool = pool;
43
- this.operations = operations;
44
- this.schema = schema;
45
- }
46
-
47
- updateWorkflowResults(
48
- {
49
- // workflowName,
50
- // runId,
51
- // stepId,
52
- // result,
53
- // runtimeContext,
54
- }: {
55
- workflowName: string;
56
- runId: string;
57
- stepId: string;
58
- result: StepResult<any, any, any, any>;
59
- runtimeContext: Record<string, any>;
60
- },
61
- ): Promise<Record<string, StepResult<any, any, any, any>>> {
62
- throw new Error('Method not implemented.');
63
- }
64
- updateWorkflowState(
65
- {
66
- // workflowName,
67
- // runId,
68
- // opts,
69
- }: {
70
- workflowName: string;
71
- runId: string;
72
- opts: {
73
- status: string;
74
- result?: StepResult<any, any, any, any>;
75
- error?: string;
76
- suspendedPaths?: Record<string, number[]>;
77
- waitingPaths?: Record<string, number[]>;
78
- };
79
- },
80
- ): Promise<WorkflowRunState | undefined> {
81
- throw new Error('Method not implemented.');
82
- }
83
-
84
- async persistWorkflowSnapshot({
85
- workflowName,
86
- runId,
87
- snapshot,
88
- }: {
89
- workflowName: string;
90
- runId: string;
91
- snapshot: WorkflowRunState;
92
- }): Promise<void> {
93
- const table = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
94
- const now = new Date().toISOString();
95
- try {
96
- const request = this.pool.request();
97
- request.input('workflow_name', workflowName);
98
- request.input('run_id', runId);
99
- request.input('snapshot', JSON.stringify(snapshot));
100
- request.input('createdAt', sql.DateTime2, new Date(now));
101
- request.input('updatedAt', sql.DateTime2, new Date(now));
102
- const mergeSql = `MERGE INTO ${table} AS target
103
- USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
104
- ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
105
- WHEN MATCHED THEN UPDATE SET
106
- snapshot = @snapshot,
107
- [updatedAt] = @updatedAt
108
- WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, snapshot, [createdAt], [updatedAt])
109
- VALUES (@workflow_name, @run_id, @snapshot, @createdAt, @updatedAt);`;
110
- await request.query(mergeSql);
111
- } catch (error) {
112
- throw new MastraError(
113
- {
114
- id: 'MASTRA_STORAGE_MSSQL_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED',
115
- domain: ErrorDomain.STORAGE,
116
- category: ErrorCategory.THIRD_PARTY,
117
- details: {
118
- workflowName,
119
- runId,
120
- },
121
- },
122
- error,
123
- );
124
- }
125
- }
126
-
127
- async loadWorkflowSnapshot({
128
- workflowName,
129
- runId,
130
- }: {
131
- workflowName: string;
132
- runId: string;
133
- }): Promise<WorkflowRunState | null> {
134
- try {
135
- const result = await this.operations.load({
136
- tableName: TABLE_WORKFLOW_SNAPSHOT,
137
- keys: {
138
- workflow_name: workflowName,
139
- run_id: runId,
140
- },
141
- });
142
- if (!result) {
143
- return null;
144
- }
145
- return (result as any).snapshot;
146
- } catch (error) {
147
- throw new MastraError(
148
- {
149
- id: 'MASTRA_STORAGE_MSSQL_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED',
150
- domain: ErrorDomain.STORAGE,
151
- category: ErrorCategory.THIRD_PARTY,
152
- details: {
153
- workflowName,
154
- runId,
155
- },
156
- },
157
- error,
158
- );
159
- }
160
- }
161
-
162
- async getWorkflowRunById({
163
- runId,
164
- workflowName,
165
- }: {
166
- runId: string;
167
- workflowName?: string;
168
- }): Promise<WorkflowRun | null> {
169
- try {
170
- const conditions: string[] = [];
171
- const paramMap: Record<string, any> = {};
172
-
173
- if (runId) {
174
- conditions.push(`[run_id] = @runId`);
175
- paramMap['runId'] = runId;
176
- }
177
-
178
- if (workflowName) {
179
- conditions.push(`[workflow_name] = @workflowName`);
180
- paramMap['workflowName'] = workflowName;
181
- }
182
-
183
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
184
- const tableName = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
185
- const query = `SELECT * FROM ${tableName} ${whereClause}`;
186
- const request = this.pool.request();
187
- Object.entries(paramMap).forEach(([key, value]) => request.input(key, value));
188
- const result = await request.query(query);
189
-
190
- if (!result.recordset || result.recordset.length === 0) {
191
- return null;
192
- }
193
-
194
- return parseWorkflowRun(result.recordset[0]);
195
- } catch (error) {
196
- throw new MastraError(
197
- {
198
- id: 'MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED',
199
- domain: ErrorDomain.STORAGE,
200
- category: ErrorCategory.THIRD_PARTY,
201
- details: {
202
- runId,
203
- workflowName: workflowName || '',
204
- },
205
- },
206
- error,
207
- );
208
- }
209
- }
210
-
211
- async getWorkflowRuns({
212
- workflowName,
213
- fromDate,
214
- toDate,
215
- limit,
216
- offset,
217
- resourceId,
218
- }: {
219
- workflowName?: string;
220
- fromDate?: Date;
221
- toDate?: Date;
222
- limit?: number;
223
- offset?: number;
224
- resourceId?: string;
225
- } = {}): Promise<WorkflowRuns> {
226
- try {
227
- const conditions: string[] = [];
228
- const paramMap: Record<string, any> = {};
229
-
230
- if (workflowName) {
231
- conditions.push(`[workflow_name] = @workflowName`);
232
- paramMap['workflowName'] = workflowName;
233
- }
234
-
235
- if (resourceId) {
236
- const hasResourceId = await this.operations.hasColumn(TABLE_WORKFLOW_SNAPSHOT, 'resourceId');
237
- if (hasResourceId) {
238
- conditions.push(`[resourceId] = @resourceId`);
239
- paramMap['resourceId'] = resourceId;
240
- } else {
241
- console.warn(`[${TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
242
- }
243
- }
244
-
245
- if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
246
- conditions.push(`[createdAt] >= @fromDate`);
247
- paramMap[`fromDate`] = fromDate.toISOString();
248
- }
249
-
250
- if (toDate instanceof Date && !isNaN(toDate.getTime())) {
251
- conditions.push(`[createdAt] <= @toDate`);
252
- paramMap[`toDate`] = toDate.toISOString();
253
- }
254
-
255
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
256
- let total = 0;
257
- const tableName = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
258
- const request = this.pool.request();
259
- Object.entries(paramMap).forEach(([key, value]) => {
260
- if (value instanceof Date) {
261
- request.input(key, sql.DateTime, value);
262
- } else {
263
- request.input(key, value);
264
- }
265
- });
266
-
267
- if (limit !== undefined && offset !== undefined) {
268
- const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
269
- const countResult = await request.query(countQuery);
270
- total = Number(countResult.recordset[0]?.count || 0);
271
- }
272
-
273
- let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
274
- if (limit !== undefined && offset !== undefined) {
275
- query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
276
- request.input('limit', limit);
277
- request.input('offset', offset);
278
- }
279
- const result = await request.query(query);
280
- const runs = (result.recordset || []).map(row => parseWorkflowRun(row));
281
- return { runs, total: total || runs.length };
282
- } catch (error) {
283
- throw new MastraError(
284
- {
285
- id: 'MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED',
286
- domain: ErrorDomain.STORAGE,
287
- category: ErrorCategory.THIRD_PARTY,
288
- details: {
289
- workflowName: workflowName || 'all',
290
- },
291
- },
292
- error,
293
- );
294
- }
295
- }
296
- }