/
options.go
62 lines (49 loc) · 1.27 KB
/
options.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
package model
import (
"database/sql/driver"
"encoding/json"
"errors"
"github.com/bojand/ghz/runner"
"github.com/jinzhu/gorm"
)
// Options represents a report detail
type Options struct {
Model
Report *Report `json:"-"`
// Run id
ReportID uint `json:"reportID" gorm:"type:integer REFERENCES reports(id) ON DELETE CASCADE;not null"`
Info *OptionsInfo `json:"info,omitempty" gorm:"type:TEXT"`
}
// BeforeSave is called by GORM before save
func (o *Options) BeforeSave(scope *gorm.Scope) error {
if o.ReportID == 0 && o.Report == nil {
return errors.New("Options must belong to a report")
}
return nil
}
// OptionsInfo represents the report options
type OptionsInfo runner.Options
// Value converts options struct to a database value
func (o OptionsInfo) Value() (driver.Value, error) {
v, err := json.Marshal(o)
if err != nil {
return nil, err
}
return string(v), nil
}
// Scan converts database value to an Options struct
func (o *OptionsInfo) Scan(src interface{}) error {
var sourceStr string
sourceByte, ok := src.([]byte)
if !ok {
sourceStr, ok = src.(string)
if !ok {
return errors.New("type assertion from string / byte")
}
sourceByte = []byte(sourceStr)
}
if err := json.Unmarshal(sourceByte, o); err != nil {
return err
}
return nil
}