database

package
v0.0.0-...-f26e2e9 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2025 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Alert

type Alert struct {
	ID             string     `db:"id" json:"id"`
	Name           string     `db:"name" json:"name"`
	Description    string     `db:"description" json:"description"`
	Severity       string     `db:"severity" json:"severity"`
	Status         string     `db:"status" json:"status"`
	Resource       string     `db:"resource" json:"resource"`
	ResourceID     *string    `db:"resource_id" json:"resource_id,omitempty"`
	MetricName     string     `db:"metric_name" json:"metric_name"`
	Threshold      float64    `db:"threshold" json:"threshold"`
	CurrentValue   float64    `db:"current_value" json:"current_value"`
	Labels         JSONB      `db:"labels" json:"labels,omitempty"`
	StartTime      time.Time  `db:"start_time" json:"start_time"`
	EndTime        *time.Time `db:"end_time" json:"end_time,omitempty"`
	AcknowledgedBy *string    `db:"acknowledged_by" json:"acknowledged_by,omitempty"`
	AcknowledgedAt *time.Time `db:"acknowledged_at" json:"acknowledged_at,omitempty"`
	CreatedAt      time.Time  `db:"created_at" json:"created_at"`
	UpdatedAt      time.Time  `db:"updated_at" json:"updated_at"`
}

Alert represents an alert in the database

type AlertRepository

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

AlertRepository provides database operations for alerts

func NewAlertRepository

func NewAlertRepository(db *DB) *AlertRepository

NewAlertRepository creates a new alert repository

func (*AlertRepository) Acknowledge

func (r *AlertRepository) Acknowledge(ctx context.Context, alertID, acknowledgedBy string) error

Acknowledge acknowledges an alert

func (*AlertRepository) Create

func (r *AlertRepository) Create(ctx context.Context, alert *Alert) error

Create creates a new alert

func (*AlertRepository) GetActive

func (r *AlertRepository) GetActive(ctx context.Context) ([]*Alert, error)

GetActive retrieves all active alerts

type AuditLog

type AuditLog struct {
	ID           int       `db:"id" json:"id"`
	UserID       *int      `db:"user_id" json:"user_id,omitempty"`
	Action       string    `db:"action" json:"action"`
	Resource     string    `db:"resource" json:"resource"`
	ResourceID   *string   `db:"resource_id" json:"resource_id,omitempty"`
	Details      JSONB     `db:"details" json:"details,omitempty"`
	IPAddress    string    `db:"ip_address" json:"ip_address"`
	UserAgent    string    `db:"user_agent" json:"user_agent"`
	Success      bool      `db:"success" json:"success"`
	ErrorMessage *string   `db:"error_message" json:"error_message,omitempty"`
	Timestamp    time.Time `db:"timestamp" json:"timestamp"`
}

AuditLog represents an audit log entry

type AuditRepository

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

AuditRepository provides database operations for audit logs

func NewAuditRepository

func NewAuditRepository(db *DB) *AuditRepository

NewAuditRepository creates a new audit repository

func (*AuditRepository) Log

func (r *AuditRepository) Log(ctx context.Context, entry *AuditLog) error

Log creates an audit log entry

type CacheEntry

type CacheEntry struct {
	Data      interface{}
	ExpiresAt time.Time
	Size      int
}

CacheEntry represents a cached query result

type ConnectionPoolConfig

type ConnectionPoolConfig struct {
	MaxOpenConns        int           // Maximum open connections
	MaxIdleConns        int           // Maximum idle connections
	ConnMaxLifetime     time.Duration // Maximum connection lifetime
	ConnMaxIdleTime     time.Duration // Maximum idle time
	HealthCheckInterval time.Duration // Health check interval
}

ConnectionPoolConfig optimized for high performance

func DefaultPoolConfig

func DefaultPoolConfig() ConnectionPoolConfig

DefaultPoolConfig returns optimized connection pool settings

type DB

type DB struct {
	*sqlx.DB
}

DB wraps sqlx.DB with additional functionality

func New

func New(databaseURL string) (*DB, error)

New creates a new database connection

type JSONB

type JSONB map[string]interface{}

JSONB represents a PostgreSQL JSONB field

func (*JSONB) Scan

func (j *JSONB) Scan(value interface{}) error

Scan implements the sql.Scanner interface for JSONB

func (JSONB) Value

func (j JSONB) Value() (driver.Value, error)

Value implements the driver.Valuer interface for JSONB

