bookie/db.go

48 lines
892 B
Go
Raw Normal View History

2018-01-05 17:43:36 +00:00
package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
"io/ioutil"
"os"
"strings"
)
// getDB opens a DB object and returns a usable DB instance
func getDB(path string) (*sql.DB, error) {
var fillDB bool
_, err := os.Stat(path)
if err != nil {
fmt.Println("Database does not exist, creating and applying schema")
fillDB = true
} else {
fillDB = false
}
db, err := sql.Open("sqlite3", path)
if err != nil {
fmt.Println("Could not open database")
panic(err)
}
if fillDB {
file, err := ioutil.ReadFile("./schema.sql")
if err != nil {
fmt.Println("database empty, but cold not read schema file")
panic(err)
}
requests := strings.Split(string(file), ";")
for _, request := range requests {
_, err := db.Exec(request)
if err != nil {
fmt.Println("Could not execute:", request)
panic(err)
}
}
}
return db, nil
}