-
Notifications
You must be signed in to change notification settings - Fork 0
/
dao.go
107 lines (92 loc) · 2.18 KB
/
dao.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
package main
import (
"database/sql"
"github.com/coopernurse/gorp"
_ "github.com/mattn/go-sqlite3"
"log"
"time"
)
type Thermometer struct {
Id int64 `id`
Temperature int `temperature`
Created int64 `created_at`
Updated int64 `updated_at`
}
type DAO struct {
dbmap *gorp.DbMap
}
func NewDAO() *DAO {
db, err := sql.Open("sqlite3", "thermistor_db.bin")
if err != nil {
log.Println("sql.Open failed", err)
return nil
}
dao := DAO{}
dao.dbmap = &gorp.DbMap{Db: db, Dialect: gorp.SqliteDialect{}}
dao.dbmap.AddTableWithName(Thermometer{}, "thermometer").SetKeys(true, "Id")
if err = dao.dbmap.CreateTablesIfNotExists(); err != nil {
log.Println("Create tables failed", err)
return nil
}
return &dao
}
func (self *DAO) Insert(temperature int) error {
//set created and updated with datetime
t := Thermometer{
Temperature: temperature,
Created: time.Now().UnixNano(),
Updated: time.Now().UnixNano(),
}
if err := self.dbmap.Insert(&t); err != nil {
log.Println("Insert failed", err)
return err
}
return nil
}
func (self *DAO) GetById(id int64) (*Thermometer, error) {
obj, err := self.dbmap.Get(Thermometer{}, id)
if err != nil {
log.Println("Select One failed", err)
return nil, err
}
t := obj.(*Thermometer)
return t, nil
}
func (self *DAO) GetAll() ([]Thermometer, error) {
var l []Thermometer
_, err := self.dbmap.Select(&l, "select * from thermometer order by id")
if err != nil {
log.Println("Select failed", err)
return l, err
}
return l, nil
}
func (self *DAO) Update(t *Thermometer) (int64, error) {
//only set updated with datetime
t.Updated = time.Now().UnixNano()
count, err := self.dbmap.Update(t)
if err != nil {
log.Println("Update failed", err)
return -1, err
}
return count, nil
}
func (self *DAO) Delete(t *Thermometer) (int64, error) {
count, err := self.dbmap.Delete(t)
if err != nil {
log.Println("Delete failed", err)
return -1, err
}
return count, nil
}
func (self *DAO) DeleteAll() error {
// delete any existing rows
if err := self.dbmap.TruncateTables(); err != nil {
log.Println("TruncateTables failed", err)
return err
}
return nil
}
func (self *DAO) Close() {
self.dbmap.Db.Close()
}