From 0b09873891d31222ac309fe73b291066c28b36a6 Mon Sep 17 00:00:00 2001 From: Icemap Date: Sun, 29 Jan 2023 14:03:04 +0800 Subject: [PATCH 1/3] feat: support auto_random through default tag --- mysql.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/mysql.go b/mysql.go index 8617eb6..0a68b95 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,32 @@ 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.HasDefaultValue = false + field.DefaultValue = "" + + return true, "bigint auto_random" + } + + 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" From 120c47ff4031e3589c266b82f78324bc60cd6b69 Mon Sep 17 00:00:00 2001 From: Icemap Date: Mon, 30 Jan 2023 14:43:50 +0800 Subject: [PATCH 2/3] fix: unsigned type support --- mysql.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/mysql.go b/mysql.go index 0a68b95..0ddefdd 100644 --- a/mysql.go +++ b/mysql.go @@ -436,7 +436,12 @@ func autoRandomType(field *schema.Field) (bool, string) { field.HasDefaultValue = false field.DefaultValue = "" - return true, "bigint auto_random" + sqlType := "bigint" + if field.DataType == schema.Uint { + sqlType += " unsigned" + } + sqlType += " auto_random" + return true, sqlType } return false, "" From b3a1a34c829a1208cb2d3575316c1e7a8dee6590 Mon Sep 17 00:00:00 2001 From: Icemap Date: Mon, 30 Jan 2023 21:30:39 +0800 Subject: [PATCH 3/3] fix: keeping the HasDefaultValue value is true for auto_random --- mysql.go | 1 - 1 file changed, 1 deletion(-) diff --git a/mysql.go b/mysql.go index 0ddefdd..9865b55 100644 --- a/mysql.go +++ b/mysql.go @@ -433,7 +433,6 @@ func (dialector Dialector) getSchemaBytesType(field *schema.Field) string { func autoRandomType(field *schema.Field) (bool, string) { if field.PrimaryKey && field.HasDefaultValue && strings.ToLower(strings.TrimSpace(field.DefaultValue)) == AutoRandomTag { - field.HasDefaultValue = false field.DefaultValue = "" sqlType := "bigint"