db

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2025 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Database

type Database struct {
	ReaderDb *sqlx.DB // Database connection for read operations
	// contains filtered or unexported fields
}

Database manages SQLite database connections with WAL mode and connection pooling. It provides both reader and writer connections with mutex protection for write operations and embedded schema migration support using goose.

func NewDatabase

func NewDatabase(config *SqliteDatabaseConfig, logger logrus.FieldLogger) *Database

NewDatabase creates a new Database instance with the specified configuration and logger. The database connections are not initialized until Init() is called.

func (*Database) ApplyEmbeddedDbSchema

func (d *Database) ApplyEmbeddedDbSchema(version int64) error

ApplyEmbeddedDbSchema applies database schema migrations using embedded SQL files. Supports different migration strategies: -2 (all), -1 (one up), or specific version. Uses goose migration library with allowMissing option for flexible schema management.

func (*Database) Close

func (d *Database) Close() error

Close closes the database writer connection. Should be called during application shutdown to ensure proper cleanup.

func (*Database) CountNodes

func (d *Database) CountNodes() (int, error)

CountNodes returns the total number of nodes.

func (*Database) DeleteNode

func (d *Database) DeleteNode(tx *sqlx.Tx, nodeID []byte) error

DeleteNode removes a node from the database within a transaction.

func (*Database) DeleteNodesBefore

func (d *Database) DeleteNodesBefore(tx *sqlx.Tx, timestamp int64) (int64, error)

DeleteNodesBefore removes nodes with last_active older than the given timestamp.

func (*Database) DeleteState

func (d *Database) DeleteState(tx *sqlx.Tx, key string) error

DeleteState removes a state entry by key.

func (*Database) GetInactiveNodes

func (d *Database) GetInactiveNodes(n int) ([]*Node, error)

GetInactiveNodes retrieves N nodes ordered by oldest last_active time. Nodes with NULL last_active (never active) are returned first.

func (*Database) GetNode

func (d *Database) GetNode(nodeID []byte) (*Node, error)

GetNode retrieves a single node by ID from the database.

func (*Database) GetNodes

func (d *Database) GetNodes() ([]*Node, error)

GetNodes retrieves all nodes from the database.

func (*Database) GetRandomNodes

func (d *Database) GetRandomNodes(n int) ([]*Node, error)

GetRandomNodes retrieves N random nodes from the database.

func (*Database) GetState

func (d *Database) GetState(key string) ([]byte, error)

GetState retrieves a state value by key.

func (*Database) GetStats

func (d *Database) GetStats() DatabaseStats

GetStats returns database statistics from the SQL driver.

func (*Database) Init

func (d *Database) Init() error

Init initializes the database connections with WAL mode and connection pooling. Sets default connection limits (50 max open, 10 max idle) if not specified. Enables WAL mode for better concurrent access and configures connection timeouts.

func (*Database) InsertNode

func (d *Database) InsertNode(tx *sqlx.Tx, node *Node) error

InsertNode creates a new node record in the database within a transaction.

func (*Database) NodeExists

func (d *Database) NodeExists(nodeID []byte) (bool, uint64, error)

NodeExists checks if a node exists in the database.

func (*Database) RunDBTransaction

func (d *Database) RunDBTransaction(handler func(tx *sqlx.Tx) error) error

RunDBTransaction executes a function within a database transaction with automatic rollback. The transaction is protected by a mutex to ensure sequential write operations. Automatically rolls back on error and commits on success.

func (*Database) SetState

func (d *Database) SetState(tx *sqlx.Tx, key string, value []byte) error

SetState stores a state value by key. If tx is nil, creates and manages its own transaction automatically.

func (*Database) UpdateNodeENR

func (d *Database) UpdateNodeENR(tx *sqlx.Tx, nodeID []byte, ip []byte, ipv6 []byte, port int, seq uint64, forkDigest []byte, enr []byte) error

UpdateNodeENR performs an ENR update that preserves stats and timestamps. On insert: creates node with ENR info and default stats (first_seen = now, others NULL/0) On update: updates only seq, enr, ip, ipv6, port, fork_digest (preserves all stats and timestamps)

func (*Database) UpdateNodeLastActive

func (d *Database) UpdateNodeLastActive(tx *sqlx.Tx, nodeID []byte, timestamp int64) error

UpdateNodeLastActive updates the last_active timestamp of a node.

func (*Database) UpdateNodeLastSeen

func (d *Database) UpdateNodeLastSeen(tx *sqlx.Tx, nodeID []byte, timestamp int64) error

UpdateNodeLastSeen updates only the last_seen timestamp.

func (*Database) UpdateNodeSeq

func (d *Database) UpdateNodeSeq(tx *sqlx.Tx, nodeID []byte, seq uint64, enr []byte) error

UpdateNodeSeq updates just the sequence number and ENR of a node.

func (*Database) UpsertNode

func (d *Database) UpsertNode(tx *sqlx.Tx, node *Node) error

UpsertNode inserts or updates a node record in the database within a transaction. Note: last_active is NOT updated by this method - use UpdateNodeLastActive() instead.

type DatabaseStats

type DatabaseStats struct {
	TotalQueries      int64         // Total queries from SQL driver stats
	Transactions      int64         // Total transactions executed
	OpenConnections   int           // Current number of open connections
	InUse             int           // Connections currently in use
	Idle              int           // Connections currently idle
	WaitCount         int64         // Total number of times waited for a connection
	WaitDuration      time.Duration // Total time blocked waiting for connections
	MaxIdleClosed     int64         // Total connections closed due to SetMaxIdleConns
	MaxLifetimeClosed int64         // Total connections closed due to SetConnMaxLifetime
}

DatabaseStats contains statistics about database operations.

type Node

type Node struct {
	NodeID       []byte        `db:"nodeid"`        // 32-byte node ID
	IP           []byte        `db:"ip"`            // IPv4 address (4 bytes)
	IPv6         []byte        `db:"ipv6"`          // IPv6 address (16 bytes)
	Port         int           `db:"port"`          // UDP port
	Seq          uint64        `db:"seq"`           // ENR sequence number
	ForkDigest   []byte        `db:"fork_digest"`   // 4-byte fork digest
	FirstSeen    int64         `db:"first_seen"`    // Unix timestamp
	LastSeen     sql.NullInt64 `db:"last_seen"`     // Unix timestamp (nullable)
	LastActive   sql.NullInt64 `db:"last_active"`   // Unix timestamp (nullable)
	ENR          []byte        `db:"enr"`           // RLP-encoded ENR
	SuccessCount int           `db:"success_count"` // Successful pings
	FailureCount int           `db:"failure_count"` // Failed pings
	AvgRTT       int           `db:"avg_rtt"`       // Average RTT in milliseconds
}

Node represents a discovered bootnode peer stored in the database.

type SqliteDatabaseConfig

type SqliteDatabaseConfig struct {
	File         string `yaml:"file"`         // Database file path
	MaxOpenConns int    `yaml:"maxOpenConns"` // Maximum number of open connections to the database
	MaxIdleConns int    `yaml:"maxIdleConns"` // Maximum number of idle connections in the pool
}

SqliteDatabaseConfig defines the configuration for SQLite database connections. It specifies the database file path and connection pool limits for managing concurrent database access efficiently.

type State

type State struct {
	Key   string `db:"key"`   // State key identifier
	Value []byte `db:"value"` // State value (raw bytes)
}

State represents a key-value pair for storing runtime state.

Jump to

Keyboard shortcuts

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