package database import ( "fmt" "log" "pool-stats/models" "time" "github.com/ostafen/clover/v2" "github.com/ostafen/clover/v2/document" c "github.com/ostafen/clover/v2/query" badgerstore "github.com/ostafen/clover/v2/store/badger" ) const ( CollectionName = "shares" ) func InitDatabase(path string) (*clover.DB, error) { store, err := badgerstore.Open(path) if err != nil { return nil, fmt.Errorf("failed to open BadgerDB store: %v", err) } db, err := clover.OpenWithStore(store) if err != nil { return nil, fmt.Errorf("failed to open CloverDB: %v", err) } // Ensure collection exists hasCollection, err := db.HasCollection(CollectionName) if err != nil { return nil, fmt.Errorf("failed to check collection: %v", err) } if !hasCollection { if err := db.CreateCollection(CollectionName); err != nil { return nil, fmt.Errorf("failed to create collection: %v", err) } if err := db.CreateIndex(CollectionName, "CreateDate"); err != nil { return nil, fmt.Errorf("failed to create index: %v", err) } } return db, nil } func GetHighestShareInRange(db *clover.DB, collection string, since time.Time) (*document.Document, error) { // Convert `since` to the format in `createdate` lower := since.Unix() upper := time.Now().Unix() // Filter by timestamp range criteria := c.Field("CreateDate").GtEq(fmt.Sprint(lower)). And(c.Field("CreateDate").LtEq(fmt.Sprint(upper))) // Query sorted by "sdiff" descending, limit 1 results, err := db.FindAll(c.NewQuery(collection). Where(criteria). Sort(c.SortOption{Field: "SDiff", Direction: -1}). Limit(1)) if err != nil || len(results) == 0 { return nil, err } return results[0], nil } func PrintAllHashes(db *clover.DB) { docs, err := db.FindAll(c.NewQuery(CollectionName)) if err != nil { log.Fatalf("Failed to read from collection: %v", err) } for _, doc := range docs { hash := doc.Get("Hash") fmt.Println(hash) } } func ListShares(db *clover.DB, offset int, count int) []models.ShareLog { results, err := db.FindAll( c.NewQuery(CollectionName). Sort(c.SortOption{Field: "CreateDate", Direction: -1}). Skip(offset). Limit(count), ) if err != nil { log.Printf("failed to list shares: %v", err) return nil } shareLogs := make([]models.ShareLog, len(results)) for idx, doc := range results { var shareLog models.ShareLog doc.Unmarshal(&shareLog) shareLogs[idx] = shareLog } return shareLogs }