Skip to content

Instantly share code, notes, and snippets.

@omaciel
Forked from majest/main.go
Created August 15, 2023 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omaciel/3c0ee56ac06b40db1affda5a600bf22b to your computer and use it in GitHub Desktop.
Save omaciel/3c0ee56ac06b40db1affda5a600bf22b to your computer and use it in GitHub Desktop.
Sqlite with GORM using UUID
package main
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"
)
func main() {
const CustomDriverName = "sqlite3_extended"
const File = "./test.db"
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, File)
if err != nil {
panic(err)
}
db, err := gorm.Open(sqlite.Dialector{
DriverName: CustomDriverName,
DSN: File,
Conn: conn,
}, &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
SkipDefaultTransaction: true,
DisableNestedTransaction: true,
})
if err != nil {
log.Fatal(err)
}
type Product struct {
ID uuid.UUID `gorm:"type:uuid;primaryKey;default:(gen_random_uuid())"`
Test string
}
db.AutoMigrate(&Product{})
product := &Product{Test: "test"}
log.Info(product)
products := []Product{}
db.Find(&products)
log.Info(products)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment