MSSQL 存储
MSSQL 存储实现使用 Microsoft SQL Server 数据库提供可用于生产环境的存储方案。
安装安装的直接链接
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/mssql@latest
pnpm add @mastra/mssql@latest
yarn add @mastra/mssql@latest
bun add @mastra/mssql@latest
使用方法使用方法的直接链接
import { MSSQLStore } from '@mastra/mssql'
const storage = new MSSQLStore({
id: 'mssql-storage',
connectionString: process.env.DATABASE_URL,
})
参数参数的直接链接
connectionString:
string
MSSQL 连接字符串(例如 Server=localhost,1433;Database=mydb;User Id=sa;Password=password;Encrypt=true;TrustServerCertificate=true)
schemaName?:
string
希望 storage 使用的 schema 名称。未提供时将使用默认 schema。
构造函数示例构造函数示例的直接链接
可以通过以下方式实例化 MSSQLStore:
import { MSSQLStore } from '@mastra/mssql'
// Using a connection string only
const store1 = new MSSQLStore({
id: 'mssql-storage-1',
connectionString:
'Server=localhost,1433;Database=mydb;User Id=sa;Password=password;Encrypt=true;TrustServerCertificate=true',
})
// Using a connection string with a custom schema name
const store2 = new MSSQLStore({
id: 'mssql-storage-2',
connectionString:
'Server=localhost,1433;Database=mydb;User Id=sa;Password=password;Encrypt=true;TrustServerCertificate=true',
schemaName: 'custom_schema', // optional
})
// Using individual connection parameters
const store4 = new MSSQLStore({
id: 'mssql-storage-3',
server: 'localhost',
port: 1433,
database: 'mydb',
user: 'user',
password: 'password',
})
// Individual parameters with schemaName
const store5 = new MSSQLStore({
id: 'mssql-storage-4',
server: 'localhost',
port: 1433,
database: 'mydb',
user: 'user',
password: 'password',
schemaName: 'custom_schema', // optional
})
补充说明补充说明的直接链接
Schema 管理Schema 管理的直接链接
该存储实现会自动处理 schema 创建和更新。它会创建以下表:
mastra_workflow_snapshot:存储 Workflow 状态和执行数据mastra_evals:存储评估结果和元数据mastra_threads:存储对话线程mastra_messages:存储单条消息mastra_traces:存储遥测和 tracing 数据mastra_scorers:存储评分和评估数据mastra_resources:存储资源工作记忆数据
初始化初始化的直接链接
将 storage 传递给 Mastra class 时,会在任何存储操作之前自动调用 init():
import { Mastra } from '@mastra/core'
import { MSSQLStore } from '@mastra/mssql'
const storage = new MSSQLStore({
connectionString: process.env.DATABASE_URL,
})
const mastra = new Mastra({
storage, // init() is called automatically
})
如果不通过 Mastra 而直接使用 storage,必须显式调用 init() 来创建表:
import { MSSQLStore } from '@mastra/mssql'
const storage = new MSSQLStore({
id: 'mssql-storage',
connectionString: process.env.DATABASE_URL,
})
// Required when using storage directly
await storage.init()
// Access domain-specific stores via getStore()
const memoryStore = await storage.getStore('memory')
const thread = await memoryStore?.getThreadById({ threadId: '...' })
注意
如果未调用 init(),不会创建表,存储操作将静默失败或抛出错误。
直接访问数据库和连接池直接访问数据库和连接池的直接链接
MSSQLStore 将 mssql 连接池作为公共字段暴露:
store.pool // mssql connection pool instance
它支持直接查询和自定义事务管理。使用这些字段时:
- 需要自行妥善处理连接和事务。
- 关闭 store(
store.close())会销毁关联的连接池。 - 直接访问会绕过 MSSQLStore 方法提供的任何额外逻辑或验证。
这种方式适用于需要低级别访问的高级场景。