type MetricsRepository

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

MetricsRepository provides database operations for metrics

func NewMetricsRepository

func NewMetricsRepository(db *DB) *MetricsRepository

NewMetricsRepository creates a new metrics repository

func (*MetricsRepository) CreateSystemMetric

func (r *MetricsRepository) CreateSystemMetric(ctx context.Context, metric *SystemMetric) error

CreateSystemMetric creates a system metric record

func (*MetricsRepository) CreateVMMetric

func (r *MetricsRepository) CreateVMMetric(ctx context.Context, metric *VMMetric) error

CreateVMMetric creates a new VM metric record

func (*MetricsRepository) GetLatestVMMetrics

func (r *MetricsRepository) GetLatestVMMetrics(ctx context.Context) ([]*VMMetric, error)

GetLatestVMMetrics retrieves the latest metrics for all VMs with optimized query

func (*MetricsRepository) GetSystemMetrics

func (r *MetricsRepository) GetSystemMetrics(ctx context.Context, nodeID string, start, end time.Time) ([]*SystemMetric, error)

GetSystemMetrics retrieves system metrics within a time range

func (*MetricsRepository) GetVMMetrics

func (r *MetricsRepository) GetVMMetrics(ctx context.Context, vmID string, start, end time.Time) ([]*VMMetric, error)

GetVMMetrics retrieves VM metrics within a time range

type Migration

type Migration struct {
	ID               string     `db:"id" json:"id"`
	VMID             string     `db:"vm_id" json:"vm_id"`
	SourceNodeID     string     `db:"source_node_id" json:"source_node_id"`
	TargetNodeID     string     `db:"target_node_id" json:"target_node_id"`
	Type             string     `db:"type" json:"type"`     // cold, warm, live
	Status           string     `db:"status" json:"status"` // pending, running, completed, failed
	Progress         float64    `db:"progress" json:"progress"`
	BytesTotal       int64      `db:"bytes_total" json:"bytes_total"`
	BytesTransferred int64      `db:"bytes_transferred" json:"bytes_transferred"`
	StartedAt        *time.Time `db:"started_at" json:"started_at,omitempty"`
	CompletedAt      *time.Time `db:"completed_at" json:"completed_at,omitempty"`
	ErrorMessage     *string    `db:"error_message" json:"error_message,omitempty"`
	CreatedAt        time.Time  `db:"created_at" json:"created_at"`
	UpdatedAt        time.Time  `db:"updated_at" json:"updated_at"`
}

Migration represents a VM migration record

type Node

type Node struct {
	ID           string    `db:"id" json:"id"`
	Name         string    `db:"name" json:"name"`
	Address      string    `db:"address" json:"address"`
	Status       string    `db:"status" json:"status"` // online, offline, maintenance
	Capabilities JSONB     `db:"capabilities" json:"capabilities,omitempty"`
	Resources    JSONB     `db:"resources" json:"resources,omitempty"`
	Labels       JSONB     `db:"labels" json:"labels,omitempty"`
	LastSeen     time.Time `db:"last_seen" json:"last_seen"`
	CreatedAt    time.Time `db:"created_at" json:"created_at"`
	UpdatedAt    time.Time `db:"updated_at" json:"updated_at"`
}

Node represents a hypervisor node in the cluster

type OptimizedDB

type OptimizedDB struct {
	*sqlx.DB
	// contains filtered or unexported fields
}

OptimizedDB wraps sqlx.DB with query optimization features

func NewOptimized

func NewOptimized(databaseURL string, config ConnectionPoolConfig) (*OptimizedDB, error)

NewOptimized creates an optimized database connection

func (*OptimizedDB) Close

func (db *OptimizedDB) Close() error

Close closes the database connection and cleans up resources

func (*OptimizedDB) GetCacheStats

func (db *OptimizedDB) GetCacheStats() map[string]interface{}

GetCacheStats returns cache statistics

func (*OptimizedDB) GetPrepared

func (db *OptimizedDB) GetPrepared(key, query string) (*sqlx.Stmt, error)

GetPrepared returns a cached prepared statement or creates a new one

func (*OptimizedDB) PrepareNamed

func (db *OptimizedDB) PrepareNamed(query string) (*sqlx.NamedStmt, error)

PrepareNamed prepares and caches a named query

func (*OptimizedDB) QueryWithCache

func (db *OptimizedDB) QueryWithCache(ctx context.Context, key string, dest interface{}, query string, args ...interface{}) error

