Skip to content

Instantly share code, notes, and snippets.

@majest
Created June 25, 2021 09:59
Show Gist options
  • Save majest/efa68db07b5082da69f04bd4d7048aa5 to your computer and use it in GitHub Desktop.
Save majest/efa68db07b5082da69f04bd4d7048aa5 to your computer and use it in GitHub Desktop.
gorm-sqlite
package sqlite
import (
"database/sql"
sqliteGo "github.com/mattn/go-sqlite3"
uuid "github.com/satori/go.uuid"
log "github.com/sirupsen/logrus"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
type Connection struct {
Db *gorm.DB
}
// NewConnection creates new sqlite connection
func NewConnection() *Connection {
sqliteDSN := "file::memory:?cache=shared"
const CustomDriverName = "sqlite3_extended"
sql.Register(CustomDriverName,
&sqliteGo.SQLiteDriver{
ConnectHook: func(conn *sqliteGo.SQLiteConn) error {
err := conn.RegisterFunc(
"gen_random_uuid",
func(arguments ...interface{}) (string, error) {
return uuid.NewV4().String(), nil // Return a string value.
},
true,
)
return err
},
},
)
conn, err := sql.Open(CustomDriverName, sqliteDSN)
if err != nil {
panic(err)
}
db, err := gorm.Open(sqlite.Dialector{
DriverName: CustomDriverName,
DSN: sqliteDSN,
Conn: conn,
}, &gorm.Config{
Logger: logger.Default.LogMode(logger.Error),
SkipDefaultTransaction: true,
DisableNestedTransaction: true,
DisableForeignKeyConstraintWhenMigrating: true,
})
if err != nil {
log.Fatal(err)
}
err = db.Callback().Create().Before("gorm:create").Register("override_uuid", OverrideUuid)
if err != nil {
log.Fatal(err)
}
return &Connection{Db: db}
}
func (c *Connection) GetDb() *gorm.DB {
return c.Db
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment