Skip to content

Commit

Permalink
Support the AUTO_RANDOM Field (#104)
Browse files Browse the repository at this point in the history
* feat: support auto_random through default tag

* fix: unsigned type support

* fix: keeping the HasDefaultValue value is true for auto_random
  • Loading branch information
Cheese authored Jan 31, 2023
1 parent 332829e commit e1a37d1
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ import (
"gorm.io/gorm/utils"
)

const (
AutoRandomTag = "auto_random()" // Treated as an auto_random field for tidb
)

type Config struct {
DriverName string
ServerVersion string
Expand Down Expand Up @@ -417,7 +421,36 @@ func (dialector Dialector) getSchemaBytesType(field *schema.Field) string {
return "longblob"
}

// autoRandomType
// field.DataType MUST be `schema.Int` or `schema.Uint`
// Judgement logic:
// 1. Is PrimaryKey;
// 2. Has default value;
// 3. Default value is "auto_random()";
// 4. IGNORE the field.Size, it MUST be bigint;
// 5. CLEAR the default tag, and return true;
// 6. Otherwise, return false.
func autoRandomType(field *schema.Field) (bool, string) {
if field.PrimaryKey && field.HasDefaultValue &&
strings.ToLower(strings.TrimSpace(field.DefaultValue)) == AutoRandomTag {
field.DefaultValue = ""

sqlType := "bigint"
if field.DataType == schema.Uint {
sqlType += " unsigned"
}
sqlType += " auto_random"
return true, sqlType
}

return false, ""
}

func (dialector Dialector) getSchemaIntAndUnitType(field *schema.Field) string {
if autoRandom, typeString := autoRandomType(field); autoRandom {
return typeString
}

constraint := func(sqlType string) string {
if field.DataType == schema.Uint {
sqlType += " unsigned"
Expand Down

0 comments on commit e1a37d1

Please sign in to comment.