storage

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2025 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MaxCommandLength    = 65536 // Maximum command text length
	MaxWorkingDirLength = 4096  // Maximum working directory path length
	MaxHostnameLength   = 253   // RFC 1035 hostname limit
	MaxSessionIDLength  = 36    // UUID length
	MaxEnvironmentVars  = 100   // Maximum number of environment variables to store
	MaxEnvironmentSize  = 8192  // Maximum total size of environment data
	MaxNoteLength       = 1000  // Maximum note text length
	MaxTagLength        = 50    // Maximum tag name length
	MaxTagsPerCommand   = 5     // Maximum number of tags per command

	// Schema version constants
	CurrentSchemaVersion = 2
	MinSupportedVersion  = 1
)

Constants for database constraints and limits

View Source
const (
	SyncStatusLocal    = 0
	SyncStatusSynced   = 1
	SyncStatusConflict = 2
)

Sync status constants

Variables

View Source
var DatabaseConstraints = map[string]interface{}{
	"max_command_length":     MaxCommandLength,
	"max_working_dir_length": MaxWorkingDirLength,
	"max_hostname_length":    MaxHostnameLength,
	"max_session_id_length":  MaxSessionIDLength,
	"max_note_length":        MaxNoteLength,
	"max_tag_length":         MaxTagLength,
	"max_tags_per_command":   MaxTagsPerCommand,
	"current_schema_version": CurrentSchemaVersion,
}

DatabaseConstraints defines database-level constraints

Functions

This section is empty.

Types

type CommandRecord

type CommandRecord struct {
	// Database identifier
	ID int64 `json:"id"` // Database record ID for deletion operations

	// Core command information
	Command   string            `json:"command"`              // The actual command text
	ExitCode  int               `json:"exit_code"`            // Command exit code
	Duration  int64             `json:"duration_ms"`          // Execution duration in milliseconds
	Note      string            `json:"note,omitempty"`       // Optional user note about the command
	Tags      []string          `json:"tags,omitempty"`       // Optional tags for command categorization
	TagColors map[string]string `json:"tag_colors,omitempty"` // Optional per-command tag colors (tag_name -> hex_color)

	// Context information
	WorkingDir string `json:"working_dir"`  // Directory where command was executed
	Timestamp  int64  `json:"timestamp_ms"` // Unix timestamp in milliseconds
	SessionID  string `json:"session_id"`   // Session UUID
	Hostname   string `json:"hostname"`     // Machine hostname

	// Optional context
	GitRoot   string `json:"git_root,omitempty"`   // Git repository root if applicable
	GitBranch string `json:"git_branch,omitempty"` // Git branch if applicable
	GitCommit string `json:"git_commit,omitempty"` // Git commit hash if applicable

	// Environment context
	User        string            `json:"user"`                  // Username
	Shell       string            `json:"shell"`                 // Shell type (bash, zsh, etc.)
	TTY         string            `json:"tty,omitempty"`         // TTY device
	Environment map[string]string `json:"environment,omitempty"` // Relevant environment variables

	// Metadata
	Version   int   `json:"version"`       // Schema version for future compatibility
	CreatedAt int64 `json:"created_at_ms"` // Record creation timestamp

	// NEW: Sync-related fields (backward compatible)
	DeviceID   string `json:"device_id,omitempty"`
	RecordHash string `json:"record_hash,omitempty"`
	LastSynced *int64 `json:"last_synced,omitempty"` // Unix timestamp in ms
	SyncStatus int    `json:"sync_status,omitempty"` // 0=local, 1=synced, 2=conflict
}

CommandRecord represents a single command execution with all contextual information

func NewCommandRecord

func NewCommandRecord(command string, exitCode int, duration int64, workingDir, sessionID, hostname string) *CommandRecord

NewCommandRecord creates a new command record with current timestamp

func (*CommandRecord) AddTag added in v0.3.0

func (cr *CommandRecord) AddTag(tag string) error

AddTag adds a tag to the command if it doesn't already exist

func (*CommandRecord) ClearNote added in v0.2.0

func (cr *CommandRecord) ClearNote()

ClearNote removes the note from the command

func (*CommandRecord) ClearTagColor added in v0.3.0

func (cr *CommandRecord) ClearTagColor(tagName string)

ClearTagColor removes a tag's color from this command's TagColors

