Created
March 9, 2021 04:34
-
-
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".
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 ( | |
"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