QueryWithCache executes a query with caching

type OptimizedVMRepository

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

OptimizedVMRepository with query optimization

func NewOptimizedVMRepository

func NewOptimizedVMRepository(db *OptimizedDB) *OptimizedVMRepository

NewOptimizedVMRepository creates an optimized VM repository

func (*OptimizedVMRepository) BulkInsertMetrics

func (r *OptimizedVMRepository) BulkInsertMetrics(ctx context.Context, metrics []VMMetric) error

BulkInsertMetrics efficiently inserts multiple metrics using COPY

func (*OptimizedVMRepository) GetDashboardStats

func (r *OptimizedVMRepository) GetDashboardStats(ctx context.Context, orgID string) (map[string]interface{}, error)

GetDashboardStats retrieves pre-computed dashboard statistics

func (*OptimizedVMRepository) GetNodeCapacity

func (r *OptimizedVMRepository) GetNodeCapacity(ctx context.Context) ([]map[string]interface{}, error)

GetNodeCapacity retrieves node capacity using materialized view

func (*OptimizedVMRepository) GetVMMetricsOptimized

func (r *OptimizedVMRepository) GetVMMetricsOptimized(ctx context.Context, vmID string, start, end time.Time) ([]*VMMetric, error)

GetVMMetricsOptimized retrieves metrics using appropriate materialized view

func (*OptimizedVMRepository) ListVMsFast

func (r *OptimizedVMRepository) ListVMsFast(ctx context.Context, filters map[string]interface{}) ([]*VM, error)

ListVMsFast uses materialized view for fast VM listing

type QueryCache

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

QueryCache implements an LRU cache for query results

func (*QueryCache) Get

func (c *QueryCache) Get(key string) interface{}

Cache methods

func (*QueryCache) GetHitRate

func (c *QueryCache) GetHitRate() float64

func (*QueryCache) Set

func (c *QueryCache) Set(key string, data interface{}, ttl time.Duration)

type QueryMetrics

type QueryMetrics struct {
	Query        string
	Duration     time.Duration
	RowsAffected int64
	CacheHit     bool
	Timestamp    time.Time
}

QueryMetrics tracks query performance

type Repositories

type Repositories struct {
	Users    *UserRepository
	VMs      *VMRepository
	Metrics  *MetricsRepository
	Alerts   *AlertRepository
	Audit    *AuditRepository
	Sessions *SessionRepository
}

Repositories bundles all repositories together

func NewRepositories

func NewRepositories(db *DB) *Repositories

NewRepositories creates all repositories

type Session

type Session struct {
	ID        string    `db:"id" json:"id"`
	UserID    int       `db:"user_id" json:"user_id"`
	Token     string    `db:"token" json:"-"`
	ExpiresAt time.Time `db:"expires_at" json:"expires_at"`
	IPAddress string    `db:"ip_address" json:"ip_address"`
	UserAgent string    `db:"user_agent" json:"user_agent"`
	IsActive  bool      `db:"is_active" json:"is_active"`
	CreatedAt time.Time `db:"created_at" json:"created_at"`
	UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
}

Session represents a user session

type SessionRepository

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

SessionRepository provides database operations for sessions

func NewSessionRepository

func NewSessionRepository(db *DB) *SessionRepository

NewSessionRepository creates a new session repository

func (*SessionRepository) Create

func (r *SessionRepository) Create(ctx context.Context, session *Session) error

Create creates a new session

func (*SessionRepository) GetByToken

func (r *SessionRepository) GetByToken(ctx context.Context, token string) (*Session, error)

GetByToken retrieves a session by token

func (*SessionRepository) Invalidate

func (r *SessionRepository) Invalidate(ctx context.Context, token string) error

Invalidate invalidates a session

type SystemMetric

type SystemMetric struct {
	ID              int       `db:"id" json:"id"`
	NodeID          string    `db:"node_id" json:"node_id"`
	CPUUsage        float64   `db:"cpu_usage" json:"cpu_usage"`
	MemoryUsage     float64   `db:"memory_usage" json:"memory_usage"`
	MemoryTotal     int64     `db:"memory_total" json:"memory_total"`
	MemoryAvailable int64     `db:"memory_available" json:"memory_available"`
	DiskUsage       float64   `db:"disk_usage" json:"disk_usage"`
	DiskTotal       int64     `db:"disk_total" json:"disk_total"`
	DiskAvailable   int64     `db:"disk_available" json:"disk_available"`
	NetworkSent     int64     `db:"network_sent" json:"network_sent"`
	NetworkRecv     int64     `db:"network_recv" json:"network_recv"`
	LoadAverage1    float64   `db:"load_average_1" json:"load_average_1"`
	LoadAverage5    float64   `db:"load_average_5" json:"load_average_5"`
	LoadAverage15   float64   `db:"load_average_15" json:"load_average_15"`
	Timestamp       time.Time `db:"timestamp" json:"timestamp"`
}