func (*CommandRecord) GetNotePreview added in v0.2.0

func (cr *CommandRecord) GetNotePreview(maxLength int) string

GetNotePreview returns a truncated preview of the note for display

func (*CommandRecord) GetTagColor added in v0.3.0

func (cr *CommandRecord) GetTagColor(tagName string) string

GetTagColor returns the color for a given tag name from this command's TagColors

func (*CommandRecord) GetTagsString added in v0.3.0

func (cr *CommandRecord) GetTagsString() string

GetTagsString returns tags as a comma-separated string

func (*CommandRecord) HasNote added in v0.2.0

func (cr *CommandRecord) HasNote() bool

HasNote returns true if the command has a note

func (*CommandRecord) HasTag added in v0.3.0

func (cr *CommandRecord) HasTag(tag string) bool

HasTag checks if the command has a specific tag

func (*CommandRecord) HasTagColor added in v0.3.0

func (cr *CommandRecord) HasTagColor(tagName string) bool

HasTagColor checks if this command has a specific color set for a tag

func (*CommandRecord) HasTags added in v0.3.0

func (cr *CommandRecord) HasTags() bool

HasTags returns true if the command has tags

func (*CommandRecord) IsNoteValid added in v0.2.0

func (cr *CommandRecord) IsNoteValid() bool

IsNoteValid validates the note length

func (*CommandRecord) IsValid

func (cr *CommandRecord) IsValid() bool

IsValid validates that the command record has required fields

func (*CommandRecord) MarkSynced

func (cr *CommandRecord) MarkSynced()

MarkSynced marks the record as successfully synced

func (*CommandRecord) NeedsSync

func (cr *CommandRecord) NeedsSync() bool

NeedsSync returns true if the record needs to be synced

func (*CommandRecord) RemoveTag added in v0.3.0

func (cr *CommandRecord) RemoveTag(tag string) bool

RemoveTag removes a tag from the command

func (*CommandRecord) SetNote added in v0.2.0

func (cr *CommandRecord) SetNote(note string) error

SetNote sets a note for the command with validation

func (*CommandRecord) SetTagColor added in v0.3.0

func (cr *CommandRecord) SetTagColor(tagName, color string)

SetTagColor sets the color for a tag in this command's TagColors

func (*CommandRecord) SetTags added in v0.3.0

func (cr *CommandRecord) SetTags(tags []string) error

SetTags sets the tags for the command with validation

type Database

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

Database wraps sql.DB with additional functionality for CommandChronicles

func NewDatabase

func NewDatabase(cfg *config.Config, opts *DatabaseOptions) (*Database, error)

NewDatabase creates a new database instance with the given configuration

func (*Database) BeginTransaction

func (db *Database) BeginTransaction() (*sql.Tx, error)

BeginTransaction is an alias for BeginTx for compatibility

func (*Database) BeginTx

func (db *Database) BeginTx() (*sql.Tx, error)

BeginTx starts a database transaction with proper context

func (*Database) CheckIntegrity

func (db *Database) CheckIntegrity() error

CheckIntegrity performs database integrity check

func (*Database) Close

func (db *Database) Close() error

Close closes the database connection

func (*Database) ExecContext

func (db *Database) ExecContext(query string, args ...interface{}) (sql.Result, error)

ExecContext executes a query with context and timeout

func (*Database) GetAllEncryptedRecords

func (db *Database) GetAllEncryptedRecords(tx *sql.Tx) ([]EncryptedHistoryRecord, error)

GetAllEncryptedRecords retrieves all encrypted records from the database

func (*Database) GetConfig

func (db *Database) GetConfig() *config.DatabaseConfig

GetConfig returns the database configuration

func (*Database) GetDB

func (db *Database) GetDB() *sql.DB

GetDB returns the underlying sql.DB instance

func (*Database) GetLastCommandTimestamp added in v0.2.0

func (db *Database) GetLastCommandTimestamp() (int64, error)

GetLastCommandTimestamp returns the timestamp of the most recent command

func (*Database) GetMigrator

func (db *Database) GetMigrator() *Migrator

GetMigrator returns the database migrator

func (*Database) GetPath

func (db *Database) GetPath() string

GetPath returns the database file path

func (*Database) GetSize

func (db *Database) GetSize() (int64, error)

