This repository has been archived by the owner on Mar 24, 2024. It is now read-only.
generated from yandex-praktikum/go-musthave-devops-tpl
/
storage.go
49 lines (41 loc) · 1.49 KB
/
storage.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Package storage implements inetrface to diffent ways of storing metrics data.
package storage
import (
"context"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/rs/zerolog/log"
)
type Storage interface {
Push(ctx context.Context, key string, record Record) error
PushBatch(ctx context.Context, data map[string]Record) error
Get(ctx context.Context, key string) (Record, error)
GetAll(ctx context.Context) ([]Record, error)
Close(ctx context.Context) error
}
// NewDataStore create new DataStore object encapsulating particular storage type.
// New storage is picked according to the following priority:
// - if DB connection was initialized, use database storage;
// - if filePath is set, use file backed storage;
// - otherwise store data in memory.
func NewDataStore(pool *pgxpool.Pool, filePath string, storeInterval time.Duration) Storage {
if pool != nil {
log.Info().Msg("Attached database storage")
return NewDatabaseStorage(pool)
}
if len(filePath) == 0 {
log.Info().Msg("Attached in-memory storage")
return NewMemStorage()
}
log.Info().Msg("Attached file-backed storage")
return NewFileBackedStorage(filePath, storeInterval == 0)
}
type DBConnPool interface {
Acquire(ctx context.Context) (*pgxpool.Conn, error)
Ping(ctx context.Context) error
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults
Close()
}