Skip to content

Commit

Permalink
feat(core): initial sql library (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
moul committed Jul 26, 2018
1 parent 0d3e184 commit 220ebe1
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
Empty file removed core/sql/.gitkeep
Empty file.
38 changes: 38 additions & 0 deletions core/sql/gorm.go
@@ -0,0 +1,38 @@
package sql

import (
"errors"

"github.com/go-gormigrate/gormigrate"
"github.com/jinzhu/gorm"

"github.com/berty/berty/core/api/entity"
)

// Init configures an active gorm connection
func Init(db *gorm.DB) (*gorm.DB, error) {
db = db.Set("gorm:auto_preload", true)
db = db.Set("gorm:association_autoupdate", false)

// FIXME: configure zap logger
// FIXME: configure hard delete

m := gormigrate.New(db, gormigrate.DefaultOptions, []*gormigrate.Migration{
{
ID: "1",
Migrate: func(tx *gorm.DB) error {
return tx.AutoMigrate(
entity.Contact{},
).Error
},
Rollback: func(tx *gorm.DB) error {
return errors.New("not implemented")
},
},
})
if err := m.Migrate(); err != nil {
return nil, err
}

return db, nil
}
33 changes: 33 additions & 0 deletions core/sql/gorm_test.go
@@ -0,0 +1,33 @@
package sql

import (
"io/ioutil"
"os"
"testing"

"github.com/berty/berty/core/sql/sqlcipher"
. "github.com/smartystreets/goconvey/convey"
)

func TestInit(t *testing.T) {
Convey("testing Init", t, func() {
tmpFile, err := ioutil.TempFile("", "sqlite")
So(err, ShouldBeNil)
defer os.Remove(tmpFile.Name())

// create a database
db, err := sqlcipher.Open(tmpFile.Name(), []byte(`s3cur3`))
So(err, ShouldBeNil)
So(db, ShouldNotBeNil)
defer db.Close()

// disable logger for the tests
db.LogMode(false)

// call init
db, err = Init(db)
So(err, ShouldBeNil)
So(db, ShouldNotBeNil)
So(db.HasTable("contacts"), ShouldBeTrue)
})
}

0 comments on commit 220ebe1

Please sign in to comment.