Skip to content

Commit f647a05

Browse files
Introduced data manager package
1 parent 40895a4 commit f647a05

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

src/distributed/datamanager/db.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package datamanager
2+
3+
import (
4+
"database/sql"
5+
// for the initialization of the library
6+
_ "github.com/lib/pq"
7+
)
8+
9+
var db *sql.DB
10+
11+
func init() {
12+
var err error
13+
db, err = sql.Open("postgres",
14+
"postres://distributed:distributed@localhost/distributed?sslmode=disable")
15+
if err != nil {
16+
panic(err.Error())
17+
}
18+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package datamanager
2+
3+
import (
4+
"distributed/dto"
5+
"errors"
6+
)
7+
8+
// To cache the relationship between the sensor's
9+
// names and theire IDs in the database so that we
10+
// need not constantly query the database
11+
var sensors map[string]int
12+
13+
// SaveReader is a save function that accepts a pointer
14+
// to a sensor message object and return an error object
15+
func SaveReader(reading *dto.SensorMessage) error {
16+
// checking if already have the ID for the sensor
17+
if sensors[reading.Name] == 0 {
18+
// not found in cache, fetching relationship
19+
getSensors()
20+
}
21+
22+
// checking if current sensor's name is mapped
23+
// after querying db
24+
if sensors[reading.Name] == 0 {
25+
return errors.New("Unable to find the sensor for name '" +
26+
reading.Name + "'")
27+
}
28+
29+
// insert reading, of sensor exists
30+
q := `
31+
INSERT INTO sensor_reading
32+
(value, senosr_id, taken_on)
33+
VALUES
34+
($1, $2, $3)
35+
`
36+
37+
_, err := db.Exec(q, reading.Value, sensors[reading.Name], reading.Timestamp)
38+
39+
return err
40+
41+
}
42+
43+
func getSensors() {
44+
// Re- initializing the map so that
45+
// any stale data is discarded
46+
sensors = make(map[string]int)
47+
48+
q := `SELECT id, name FROM sensor`
49+
50+
// Querying the database
51+
rows, _ := db.Query(q)
52+
53+
for rows.Next() {
54+
var id int
55+
var name string
56+
rows.Scan(&id, &name)
57+
58+
// updating map
59+
sensors[name] = id
60+
}
61+
}

0 commit comments

Comments
 (0)