database

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 3, 2026 License: Apache-2.0, BSD-3-Clause, MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetSupportedDrivers

func GetSupportedDrivers() []string

GetSupportedDrivers returns the list of supported remote database drivers Per AI.md PART 6-10: Multi-database driver support

func IsRemoteDriver

func IsRemoteDriver(driver string) bool

IsRemoteDriver returns true if the driver is a remote database driver

func ValidateRemoteConnection

func ValidateRemoteConnection(cfg *RemoteDBConfig) error

ValidateRemoteConnection tests the connection to a remote database

Types

type APIToken

type APIToken struct {
	ID          int64      `json:"id"`
	Name        string     `json:"name"`
	Token       string     `json:"token"`
	Description string     `json:"description,omitempty"`
	Permissions []string   `json:"permissions,omitempty"`
	RateLimit   int        `json:"rate_limit"`
	Active      bool       `json:"active"`
	LastUsed    *time.Time `json:"last_used,omitempty"`
	ExpiresAt   *time.Time `json:"expires_at,omitempty"`
	CreatedAt   time.Time  `json:"created_at"`
}

APIToken represents an API token

type AdminSession

type AdminSession struct {
	ID        int64     `json:"id"`
	UserID    int64     `json:"user_id"`
	Token     string    `json:"token"`
	IPAddress string    `json:"ip_address,omitempty"`
	UserAgent string    `json:"user_agent,omitempty"`
	ExpiresAt time.Time `json:"expires_at"`
	CreatedAt time.Time `json:"created_at"`
}

AdminSession represents an admin session

type AdminUser

type AdminUser struct {
	ID           int64      `json:"id"`
	Username     string     `json:"username"`
	PasswordHash string     `json:"-"`
	Email        string     `json:"email,omitempty"`
	Role         string     `json:"role"`
	Active       bool       `json:"active"`
	LastLogin    *time.Time `json:"last_login,omitempty"`
	CreatedAt    time.Time  `json:"created_at"`
	UpdatedAt    time.Time  `json:"updated_at"`
}

AdminUser represents an admin user

type AuditLogEntry

type AuditLogEntry struct {
	ID        int64     `json:"id"`
	Timestamp time.Time `json:"timestamp"`
	UserID    *int64    `json:"user_id,omitempty"`
	Action    string    `json:"action"`
	Resource  string    `json:"resource,omitempty"`
	Details   string    `json:"details,omitempty"`
	IPAddress string    `json:"ip_address,omitempty"`
	UserAgent string    `json:"user_agent,omitempty"`
}

AuditLogEntry represents an audit log entry

type BlockedIP

type BlockedIP struct {
	ID        int64      `json:"id"`
	IPAddress string     `json:"ip_address"`
	Reason    string     `json:"reason,omitempty"`
	BlockedBy string     `json:"blocked_by,omitempty"`
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
	CreatedAt time.Time  `json:"created_at"`
}

BlockedIP represents a blocked IP address

type ClusterManager

type ClusterManager struct {
	// contains filtered or unexported fields
}

ClusterManager manages cluster operations per AI.md PART 24

func NewClusterManager

func NewClusterManager(dm *DatabaseManager) (*ClusterManager, error)

NewClusterManager creates a new cluster manager

func (*ClusterManager) GenerateJoinToken

func (cm *ClusterManager) GenerateJoinToken(ctx context.Context) (string, error)

GenerateJoinToken generates a join token for new nodes

func (*ClusterManager) GetNode

func (cm *ClusterManager) GetNode(ctx context.Context, nodeID string) (*ClusterNode, error)

GetNode returns a specific node by ID

func (*ClusterManager) GetNodes

func (cm *ClusterManager) GetNodes(ctx context.Context) ([]*ClusterNode, error)

GetNodes returns all nodes in the cluster

func (*ClusterManager) Hostname

func (cm *ClusterManager) Hostname() string

