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
你想讓儲存使用的 schema 名稱。如未提供,將使用預設 schema。
Constructor 範例Constructor 範例 的直接連結
你可以用以下方式建立 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:儲存評估結果及 metadatamastra_threads:儲存對話 threadmastra_messages:儲存個別訊息mastra_traces:儲存遙測及 tracing 資料mastra_scorers:儲存評分及評估資料mastra_resources:儲存資源的 working memory 資料
初始化初始化 的直接連結
當你把 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(),系統不會建立資料表,而儲存操作會在沒有提示的情況下失敗或拋出錯誤。
直接存取資料庫及 connection pool直接存取資料庫及 connection pool 的直接連結
MSSQLStore 以公開欄位的方式提供 mssql connection pool:
store.pool // mssql connection pool instance
它支援直接查詢及自訂 transaction 管理。使用這些欄位時:
- 你有責任妥善處理連線及 transaction。
- 關閉 store(
store.close())會銷毀相關的 connection pool。 - 直接存取會繞過 MSSQLStore 方法所提供的任何額外邏輯或驗證。
此方式適合需要低階存取的進階情境。