Skip to content

Commit 1dd9747

Browse files
authored
[CockroachDB] Fixing how it handle fields DEFAULT values and column types (#143)
* CockroachDB default types In cockroachdb, the default values returns something like `field:::TIMESTAMPZ`, and the validation here is only by the default value, without its type, this regex is required. * - considering column aliases for type checking in AlterColumn method * Merging cockroachdb + postgreSQL regex together. It work in all these cases: `'field'::character varying` `'field':::character varying` `field::character varying` `field:::character varying`
1 parent 915abc3 commit 1dd9747

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

migrator.go

+16-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import (
66
"regexp"
77
"strings"
88

9-
"github.com/jackc/pgx/v5"
109
"gorm.io/gorm"
1110
"gorm.io/gorm/clause"
1211
"gorm.io/gorm/migrator"
@@ -281,7 +280,22 @@ func (m Migrator) AlterColumn(value interface{}, field string) error {
281280
}
282281

283282
fileType := clause.Expr{SQL: m.DataTypeOf(field)}
283+
// check for typeName and SQL name
284+
isSameType := true
284285
if fieldColumnType.DatabaseTypeName() != fileType.SQL {
286+
isSameType = false
287+
// if different, also check for aliases
288+
aliases := m.GetTypeAliases(fieldColumnType.DatabaseTypeName())
289+
for _, alias := range aliases {
290+
if strings.HasPrefix(fileType.SQL, alias) {
291+
isSameType = true
292+
break
293+
}
294+
}
295+
}
296+
297+
// not same, migrate
298+
if !isSameType {
285299
filedColumnAutoIncrement, _ := fieldColumnType.AutoIncrement()
286300
if field.AutoIncrement && filedColumnAutoIncrement { // update
287301
serialDatabaseType, _ := getSerialDatabaseType(fileType.SQL)
@@ -423,7 +437,7 @@ func (m Migrator) ColumnTypes(value interface{}) (columnTypes []gorm.ColumnType,
423437
}
424438

425439
if column.DefaultValueValue.Valid {
426-
column.DefaultValueValue.String = regexp.MustCompile(`'(.*)'::[\w\s]+$`).ReplaceAllString(column.DefaultValueValue.String, "$1")
440+
column.DefaultValueValue.String = regexp.MustCompile(`'?(.*)\b'?:+[\w\s]+$`).ReplaceAllString(column.DefaultValueValue.String, "$1")
427441
}
428442

429443
if datetimePrecision.Valid {

0 commit comments

Comments
 (0)