Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion sql/plan/alter_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -1411,7 +1411,15 @@ func (i *modifyColumnIter) rewriteTable(ctx *sql.Context, rwt sql.RewritableTabl
}
}

oldPkSchema, newPkSchema := sql.SchemaToPrimaryKeySchema(rwt, rwt.Schema()), sql.SchemaToPrimaryKeySchema(rwt, newSch)
var renames []sql.ColumnRename
if i.m.columnName != i.m.column.Name {
renames = []sql.ColumnRename{{
Before: i.m.columnName, After: i.m.column.Name,
}}
}

oldPkSchema := sql.SchemaToPrimaryKeySchema(rwt, rwt.Schema())
newPkSchema := sql.SchemaToPrimaryKeySchema(rwt, newSch, renames...)

rewriteRequired := false
if i.m.targetSchema[oldColIdx].Nullable && !i.m.column.Nullable {
Expand Down
23 changes: 19 additions & 4 deletions sql/schemas.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,21 +150,32 @@ func NewPrimaryKeySchema(s Schema, pkOrds ...int) PrimaryKeySchema {

// SchemaToPrimaryKeySchema adapts the schema given to a PrimaryKey schema using the primary keys of the table given, if
// present. The resulting PrimaryKeySchema may have an empty key set if the table has no primary keys. Matching for
// ordinals is performed by column name.
func SchemaToPrimaryKeySchema(table Table, sch Schema) PrimaryKeySchema {
// ordinals is performed by column name, with the aid of |renames| when provided.
func SchemaToPrimaryKeySchema(table Table, sch Schema, renames ...ColumnRename) PrimaryKeySchema {
var pks []*Column
if pkt, ok := table.(PrimaryKeyTable); ok {
schema := pkt.PrimaryKeySchema()
for _, ordinal := range schema.PkOrdinals {
pks = append(pks, schema.Schema[ordinal])
}
} else {
// set PkOrdinals by schema order
return NewPrimaryKeySchema(sch)
}

mapping := make(map[string]string)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mapping is a bit generic as a name. Maybe change to oldToNewNames or something along those lines.

for _, r := range renames {
mapping[strings.ToLower(r.Before)] = r.After
}

ords := make([]int, len(pks))
for i, pk := range pks {
ords[i] = sch.IndexOf(pk.Name, pk.Source)
name := strings.ToLower(pk.Name)
if n, ok := mapping[name]; ok {
name = n
}
ords[i] = sch.IndexOf(name, pk.Source)
}

return NewPrimaryKeySchema(sch, ords...)
}

Expand All @@ -173,3 +184,7 @@ type ColumnOrder struct {
First bool // True if this column should come first
AfterColumn string // Set to the name of the column after which this column should appear
}

type ColumnRename struct {
Before, After string
}