Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support the AUTO_RANDOM Field #104

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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