Hostname returns this node's hostname

func (*ClusterManager) IsClusterMode

func (cm *ClusterManager) IsClusterMode() bool

IsClusterMode returns true if running in cluster mode

func (*ClusterManager) IsPrimary

func (cm *ClusterManager) IsPrimary() bool

IsPrimary returns true if this node is the primary

func (*ClusterManager) LeaveCluster

func (cm *ClusterManager) LeaveCluster(ctx context.Context) error

LeaveCluster removes this node from the cluster

func (*ClusterManager) Mode

func (cm *ClusterManager) Mode() ClusterMode

Mode returns the current cluster mode

func (*ClusterManager) NodeID

func (cm *ClusterManager) NodeID() string

NodeID returns this node's ID

func (*ClusterManager) Start

func (cm *ClusterManager) Start(ctx context.Context) error

Start starts the cluster manager

func (*ClusterManager) Stop

func (cm *ClusterManager) Stop()

Stop stops the cluster manager

type ClusterMode

type ClusterMode string

ClusterMode represents the cluster operating mode

const (
	// ClusterModeStandalone is single-node mode (SQLite)
	ClusterModeStandalone ClusterMode = "standalone"
	// ClusterModeCluster is multi-node mode (PostgreSQL/MySQL)
	ClusterModeCluster ClusterMode = "cluster"
)

type ClusterNode

type ClusterNode struct {
	ID        string
	Hostname  string
	Address   string
	Port      int
	Version   string
	IsPrimary bool
	Status    NodeStatus
	LastSeen  time.Time
	JoinedAt  time.Time
	Metadata  map[string]string
}

ClusterNode represents a node in the cluster

type Config

type Config struct {
	Driver   string `yaml:"driver"`   // sqlite, postgres, mysql
	DSN      string `yaml:"dsn"`      // connection string (for non-sqlite)
	DataDir  string `yaml:"data_dir"` // data directory (for sqlite)
	MaxOpen  int    `yaml:"max_open"` // max open connections
	MaxIdle  int    `yaml:"max_idle"` // max idle connections
	Lifetime int    `yaml:"lifetime"` // connection max lifetime in seconds
}

Config holds database configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns default database configuration

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB represents a single database connection

func New

func New(cfg *Config) (*DB, error)

New creates a new database connection (legacy single-database mode for migration)

func (*DB) Begin

func (db *DB) Begin(ctx context.Context) (*sql.Tx, error)

Begin starts a transaction

func (*DB) Close

func (db *DB) Close() error

Close closes the database connection

func (*DB) Driver

func (db *DB) Driver() string

Driver returns the database driver name

func (*DB) Exec

func (db *DB) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec executes a query without returning rows

func (*DB) IsReady

func (db *DB) IsReady() bool

IsReady returns true if database is ready

func (*DB) IsRemote

func (db *DB) IsRemote() bool

IsRemote returns true if using a remote database (not local SQLite) Per AI.md PART 5: Cluster mode uses remote database

func (*DB) Ping

func (db *DB) Ping(ctx context.Context) error

Ping checks database connectivity

func (*DB) Query

func (db *DB) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query executes a query that returns rows

func (*DB) QueryRow

func (db *DB) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRow executes a query that returns a single row

func (*DB) SQL

func (db *DB) SQL() *sql.DB

SQL returns the underlying *sql.DB connection Use with caution - prefer the DB methods for standard operations

type DatabaseBackendConfig

type DatabaseBackendConfig struct {
	Driver   string `yaml:"driver"`   // sqlite, postgres, mysql
	DSN      string `yaml:"dsn"`      // connection string (for remote databases)
	Path     string `yaml:"path"`     // file path (for SQLite)
	MaxOpen  int    `yaml:"max_open"` // max open connections
	MaxIdle  int    `yaml:"max_idle"` // max idle connections
	Lifetime int    `yaml:"lifetime"` // connection max lifetime in seconds
}

