-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhierarchyid.go
112 lines (90 loc) · 2.21 KB
/
hierarchyid.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"database/sql/driver"
"encoding/json"
"errors"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
// HierarchyId is a structure to represent database hierarchy ids.
type HierarchyId struct {
// Path of the hierarchy (e.g "/1/2/3/4/")
Data HierarchyIdData
}
// GormDataTypeInterface to specify the nema of data type.
func (HierarchyId) GormDataType() string {
return "hierarchyid"
}
// GormDBDataTypeInterface defines the data type to apply in the database.
func (HierarchyId) GormDBDataType(db *gorm.DB, field *schema.Field) string {
if db.Dialector.Name() != "sqlserver" {
panic("hierarchyid is only supported on SQL Server")
}
return "hierarchyid"
}
// Check if a hierarchyid is a descendant of another hierarchyid
func (j *HierarchyId) IsDescendantOf(parent HierarchyId) bool {
return IsDescendantOf(j.Data, parent.Data)
}
// Get all parents of a hierarchyid.
func (j *HierarchyId) GetParents() []HierarchyId {
p := []HierarchyId{}
pd := GetParents(j.Data)
for _, d := range pd {
p = append(p, HierarchyId{Data: d})
}
return p
}
// When marshaling to JSON, we want the field formatted as a string.
func (j HierarchyId) MarshalJSON() ([]byte, error) {
return json.Marshal(ToString(j.Data))
}
// When unmarshaling from JSON, we want to parse the string into the field.
func (j *HierarchyId) UnmarshalJSON(data []byte) error {
if len(data) == 0 {
return nil
}
str := ""
err := json.Unmarshal(data, &str)
if err != nil {
return err
}
j.Data, err = FromString(str)
if err != nil {
return err
}
return nil
}
// Value implements the driver.Valuer interface.
//
// Used to provide a value to the SQL server for storage.
func (j HierarchyId) Value() (driver.Value, error) {
if j.Data == nil {
return nil, nil
}
data, err := Encode(j.Data)
if err != nil {
return nil, err
}
return data, nil
}
// Scan implements the sql.Scanner interface.
//
// Used to read the value provided by the SQL server.
func (j *HierarchyId) Scan(src any) error {
if src == nil {
j.Data = nil
return nil
}
switch src := src.(type) {
case []byte:
var err error
j.Data, err = Decode(src)
if err != nil {
return err
}
default:
return errors.New("incompatible type to scan")
}
return nil
}