-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
operations.go
94 lines (84 loc) · 2.2 KB
/
operations.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 flash
import (
"errors"
"strings"
)
type Operation uint8
const (
OperationInsert Operation = 1 << iota
OperationUpdate
OperationDelete
OperationTruncate
)
const (
OperationAll = OperationInsert | OperationUpdate | OperationDelete | OperationTruncate
)
func (o Operation) IsAtomic() bool {
return o == OperationInsert ||
o == OperationUpdate ||
o == OperationDelete ||
o == OperationTruncate
}
func (o Operation) GetAtomics() []Operation {
var operations []Operation
for mask := OperationInsert; mask != 0 && mask <= OperationTruncate; mask <<= 1 {
if o&mask != 0 {
operations = append(operations, mask)
}
}
return operations
}
// IncludeAll checks if the current operation includes all specified atomic operations.
func (o Operation) IncludeAll(targetOperation Operation) bool {
return o&targetOperation == targetOperation
}
// IncludeOne checks if the current operation includes at least one of the specified atomic operations.
func (o Operation) IncludeOne(targetOperation Operation) bool {
return o&targetOperation > 0
}
// StrictName returns the name of the operation, or throws an error if it doesn't exist
func (o Operation) StrictName() (string, error) {
switch o {
case OperationInsert:
return "INSERT", nil
case OperationUpdate:
return "UPDATE", nil
case OperationDelete:
return "DELETE", nil
case OperationTruncate:
return "TRUNCATE", nil
default:
return "UNKNOWN", errors.New("unknown operation")
}
}
// Use with caution, because no errors are returned when invalid
func (o Operation) String() string {
if o.IsAtomic() {
name, _ := o.StrictName()
return name
} else {
atomicString := []string{}
for _, atomicOperation := range o.GetAtomics() {
atomicString = append(atomicString, atomicOperation.String())
}
if len(atomicString) > 1 {
return strings.Join(atomicString, " | ")
} else {
return "UNKNOWN"
}
}
}
func OperationFromName(name string) (Operation, error) {
switch strings.ToUpper(name) {
case "INSERT":
return OperationInsert, nil
case "UPDATE":
return OperationUpdate, nil
case "DELETE":
return OperationDelete, nil
case "TRUNCATE":
return OperationTruncate, nil
default:
return 0, errors.New("unknown operation name")
}
}