DatabaseBackendConfig represents configuration for a single database backend

type DatabaseManager

type DatabaseManager struct {
	// contains filtered or unexported fields
}

DatabaseManager manages both server and users databases per AI.md PART 24 Two separate databases: - server.db: Admin credentials, server state, scheduler - user.db: User accounts, tokens, sessions

func NewDatabaseManager

func NewDatabaseManager(cfg *Config) (*DatabaseManager, error)

NewDatabaseManager creates a new database manager with two databases

func (*DatabaseManager) Close

func (dm *DatabaseManager) Close() error

Close closes both database connections

func (*DatabaseManager) IsClusterMode

func (dm *DatabaseManager) IsClusterMode() bool

IsClusterMode returns true if running in cluster mode (remote database) Per AI.md PART 5: Cluster mode uses remote database as source of truth

func (*DatabaseManager) IsReady

func (dm *DatabaseManager) IsReady() bool

IsReady returns true if both databases are ready

func (*DatabaseManager) Ping

func (dm *DatabaseManager) Ping(ctx context.Context) error

Ping checks connectivity to both databases

func (*DatabaseManager) ServerDB

func (dm *DatabaseManager) ServerDB() *DB

ServerDB returns the server database connection

func (*DatabaseManager) UsersDB

func (dm *DatabaseManager) UsersDB() *DB

UsersDB returns the users database connection

type DatabaseMigrator

type DatabaseMigrator struct {
	// contains filtered or unexported fields
}

DatabaseMigrator handles migrations for both databases per AI.md PART 24

func NewDatabaseMigrator

func NewDatabaseMigrator(dm *DatabaseManager) *DatabaseMigrator

NewDatabaseMigrator creates a new migrator for both databases

func (*DatabaseMigrator) GetServerMigrator

func (dbm *DatabaseMigrator) GetServerMigrator() *Migrator

GetServerMigrator returns the server database migrator

func (*DatabaseMigrator) GetUsersMigrator

func (dbm *DatabaseMigrator) GetUsersMigrator() *Migrator

GetUsersMigrator returns the users database migrator

func (*DatabaseMigrator) MigrateAll

func (dbm *DatabaseMigrator) MigrateAll(ctx context.Context) error

MigrateAll runs migrations for both databases

type EngineStats

type EngineStats struct {
	ID              int64     `json:"id"`
	Date            time.Time `json:"date"`
	Engine          string    `json:"engine"`
	QueryCount      int       `json:"query_count"`
	ResultCount     int       `json:"result_count"`
	ErrorCount      int       `json:"error_count"`
	AvgResponseTime float64   `json:"avg_response_time"`
}

EngineStats represents engine statistics

type Migration

type Migration struct {
	Version     int
	Description string
	Up          string
	Down        string
}

Migration represents a database migration

type MigrationManager

type MigrationManager struct {
	// contains filtered or unexported fields
}

MigrationManager handles migration from SQLite to remote database Per AI.md PART 24: Auto-migrate local → remote

func NewMigrationManager

func NewMigrationManager(sourceDB *DB, targetDB *RemoteDB, dataDir string) *MigrationManager

NewMigrationManager creates a new migration manager

func (*MigrationManager) BackupBeforeMigration

func (mm *MigrationManager) BackupBeforeMigration(dbPath string) (string, error)

BackupBeforeMigration creates a backup of the SQLite database before migration

func (*MigrationManager) MigrateToRemote

func (mm *MigrationManager) MigrateToRemote(ctx context.Context, progress chan<- MigrationProgress) error

MigrateToRemote migrates a SQLite database to the remote database

type MigrationProgress

type MigrationProgress struct {
	Phase        string    `json:"phase"`
	Table        string    `json:"table"`
	TotalRows    int64     `json:"total_rows"`
	MigratedRows int64     `json:"migrated_rows"`
	StartTime    time.Time `json:"start_time"`
	Error        string    `json:"error,omitempty"`
}

