Last active
October 24, 2024 16:10
-
-
Save majest/45de01524eb53477c517b43fc6f110ab to your computer and use it in GitHub Desktop.
Sqlite with GORM using UUID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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