-
Notifications
You must be signed in to change notification settings - Fork 4
/
userguilds.go
91 lines (74 loc) · 2.25 KB
/
userguilds.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package database
import (
"context"
"github.com/jackc/pgtype"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
)
type UserGuild struct {
GuildId uint64
Name string
Owner bool
UserPermissions uint64
Icon string
}
type UserGuildsTable struct {
*pgxpool.Pool
}
func newUserGuildsTable(db *pgxpool.Pool) *UserGuildsTable {
return &UserGuildsTable{
db,
}
}
func (u *UserGuildsTable) Schema() string {
return `
CREATE TABLE IF NOT EXISTS user_guilds(
"user_id" int8 NOT NULL,
"guild_id" int8 NOT NULL,
"name" varchar(100) NOT NULL,
"owner" bool NOT NULL,
"permissions" int8 NOT NULL,
"icon" varchar(34),
FOREIGN KEY ("user_id") REFERENCES dashboard_users("user_id") ON DELETE CASCADE,
PRIMARY KEY("user_id", "guild_id")
);`
}
func (u *UserGuildsTable) Get(ctx context.Context, userId uint64) (guilds []UserGuild, e error) {
query := `SELECT "guild_id", "name", "owner", "permissions", "icon" FROM user_guilds WHERE "user_id" = $1;`
rows, err := u.Query(ctx, query, userId)
defer rows.Close()
if err != nil && err != pgx.ErrNoRows {
e = err
return
}
for rows.Next() {
var guild UserGuild
if err := rows.Scan(&guild.GuildId, &guild.Name, &guild.Owner, &guild.UserPermissions, &guild.Icon); err != nil {
e = err
continue
}
guilds = append(guilds, guild)
}
return
}
func (u *UserGuildsTable) Set(ctx context.Context, userId uint64, guilds []UserGuild) (err error) {
// create slice of guild ids
var guildIds []uint64
for _, guild := range guilds {
guildIds = append(guildIds, guild.GuildId)
}
guildIdArray := &pgtype.Int8Array{}
if err = guildIdArray.Set(guildIds); err != nil {
return
}
batch := &pgx.Batch{}
batch.Queue(`DELETE FROM user_guilds WHERE "user_id" = $1 AND NOT ("guild_id" = ANY($2));`, userId, guildIdArray)
for _, guild := range guilds {
query := `INSERT INTO user_guilds("user_id", "guild_id", "name", "owner", "permissions", "icon") VALUES($1, $2, $3, $4, $5, $6) ON CONFLICT("user_id", "guild_id") DO UPDATE SET "name" = $3, "owner" = $4, "permissions" = $5, "icon" = $6;`
batch.Queue(query, userId, guild.GuildId, guild.Name, guild.Owner, guild.UserPermissions, guild.Icon)
}
br := u.SendBatch(ctx, batch)
defer br.Close()
_, err = br.Exec()
return
}