MigrationProgress represents the progress of a migration

type Migrator

type Migrator struct {
	// contains filtered or unexported fields
}

Migrator handles database migrations

func NewMigrator

func NewMigrator(db *DB) *Migrator

NewMigrator creates a new migrator (legacy single-database mode)

func (*Migrator) GetMigrations

func (m *Migrator) GetMigrations() []Migration

GetMigrations returns all migrations

func (*Migrator) GetVersion

func (m *Migrator) GetVersion(ctx context.Context) (int, error)

GetVersion returns the current schema version

func (*Migrator) Migrate

func (m *Migrator) Migrate(ctx context.Context) error

Migrate runs all pending migrations

func (*Migrator) Register

func (m *Migrator) Register(migration Migration)

Register adds a migration

func (*Migrator) Rollback

func (m *Migrator) Rollback(ctx context.Context) error

Rollback rolls back the last migration

type MixedDB

type MixedDB struct {
	// contains filtered or unexported fields
}

MixedDB represents a database that can be SQLite or remote

func (*MixedDB) Begin

func (mdb *MixedDB) Begin(ctx context.Context) (*sql.Tx, error)

Begin starts a transaction

func (*MixedDB) Close

func (mdb *MixedDB) Close() error

Close closes the database connection

func (*MixedDB) Driver

func (mdb *MixedDB) Driver() string

Driver returns the database driver name

func (*MixedDB) Exec

func (mdb *MixedDB) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec executes a query without returning rows

func (*MixedDB) GetPlaceholder

func (mdb *MixedDB) GetPlaceholder(index int) string

GetPlaceholder returns the placeholder format for the database

func (*MixedDB) IsLocal

func (mdb *MixedDB) IsLocal() bool

IsLocal returns true if using SQLite (local storage)

func (*MixedDB) IsReady

func (mdb *MixedDB) IsReady() bool

IsReady returns true if the database is ready

func (*MixedDB) IsRemote

func (mdb *MixedDB) IsRemote() bool

IsRemote returns true if using a remote database

func (*MixedDB) Ping

func (mdb *MixedDB) Ping(ctx context.Context) error

Ping checks database connectivity

func (*MixedDB) Query

func (mdb *MixedDB) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query executes a query that returns rows

func (*MixedDB) QueryRow

func (mdb *MixedDB) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRow executes a query that returns a single row

func (*MixedDB) SupportsReturning

func (mdb *MixedDB) SupportsReturning() bool

SupportsReturning returns true if the database supports RETURNING clause

func (*MixedDB) SupportsUpsert

func (mdb *MixedDB) SupportsUpsert() bool

SupportsUpsert returns true if the database supports upsert operations

type MixedModeConfig

type MixedModeConfig struct {
	// ServerDBConfig for server.db (admin credentials, scheduler, audit)
	// Can be SQLite, PostgreSQL, or MySQL
	ServerDB DatabaseBackendConfig `yaml:"server_db"`

	// UsersDBConfig for user.db (user accounts, sessions)
	// Can be SQLite, PostgreSQL, or MySQL
	UsersDB DatabaseBackendConfig `yaml:"users_db"`
}

MixedModeConfig holds configuration for mixed mode database operation Per AI.md PART 24: Mixed Mode (heterogeneous database backends)

func DefaultMixedModeConfig

func DefaultMixedModeConfig(dataDir string) *MixedModeConfig

DefaultMixedModeConfig returns default mixed mode configuration Both databases use SQLite by default (standalone mode)

type MixedModeManager

type MixedModeManager struct {
	// contains filtered or unexported fields
}

MixedModeManager manages databases with potentially different backends Per AI.md PART 24: Mixed Mode (heterogeneous database backends)

func NewMixedModeManager

func NewMixedModeManager(cfg *MixedModeConfig) (*MixedModeManager, error)

NewMixedModeManager creates a new mixed mode manager

func (*MixedModeManager) Close

func (mm *MixedModeManager) Close() error

Close closes both database connections

func (*MixedModeManager) GetMode

func (mm *MixedModeManager) GetMode() string

GetMode returns a string describing the current mode

func (*MixedModeManager) GetStatus

func (mm *MixedModeManager) GetStatus() map[string]interface{}

GetStatus returns detailed status information

func (*MixedModeManager) IsMixedMode

func (mm *MixedModeManager) IsMixedMode() bool

IsMixedMode returns true if the databases use different backends

func (*MixedModeManager) IsReady

func (mm *MixedModeManager) IsReady() bool

IsReady returns true if both databases are ready

func (*MixedModeManager) ServerDB

func (mm *MixedModeManager) ServerDB() *MixedDB

ServerDB returns the server database

func (*MixedModeManager) UsersDB

func (mm *MixedModeManager) UsersDB() *MixedDB

UsersDB returns the users database

type NodeStatus

type NodeStatus string

NodeStatus represents a cluster node's status

const (
	NodeStatusOnline  NodeStatus = "online"
	NodeStatusOffline NodeStatus = "offline"
	NodeStatusJoining NodeStatus = "joining"
	NodeStatusLeaving NodeStatus = "leaving"
)

type RemoteDB

type RemoteDB struct {
	// contains filtered or unexported fields
}

RemoteDB represents a connection to a remote database

func NewRemoteDB

func NewRemoteDB(cfg *RemoteDBConfig) (*RemoteDB, error)

NewRemoteDB creates a new remote database connection

func (*RemoteDB) Close

func (rdb *RemoteDB) Close() error

Close closes the remote database connection

func (*RemoteDB) DB

func (rdb *RemoteDB) DB() *sql.DB

DB returns the underlying sql.DB

func (*RemoteDB) IsReady

func (rdb *RemoteDB) IsReady() bool

IsReady returns true if the remote database is ready

type RemoteDBConfig

type RemoteDBConfig struct {
	Driver   string `yaml:"driver"`   // postgres, mysql
	Host     string `yaml:"host"`     // database host
	Port     int    `yaml:"port"`     // database port
	Database string `yaml:"database"` // database name
	Username string `yaml:"username"` // database user
	Password string `yaml:"password"` // database password
	SSLMode  string `yaml:"ssl_mode"` // disable, require, verify-ca, verify-full (postgres)
	Options  string `yaml:"options"`  // additional connection options
}

RemoteDBConfig holds configuration for remote database connections Per AI.md PART 24: Remote database support (PostgreSQL, MySQL/MariaDB)

func DefaultRemoteDBConfig

func DefaultRemoteDBConfig() *RemoteDBConfig

DefaultRemoteDBConfig returns default remote database configuration

func (*RemoteDBConfig) BuildDSN

func (r *RemoteDBConfig) BuildDSN() string

BuildDSN builds the connection string for the remote database Per AI.md PART 6-10: Multi-database driver support

type Repository

type Repository struct {
	// contains filtered or unexported fields
}

Repository provides database operations

func NewRepository

func NewRepository(db *DB) *Repository

NewRepository creates a new repository

func (*Repository) BlockIP

func (r *Repository) BlockIP(ctx context.Context, ip *BlockedIP) error

BlockIP blocks an IP address

func (*Repository) CleanupOldAuditLogs

func (r *Repository) CleanupOldAuditLogs(ctx context.Context, olderThanDays int) (int64, error)

CleanupOldAuditLogs removes audit logs older than specified days

func (*Repository) CreateAPIToken

func (r *Repository) CreateAPIToken(ctx context.Context, token *APIToken) error

CreateAPIToken creates a new API token

func (*Repository) CreateAdminSession

func (r *Repository) CreateAdminSession(ctx context.Context, session *AdminSession) error

CreateAdminSession creates a new admin session

