101 lines
2.5 KiB
Go
101 lines
2.5 KiB
Go
package gaypoints
|
|
|
|
import (
|
|
"database/sql"
|
|
_ "github.com/mattn/go-sqlite3"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
var gpSelectUser *sql.Stmt
|
|
|
|
var gpSelectChat *sql.Stmt
|
|
|
|
var gpSet *sql.Stmt
|
|
|
|
func sqlGetAllGP(chatid int64) (gaypoints []gaypointShortDetails) {
|
|
rows, err := gpSelectChat.Query(chatid)
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("failed to execute SQL to get get gaypoints for chat")
|
|
return
|
|
}
|
|
|
|
var c int64
|
|
var b int64
|
|
for rows.Next() {
|
|
switch err := rows.Scan(&c, &b); err {
|
|
case nil:
|
|
gaypoints = append(gaypoints, gaypointShortDetails{
|
|
userID: c,
|
|
gaypoints: b,
|
|
})
|
|
default:
|
|
log.Error().Err(err).Msg("failed to parse SQL to get get gaypoints for chat")
|
|
return
|
|
|
|
}
|
|
log.Debug().Msg("executed SQL to get gaypoints for chat")
|
|
}
|
|
|
|
return gaypoints
|
|
|
|
}
|
|
|
|
func sqlGetGP(chatid int64, userid int64) (gaypoints int64) {
|
|
row := gpSelectUser.QueryRow(chatid, userid)
|
|
|
|
switch err := row.Scan(&gaypoints); err {
|
|
case sql.ErrNoRows:
|
|
gaypoints = -1
|
|
case nil:
|
|
break
|
|
default:
|
|
log.Error().Err(err).Msg("failed to execute SQL to get get gaypoints for user")
|
|
return
|
|
|
|
}
|
|
log.Debug().Msg("executed SQL to get gaypoints for user")
|
|
return gaypoints
|
|
}
|
|
|
|
func sqlSetGP(chatid int64, userid int64, gaypoints int64) {
|
|
_, err := gpSet.Exec(chatid, userid, gaypoints)
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("failed to execute SQL to get set gaypoints for user")
|
|
return
|
|
}
|
|
log.Debug().Msg("executed SQL to set gaypoints for user")
|
|
}
|
|
|
|
func InitDB() {
|
|
const dbPath string = "./bloater.db"
|
|
log.Info().Str("dbpath", dbPath).Msg("init database")
|
|
db, err := sql.Open("sqlite3", dbPath)
|
|
if err != nil {
|
|
log.Panic().Err(err).Msg("failed to open sqlite database")
|
|
}
|
|
|
|
_, err = db.Exec("CREATE TABLE IF NOT EXISTS gaypoints (chatid bigint, userid bigint,gaypoints bigint,UNIQUE(chatid,userid))")
|
|
if err != nil {
|
|
log.Panic().Err(err).Msg("failed to create table")
|
|
}
|
|
|
|
gpSelectUser, err = db.Prepare("SELECT gaypoints FROM gaypoints WHERE chatid = ? AND userid = ?")
|
|
|
|
if err != nil {
|
|
log.Panic().Err(err).Msg("failed to create sql statement")
|
|
}
|
|
|
|
gpSelectChat, err = db.Prepare("SELECT userid,gaypoints FROM gaypoints WHERE chatid = ? ORDER BY gaypoints DESC")
|
|
|
|
if err != nil {
|
|
log.Panic().Err(err).Msg("failed to create sql statement")
|
|
}
|
|
|
|
gpSet, err = db.Prepare("INSERT OR REPLACE INTO gaypoints (chatid, userid, gaypoints) values (?,?,?)")
|
|
|
|
if err != nil {
|
|
log.Panic().Err(err).Msg("failed to create sql statement")
|
|
}
|
|
|
|
log.Info().Msg("init database: done")
|
|
}
|