mirror of https://github.com/go-gorm/gorm.git
81 lines
1.7 KiB
Go
81 lines
1.7 KiB
Go
package sqlite
|
|
|
|
import (
|
|
"database/sql"
|
|
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/callbacks"
|
|
"gorm.io/gorm/clause"
|
|
"gorm.io/gorm/logger"
|
|
"gorm.io/gorm/migrator"
|
|
"gorm.io/gorm/schema"
|
|
_ "github.com/mattn/go-sqlite3"
|
|
)
|
|
|
|
type Dialector struct {
|
|
DSN string
|
|
}
|
|
|
|
func Open(dsn string) gorm.Dialector {
|
|
return &Dialector{DSN: dsn}
|
|
}
|
|
|
|
func (dialector Dialector) Name() string {
|
|
return "sqlite"
|
|
}
|
|
|
|
func (dialector Dialector) Initialize(db *gorm.DB) (err error) {
|
|
// register callbacks
|
|
callbacks.RegisterDefaultCallbacks(db, &callbacks.Config{
|
|
LastInsertIDReversed: true,
|
|
})
|
|
db.ConnPool, err = sql.Open("sqlite3", dialector.DSN)
|
|
return
|
|
}
|
|
|
|
func (dialector Dialector) Migrator(db *gorm.DB) gorm.Migrator {
|
|
return Migrator{migrator.Migrator{Config: migrator.Config{
|
|
DB: db,
|
|
Dialector: dialector,
|
|
CreateIndexAfterCreateTable: true,
|
|
}}}
|
|
}
|
|
|
|
func (dialector Dialector) BindVarTo(writer clause.Writer, stmt *gorm.Statement, v interface{}) {
|
|
writer.WriteByte('?')
|
|
}
|
|
|
|
func (dialector Dialector) QuoteTo(writer clause.Writer, str string) {
|
|
writer.WriteByte('`')
|
|
writer.WriteString(str)
|
|
writer.WriteByte('`')
|
|
}
|
|
|
|
func (dialector Dialector) Explain(sql string, vars ...interface{}) string {
|
|
return logger.ExplainSQL(sql, nil, `"`, vars...)
|
|
}
|
|
|
|
func (dialector Dialector) DataTypeOf(field *schema.Field) string {
|
|
switch field.DataType {
|
|
case schema.Bool:
|
|
return "numeric"
|
|
case schema.Int, schema.Uint:
|
|
if field.AutoIncrement {
|
|
// https://www.sqlite.org/autoinc.html
|
|
return "integer PRIMARY KEY AUTOINCREMENT"
|
|
} else {
|
|
return "integer"
|
|
}
|
|
case schema.Float:
|
|
return "real"
|
|
case schema.String:
|
|
return "text"
|
|
case schema.Time:
|
|
return "datetime"
|
|
case schema.Bytes:
|
|
return "blob"
|
|
}
|
|
|
|
return ""
|
|
}
|