SystemMetric represents system-wide performance metrics

type User

type User struct {
	ID           int       `db:"id" json:"id"`
	Username     string    `db:"username" json:"username"`
	Email        string    `db:"email" json:"email"`
	PasswordHash string    `db:"password_hash" json:"-"`
	Role         string    `db:"role" json:"role"`
	TenantID     string    `db:"tenant_id" json:"tenant_id"`
	CreatedAt    time.Time `db:"created_at" json:"created_at"`
	UpdatedAt    time.Time `db:"updated_at" json:"updated_at"`
}

User represents a user in the database

type UserRepository

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

UserRepository provides database operations for users

func NewUserRepository

func NewUserRepository(db *DB) *UserRepository

NewUserRepository creates a new user repository

func (*UserRepository) Create

func (r *UserRepository) Create(ctx context.Context, user *User) error

Create creates a new user

func (*UserRepository) GetByID

func (r *UserRepository) GetByID(ctx context.Context, id int) (*User, error)

GetByID retrieves a user by ID

func (*UserRepository) GetByUsername

func (r *UserRepository) GetByUsername(ctx context.Context, username string) (*User, error)

GetByUsername retrieves a user by username

type VM

type VM struct {
	ID        string    `db:"id" json:"id"`
	Name      string    `db:"name" json:"name"`
	State     string    `db:"state" json:"state"`
	NodeID    *string   `db:"node_id" json:"node_id,omitempty"`
	OwnerID   *int      `db:"owner_id" json:"owner_id,omitempty"`
	TenantID  string    `db:"tenant_id" json:"tenant_id"`
	Config    JSONB     `db:"config" json:"config,omitempty"`
	CreatedAt time.Time `db:"created_at" json:"created_at"`
	UpdatedAt time.Time `db:"updated_at" json:"updated_at"`

	// Preloaded relationships to prevent N+1 queries
	OwnerUsername string  `db:"-" json:"owner_username,omitempty"`
	TenantName    string  `db:"-" json:"tenant_name,omitempty"`
	LatestCPU     float64 `db:"-" json:"latest_cpu,omitempty"`
	LatestMemory  float64 `db:"-" json:"latest_memory,omitempty"`
}

VM represents a virtual machine in the database with preloaded relationships

type VMMetric

type VMMetric struct {
	ID          int       `db:"id" json:"id"`
	VMID        string    `db:"vm_id" json:"vm_id"`
	CPUUsage    float64   `db:"cpu_usage" json:"cpu_usage"`
	MemoryUsage float64   `db:"memory_usage" json:"memory_usage"`
	DiskUsage   float64   `db:"disk_usage" json:"disk_usage"`
	NetworkSent int64     `db:"network_sent" json:"network_sent"`
	NetworkRecv int64     `db:"network_recv" json:"network_recv"`
	IOPS        int       `db:"iops" json:"iops"`
	Timestamp   time.Time `db:"timestamp" json:"timestamp"`
}

VMMetric represents VM performance metrics in the database

type VMRepository

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

VMRepository provides database operations for VMs

func NewVMRepository

func NewVMRepository(db *DB) *VMRepository

NewVMRepository creates a new VM repository

func (*VMRepository) Create

func (r *VMRepository) Create(ctx context.Context, vm *VM) error

Create creates a new VM record

func (*VMRepository) Delete

func (r *VMRepository) Delete(ctx context.Context, id string) error

Delete deletes a VM record

func (*VMRepository) GetByID

func (r *VMRepository) GetByID(ctx context.Context, id string) (*VM, error)

GetByID retrieves a VM by ID

func (*VMRepository) List

func (r *VMRepository) List(ctx context.Context, filters map[string]interface{}) ([]*VM, error)

List retrieves all VMs with optional filtering and eager loading to prevent N+1 queries

func (*VMRepository) Update

func (r *VMRepository) Update(ctx context.Context, vm *VM) error

Update updates a VM record

Jump to

Keyboard shortcuts

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