2022-11-12 14:20:29 +00:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2022-11-12 16:22:55 +00:00
|
|
|
"errors"
|
2022-11-12 14:20:29 +00:00
|
|
|
"fmt"
|
2023-11-23 12:39:49 +00:00
|
|
|
"log"
|
2022-11-12 14:20:29 +00:00
|
|
|
"sync"
|
2022-11-13 17:21:03 +00:00
|
|
|
"th7/data/core"
|
2023-11-23 12:39:49 +00:00
|
|
|
"time"
|
2022-11-12 14:20:29 +00:00
|
|
|
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
|
|
|
)
|
|
|
|
|
|
|
|
type SQLite3Adapter struct {
|
|
|
|
mu sync.Mutex
|
|
|
|
db *sql.DB
|
|
|
|
}
|
|
|
|
|
2022-11-12 16:22:55 +00:00
|
|
|
func NewSQLite3Adapter(dbInfo map[string]interface{}) (*SQLite3Adapter, error) {
|
2022-11-12 14:20:29 +00:00
|
|
|
|
|
|
|
var adapter SQLite3Adapter
|
|
|
|
|
2022-11-12 16:22:55 +00:00
|
|
|
// if path is given ...
|
|
|
|
if _, ok := dbInfo["path"]; !ok {
|
|
|
|
return &adapter, errors.New("sqlite3 requires a path config variable")
|
|
|
|
}
|
|
|
|
|
|
|
|
path := fmt.Sprint(dbInfo["path"])
|
|
|
|
|
2022-11-12 14:20:29 +00:00
|
|
|
db, err := sql.Open("sqlite3", path)
|
|
|
|
if err != nil {
|
|
|
|
return &adapter, err
|
|
|
|
}
|
|
|
|
|
|
|
|
adapter.db = db
|
|
|
|
|
|
|
|
const create string = `
|
|
|
|
CREATE TABLE IF NOT EXISTS logs (
|
|
|
|
id INTEGER NOT NULL,
|
|
|
|
value REAL NOT NULL,
|
|
|
|
timestamp TEXT NOT NULL
|
|
|
|
);`
|
|
|
|
|
|
|
|
if _, err := adapter.db.Exec(create); err != nil {
|
|
|
|
return &adapter, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &adapter, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ad *SQLite3Adapter) Close() {
|
|
|
|
ad.db.Close()
|
|
|
|
}
|
|
|
|
|
2023-11-23 12:39:49 +00:00
|
|
|
func (ad *SQLite3Adapter) Save(channels []core.Channel) error {
|
2022-11-12 14:20:29 +00:00
|
|
|
ad.mu.Lock()
|
|
|
|
defer ad.mu.Unlock()
|
|
|
|
|
2023-11-23 12:39:49 +00:00
|
|
|
insertLogSQL := `INSERT INTO logs (id, value, timestamp) VALUES (?, ?, ?)`
|
|
|
|
statement, err := ad.db.Prepare(insertLogSQL)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalln(err.Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
timestamp := time.Now().Format(time.RFC1123)
|
|
|
|
|
|
|
|
for c := range channels {
|
|
|
|
|
|
|
|
_, err = statement.Exec(channels[c].Id, channels[c].Value, timestamp)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalln(err.Error())
|
|
|
|
}
|
|
|
|
fmt.Printf("[%s] INSERTED id=%d value=%f\n", timestamp, channels[c].Id, channels[c].Value)
|
|
|
|
}
|
|
|
|
|
2022-11-16 00:07:01 +00:00
|
|
|
return nil
|
2022-11-12 14:20:29 +00:00
|
|
|
}
|