dialect/sql/schema: support setting default value expressions on id fields (#3089)

This commit is contained in:
Ariel Mashraki
2022-11-13 18:55:04 +02:00
committed by GitHub
parent 53bdc325c0
commit 891fc8fecf
24 changed files with 1839 additions and 9 deletions

View File

@@ -11,6 +11,7 @@ import (
"errors"
"fmt"
"net/url"
"reflect"
"sort"
"strings"
@@ -1102,3 +1103,16 @@ func (a *Atlas) legacyMigrate() (*Migrate, error) {
}
return m, nil
}
// removeAttr is a temporary patch due to compiler errors we get by using the generic
// schema.RemoveAttr function (<autogenerated>:1: internal compiler error: panic: ...).
// Can be removed in Go 1.20. See: https://github.com/golang/go/issues/54302.
func removeAttr(attrs []schema.Attr, t reflect.Type) []schema.Attr {
f := make([]schema.Attr, 0, len(attrs))
for _, a := range attrs {
if reflect.TypeOf(a) != t {
f = append(f, a)
}
}
return f
}

View File

@@ -8,6 +8,7 @@ import (
"context"
"fmt"
"math"
"reflect"
"strconv"
"strings"
@@ -932,8 +933,12 @@ func (d *MySQL) atUniqueC(t1 *Table, c1 *Column, t2 *schema.Table, c2 *schema.Co
t2.AddIndexes(schema.NewUniqueIndex(c1.Name).AddColumns(c2))
}
func (d *MySQL) atIncrementC(_ *schema.Table, c *schema.Column) {
c.AddAttrs(&mysql.AutoIncrement{})
func (d *MySQL) atIncrementC(t *schema.Table, c *schema.Column) {
if c.Default != nil {
t.Attrs = removeAttr(t.Attrs, reflect.TypeOf(&mysql.AutoIncrement{}))
} else {
c.AddAttrs(&mysql.AutoIncrement{})
}
}
func (d *MySQL) atIncrementT(t *schema.Table, v int64) {

View File

@@ -7,6 +7,7 @@ package schema
import (
"context"
"fmt"
"reflect"
"strconv"
"strings"
"unicode"
@@ -769,7 +770,10 @@ func (d *Postgres) atImplicitIndexName(idx *Index, t1 *Table, c1 *Column) bool {
}
func (d *Postgres) atIncrementC(t *schema.Table, c *schema.Column) {
if _, ok := c.Type.Type.(*postgres.SerialType); ok {
// Skip marking this column as an identity in case it is
// serial type or a default was already defined for it.
if _, ok := c.Type.Type.(*postgres.SerialType); ok || c.Default != nil {
t.Attrs = removeAttr(t.Attrs, reflect.TypeOf(&postgres.Identity{}))
return
}
id := &postgres.Identity{}

View File

@@ -8,6 +8,7 @@ import (
"context"
stdsql "database/sql"
"fmt"
"reflect"
"strconv"
"strings"
@@ -473,8 +474,12 @@ func (d *SQLite) atImplicitIndexName(idx *Index, t1 *Table, c1 *Column) bool {
return err == nil && i > 0
}
func (d *SQLite) atIncrementC(_ *schema.Table, c *schema.Column) {
c.AddAttrs(&sqlite.AutoIncrement{})
func (d *SQLite) atIncrementC(t *schema.Table, c *schema.Column) {
if c.Default != nil {
t.Attrs = removeAttr(t.Attrs, reflect.TypeOf(&sqlite.AutoIncrement{}))
} else {
c.AddAttrs(&sqlite.AutoIncrement{})
}
}
func (d *SQLite) atIncrementT(t *schema.Table, v int64) {