diff options
author | Matthew Lemon <lemon@matthewlemon.com> | 2020-07-20 20:23:41 +0100 |
---|---|---|
committer | Matthew Lemon <lemon@matthewlemon.com> | 2020-07-20 20:23:41 +0100 |
commit | c7766d087d6cdd691e60f4b2d317030543209c08 (patch) | |
tree | 2fbb285b78d5590e7ca1bce2a0e486bd9569dad3 /pkg | |
parent | ccbf44bac566ff312f168e563afb003cf0ee3da3 (diff) |
first test passing that puts datamap data into sqlite3
Diffstat (limited to 'pkg')
-rw-r--r-- | pkg/db/setup.go | 39 | ||||
-rw-r--r-- | pkg/db/setup_test.go | 9 | ||||
-rw-r--r-- | pkg/db/testdata/test.db | bin | 12288 -> 135168 bytes |
3 files changed, 43 insertions, 5 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 +} diff --git a/pkg/db/setup_test.go b/pkg/db/setup_test.go index d5f12ba..3787d2e 100644 --- a/pkg/db/setup_test.go +++ b/pkg/db/setup_test.go @@ -59,10 +59,9 @@ func TestDatamapGoesIntoDB(t *testing.T) { if err != nil { t.Fatal("Expected to be able to set up the database.") } - - d, _ := reader.ReadDML("testdata/datamap.csv") - for _, x := range d { - t.Log(x.Key) + d, _ := reader.ReadDML("./testdata/datamap.csv") + err = DatamapToDB(d, db, "First Datamap") + if err != nil { + t.Errorf("Unable to write datamap to database file because %v.", err) } - } diff --git a/pkg/db/testdata/test.db b/pkg/db/testdata/test.db Binary files differindex 26c2e03..81de353 100644 --- a/pkg/db/testdata/test.db +++ b/pkg/db/testdata/test.db |