scsusers/meta.go

71 lines
1.6 KiB
Go
Raw Normal View History

2023-09-26 20:45:19 +00:00
package scsusers
import (
2023-10-07 13:48:40 +00:00
"database/sql"
2023-09-26 20:45:19 +00:00
"fmt"
"log"
)
type Metadata struct {
MetaKey string `db:"meta_key"`
MetaValue string `db:"meta_value"`
}
2023-10-07 13:48:40 +00:00
func (u *UserData) LoadMeta() bool {
q:= fmt.Sprintf("select meta_key, meta_value, id from %s_meta where user=?", c.TablePrefix)
rows, err := c.db.Query(q, u.UserID)
if err != nil && err != sql.ErrNoRows {
log.Printf("scsuser.Get: select: %s", err.Error())
return false
}
for rows.Next() {
var m metadata
rows.Scan(m.Key, m.Value, m.ID)
u.Meta[m.Key] = m
log.Printf("Loaded meta key %s id %d value %s", m.Key, m.ID, m.Value)
}
return true
}
2023-09-26 20:45:19 +00:00
func (u *UserData) Get(key string) (string, bool) {
tmp, ok := u.Meta[key]
return tmp.Value, ok
}
func (u *UserData) Delete(key string) {
tmp, ok := u.Meta[key]
if ok {
_, err := c.db.Query(fmt.Sprintf("delete from %s_meta where id=?", c.TablePrefix), tmp.ID)
if err != nil {
log.Printf("scsauth: set: delete: %s", err.Error())
}
2023-10-06 23:06:54 +00:00
delete(u.Meta, key)
2023-09-26 20:45:19 +00:00
}
}
func (u *UserData) Set(key, value string) error {
tmp, ok := u.Meta[key]
if ok {
_, err := c.db.Query(fmt.Sprintf("delete from %s_meta where id=?", c.TablePrefix), tmp.ID)
if err != nil {
log.Printf("scsauth: set: delete: %s", err.Error())
return err
}
}
var insertid int64
2023-10-06 23:41:11 +00:00
err := c.db.Get(&insertid, fmt.Sprintf("insert into %s_meta (user, meta_key, meta_value) VALUES (?,?,?) returning id", c.TablePrefix), u.UserID, key, value)
2023-09-26 20:45:19 +00:00
if err != nil {
log.Printf("scsauth: set: insert: %s", err.Error())
return err
}
var m metadata
m.Key = key
m.Value = value
m.ID = insertid
u.Meta[key] = m
2023-10-07 13:41:57 +00:00
log.Printf("%#v", u)
2023-09-26 20:45:19 +00:00
return nil
}