102 lines
2.6 KiB
Go
102 lines
2.6 KiB
Go
package gaypoints
|
|
|
|
import (
|
|
"database/sql"
|
|
"github.com/rs/zerolog/log"
|
|
_ "modernc.org/sqlite"
|
|
)
|
|
|
|
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 Query. Can't 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 Result. Can't get gaypoints for chat")
|
|
return
|
|
|
|
}
|
|
|
|
log.Trace().Int64("ChatID", chatid).Interface("GP", gaypoints).Msg(("SQL: got SQL 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 Query. Can't get gaypoints for User")
|
|
return
|
|
|
|
}
|
|
log.Trace().Int64("ChatID", chatid).Int64("UserID", userid).Interface("GP", gaypoints).Msg(("SQL: got SQL 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 Query. Can't set gaypoints for User")
|
|
return
|
|
}
|
|
log.Info().Int64("ChatID", chatid).Int64("UserID", userid).Interface("GP", gaypoints).Msg(("SQL: set SQL for User"))
|
|
}
|
|
|
|
func InitDB() {
|
|
const dbPath string = "data/db/gaypoints.db"
|
|
db, err := sql.Open("sqlite", 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().Str("dbpath", dbPath).Msg("Database prepared and connected")
|
|
}
|