63 lines
1.4 KiB
Go
63 lines
1.4 KiB
Go
package dao
|
|
|
|
import (
|
|
"context"
|
|
|
|
"git.xeserv.us/xena/gorqlite"
|
|
"github.com/opentracing/opentracing-go"
|
|
splog "github.com/opentracing/opentracing-go/log"
|
|
)
|
|
|
|
type Users struct {
|
|
conn gorqlite.Connection
|
|
}
|
|
|
|
func NewUsers(conn gorqlite.Connection) *Users {
|
|
return &Users{conn: conn}
|
|
}
|
|
|
|
func (u *Users) Migrate(ctx context.Context) error {
|
|
sp, ctx := opentracing.StartSpanFromContext(ctx, "users.migrate")
|
|
defer sp.Finish()
|
|
|
|
migrationDDL := []string{
|
|
`CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, discord_id UNIQUE TEXT, score INTEGER)`,
|
|
}
|
|
|
|
res, err := u.conn.Write(migrationDDL)
|
|
if err != nil {
|
|
sp.LogFields(splog.Error(err))
|
|
return err
|
|
}
|
|
|
|
for i, re := range res {
|
|
if re.Err != nil {
|
|
sp.LogFields(splog.Error(err))
|
|
return err
|
|
}
|
|
|
|
sp.LogFields(splog.Int("migration.step", i), splog.Float64("timing", re.Timing), splog.Int64("rows.affected", re.RowsAffected))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (u *Users) Insert(ctx context.Context, discordID string) (int64, error) {
|
|
sp, ctx := opentracing.StartSpanFromContext(ctx, "users.insert")
|
|
defer sp.Finish()
|
|
sp.LogFields(splog.String("discord.id", discordID))
|
|
|
|
re, err := u.conn.WriteOne(gorqlite.NewPreparedStatement("INSERT INTO users (discord_id) VALUES (%s)").Bind(discordID))
|
|
if err != nil {
|
|
sp.LogFields(splog.Error(err))
|
|
return -1, err
|
|
}
|
|
|
|
if re.Err != nil {
|
|
sp.LogFields(splog.Error(re.Err))
|
|
return -1, err
|
|
}
|
|
|
|
return re.LastInsertID, nil
|
|
}
|