@mastra/mssql 0.0.0-just-snapshot-20251014192224 → 0.0.0-main-test-05-11-2025-2-20251105214713

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/README.md CHANGED
@@ -17,78 +17,356 @@ 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' });
55
- const messages = await store.getMessages({ threadId: 'thread-123' });
101
+ const messages = await store.listMessages({ threadId: 'thread-123' });
56
102
  ```
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
+ - `listThreadsByResourceId({ resourceId, offset, limit, orderBy? })`: List paginated threads for a resource
213
+
214
+ ### Messages
215
+
216
+ - `saveMessages({ messages })`: Save multiple messages with atomic transaction
217
+ - `listMessagesById({ messageIds })`: Get messages by their IDs
218
+ - `listMessages({ threadId, resourceId?, page?, perPage?, orderBy?, filter? })`: Get paginated messages for a thread with filtering and sorting
219
+ - `updateMessages({ messages })`: Update existing messages with atomic transaction
220
+ - `deleteMessages(messageIds)`: Delete specific messages with atomic transaction
221
+
222
+ ### Resources
223
+
224
+ - `saveResource({ resource })`: Save a resource with working memory
90
225
  - `getResourceById({ resourceId })`: Get a resource by ID
91
- - `updateResource({ resourceId, ... })`: Update a resource
226
+ - `updateResource({ resourceId, workingMemory?, metadata? })`: Update resource working memory and metadata
227
+
228
+ ### AI Tracing & Observability
229
+
230
+ - `createAISpan(span)`: Create an AI trace span
231
+ - `updateAISpan({ spanId, traceId, updates })`: Update an existing span
232
+ - `getAITrace(traceId)`: Get complete trace with all spans
233
+ - `getAITracesPaginated({ filters?, pagination? })`: Query traces with pagination and filters
234
+ - `batchCreateAISpans({ records })`: Batch create multiple spans
235
+ - `batchUpdateAISpans({ records })`: Batch update multiple spans
236
+ - `batchDeleteAITraces({ traceIds })`: Batch delete traces
237
+
238
+ ### Index Management
239
+
240
+ - `createIndex({ name, table, columns, unique?, where? })`: Create a new index
241
+ - `listIndexes(tableName?)`: List all indexes or indexes for a specific table
242
+ - `describeIndex(indexName)`: Get detailed index statistics and information
243
+ - `dropIndex(indexName)`: Drop an existing index
244
+
245
+ ### Workflows
246
+
247
+ - `persistWorkflowSnapshot({ workflowName, runId, resourceId?, snapshot })`: Save workflow execution state
248
+ - `loadWorkflowSnapshot({ workflowName, runId })`: Load workflow execution state
249
+ - `updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext })`: Update step results (transaction + row locking)
250
+ - `updateWorkflowState({ workflowName, runId, opts })`: Update workflow run status (transaction + row locking)
251
+ - `listWorkflowRuns({ workflowName?, fromDate?, toDate?, limit?, offset?, resourceId? })`: Query workflow runs
252
+ - `getWorkflowRunById({ runId, workflowName? })`: Get specific workflow run
253
+
254
+ ### Scores & Evaluation
255
+
256
+ - `saveScore(score)`: Save evaluation score
257
+ - `getScoreById({ id })`: Get score by ID
258
+ - `listScoresByScorerId({ scorerId, pagination, entityId?, entityType?, source? })`: Get scores by scorer
259
+ - `listScoresByRunId({ runId, pagination })`: Get scores for a run
260
+ - `listScoresByEntityId({ entityId, entityType, pagination })`: Get scores for an entity
261
+ - `listScoresBySpan({ traceId, spanId, pagination })`: Get scores for a trace span
262
+
263
+ ### Traces (Legacy)
264
+
265
+ - `getTracesPaginated({ filters?, pagination? })`: Get paginated legacy traces
266
+ - `batchTraceInsert({ records })`: Batch insert legacy trace records
267
+
268
+ ### Evals (Legacy)
269
+
270
+ - `getEvals({ agentName?, type?, page?, perPage? })`: Get paginated evaluations
271
+
272
+ ### Low-level Operations
273
+
274
+ - `createTable({ tableName, schema })`: Create a new table
275
+ - `alterTable({ tableName, schema, ifNotExists })`: Add columns to existing table
276
+ - `clearTable({ tableName })`: Remove all rows from a table
277
+ - `dropTable({ tableName })`: Drop a table
278
+ - `insert({ tableName, record })`: Insert a single record
279
+ - `batchInsert({ tableName, records })`: Batch insert multiple records
280
+ - `load<R>({ tableName, keys })`: Load a record by key(s)
281
+
282
+ ## Index Management
283
+
284
+ The MSSQL store provides comprehensive index management capabilities to optimize query performance.
285
+
286
+ ### Automatic Performance Indexes
287
+
288
+ MSSQL storage automatically creates composite indexes during initialization for common query patterns. These indexes significantly improve performance for filtered queries with sorting.
289
+
290
+ ### Creating Custom Indexes
291
+
292
+ ```typescript
293
+ // Basic index for common queries
294
+ await store.createIndex({
295
+ name: 'idx_threads_resource',
296
+ table: 'mastra_threads',
297
+ columns: ['resourceId'],
298
+ });
299
+
300
+ // Composite index with sort order for filtering + sorting
301
+ await store.createIndex({
302
+ name: 'idx_messages_composite',
303
+ table: 'mastra_messages',
304
+ columns: ['thread_id', 'seq_id DESC'],
305
+ });
306
+
307
+ // Unique index for constraints
308
+ await store.createIndex({
309
+ name: 'idx_unique_constraint',
310
+ table: 'mastra_resources',
311
+ columns: ['id'],
312
+ unique: true,
313
+ });
314
+
315
+ // Filtered index (partial indexing)
316
+ await store.createIndex({
317
+ name: 'idx_active_threads',
318
+ table: 'mastra_threads',
319
+ columns: ['resourceId'],
320
+ where: "status = 'active'",
321
+ });
322
+ ```
323
+
324
+ ### Managing Indexes
325
+
326
+ ```typescript
327
+ // List all indexes
328
+ const allIndexes = await store.listIndexes();
329
+
330
+ // List indexes for specific table
331
+ const threadIndexes = await store.listIndexes('mastra_threads');
332
+
333
+ // Get detailed statistics for an index
334
+ const stats = await store.describeIndex('idx_threads_resource');
335
+ console.log(stats);
336
+ // {
337
+ // name: 'idx_threads_resource',
338
+ // table: 'mastra_threads',
339
+ // columns: ['resourceId', 'seq_id'],
340
+ // unique: false,
341
+ // size: '128 KB',
342
+ // method: 'nonclustered',
343
+ // scans: 1542, // Number of index seeks
344
+ // tuples_read: 45230, // Tuples read via index
345
+ // tuples_fetched: 12050 // Tuples fetched via index
346
+ // }
347
+
348
+ // Drop an index
349
+ await store.dropIndex('idx_threads_resource');
350
+ ```
351
+
352
+ ### Monitoring Index Performance
353
+
354
+ ```typescript
355
+ // Check index usage statistics
356
+ const stats = await store.describeIndex('idx_threads_resource');
357
+
358
+ // Identify unused indexes
359
+ if (stats.scans === 0) {
360
+ console.log(`Index ${stats.name} is unused - consider removing`);
361
+ await store.dropIndex(stats.name);
362
+ }
363
+
364
+ // Monitor index efficiency
365
+ const efficiency = stats.tuples_fetched / stats.tuples_read;
366
+ if (efficiency < 0.5) {
367
+ console.log(`Index ${stats.name} has low efficiency: ${efficiency}`);
368
+ }
369
+ ```
92
370
 
93
371
  ## Related Links
94
372