@mastra/mssql 0.4.7 → 0.5.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/CHANGELOG.md CHANGED
@@ -1,5 +1,65 @@
1
1
  # @mastra/mssql
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Implemented AI tracing and observability features ([#9368](https://github.com/mastra-ai/mastra/pull/9368))
8
+ - Added createAISpan, updateAISpan, getAITrace, getAITracesPaginated
9
+ - Added batchCreateAISpans, batchUpdateAISpans, batchDeleteAITraces
10
+ - Automatic performance indexes for AI spans
11
+
12
+ Implemented workflow update methods
13
+ - Added updateWorkflowResults with row-level locking (UPDLOCK, HOLDLOCK)
14
+ - Added updateWorkflowState with row-level locking
15
+ - Concurrent update protection for parallel workflow execution
16
+
17
+ Added index management API
18
+ - Added createIndex, listIndexes, describeIndex, dropIndex methods
19
+ - Exposed index management methods directly on store instance
20
+ - Support for composite indexes, unique constraints, and filtered indexes
21
+
22
+ Documentation improvements
23
+ - Comprehensive README with complete API reference (58 methods)
24
+ - Detailed feature descriptions for all storage capabilities
25
+ - Index management examples and best practices
26
+ - Updated to reflect all atomic transaction usage
27
+
28
+ ### Patch Changes
29
+
30
+ - Updated dependencies [[`f57a81e`](https://github.com/mastra-ai/mastra/commit/f57a81e6ce644e45bf1c9618778cc54c50a84ad4), [`2afd345`](https://github.com/mastra-ai/mastra/commit/2afd3450825b76e41f7973baddf13867ea042e40), [`fc79af3`](https://github.com/mastra-ai/mastra/commit/fc79af3915d1c456729cbd753673b0c0564340d8), [`eefc89e`](https://github.com/mastra-ai/mastra/commit/eefc89ee69f05bb71661473a807fc7dc03d56f17), [`60bd45d`](https://github.com/mastra-ai/mastra/commit/60bd45de021f0dfbe6583928f6da5169cb5585ba), [`a30093d`](https://github.com/mastra-ai/mastra/commit/a30093de98c1836dcd5dfddf09649010712b8c95), [`0fe7adb`](https://github.com/mastra-ai/mastra/commit/0fe7adb0f20f59a6bb41f235d01f8b7a880ea6e7), [`a42e496`](https://github.com/mastra-ai/mastra/commit/a42e49686a7486e2e9e9397fa98e5ff7a71dc1b0), [`3670db7`](https://github.com/mastra-ai/mastra/commit/3670db7e8e798f9d65fac5bfb732134a1f26ba7b), [`e40d4d0`](https://github.com/mastra-ai/mastra/commit/e40d4d0a0971b4505e7c9de73c656066c7565653), [`fc843ff`](https://github.com/mastra-ai/mastra/commit/fc843ff4d1d149317b6324553ce5ad7972062a78), [`ff16f9b`](https://github.com/mastra-ai/mastra/commit/ff16f9b9dbc701b26b6c4e9872f759f3880f9327), [`35e6cf7`](https://github.com/mastra-ai/mastra/commit/35e6cf722fef16ea0301eb9cf5a32fe9ccb12d22), [`30a2e36`](https://github.com/mastra-ai/mastra/commit/30a2e369485e0e59c4faa1d83c5635c2260b304c)]:
31
+ - @mastra/core@0.23.2
32
+
33
+ ## 0.5.0-alpha.0
34
+
35
+ ### Minor Changes
36
+
37
+ - Implemented AI tracing and observability features ([#9368](https://github.com/mastra-ai/mastra/pull/9368))
38
+ - Added createAISpan, updateAISpan, getAITrace, getAITracesPaginated
39
+ - Added batchCreateAISpans, batchUpdateAISpans, batchDeleteAITraces
40
+ - Automatic performance indexes for AI spans
41
+
42
+ Implemented workflow update methods
43
+ - Added updateWorkflowResults with row-level locking (UPDLOCK, HOLDLOCK)
44
+ - Added updateWorkflowState with row-level locking
45
+ - Concurrent update protection for parallel workflow execution
46
+
47
+ Added index management API
48
+ - Added createIndex, listIndexes, describeIndex, dropIndex methods
49
+ - Exposed index management methods directly on store instance
50
+ - Support for composite indexes, unique constraints, and filtered indexes
51
+
52
+ Documentation improvements
53
+ - Comprehensive README with complete API reference (58 methods)
54
+ - Detailed feature descriptions for all storage capabilities
55
+ - Index management examples and best practices
56
+ - Updated to reflect all atomic transaction usage
57
+
58
+ ### Patch Changes
59
+
60
+ - Updated dependencies [[`2afd345`](https://github.com/mastra-ai/mastra/commit/2afd3450825b76e41f7973baddf13867ea042e40), [`eefc89e`](https://github.com/mastra-ai/mastra/commit/eefc89ee69f05bb71661473a807fc7dc03d56f17), [`0fe7adb`](https://github.com/mastra-ai/mastra/commit/0fe7adb0f20f59a6bb41f235d01f8b7a880ea6e7), [`a42e496`](https://github.com/mastra-ai/mastra/commit/a42e49686a7486e2e9e9397fa98e5ff7a71dc1b0), [`3670db7`](https://github.com/mastra-ai/mastra/commit/3670db7e8e798f9d65fac5bfb732134a1f26ba7b), [`fc843ff`](https://github.com/mastra-ai/mastra/commit/fc843ff4d1d149317b6324553ce5ad7972062a78)]:
61
+ - @mastra/core@0.23.2-alpha.0
62
+
3
63
  ## 0.4.7
4
64
 
5
65
  ### Patch Changes
package/README.md CHANGED
@@ -17,38 +17,84 @@ npm install @mastra/mssql
17
17
 
18
18
  ### Storage
19
19
 
20
+ #### Basic Configuration
21
+
22
+ MSSQLStore supports multiple connection methods:
23
+
24
+ **1. Connection String (Recommended)**
25
+
20
26
  ```typescript
21
27
  import { MSSQLStore } from '@mastra/mssql';
22
28
 
29
+ const store = new MSSQLStore({
30
+ connectionString:
31
+ 'Server=localhost,1433;Database=mastra;User Id=sa;Password=yourPassword;Encrypt=true;TrustServerCertificate=true',
32
+ });
33
+ ```
34
+
35
+ **2. Server/Port/Database Configuration**
36
+
37
+ ```typescript
23
38
  const store = new MSSQLStore({
24
39
  server: 'localhost',
25
40
  port: 1433,
26
41
  database: 'mastra',
27
42
  user: 'sa',
28
43
  password: 'yourStrong(!)Password',
29
- // options: { encrypt: true, trustServerCertificate: true }, // Optional
44
+ options: { encrypt: true, trustServerCertificate: true }, // Optional
30
45
  });
46
+ ```
31
47
 
32
- // Create a thread
33
- await store.saveThread({
34
- id: 'thread-123',
35
- resourceId: 'resource-456',
36
- title: 'My Thread',
37
- metadata: { key: 'value' },
48
+ #### Advanced Options
49
+
50
+ ```typescript
51
+ const store = new MSSQLStore({
52
+ connectionString:
53
+ 'Server=localhost,1433;Database=mastra;User Id=sa;Password=yourPassword;Encrypt=true;TrustServerCertificate=true',
54
+ schemaName: 'custom_schema', // Use custom schema (default: dbo)
55
+ options: {
56
+ encrypt: true,
57
+ trustServerCertificate: true,
58
+ connectTimeout: 30000,
59
+ requestTimeout: 30000,
60
+ pool: {
61
+ max: 20,
62
+ min: 0,
63
+ idleTimeoutMillis: 30000,
64
+ },
65
+ },
38
66
  });
67
+ ```
39
68
 
40
- // Add messages to thread
41
- await store.saveMessages([
42
- {
43
- id: 'msg-789',
44
- threadId: 'thread-123',
45
- role: 'user',
46
- type: 'text',
47
- content: [{ type: 'text', text: 'Hello' }],
69
+ #### Usage Example
70
+
71
+ ```typescript
72
+ // Create a thread
73
+ await store.saveThread({
74
+ thread: {
75
+ id: 'thread-123',
48
76
  resourceId: 'resource-456',
77
+ title: 'My Thread',
78
+ metadata: { key: 'value' },
49
79
  createdAt: new Date(),
80
+ updatedAt: new Date(),
50
81
  },
51
- ]);
82
+ });
83
+
84
+ // Add messages to thread
85
+ await store.saveMessages({
86
+ messages: [
87
+ {
88
+ id: 'msg-789',
89
+ threadId: 'thread-123',
90
+ role: 'user',
91
+ type: 'text',
92
+ content: [{ type: 'text', text: 'Hello' }],
93
+ resourceId: 'resource-456',
94
+ createdAt: new Date(),
95
+ },
96
+ ],
97
+ });
52
98
 
53
99
  // Query threads and messages
54
100
  const savedThread = await store.getThreadById({ threadId: 'thread-123' });
@@ -57,38 +103,271 @@ const messages = await store.getMessages({ threadId: 'thread-123' });
57
103
 
58
104
  ## Configuration
59
105
 
60
- The MSSQL store can be initialized with either:
106
+ ### Connection Methods
107
+
108
+ MSSQLStore supports multiple connection methods:
109
+
110
+ 1. **Connection String**
61
111
 
62
- - `connectionString`: Microsoft SQL Server connection string
63
- - Configuration object with server, port, database, user, and password
112
+ ```typescript
113
+ {
114
+ connectionString: 'Server=localhost,1433;Database=mastra;User Id=sa;Password=yourPassword;Encrypt=true;TrustServerCertificate=true';
115
+ }
116
+ ```
64
117
 
65
- Connection pool settings are managed by the [mssql](https://www.npmjs.com/package/mssql) package.
118
+ 2. **Server/Port/Database**
119
+ ```typescript
120
+ {
121
+ server: 'localhost',
122
+ port: 1433,
123
+ database: 'mastra',
124
+ user: 'sa',
125
+ password: 'password'
126
+ }
127
+ ```
128
+
129
+ ### Optional Configuration
130
+
131
+ - `schemaName`: Custom SQL Server schema (default: `dbo`)
132
+ - `options.encrypt`: Enable encryption (default: `true`)
133
+ - `options.trustServerCertificate`: Trust self-signed certificates (default: `true`)
134
+ - `options.connectTimeout`: Connection timeout in milliseconds (default: `15000`)
135
+ - `options.requestTimeout`: Request timeout in milliseconds (default: `15000`)
136
+ - `options.pool.max`: Maximum pool connections (default: `10`)
137
+ - `options.pool.min`: Minimum pool connections (default: `0`)
138
+ - `options.pool.idleTimeoutMillis`: Idle connection timeout (default: `30000`)
139
+
140
+ ### Default Connection Pool Settings
141
+
142
+ - Maximum connections: 10
143
+ - Minimum connections: 0
144
+ - Idle timeout: 30 seconds
145
+ - Connection timeout: 15 seconds
146
+ - Request timeout: 15 seconds
66
147
 
67
148
  ## Features
68
149
 
69
- - Thread and message storage with JSON support
70
- - Atomic transactions for data consistency
71
- - Efficient batch operations
72
- - Rich metadata support
73
- - Timestamp tracking
74
- - Cascading deletes (emulated)
150
+ ### Storage Features
151
+
152
+ - **Thread and Message Management**
153
+ - Thread and message storage with JSON support
154
+ - Message format versioning (v1 and v2)
155
+ - Pagination support for threads and messages
156
+ - Atomic transactions for batch operations (save, update, delete)
157
+ - Automatic thread timestamp updates
158
+ - Cascading deletes
159
+ - **Resources**
160
+ - Resource storage with working memory
161
+ - Rich metadata support
162
+ - Update working memory and metadata independently
163
+
164
+ - **AI Tracing & Observability**
165
+ - Trace AI agent execution with spans
166
+ - Query traces with pagination and filtering
167
+ - Batch operations for high-volume tracing
168
+ - Parent-child span relationships
169
+ - Span metadata and timing information
170
+
171
+ - **Workflow Management**
172
+ - Persist and restore workflow execution state
173
+ - Track workflow run history
174
+ - Step-by-step result tracking with row-level locking
175
+ - Workflow status management with row-level locking
176
+ - Query workflow runs by date range or resource
177
+ - Concurrent update protection for parallel workflow execution
178
+
179
+ - **Scoring & Evaluation**
180
+ - Store evaluation scores and metrics
181
+ - Query scores by scorer, run, entity, or span
182
+ - Support for multiple scoring sources
183
+ - Pagination support for large score datasets
184
+
185
+ - **Performance & Scalability**
186
+ - Connection pooling with configurable limits
187
+ - Atomic transactions for all batch operations
188
+ - Efficient batch insert/update/delete with transaction safety
189
+ - Row-level locking for concurrent updates
190
+ - Automatic performance indexes
191
+ - Index management (create, list, describe, drop)
192
+ - Timestamp tracking with high precision
193
+ - **Data Management**
194
+ - Custom schema support
195
+ - Table operations (create, alter, clear, drop)
196
+ - Low-level insert and load operations
197
+ - JSON data type support
75
198
 
76
199
  ## Storage Methods
77
200
 
201
+ ### Initialization & Connection
202
+
203
+ - `init()`: Initialize the store and create tables
204
+ - `close()`: Close database connection pool
205
+
206
+ ### Threads
207
+
78
208
  - `saveThread({ thread })`: Create or update a thread
79
209
  - `getThreadById({ threadId })`: Get a thread by ID
210
+ - `updateThread({ id, title, metadata })`: Update thread title and metadata
80
211
  - `deleteThread({ threadId })`: Delete a thread and its messages
81
- - `saveMessages({ messages })`: Save multiple messages in a transaction
82
- - `getMessages({ threadId })`: Get all messages for a thread
83
- - `updateMessages({ messages })`: Update messages by ID
84
- - `getThreadsByResourceIdPaginated({ resourceId, page, perPage })`: Paginated thread listing
85
- - `getMessagesPaginated({ threadId, selectBy })`: Paginated message listing
86
- - `clearTable({ tableName })`: Remove all rows from a table (with cascade)
87
- - `createTable({ tableName, schema })`: Create a table if it does not exist
88
- - `alterTable({ tableName, schema, ifNotExists })`: Add columns if they do not exist
89
- - `saveResource({ resource })`: Save a resource
212
+ - `getThreadsByResourceIdPaginated({ resourceId, page, perPage, orderBy?, sortDirection? })`: Get paginated threads for a resource
213
+
214
+ ### Messages
215
+
216
+ - `saveMessages({ messages, format? })`: Save multiple messages with atomic transaction (supports v1 and v2 formats)
217
+ - `getMessages({ threadId, format? })`: Get all messages for a thread
218
+ - `getMessagesById({ messageIds, format? })`: Get messages by their IDs
219
+ - `getMessagesPaginated({ threadId, format?, page?, perPage? })`: Get paginated messages for a thread
220
+ - `updateMessages({ messages })`: Update existing messages with atomic transaction
221
+ - `deleteMessages(messageIds)`: Delete specific messages with atomic transaction
222
+
223
+ ### Resources
224
+
225
+ - `saveResource({ resource })`: Save a resource with working memory
90
226
  - `getResourceById({ resourceId })`: Get a resource by ID
91
- - `updateResource({ resourceId, ... })`: Update a resource
227
+ - `updateResource({ resourceId, workingMemory?, metadata? })`: Update resource working memory and metadata
228
+
229
+ ### AI Tracing & Observability
230
+
231
+ - `createAISpan(span)`: Create an AI trace span
232
+ - `updateAISpan({ spanId, traceId, updates })`: Update an existing span
233
+ - `getAITrace(traceId)`: Get complete trace with all spans
234
+ - `getAITracesPaginated({ filters?, pagination? })`: Query traces with pagination and filters
235
+ - `batchCreateAISpans({ records })`: Batch create multiple spans
236
+ - `batchUpdateAISpans({ records })`: Batch update multiple spans
237
+ - `batchDeleteAITraces({ traceIds })`: Batch delete traces
238
+
239
+ ### Index Management
240
+
241
+ - `createIndex({ name, table, columns, unique?, where? })`: Create a new index
242
+ - `listIndexes(tableName?)`: List all indexes or indexes for a specific table
243
+ - `describeIndex(indexName)`: Get detailed index statistics and information
244
+ - `dropIndex(indexName)`: Drop an existing index
245
+
246
+ ### Workflows
247
+
248
+ - `persistWorkflowSnapshot({ workflowName, runId, resourceId?, snapshot })`: Save workflow execution state
249
+ - `loadWorkflowSnapshot({ workflowName, runId })`: Load workflow execution state
250
+ - `updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext })`: Update step results (transaction + row locking)
251
+ - `updateWorkflowState({ workflowName, runId, opts })`: Update workflow run status (transaction + row locking)
252
+ - `getWorkflowRuns({ workflowName?, fromDate?, toDate?, limit?, offset?, resourceId? })`: Query workflow runs
253
+ - `getWorkflowRunById({ runId, workflowName? })`: Get specific workflow run
254
+
255
+ ### Scores & Evaluation
256
+
257
+ - `saveScore(score)`: Save evaluation score
258
+ - `getScoreById({ id })`: Get score by ID
259
+ - `getScoresByScorerId({ scorerId, pagination, entityId?, entityType?, source? })`: Get scores by scorer
260
+ - `getScoresByRunId({ runId, pagination })`: Get scores for a run
261
+ - `getScoresByEntityId({ entityId, entityType, pagination })`: Get scores for an entity
262
+ - `getScoresBySpan({ traceId, spanId, pagination })`: Get scores for a trace span
263
+
264
+ ### Traces (Legacy)
265
+
266
+ - `getTracesPaginated({ filters?, pagination? })`: Get paginated legacy traces
267
+ - `batchTraceInsert({ records })`: Batch insert legacy trace records
268
+
269
+ ### Evals (Legacy)
270
+
271
+ - `getEvals({ agentName?, type?, page?, perPage? })`: Get paginated evaluations
272
+
273
+ ### Low-level Operations
274
+
275
+ - `createTable({ tableName, schema })`: Create a new table
276
+ - `alterTable({ tableName, schema, ifNotExists })`: Add columns to existing table
277
+ - `clearTable({ tableName })`: Remove all rows from a table
278
+ - `dropTable({ tableName })`: Drop a table
279
+ - `insert({ tableName, record })`: Insert a single record
280
+ - `batchInsert({ tableName, records })`: Batch insert multiple records
281
+ - `load<R>({ tableName, keys })`: Load a record by key(s)
282
+
283
+ ## Index Management
284
+
285
+ The MSSQL store provides comprehensive index management capabilities to optimize query performance.
286
+
287
+ ### Automatic Performance Indexes
288
+
289
+ MSSQL storage automatically creates composite indexes during initialization for common query patterns. These indexes significantly improve performance for filtered queries with sorting.
290
+
291
+ ### Creating Custom Indexes
292
+
293
+ ```typescript
294
+ // Basic index for common queries
295
+ await store.createIndex({
296
+ name: 'idx_threads_resource',
297
+ table: 'mastra_threads',
298
+ columns: ['resourceId'],
299
+ });
300
+
301
+ // Composite index with sort order for filtering + sorting
302
+ await store.createIndex({
303
+ name: 'idx_messages_composite',
304
+ table: 'mastra_messages',
305
+ columns: ['thread_id', 'seq_id DESC'],
306
+ });
307
+
308
+ // Unique index for constraints
309
+ await store.createIndex({
310
+ name: 'idx_unique_constraint',
311
+ table: 'mastra_resources',
312
+ columns: ['id'],
313
+ unique: true,
314
+ });
315
+
316
+ // Filtered index (partial indexing)
317
+ await store.createIndex({
318
+ name: 'idx_active_threads',
319
+ table: 'mastra_threads',
320
+ columns: ['resourceId'],
321
+ where: "status = 'active'",
322
+ });
323
+ ```
324
+
325
+ ### Managing Indexes
326
+
327
+ ```typescript
328
+ // List all indexes
329
+ const allIndexes = await store.listIndexes();
330
+
331
+ // List indexes for specific table
332
+ const threadIndexes = await store.listIndexes('mastra_threads');
333
+
334
+ // Get detailed statistics for an index
335
+ const stats = await store.describeIndex('idx_threads_resource');
336
+ console.log(stats);
337
+ // {
338
+ // name: 'idx_threads_resource',
339
+ // table: 'mastra_threads',
340
+ // columns: ['resourceId', 'seq_id'],
341
+ // unique: false,
342
+ // size: '128 KB',
343
+ // method: 'nonclustered',
344
+ // scans: 1542, // Number of index seeks
345
+ // tuples_read: 45230, // Tuples read via index
346
+ // tuples_fetched: 12050 // Tuples fetched via index
347
+ // }
348
+
349
+ // Drop an index
350
+ await store.dropIndex('idx_threads_resource');
351
+ ```
352
+
353
+ ### Monitoring Index Performance
354
+
355
+ ```typescript
356
+ // Check index usage statistics
357
+ const stats = await store.describeIndex('idx_threads_resource');
358
+
359
+ // Identify unused indexes
360
+ if (stats.scans === 0) {
361
+ console.log(`Index ${stats.name} is unused - consider removing`);
362
+ await store.dropIndex(stats.name);
363
+ }
364
+
365
+ // Monitor index efficiency
366
+ const efficiency = stats.tuples_fetched / stats.tuples_read;
367
+ if (efficiency < 0.5) {
368
+ console.log(`Index ${stats.name} has low efficiency: ${efficiency}`);
369
+ }
370
+ ```
92
371
 
93
372
  ## Related Links
94
373