gorm/dialects/sqlite/sqlite.go

65 lines
1.3 KiB
Go
Raw Normal View History

2020-02-02 03:35:01 +03:00
package sqlite
import (
2020-02-03 05:40:03 +03:00
"database/sql"
2020-02-02 09:40:44 +03:00
"github.com/jinzhu/gorm"
2020-02-02 03:35:01 +03:00
"github.com/jinzhu/gorm/callbacks"
2020-02-22 12:53:57 +03:00
"github.com/jinzhu/gorm/migrator"
"github.com/jinzhu/gorm/schema"
2020-02-02 03:35:01 +03:00
_ "github.com/mattn/go-sqlite3"
)
type Dialector struct {
2020-02-03 05:40:03 +03:00
DSN string
2020-02-02 03:35:01 +03:00
}
func Open(dsn string) gorm.Dialector {
2020-02-03 05:40:03 +03:00
return &Dialector{DSN: dsn}
2020-02-02 03:35:01 +03:00
}
2020-02-03 05:40:03 +03:00
func (dialector Dialector) Initialize(db *gorm.DB) (err error) {
2020-02-02 03:35:01 +03:00
// register callbacks
callbacks.RegisterDefaultCallbacks(db)
2020-02-03 05:40:03 +03:00
db.DB, err = sql.Open("sqlite3", dialector.DSN)
return
2020-02-02 03:35:01 +03:00
}
2020-02-22 12:53:57 +03:00
func (dialector Dialector) Migrator(db *gorm.DB) gorm.Migrator {
2020-02-22 14:41:01 +03:00
return Migrator{migrator.Migrator{Config: migrator.Config{
DB: db,
Dialector: dialector,
}}}
2020-02-02 03:35:01 +03:00
}
2020-02-22 12:53:57 +03:00
func (dialector Dialector) BindVar(stmt *gorm.Statement, v interface{}) string {
2020-02-02 03:35:01 +03:00
return "?"
}
2020-02-05 06:14:58 +03:00
2020-02-22 12:53:57 +03:00
func (dialector Dialector) QuoteChars() [2]byte {
2020-02-05 06:14:58 +03:00
return [2]byte{'`', '`'} // `name`
}
2020-02-22 12:53:57 +03:00
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, schema.Time:
return "TEXT"
case schema.Bytes:
return "BLOB"
}
return ""
}