GetSize returns the size of the database file in bytes

func (*Database) IsConnected

func (db *Database) IsConnected() bool

IsConnected returns true if the database connection is active

func (*Database) QueryContext

func (db *Database) QueryContext(query string, args ...interface{}) (*sql.Rows, error)

QueryContext executes a query with context and timeout

func (*Database) QueryRowContext

func (db *Database) QueryRowContext(query string, args ...interface{}) *sql.Row

QueryRowContext executes a query expecting a single row with context and timeout

func (*Database) SetSecureDeleteMode

func (db *Database) SetSecureDeleteMode(enabled bool) error

SetSecureDeleteMode enables or disables secure delete

func (*Database) Stats

func (db *Database) Stats() sql.DBStats

Stats returns database statistics

func (*Database) UpdateEncryptedData

func (db *Database) UpdateEncryptedData(tx *sql.Tx, recordID int64, newEncryptedData []byte) error

UpdateEncryptedData updates the encrypted data for a specific record

func (*Database) Vacuum

func (db *Database) Vacuum() error

Vacuum performs database maintenance

type DatabaseOptions

type DatabaseOptions struct {
	Config          *config.DatabaseConfig
	CreateIfMissing bool
	MigrateOnOpen   bool
	ValidateSchema  bool
}

DatabaseOptions contains options for database initialization

type DatabaseSchema

type DatabaseSchema struct {
	// Current schema version
	Version int

	// DDL statements
	Tables  []string
	Indexes []string

	// Migration statements for future use
	Migrations map[int][]string
}

DatabaseSchema contains all SQL statements for database initialization

func GetCurrentSchema

func GetCurrentSchema() *DatabaseSchema

GetCurrentSchema returns the current database schema

type EncryptedHistoryRecord

type EncryptedHistoryRecord struct {
	ID            int64  `db:"id"`
	EncryptedData []byte `db:"encrypted_data"` // Encrypted CommandRecord JSON
	Timestamp     int64  `db:"timestamp"`      // Unencrypted timestamp for indexing
	Session       string `db:"session"`        // Unencrypted session ID for filtering
	Hostname      string `db:"hostname"`       // Unencrypted hostname for filtering
	CreatedAt     int64  `db:"created_at"`     // Record insertion timestamp
}

EncryptedHistoryRecord represents a row in the history table

func (*EncryptedHistoryRecord) GetSearchableFields

func (ehr *EncryptedHistoryRecord) GetSearchableFields() map[string]interface{}

GetSearchableFields returns fields that can be searched without decryption

type Migrator

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

Migrator handles database schema migrations

func NewMigrator

func NewMigrator(db *sql.DB, schema *DatabaseSchema) *Migrator

NewMigrator creates a new database migrator

func (*Migrator) CheckIntegrity

func (m *Migrator) CheckIntegrity() error

CheckIntegrity performs a comprehensive database integrity check

func (*Migrator) GetCurrentVersion

func (m *Migrator) GetCurrentVersion() (int, error)

GetCurrentVersion returns the current schema version from the database

func (*Migrator) GetMigrationHistory

func (m *Migrator) GetMigrationHistory() ([]SchemaVersion, error)

GetMigrationHistory returns the migration history

func (*Migrator) InitializeSchema

func (m *Migrator) InitializeSchema() error

InitializeSchema creates the initial database schema

func (*Migrator) MigrateToLatest

func (m *Migrator) MigrateToLatest() error

MigrateToLatest migrates the database to the latest schema version

func (*Migrator) ValidateSchema

func (m *Migrator) ValidateSchema() error

ValidateSchema performs integrity checks on the database schema

type SchemaVersion

type SchemaVersion struct {
	Version     int    `db:"version"`
	AppliedAt   int64  `db:"applied_at"`
	Description string `db:"description"`
}

SchemaVersion represents the schema version tracking

type SessionMetadata

type SessionMetadata struct {
	SessionID string `db:"session_id"`
	StartTime int64  `db:"start_time"`
	EndTime   *int64 `db:"end_time"` // NULL until session ends
	Hostname  string `db:"hostname"`
	UserName  string `db:"user_name"`
	ShellType string `db:"shell_type"`
	CreatedAt int64  `db:"created_at"`
}

SessionMetadata represents session tracking information

Jump to

Keyboard shortcuts

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