func (*Repository) CreateAdminUser

func (r *Repository) CreateAdminUser(ctx context.Context, user *AdminUser) error

CreateAdminUser creates a new admin user

func (*Repository) DeleteAPIToken

func (r *Repository) DeleteAPIToken(ctx context.Context, tokenID int64) error

DeleteAPIToken deletes an API token

func (*Repository) DeleteAdminSession

func (r *Repository) DeleteAdminSession(ctx context.Context, token string) error

DeleteAdminSession deletes a session

func (*Repository) DeleteExpiredSessions

func (r *Repository) DeleteExpiredSessions(ctx context.Context) (int64, error)

DeleteExpiredSessions removes all expired sessions

func (*Repository) GetAPITokenByToken

func (r *Repository) GetAPITokenByToken(ctx context.Context, token string) (*APIToken, error)

GetAPITokenByToken retrieves an API token

func (*Repository) GetAdminSessionByToken

func (r *Repository) GetAdminSessionByToken(ctx context.Context, token string) (*AdminSession, error)

GetAdminSessionByToken retrieves a session by token

func (*Repository) GetAdminUserByID

func (r *Repository) GetAdminUserByID(ctx context.Context, id int64) (*AdminUser, error)

GetAdminUserByID retrieves an admin user by ID

func (*Repository) GetAdminUserByUsername

func (r *Repository) GetAdminUserByUsername(ctx context.Context, username string) (*AdminUser, error)

GetAdminUserByUsername retrieves an admin user by username

func (*Repository) GetAuditLog

func (r *Repository) GetAuditLog(ctx context.Context, limit, offset int) ([]*AuditLogEntry, error)

GetAuditLog retrieves audit log entries

func (*Repository) GetSearchStats

func (r *Repository) GetSearchStats(ctx context.Context, startDate, endDate time.Time) ([]*SearchStats, error)

GetSearchStats retrieves search statistics for a date range

func (*Repository) IsIPBlocked

func (r *Repository) IsIPBlocked(ctx context.Context, ipAddress string) (bool, error)

IsIPBlocked checks if an IP is blocked

func (*Repository) ListAPITokens

func (r *Repository) ListAPITokens(ctx context.Context) ([]*APIToken, error)

ListAPITokens lists all API tokens

func (*Repository) ListBlockedIPs

func (r *Repository) ListBlockedIPs(ctx context.Context) ([]*BlockedIP, error)

ListBlockedIPs lists all blocked IPs

func (*Repository) RecordAudit

func (r *Repository) RecordAudit(ctx context.Context, entry *AuditLogEntry) error

RecordAudit records an audit log entry

func (*Repository) RecordSearchStats

func (r *Repository) RecordSearchStats(ctx context.Context, queryCount, resultCount int, responseTime float64, engines, categories []string) error

RecordSearchStats records search statistics

func (*Repository) UnblockIP

func (r *Repository) UnblockIP(ctx context.Context, ipAddress string) error

UnblockIP removes an IP block

func (*Repository) UpdateAPITokenLastUsed

func (r *Repository) UpdateAPITokenLastUsed(ctx context.Context, tokenID int64) error

UpdateAPITokenLastUsed updates the last used time

func (*Repository) UpdateAdminUserLastLogin

func (r *Repository) UpdateAdminUserLastLogin(ctx context.Context, userID int64) error

UpdateAdminUserLastLogin updates the last login time

type SearchStats

type SearchStats struct {
	ID              int64     `json:"id"`
	Date            time.Time `json:"date"`
	Hour            int       `json:"hour"`
	QueryCount      int       `json:"query_count"`
	ResultCount     int       `json:"result_count"`
	AvgResponseTime float64   `json:"avg_response_time"`
	EnginesUsed     []string  `json:"engines_used,omitempty"`
	Categories      []string  `json:"categories,omitempty"`
}

SearchStats represents search statistics

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL