From e1a37d1fff9e226ae644002af515e1cc8a778486 Mon Sep 17 00:00:00 2001 From: Cheese Date: Tue, 31 Jan 2023 17:18:31 +0800 Subject: [PATCH] Support the `AUTO_RANDOM` Field (#104) * feat: support auto_random through default tag * fix: unsigned type support * fix: keeping the HasDefaultValue value is true for auto_random --- mysql.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/mysql.go b/mysql.go index 8617eb6..9865b55 100644 --- a/mysql.go +++ b/mysql.go @@ -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 @@ -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"