This repository has been archived by the owner on Sep 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
model.go
94 lines (76 loc) · 1.8 KB
/
model.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
92
93
94
package models
import (
"context"
// Importing MySQL driver so the helper
// functions can work.
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
const (
errResourceNotFound = "The resource you requested could not be found"
)
// Conn type is a struct for connections.
type Conn struct {
db *sqlx.DB
}
// New connects to the database.
func New(db *sqlx.DB) *Conn {
return &Conn{db}
}
// Attach receives a map of int/[]int and attach
// the IDs on the given pivot table.
func (c *Conn) Attach(ctx context.Context, s map[int64][]int, pivot string) error {
for index, ids := range s {
for _, values := range ids {
query := "INSERT INTO " + pivot + " VALUES (?,?)"
_, err := c.db.ExecContext(ctx, query, index, values)
if err != nil {
return err
}
}
}
return nil
}
// Detach receives a map of int/[]int and Detach
// the IDs on the given pivot table.
func (c *Conn) Detach(ctx context.Context, s map[int64][]int, pivot, field string) error {
for index := range s {
query := "DELETE FROM " + pivot + " WHERE " + field + " = ?"
_, err := c.db.ExecContext(ctx, query, index)
if err != nil {
return err
}
}
return nil
}
// Sync receives a map of int/[]int and sync
// the IDs on the given pivot table.
func (c *Conn) Sync(ctx context.Context, s map[int64][]int, pivot, field string) error {
empty := c.IsEmpty(s)
if !empty {
err := c.Detach(ctx, s, pivot, field)
if err != nil {
return err
}
err = c.Attach(ctx, s, pivot)
if err != nil {
return err
}
} else {
err := c.Detach(ctx, s, pivot, field)
if err != nil {
return err
}
}
return nil
}
// IsEmpty checks if a given map of int/[]int is empty.
func (c *Conn) IsEmpty(s map[int64][]int) bool {
empty := true
for _, ids := range s {
if len(ids) > 0 {
empty = false
}
}
return empty
}