package postgres import ( "context" "fmt" "github.com/jackc/pgx/v5/pgxpool" "cryptoHermes/internal/entity" ) type TakerVolumeRepo struct { pool *pgxpool.Pool } func NewTakerVolumeRepo(pool *pgxpool.Pool) *TakerVolumeRepo { return &TakerVolumeRepo{pool: pool} } const takerUpsertSQL = ` INSERT INTO taker_buy_sell_volume (source, symbol, period, timestamp, buy_sell_ratio, buy_volume, sell_volume) VALUES ($1, $2, $3, $4, NULLIF($5, '')::NUMERIC, NULLIF($6, '')::NUMERIC, NULLIF($7, '')::NUMERIC) ON CONFLICT (source, symbol, period, timestamp) DO UPDATE SET buy_sell_ratio = EXCLUDED.buy_sell_ratio, buy_volume = EXCLUDED.buy_volume, sell_volume = EXCLUDED.sell_volume ` func (r *TakerVolumeRepo) UpsertMany(ctx context.Context, items []entity.TakerBuySellVolume) error { if len(items) == 0 { return nil } tx, err := r.pool.Begin(ctx) if err != nil { return err } defer tx.Rollback(ctx) for _, t := range items { if t.Timestamp == 0 { continue } if _, err := tx.Exec(ctx, takerUpsertSQL, t.Source, t.Symbol, t.Period, t.Timestamp, t.BuySellRatio, t.BuyVolume, t.SellVolume, ); err != nil { return fmt.Errorf("upsert taker %s/%s@%d: %w", t.Symbol, t.Period, t.Timestamp, err) } } return tx.Commit(ctx) } const takerFindSQL = ` SELECT source, symbol, period, timestamp, COALESCE(buy_sell_ratio::text, ''), COALESCE(buy_volume::text, ''), COALESCE(sell_volume::text, '') FROM taker_buy_sell_volume WHERE symbol = $1 AND period = $2 ORDER BY timestamp DESC LIMIT $3 ` func (r *TakerVolumeRepo) FindRecent(ctx context.Context, symbol, period string, limit int) ([]entity.TakerBuySellVolume, error) { if limit <= 0 { limit = 100 } rows, err := r.pool.Query(ctx, takerFindSQL, symbol, period, limit) if err != nil { return nil, err } defer rows.Close() out := make([]entity.TakerBuySellVolume, 0, limit) for rows.Next() { var t entity.TakerBuySellVolume if err := rows.Scan(&t.Source, &t.Symbol, &t.Period, &t.Timestamp, &t.BuySellRatio, &t.BuyVolume, &t.SellVolume); err != nil { return nil, err } out = append(out, t) } for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 { out[i], out[j] = out[j], out[i] } return out, rows.Err() }