gotidb/pkg/storage/factory.go

74 lines
1.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package storage
import (
"fmt"
"path/filepath"
)
// EngineConfig 存储引擎配置
type EngineConfig struct {
// 持久化配置
PersistenceType PersistenceType // 持久化类型
PersistenceDir string // 持久化目录
SyncEvery int // 每写入多少条数据同步一次
// memory engine特有配置
MemLen int
// BoltDB特有配置
BoltDBFilename string // BoltDB文件名
BoltDBOptions *BoltDBConfig // BoltDB选项
}
// NewStorageEngine 创建一个新的存储引擎
func NewStorageEngine(config EngineConfig) (StorageEngine, error) {
var engine StorageEngine
var err error
switch config.PersistenceType {
case PersistenceTypeNone, PersistenceTypeWAL:
// 创建内存存储引擎
memEngine := NewMemoryEngine(config.MemLen)
// 如果需要持久化启用WAL
if config.PersistenceType == PersistenceTypeWAL {
err = memEngine.EnablePersistence(PersistenceConfig{
Type: PersistenceTypeWAL,
Directory: config.PersistenceDir,
SyncEvery: config.SyncEvery,
})
if err != nil {
return nil, fmt.Errorf("failed to enable WAL persistence: %v", err)
}
}
engine = memEngine
case PersistenceTypeBoltDB:
// 创建BoltDB存储引擎
boltDBPath := filepath.Join(config.PersistenceDir, config.BoltDBFilename)
if config.BoltDBFilename == "" {
boltDBPath = filepath.Join(config.PersistenceDir, "gotidb.db")
}
boltDBConfig := config.BoltDBOptions
if boltDBConfig == nil {
boltDBConfig = &BoltDBConfig{
FilePath: boltDBPath,
}
} else {
boltDBConfig.FilePath = boltDBPath
}
boltEngine, err := NewBoltDBEngine(*boltDBConfig)
if err != nil {
return nil, fmt.Errorf("failed to create BoltDB engine: %v", err)
}
engine = boltEngine
default:
return nil, fmt.Errorf("unsupported persistence type: %s", config.PersistenceType)
}
return engine, nil
}