summaryrefslogtreecommitdiff
path: root/internal
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2026-02-28 09:43:12 +0200
committerPaul Buetow <paul@buetow.org>2026-02-28 09:43:12 +0200
commit5c320247d048da36c74b854d6b83db58e93e8121 (patch)
tree57d08eeb2e524dbeb6d2ea1cda8e55b001a927bc /internal
parent2a342d06c161fe9f5e9e6c48ed23798b876393be (diff)
refactor: split ImportFromDir into smaller functions
Extract per-file import logic into importFile helper. ImportFromDir reduced from 82 to 45 lines. Uses defer f.Close() for cleaner resource management. Task: 26d657e0-5d41-4953-adb7-38322618505a Amp-Thread-ID: https://ampcode.com/threads/T-019ca323-dde1-73ac-97f0-cebfae5922a5 Co-authored-by: Amp <amp@ampcode.com>
Diffstat (limited to 'internal')
-rw-r--r--internal/goprecords/db.go43
1 files changed, 24 insertions, 19 deletions
diff --git a/internal/goprecords/db.go b/internal/goprecords/db.go
index c11cdb0..8fa8b60 100644
--- a/internal/goprecords/db.go
+++ b/internal/goprecords/db.go
@@ -89,25 +89,8 @@ func ImportFromDir(ctx context.Context, db *sql.DB, statsDir string) error {
if idx := strings.Index(host, "."); idx > 0 {
host = host[:idx]
}
- f, err := os.Open(path)
- if err != nil {
- return fmt.Errorf("open %s: %w", path, err)
- }
- sc := bufio.NewScanner(f)
- for sc.Scan() {
- rec, ok := parseRecordLine(sc.Text())
- if !ok {
- continue
- }
- _, err := insert.ExecContext(ctx, host, rec.Uptime, rec.BootTime, rec.OS, rec.KernelName, rec.KernelMajor)
- if err != nil {
- f.Close()
- return fmt.Errorf("insert: %w", err)
- }
- }
- f.Close()
- if err := sc.Err(); err != nil {
- return fmt.Errorf("scan %s: %w", path, err)
+ if err := importFile(ctx, insert, path, host); err != nil {
+ return err
}
}
@@ -117,6 +100,28 @@ func ImportFromDir(ctx context.Context, db *sql.DB, statsDir string) error {
return nil
}
+func importFile(ctx context.Context, insert *sql.Stmt, path, host string) error {
+ f, err := os.Open(path)
+ if err != nil {
+ return fmt.Errorf("open %s: %w", path, err)
+ }
+ defer f.Close()
+ sc := bufio.NewScanner(f)
+ for sc.Scan() {
+ rec, ok := parseRecordLine(sc.Text())
+ if !ok {
+ continue
+ }
+ if _, err := insert.ExecContext(ctx, host, rec.Uptime, rec.BootTime, rec.OS, rec.KernelName, rec.KernelMajor); err != nil {
+ return fmt.Errorf("insert: %w", err)
+ }
+ }
+ if err := sc.Err(); err != nil {
+ return fmt.Errorf("scan %s: %w", path, err)
+ }
+ return nil
+}
+
// LoadAggregates reads all rows from the DB and builds Aggregates (same shape as file-based aggregation).
func LoadAggregates(ctx context.Context, db *sql.DB) (*Aggregates, error) {
rows, err := db.QueryContext(ctx, "SELECT host, uptime_sec, boot_time, os, os_kernel_name, os_kernel_major FROM record ORDER BY host, boot_time")