Add sqlschema

This commit is contained in:
Jinzhu 2018-03-18 23:12:40 +08:00
parent 7ee0af3283
commit f2f5133fc0
3 changed files with 115 additions and 0 deletions

View File

@ -0,0 +1,72 @@
package sqlschema
import (
"database/sql"
"fmt"
"strconv"
"github.com/jinzhu/gorm/schema"
)
// SQLSchema sql schema
type SQLSchema struct {
*schema.Schema
Fields []*Field
}
// Field SQLSchema Field
type Field struct {
*schema.Field
DataType sql.NullString
Precision sql.NullInt64
Length sql.NullInt64
Nullable sql.NullBool
Unique sql.NullBool
}
// Parse parse sql schema
func Parse(dest interface{}) *SQLSchema {
s := schema.Parse(dest)
sqlSchema := &SQLSchema{
Schema: s,
}
for _, f := range s.Fields {
if f.IsNormal {
field := &Field{Field: f}
if s, ok := field.TagSettings["TYPE"]; ok {
_ = field.DataType.Scan(s)
}
if num, ok := field.TagSettings["SIZE"]; ok {
n, err := strconv.Atoi(num)
if err != nil {
fmt.Println(err)
}
_ = field.Length.Scan(n)
}
if num, ok := field.TagSettings["PRECISION"]; ok {
n, err := strconv.Atoi(num)
if err != nil {
fmt.Println(err)
}
_ = field.Precision.Scan(n)
}
if _, ok := field.TagSettings["NOT NULL"]; !ok {
_ = field.Nullable.Scan(true)
}
if _, ok := field.TagSettings["UNIQUE"]; ok {
_ = field.Nullable.Scan(true)
}
sqlSchema.Fields = append(sqlSchema.Fields, field)
}
}
return sqlSchema
}

View File

@ -0,0 +1,19 @@
package sqlschema
// ColumnType column type
type ColumnType string
const (
// Boolean boolean type
Boolean ColumnType = "boolean"
// Integer integer type
Integer ColumnType = "boolean"
// Float float type
Float ColumnType = "float"
// String string type
String ColumnType = "string"
// Text long string type
Text ColumnType = "text"
// Binary binary type
Binary ColumnType = "binary"
)

View File

@ -10,6 +10,7 @@ import (
"github.com/jinzhu/gorm"
"github.com/jinzhu/gorm/dialects/common/sqlbuilder"
"github.com/jinzhu/gorm/model"
"github.com/jinzhu/gorm/schema"
)
// Dialect Sqlite3 Dialect for GORM
@ -319,3 +320,26 @@ func (dialect *Dialect) Delete(tx *gorm.DB) (err error) {
_, err = dialect.DB.Exec(s.String(), args...)
return
}
// AutoMigrate auto migrate database
func (dialect *Dialect) AutoMigrate(value interface{}) (err error) {
// create table
// create missed column
// safe upgrade some fields (like size, change data type)
// create missed foreign key
// create missed index
return nil
}
func (dialect *Dialect) HasTable(name string) bool {
return false
}
func (dialect *Dialect) CreateTable(value interface{}) error {
s := schema.Parse(value)
return nil
}