graphdb: initialize the database semi-idempotently on every connection.

Docker-DCO-1.1-Signed-off-by: Erik Hollensbe <github@hollensbe.org> (github: erikh)
This commit is contained in:
Erik Hollensbe 2014-12-02 03:02:25 -08:00
parent 8c02df4c6c
commit 12efe03ef0
3 changed files with 45 additions and 51 deletions

View file

@ -4,31 +4,15 @@ package graphdb
import (
"database/sql"
"os"
_ "code.google.com/p/gosqlite/sqlite3" // registers sqlite
)
func NewSqliteConn(root string) (*Database, error) {
initDatabase := false
stat, err := os.Stat(root)
if err != nil {
if os.IsNotExist(err) {
initDatabase = true
} else {
return nil, err
}
}
if stat != nil && stat.Size() == 0 {
initDatabase = true
}
conn, err := sql.Open("sqlite3", root)
if err != nil {
return nil, err
}
return NewDatabase(conn, initDatabase)
return NewDatabase(conn)
}

View file

@ -73,13 +73,12 @@ func IsNonUniqueNameError(err error) bool {
}
// Create a new graph database initialized with a root entity
func NewDatabase(conn *sql.DB, init bool) (*Database, error) {
func NewDatabase(conn *sql.DB) (*Database, error) {
if conn == nil {
return nil, fmt.Errorf("Database connection cannot be nil")
}
db := &Database{conn: conn}
if init {
if _, err := conn.Exec(createEntityTable); err != nil {
return nil, err
}
@ -98,11 +97,22 @@ func NewDatabase(conn *sql.DB, init bool) (*Database, error) {
if _, err := conn.Exec("BEGIN"); err != nil {
return nil, err
}
if _, err := conn.Exec("DELETE FROM entity where id = ?", "0"); err != nil {
rollback()
return nil, err
}
if _, err := conn.Exec("INSERT INTO entity (id) VALUES (?);", "0"); err != nil {
rollback()
return nil, err
}
if _, err := conn.Exec("DELETE FROM edge where entity_id=? and name=?", "0", "/"); err != nil {
rollback()
return nil, err
}
if _, err := conn.Exec("INSERT INTO edge (entity_id, name) VALUES(?,?);", "0", "/"); err != nil {
rollback()
return nil, err
@ -111,7 +121,7 @@ func NewDatabase(conn *sql.DB, init bool) (*Database, error) {
if _, err := conn.Exec("COMMIT"); err != nil {
return nil, err
}
}
return db, nil
}

View file

@ -14,7 +14,7 @@ import (
func newTestDb(t *testing.T) (*Database, string) {
p := path.Join(os.TempDir(), "sqlite.db")
conn, err := sql.Open("sqlite3", p)
db, err := NewDatabase(conn, true)
db, err := NewDatabase(conn)
if err != nil {
t.Fatal(err)
}