Skip to content

Commit

Permalink
Align SQLite CreateDB behavior on other drivers (#503)
Browse files Browse the repository at this point in the history
Trying to create an existing SQLite DB will now produce an error.

Fixes #501.
  • Loading branch information
stanislas-m authored Dec 14, 2019
1 parent 944158f commit 51460c0
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
16 changes: 10 additions & 6 deletions dialect_sqlite.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,17 +133,21 @@ func (m *sqlite) locker(l *sync.Mutex, fn func() error) error {
}

func (m *sqlite) CreateDB() error {
d := filepath.Dir(m.ConnectionDetails.Database)
err := os.MkdirAll(d, 0766)
_, err := os.Stat(m.ConnectionDetails.Database)
if err == nil {
return errors.Errorf("could not create SQLite database '%s'; database exists", m.ConnectionDetails.Database)
}
dir := filepath.Dir(m.ConnectionDetails.Database)
err = os.MkdirAll(dir, 0766)
if err != nil {
return errors.Wrapf(err, "could not create SQLite database %s", m.ConnectionDetails.Database)
return errors.Wrapf(err, "could not create SQLite database '%s'", m.ConnectionDetails.Database)
}
_, err = os.Create(m.ConnectionDetails.Database)
if err != nil {
return errors.Wrapf(err, "could not create SQLite database %s", m.ConnectionDetails.Database)
return errors.Wrapf(err, "could not create SQLite database '%s'", m.ConnectionDetails.Database)
}

log(logging.Info, "created database %s", m.ConnectionDetails.Database)
log(logging.Info, "created database '%s'", m.ConnectionDetails.Database)
return nil
}

Expand All @@ -152,7 +156,7 @@ func (m *sqlite) DropDB() error {
if err != nil {
return errors.Wrapf(err, "could not drop SQLite database %s", m.ConnectionDetails.Database)
}
log(logging.Info, "dropped database %s", m.ConnectionDetails.Database)
log(logging.Info, "dropped database '%s'", m.ConnectionDetails.Database)
return nil
}

Expand Down
19 changes: 19 additions & 0 deletions dialect_sqlite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
package pop

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
Expand Down Expand Up @@ -144,3 +145,21 @@ func Test_ConnectionDetails_FinalizeOSPath(t *testing.T) {
r.Equal("sqlite3", cd.Dialect)
r.EqualValues(p, cd.Database)
}

func TestSqlite_CreateDB(t *testing.T) {
r := require.New(t)
dir, err := ioutil.TempDir("", "")
r.NoError(err)
p := filepath.Join(dir, "testdb.sqlite")
defer os.RemoveAll(p)
cd := &ConnectionDetails{
Dialect: "sqlite",
Database: p,
}
dialect, err := newSQLite(cd)
r.NoError(err)
r.NoError(dialect.CreateDB())

// Creating DB twice should produce an error
r.EqualError(dialect.CreateDB(), fmt.Sprintf("could not create SQLite database '%s'; database exists", p))
}

0 comments on commit 51460c0

Please sign in to comment.