Skip to content

Instantly share code, notes, and snippets.

@nathan-osman
Created March 9, 2021 04:34
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 nathan-osman/6cadc8bc53dda8867b45e35176c8cb74 to your computer and use it in GitHub Desktop.
Save nathan-osman/6cadc8bc53dda8867b45e35176c8cb74 to your computer and use it in GitHub Desktop.
Custom dialector to force sqlite driver in GORM to use "integer" type for booleans instead of "numeric".
package main
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
// CustomDialector allows for customization of the type affinity for booleans.
type CustomDialector struct {
sqlite.Dialector
}
// CustomMigrator overrides behavior of the SQLite migrator.
type CustomMigrator struct {
sqlite.Migrator
}
// DataTypeOf returns the data type for the supplied field.
func (d CustomDialector) DataTypeOf(field *schema.Field) string {
if field.DataType == schema.Bool {
return "integer"
}
return d.Dialector.DataTypeOf(field)
}
// Migrator returns the migrator for the dialector.
func (d CustomDialector) Migrator(db *gorm.DB) gorm.Migrator {
m := d.Dialector.Migrator(db).(sqlite.Migrator)
m.Migrator.Config.Dialector = d
return m
}
func main() {
c, err := gorm.Open(
CustomDialector{
sqlite.Dialector{
DSN: "filename.db",
},
},
&gorm.Config{},
)
if err != nil {
panic(err)
}
// TODO: do something with c
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment