Files
HackBrowserData/internal/sqlitex/query.go
T
Roger 3e9150249c refactor: rename core types and spell out every name (#677)
Def, Request, DirID, and Source said too little, and short variables and doc comments that skip their name hid intent.
varnamelen and staticcheck ST1020-22 now keep both from coming back.
2026-11-02 11:06:05 +08:00

46 lines
1.1 KiB
Go

package sqlitex
import (
"database/sql"
"fmt"
"os"
)
// CountRows fails fast on a scan error, unlike QueryRows, which skips the row.
func CountRows(dbPath string, journalOff bool, query string) (int, error) {
if _, err := os.Stat(dbPath); err != nil {
return 0, fmt.Errorf("database file: %w", err)
}
database, err := sql.Open("sqlite", dbPath)
if err != nil {
return 0, err
}
defer database.Close()
if journalOff {
if _, err := database.Exec("PRAGMA journal_mode=off"); err != nil {
return 0, err
}
}
var count int
if err := database.QueryRow(query).Scan(&count); err != nil {
return 0, fmt.Errorf("count rows: %w", err)
}
return count, nil
}
// QueryRows skips rows that fail to scan and logs them at debug level.
func QueryRows[T any](dbPath string, journalOff bool, query string, scanRow func(*sql.Rows) (T, error)) ([]T, error) {
var items []T
err := eachRow(dbPath, journalOff, query, func(rows *sql.Rows) error {
item, err := scanRow(rows)
if err != nil {
return err
}
items = append(items, item)
return nil
})
return items, err
}