Documentation
¶
Overview ¶
Package database provides a unified database abstraction layer (Database Hub) that supports multiple backends (SQLite, PostgreSQL, MySQL) with a common interface. SQLite is the default backend, requiring zero configuration.
Index ¶
- type Backend
- type BackendFactory
- type BackendType
- type Config
- type HealthChecker
- type HealthStatus
- type Hub
- func (h *Hub) AddBackend(ctx context.Context, name string, config Config) error
- func (h *Hub) Close() error
- func (h *Hub) DB() *sql.DB
- func (h *Hub) Exec(ctx context.Context, backendName string, query string, args ...any) (sql.Result, error)
- func (h *Hub) GetBackend(name string) (*Backend, error)
- func (h *Hub) ListBackends() []string
- func (h *Hub) Migrate(ctx context.Context, backendName string, target int) error
- func (h *Hub) Primary() *Backend
- func (h *Hub) Query(ctx context.Context, backendName string, query string, args ...any) (*sql.Rows, error)
- func (h *Hub) RegisterFactory(backendType BackendType, factory BackendFactory)
- func (h *Hub) RemoveBackend(name string) error
- func (h *Hub) Status(ctx context.Context) map[string]HealthStatus
- func (h *Hub) VectorSearch(ctx context.Context, backendName string, collection string, ...) ([]SearchResult, error)
- type HubConfig
- type JobStorage
- type MemoryDBConfig
- type Migrator
- type MySQLConfig
- type MySQLFactory
- type PostgreSQLConfig
- type PostgreSQLFactory
- type SQLiteConfig
- type SQLiteFactory
- type SearchResult
- type SessionPersister
- type VectorConfig
- type VectorStore
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Backend ¶
type Backend struct {
// Name is the identifier for this backend (e.g., "primary", "analytics")
Name string
// Type indicates the database type
Type BackendType
// DB is the underlying database connection
DB *sql.DB
// Config holds the backend configuration
Config Config
// Migrator handles schema migrations
Migrator Migrator
// Vector provides vector search capabilities (nil if not supported)
Vector VectorStore
// Health monitors database health
Health HealthChecker
}
Backend represents a database backend connection with all its capabilities.
type BackendFactory ¶
type BackendFactory interface {
// Create creates a new backend with the given configuration.
Create(config Config) (*Backend, error)
// Supports returns true if this factory can create the given backend type.
Supports(backendType BackendType) bool
}
BackendFactory creates database backends based on configuration.
type BackendType ¶
type BackendType string
BackendType identifies the type of database backend.
const ( BackendSQLite BackendType = "sqlite" BackendPostgreSQL BackendType = "postgresql" BackendMySQL BackendType = "mysql" )
type Config ¶
type Config struct {
// Type identifies the backend type
Type BackendType `yaml:"type"`
// Path is for SQLite databases
Path string `yaml:"path"`
// Host is for network databases (PostgreSQL, MySQL)
Host string `yaml:"host"`
// Port is for network databases
Port int `yaml:"port"`
// Database name
Database string `yaml:"database"`
// User for authentication
User string `yaml:"user"`
// Password for authentication (supports ${ENV_VAR} expansion)
Password string `yaml:"password"`
// SSLMode for PostgreSQL: disable, require, verify-full
SSLMode string `yaml:"ssl_mode"`
// Connection pooling
MaxOpenConns int `yaml:"max_open_conns"`
MaxIdleConns int `yaml:"max_idle_conns"`
ConnMaxLifetime time.Duration `yaml:"conn_max_lifetime"`
// Supabase-specific
SupabaseURL string `yaml:"supabase_url"`
SupabaseAnonKey string `yaml:"supabase_anon_key"`
// Vector search configuration
Vector VectorConfig `yaml:"vector"`
// Journal mode for SQLite (default: WAL)
JournalMode string `yaml:"journal_mode"`
// Busy timeout for SQLite in milliseconds (default: 5000)
BusyTimeout int `yaml:"busy_timeout"`
}
Config represents a generic database connection configuration.
type HealthChecker ¶
type HealthChecker interface {
// Ping checks basic database connectivity.
Ping(ctx context.Context) error
// Status returns detailed health status.
Status(ctx context.Context) HealthStatus
}
HealthChecker interface for monitoring database health.
type HealthStatus ¶
type HealthStatus struct {
Healthy bool `json:"healthy"`
Latency time.Duration `json:"latency"`
Version string `json:"version"`
Error string `json:"error,omitempty"`
// Connection pool metrics
OpenConnections int `json:"open_connections"`
InUse int `json:"in_use"`
Idle int `json:"idle"`
WaitCount int64 `json:"wait_count"`
WaitDuration time.Duration `json:"wait_duration"`
MaxOpenConns int `json:"max_open_conns"`
MaxIdleClosed int64 `json:"max_idle_closed"`
MaxLifetimeClosed int64 `json:"max_lifetime_closed"`
}
HealthStatus represents the health state of a database backend.
type Hub ¶
type Hub struct {
// contains filtered or unexported fields
}
Hub is the central database management system that orchestrates multiple database backends and provides a unified API.
func (*Hub) AddBackend ¶
AddBackend creates and registers a new database backend.
func (*Hub) Exec ¶
func (h *Hub) Exec(ctx context.Context, backendName string, query string, args ...any) (sql.Result, error)
Exec executes a statement on the specified backend.
func (*Hub) GetBackend ¶
GetBackend returns a backend by name, or the primary backend if name is empty.
func (*Hub) ListBackends ¶
ListBackends returns the names of all registered backends.
func (*Hub) Query ¶
func (h *Hub) Query(ctx context.Context, backendName string, query string, args ...any) (*sql.Rows, error)
Query executes a query on the specified backend.
func (*Hub) RegisterFactory ¶
func (h *Hub) RegisterFactory(backendType BackendType, factory BackendFactory)
RegisterFactory registers a backend factory for a specific backend type.
func (*Hub) RemoveBackend ¶
RemoveBackend removes a backend by name (cannot remove primary).
func (*Hub) Status ¶
func (h *Hub) Status(ctx context.Context) map[string]HealthStatus
Status returns the health status of all backends.
func (*Hub) VectorSearch ¶
func (h *Hub) VectorSearch(ctx context.Context, backendName string, collection string, queryVector []float32, k int, filter map[string]any) ([]SearchResult, error)
VectorSearch performs a vector similarity search on the specified backend. The queryVector must be pre-computed (use an embedding provider to convert text to vector).
type HubConfig ¶
type HubConfig struct {
// Backend is the primary database backend type (default: "sqlite")
Backend BackendType `yaml:"backend"`
// SQLite configuration
SQLite SQLiteConfig `yaml:"sqlite"`
// PostgreSQL configuration (includes Supabase)
PostgreSQL PostgreSQLConfig `yaml:"postgresql"`
// MySQL configuration
MySQL MySQLConfig `yaml:"mysql"`
// Additional named connections for multi-database setups
Connections map[string]Config `yaml:"connections"`
// Memory database configuration (can differ from primary)
Memory MemoryDBConfig `yaml:"memory"`
}
HubConfig represents the complete database hub configuration.
func DefaultHubConfig ¶
func DefaultHubConfig() HubConfig
DefaultHubConfig returns the default hub configuration (SQLite).
type JobStorage ¶
JobStorage interface for scheduler job persistence. This mirrors the existing JobStorage interface for compatibility.
type MemoryDBConfig ¶
type MemoryDBConfig struct {
// Backend type (default: same as primary)
Backend BackendType `yaml:"backend"`
// Path for SQLite memory database
Path string `yaml:"path"`
// UsePrimary indicates to use the primary database for memory storage
UsePrimary bool `yaml:"use_primary"`
}
MemoryDBConfig configures the memory database (can be separate from primary).
type Migrator ¶
type Migrator interface {
// CurrentVersion returns the current schema version.
CurrentVersion(ctx context.Context) (int, error)
// Migrate applies migrations up to the target version.
// If target is 0, migrates to the latest version.
Migrate(ctx context.Context, target int) error
// NeedsMigration returns true if the schema is outdated.
NeedsMigration(ctx context.Context) (bool, error)
}
Migrator interface for database schema migrations.
type MySQLConfig ¶
type MySQLConfig struct {
// Host (default: "localhost")
Host string `yaml:"host"`
// Port (default: 3306)
Port int `yaml:"port"`
// Database name
Database string `yaml:"database"`
// User for authentication
User string `yaml:"user"`
// Password for authentication (supports ${ENV_VAR} expansion)
Password string `yaml:"password"`
// Connection pooling
MaxOpenConns int `yaml:"max_open_conns"`
MaxIdleConns int `yaml:"max_idle_conns"`
ConnMaxLifetime time.Duration `yaml:"conn_max_lifetime"`
}
MySQLConfig holds MySQL configuration.
func (MySQLConfig) ToConfig ¶
func (m MySQLConfig) ToConfig() Config
ToConfig converts MySQLConfig to generic Config.
type MySQLFactory ¶
type MySQLFactory struct{}
MySQLFactory creates MySQL backends. This is a placeholder that will be implemented in the mysql.go file.
func (*MySQLFactory) Create ¶
func (f *MySQLFactory) Create(config Config) (*Backend, error)
Create creates a new MySQL backend with the given configuration.
func (*MySQLFactory) Supports ¶
func (f *MySQLFactory) Supports(backendType BackendType) bool
Supports returns true for MySQL backend type.
type PostgreSQLConfig ¶
type PostgreSQLConfig struct {
// Host (default: "localhost")
Host string `yaml:"host"`
// Port (default: 5432)
Port int `yaml:"port"`
// Database name
Database string `yaml:"database"`
// User for authentication
User string `yaml:"user"`
// Password for authentication (supports ${ENV_VAR} expansion)
Password string `yaml:"password"`
// SSL mode: disable, require, verify-ca, verify-full
SSLMode string `yaml:"ssl_mode"`
// Connection pooling
MaxOpenConns int `yaml:"max_open_conns"`
MaxIdleConns int `yaml:"max_idle_conns"`
ConnMaxLifetime time.Duration `yaml:"conn_max_lifetime"`
ConnMaxIdleTime time.Duration `yaml:"conn_max_idle_time"`
// Supabase-specific (alternative to standard config)
SupabaseURL string `yaml:"supabase_url"`
SupabaseAnonKey string `yaml:"supabase_anon_key"`
// Vector search (pgvector)
Vector VectorConfig `yaml:"vector"`
}
PostgreSQLConfig holds PostgreSQL and Supabase configuration.
func DefaultPostgreSQLConfig ¶
func DefaultPostgreSQLConfig() PostgreSQLConfig
DefaultPostgreSQLConfig returns default PostgreSQL configuration.
func (PostgreSQLConfig) ToConfig ¶
func (p PostgreSQLConfig) ToConfig() Config
ToConfig converts PostgreSQLConfig to generic Config.
type PostgreSQLFactory ¶
type PostgreSQLFactory struct {
// contains filtered or unexported fields
}
PostgreSQLFactory creates PostgreSQL backends (including Supabase).
func NewPostgreSQLFactory ¶
func NewPostgreSQLFactory(logger *slog.Logger) *PostgreSQLFactory
NewPostgreSQLFactory creates a new PostgreSQL factory.
func (*PostgreSQLFactory) Create ¶
func (f *PostgreSQLFactory) Create(config Config) (*Backend, error)
Create creates a new PostgreSQL backend with the given configuration.
func (*PostgreSQLFactory) Supports ¶
func (f *PostgreSQLFactory) Supports(backendType BackendType) bool
Supports returns true for PostgreSQL backend type.
type SQLiteConfig ¶
type SQLiteConfig struct {
// Path to the database file (default: "./data/devclaw.db")
Path string `yaml:"path"`
// Journal mode (default: WAL)
JournalMode string `yaml:"journal_mode"`
// Busy timeout in milliseconds (default: 5000)
BusyTimeout int `yaml:"busy_timeout"`
// Enable foreign keys (default: true)
ForeignKeys bool `yaml:"foreign_keys"`
}
SQLiteConfig holds SQLite-specific configuration.
func DefaultSQLiteConfig ¶
func DefaultSQLiteConfig() SQLiteConfig
DefaultSQLiteConfig returns default SQLite configuration.
func (SQLiteConfig) ToConfig ¶
func (s SQLiteConfig) ToConfig() Config
ToConfig converts SQLiteConfig to generic Config.
type SQLiteFactory ¶
type SQLiteFactory struct{}
SQLiteFactory creates SQLite backends.
func (*SQLiteFactory) Create ¶
func (f *SQLiteFactory) Create(config Config) (*Backend, error)
Create creates a new SQLite backend with the given configuration.
func (*SQLiteFactory) Supports ¶
func (f *SQLiteFactory) Supports(backendType BackendType) bool
Supports returns true for SQLite backend type.
type SearchResult ¶
type SearchResult struct {
ID string `json:"id"`
Score float64 `json:"score"`
Metadata map[string]any `json:"metadata,omitempty"`
Text string `json:"text,omitempty"`
}
SearchResult represents a single vector search result with score and metadata.
type SessionPersister ¶
type SessionPersister interface {
SaveEntry(sessionID string, entry any) error
LoadSession(sessionID string) (any, any, error)
SaveFacts(sessionID string, facts []string) error
SaveMeta(sessionID, channel, chatID string, config any, activeSkills []string) error
DeleteSession(sessionID string) error
Rotate(sessionID string, maxLines int) error
LoadAll() (map[string]any, error)
Close() error
}
SessionPersister interface for session storage operations. This mirrors the existing SessionPersister interface for compatibility.
type VectorConfig ¶
type VectorConfig struct {
// Enabled activates vector search support
Enabled bool `yaml:"enabled"`
// Dimensions of the embedding vectors (default: 1536 for OpenAI)
Dimensions int `yaml:"dimensions"`
// Provider: "native" (pgvector), "memory" (in-memory for SQLite), "external"
Provider string `yaml:"provider"`
// Index type for pgvector: "hnsw" or "ivfflat"
IndexType string `yaml:"index_type"`
// Lists parameter for IVFFlat index (default: 100)
IVFLists int `yaml:"ivf_lists"`
// M parameter for HNSW index (default: 16)
HNSWM int `yaml:"hnsw_m"`
}
VectorConfig configures vector search capabilities.
func DefaultVectorConfig ¶
func DefaultVectorConfig() VectorConfig
DefaultVectorConfig returns default vector configuration.
type VectorStore ¶
type VectorStore interface {
// Insert adds a vector with associated metadata to the collection.
Insert(ctx context.Context, collection string, id string, vector []float32, metadata map[string]any) error
// Search performs a similarity search and returns the top k results.
Search(ctx context.Context, collection string, vector []float32, k int, filter map[string]any) ([]SearchResult, error)
// Delete removes a vector from the collection.
Delete(ctx context.Context, collection string, id string) error
// SupportsVector returns true if the backend supports native vector operations.
SupportsVector() bool
}
VectorStore interface for vector similarity search operations. Implementations: pgvector (PostgreSQL), InMemoryVectorStore (SQLite fallback).