forked from picatic/norm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_model_test.go
57 lines (45 loc) · 1.22 KB
/
example_model_test.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
package norm_test
import (
"encoding/json"
"fmt"
"github.com/picatic/norm"
"github.com/picatic/norm/field"
"os"
)
type User struct {
Id field.Int64 `json:"id",sql:"id"`
FirstName field.String `json:"first_name"`
LastName field.String `json:"last_name"`
Email field.String `json:"email"`
}
func (u *User) TableName() string {
return "norm_users"
}
func (u *User) PrimaryKey() norm.PrimaryKeyer {
return norm.NewSinglePrimaryKey(field.Name("Id"))
}
// IsNew returns true if the model is new and wasn't loaded from storage
// Id must not be scanned for new models. Scanning in an Id effectively makes it appear not not new.
func (u *User) IsNew() bool {
return u.Id.Int64 == 0
}
var _ norm.Model = &User{}
// outputJson jsonEncode OR report error for use in Example Output: block
func outputJson(o interface{}) {
str, err := json.Marshal(o)
if err != nil {
fmt.Println(err.Error())
}
os.Stdout.Write(str)
}
func ExampleModel() {
user := &User{}
user.Id.Scan("1")
user.FirstName.Scan("John")
user.LastName.Scan("Smith")
user.Email.Scan("jsmith@example.org")
str, _ := json.Marshal(user)
os.Stdout.Write(str)
// Output:
// {"id":1,"first_name":"John","last_name":"Smith","email":"jsmith@example.org"}
}