Skip to content

Commit

Permalink
[CockroachDB] Fixing how it handle fields DEFAULT values and column t…
Browse files Browse the repository at this point in the history
…ypes (#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`
  • Loading branch information
rwrz committed Jan 1, 2023
1 parent 915abc3 commit 1dd9747
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions migrator.go
Expand Up @@ -6,7 +6,6 @@ import (
"regexp"
"strings"

"github.com/jackc/pgx/v5"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/migrator"
Expand Down Expand Up @@ -281,7 +280,22 @@ func (m Migrator) AlterColumn(value interface{}, field string) error {
}

fileType := clause.Expr{SQL: m.DataTypeOf(field)}
// check for typeName and SQL name
isSameType := true
if fieldColumnType.DatabaseTypeName() != fileType.SQL {
isSameType = false
// if different, also check for aliases
aliases := m.GetTypeAliases(fieldColumnType.DatabaseTypeName())
for _, alias := range aliases {
if strings.HasPrefix(fileType.SQL, alias) {
isSameType = true
break
}
}
}

// not same, migrate
if !isSameType {
filedColumnAutoIncrement, _ := fieldColumnType.AutoIncrement()
if field.AutoIncrement && filedColumnAutoIncrement { // update
serialDatabaseType, _ := getSerialDatabaseType(fileType.SQL)
Expand Down Expand Up @@ -423,7 +437,7 @@ func (m Migrator) ColumnTypes(value interface{}) (columnTypes []gorm.ColumnType,
}

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

if datetimePrecision.Valid {
Expand Down

0 comments on commit 1dd9747

Please sign in to comment.