Merge pull request #9451 from erikh/fix-sqlite

graphdb: initialize the database semi-idempotently on every connection, not just new installs.
This commit is contained in:
Jessie Frazelle 2014-12-03 17:17:20 -08:00
commit 7a025f3fdf
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,45 +73,55 @@ 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
}
if _, err := conn.Exec(createEdgeTable); err != nil {
return nil, err
}
if _, err := conn.Exec(createEdgeIndices); err != nil {
return nil, err
}
rollback := func() {
conn.Exec("ROLLBACK")
}
// Create root entities
if _, err := conn.Exec("BEGIN"); err != nil {
return nil, err
}
if _, err := conn.Exec("INSERT INTO entity (id) VALUES (?);", "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
}
if _, err := conn.Exec("COMMIT"); err != nil {
return nil, err
}
if _, err := conn.Exec(createEntityTable); err != nil {
return nil, err
}
if _, err := conn.Exec(createEdgeTable); err != nil {
return nil, err
}
if _, err := conn.Exec(createEdgeIndices); err != nil {
return nil, err
}
rollback := func() {
conn.Exec("ROLLBACK")
}
// Create root entities
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
}
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)
}