Test sqlite.DB

This commit is contained in:
Mickaël Menu 2021-01-04 20:03:32 +01:00
parent b78609269b
commit d655720181
No known key found for this signature in database
GPG Key ID: 53D73664CD359895
3 changed files with 57 additions and 1 deletions

View File

@ -14,7 +14,16 @@ type DB struct {
// Open creates a new DB instance for the SQLite database at the given path.
func Open(path string) (*DB, error) {
db, err := sql.Open("sqlite3", "file:"+path)
return open("file:" + path)
}
// OpenInMemory creates a new in-memory DB instance.
func OpenInMemory() (*DB, error) {
return open(":memory:")
}
func open(uri string) (*DB, error) {
db, err := sql.Open("sqlite3", uri)
if err != nil {
return nil, errors.Wrap(err, "failed to open the database")
}

47
adapter/sqlite/db_test.go Normal file
View File

@ -0,0 +1,47 @@
package sqlite
import (
"testing"
"github.com/mickael-menu/zk/util/assert"
"github.com/mickael-menu/zk/util/fixtures"
)
func TestOpen(t *testing.T) {
_, err := Open(fixtures.Path("sample.db"))
assert.Nil(t, err)
}
func TestClose(t *testing.T) {
db, err := Open(fixtures.Path("sample.db"))
assert.Nil(t, err)
err = db.Close()
assert.Nil(t, err)
}
func TestMigrateFrom0(t *testing.T) {
db, err := OpenInMemory()
assert.Nil(t, err)
err = db.Migrate()
assert.Nil(t, err)
// Should be able to migrate twice in a row
err = db.Migrate()
assert.Nil(t, err)
err = db.WithTransaction(func(tx Transaction) error {
var version int
err := tx.QueryRow("PRAGMA user_version").Scan(&version)
assert.Nil(t, err)
assert.Equal(t, version, 1)
_, err = tx.Exec(`
INSERT INTO notes (dir, filename, title, body, word_count, checksum)
VALUES ("ref", "tx1.md", "A reference", "Content", 1, "qwfpg")
`)
assert.Nil(t, err)
return nil
})
assert.Nil(t, err)
}

Binary file not shown.