-
Notifications
You must be signed in to change notification settings - Fork 9
/
writeread.go
102 lines (88 loc) · 2.39 KB
/
writeread.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
package main
import (
"log"
"time"
"github.com/cbrake/influxdbhelper/v2"
client "github.com/influxdata/influxdb1-client/v2"
)
const (
// Static connection configuration
influxURL = "http://localhost:8086"
db = "dbhelper"
)
var c influxdbhelper.Client
// Init initializes the database connection
func Init() (err error) {
c, err = influxdbhelper.NewClient(influxURL, "", "", "ns")
if err != nil {
return
}
// Create test database if it doesn't already exist
q := client.NewQuery("CREATE DATABASE "+db, "", "")
res, err := c.Query(q)
if err != nil {
return err
}
if res.Error() != nil {
return res.Error()
}
log.Println("dbhelper db initialized")
return nil
}
type envSample struct {
InfluxMeasurement influxdbhelper.Measurement
Time time.Time `influx:"time"`
Location string `influx:"location,tag"`
Temperature float64 `influx:"temperature"`
Humidity float64 `influx:"humidity"`
ID string `influx:"-"`
}
// we populate a few more fields when reading back
// date to verify unused fields are handled correctly
type envSampleRead struct {
InfluxMeasurement influxdbhelper.Measurement
Time time.Time `influx:"time"`
Location string `influx:"location,tag"`
City string `influx:"city,tag,field"`
Temperature float64 `influx:"temperature"`
Humidity float64 `influx:"humidity"`
Cycles float64 `influx:"cycles"`
ID string `influx:"-"`
}
func generateSampleData() []envSample {
ret := make([]envSample, 10)
for i := range ret {
ret[i] = envSample{
InfluxMeasurement: "test",
Time: time.Now(),
Location: "Rm 243",
Temperature: 70 + float64(i),
Humidity: 60 - float64(i),
ID: "12432as32",
}
}
return ret
}
func main() {
err := Init()
if err != nil {
log.Fatal("Failed to initialize db")
}
// write sample data to database
samples := generateSampleData()
c = c.UseDB(db)
for _, p := range samples {
err := c.WritePoint(p)
if err != nil {
log.Fatal("Error writing point: ", err)
}
}
// query data from db
samplesRead := []envSampleRead{}
q := `SELECT * FROM test ORDER BY time DESC LIMIT 10`
err = c.UseDB(db).DecodeQuery(q, &samplesRead)
if err != nil {
log.Fatal("Query error: ", err)
}
log.Printf("Samples read: %+v\n", samplesRead)
}