aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/db/setup.go
diff options
context:
space:
mode:
authorMatthew Lemon <lemon@matthewlemon.com>2020-07-20 20:23:41 +0100
committerMatthew Lemon <lemon@matthewlemon.com>2020-07-20 20:23:41 +0100
commitc7766d087d6cdd691e60f4b2d317030543209c08 (patch)
tree2fbb285b78d5590e7ca1bce2a0e486bd9569dad3 /pkg/db/setup.go
parentccbf44bac566ff312f168e563afb003cf0ee3da3 (diff)
first test passing that puts datamap data into sqlite3
Diffstat (limited to '')
-rw-r--r--pkg/db/setup.go39
1 files changed, 39 insertions, 0 deletions
diff --git a/pkg/db/setup.go b/pkg/db/setup.go
index e57b046..ef53cf6 100644
--- a/pkg/db/setup.go
+++ b/pkg/db/setup.go
@@ -5,8 +5,10 @@ import (
"errors"
"log"
"os"
+ "time"
_ "github.com/mattn/go-sqlite3"
+ "github.com/yulqen/datamaps-go/pkg/reader"
)
func SetupDB(path string) (*sql.DB, error) {
@@ -45,3 +47,40 @@ func SetupDB(path string) (*sql.DB, error) {
return db, nil
}
+
+//DatamapToDB takes a slice of DatamapLine and writes it to a sqlite3 db file.
+func DatamapToDB(data []reader.DatamapLine, db *sql.DB, dm_name string) error {
+ tx, err := db.Begin()
+ if err != nil {
+ return err
+ }
+ pragma := "PRAGMA foreign_keys = ON;"
+ _, err = db.Exec(pragma)
+ if err != nil {
+ log.Printf("%q: %s\n", err, pragma)
+ return err
+ }
+ stmt_dm, err := tx.Prepare("INSERT INTO datamap (name, date_created) VALUES(?,?)")
+ if err != nil {
+ return err
+ }
+ _, err = stmt_dm.Exec(dm_name, time.Now())
+
+ stmt_dml, err := tx.Prepare("INSERT INTO datamap_line (dm_id, key, sheet, cellref) VALUES(?,?,?,?);")
+ if err != nil {
+ return err
+ }
+ defer stmt_dm.Close()
+ defer stmt_dml.Close()
+ for _, dml := range data {
+ _, err = stmt_dml.Exec(1, dml.Key, dml.Sheet, dml.Cellref)
+ if err != nil {
+ return err
+ }
+ }
+ err = tx.Commit()
+ if err != nil {
+ return err
+ }
+ return nil
+}