61 lines
1.5 KiB
Go
61 lines
1.5 KiB
Go
|
package db
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"sync"
|
||
|
)
|
||
|
|
||
|
var (
|
||
|
prestigeCache = make(map[string]int)
|
||
|
prestigeMutex sync.Mutex
|
||
|
)
|
||
|
|
||
|
func SetPrestigeMultiplier(discordID string, newMultiplier int) error {
|
||
|
prestigeMutex.Lock()
|
||
|
defer prestigeMutex.Unlock()
|
||
|
|
||
|
tx, err := db.Begin()
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("db: SetPrestige: underlying SQL error on 'begin': %w", err)
|
||
|
}
|
||
|
_, err = tx.Exec("REPLACE INTO prestige(id, multiplier) VALUES(?,?)", discordID, newMultiplier)
|
||
|
if err != nil {
|
||
|
tx.Rollback()
|
||
|
return fmt.Errorf("db: SetPrestige: underlying SQL error on 'replace/prestige': %w", err)
|
||
|
}
|
||
|
_, err = tx.Exec("REPLACE INTO xp(id, xp) VALUES(?,0)", discordID)
|
||
|
if err != nil {
|
||
|
tx.Rollback()
|
||
|
return fmt.Errorf("db: SetPrestige: underlying SQL error on 'replace/xp': %w", err)
|
||
|
}
|
||
|
err = tx.Commit()
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("db: SetPrestige: underlying SQL error on 'commit': %w", err)
|
||
|
}
|
||
|
prestigeCache[discordID] = newMultiplier
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func GetPrestigeMultiplier(discordID string) (int, error) {
|
||
|
prestigeMutex.Lock()
|
||
|
defer prestigeMutex.Unlock()
|
||
|
|
||
|
if prestigeCache[discordID] > 0 {
|
||
|
return prestigeCache[discordID], nil
|
||
|
}
|
||
|
|
||
|
rows, err := db.Query("SELECT multiplier FROM prestige WHERE id=?", discordID)
|
||
|
if err != nil {
|
||
|
return 1, fmt.Errorf("db: GetPrestigeMultiplier: underlying SQL error on 'select' (%s): %w", discordID, err)
|
||
|
}
|
||
|
defer rows.Close()
|
||
|
if rows.Next() {
|
||
|
var multiplier int
|
||
|
rows.Scan(&multiplier)
|
||
|
prestigeCache[discordID] = multiplier
|
||
|
return multiplier, nil
|
||
|
}
|
||
|
prestigeCache[discordID] = 1
|
||
|
return 1, nil
|
||
|
}
|