-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathimportmapping.go
More file actions
83 lines (63 loc) · 1.97 KB
/
importmapping.go
File metadata and controls
83 lines (63 loc) · 1.97 KB
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
package database
import (
"context"
_ "embed"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
)
type ImportMappingTable struct {
*pgxpool.Pool
}
type ImportMapping struct {
GuildId uint64 `json:"guild_id"`
Area string `json:"area"`
SourceId int `json:"source_id"`
TargetId int `json:"target_id"`
}
var (
//go:embed sql/import_mapping/schema.sql
importMappingSchema string
//go:embed sql/import_mapping/set.sql
importMappingSet string
)
func newImportMapping(db *pgxpool.Pool) *ImportMappingTable {
return &ImportMappingTable{
db,
}
}
func (s ImportMappingTable) Schema() string {
return importMappingSchema
}
func (s *ImportMappingTable) GetMapping(ctx context.Context, guildId uint64) (map[string]map[int]int, error) {
query := `SELECT * FROM import_mapping WHERE "guild_id" = $1;`
rows, err := s.Query(ctx, query, guildId)
if err != nil {
return nil, err
}
mapping := make(map[string]map[int]int)
for rows.Next() {
var mappingEntry ImportMapping
if err := rows.Scan(&mappingEntry.GuildId, &mappingEntry.Area, &mappingEntry.SourceId, &mappingEntry.TargetId); err != nil {
return nil, err
}
if _, ok := mapping[mappingEntry.Area]; !ok {
mapping[mappingEntry.Area] = make(map[int]int)
}
mapping[mappingEntry.Area][mappingEntry.SourceId] = mappingEntry.TargetId
}
return mapping, nil
}
func (s *ImportMappingTable) Set(ctx context.Context, guildId uint64, area string, sourceId, targetId int) error {
_, err := s.Exec(ctx, importMappingSet, guildId, area, sourceId, targetId)
return err
}
func (s *ImportMappingTable) SetBulk(ctx context.Context, guildId uint64, area string, mappings map[int]int) error {
rows := make([][]interface{}, len(mappings))
i := 0
for sourceId, targetId := range mappings {
rows[i] = []interface{}{guildId, area, sourceId, targetId}
i++
}
_, err := s.CopyFrom(ctx, pgx.Identifier{"import_mapping"}, []string{"guild_id", "area", "source_id", "target_id"}, pgx.CopyFromRows(rows))
return err
}