gorm/dialects/sqlite/sqlite.go

66 lines
1.4 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{
2020-02-22 15:57:29 +03:00
DB: db,
Dialector: dialector,
CreateIndexAfterCreateTable: true,
2020-02-22 14:41:01 +03:00
}}}
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:
2020-02-22 15:57:29 +03:00
return "numeric"
2020-02-22 12:53:57 +03:00
case schema.Int, schema.Uint:
if field.AutoIncrement {
// https://www.sqlite.org/autoinc.html
2020-02-22 15:57:29 +03:00
return "integer PRIMARY KEY AUTOINCREMENT"
2020-02-22 12:53:57 +03:00
} else {
2020-02-22 15:57:29 +03:00
return "integer"
2020-02-22 12:53:57 +03:00
}
case schema.Float:
2020-02-22 15:57:29 +03:00
return "real"
2020-02-22 12:53:57 +03:00
case schema.String, schema.Time:
2020-02-22 15:57:29 +03:00
return "text"
2020-02-22 12:53:57 +03:00
case schema.Bytes:
2020-02-22 15:57:29 +03:00
return "blob"
2020-02-22 12:53:57 +03:00
}
return ""
}