-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathschema_changes.go
322 lines (295 loc) · 11 KB
/
schema_changes.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
// Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package upgrades
import (
"bytes"
"context"
"fmt"
"strings"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/upgrade"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/redact"
"github.com/kr/pretty"
)
type operation struct {
// Operation name.
name redact.RedactableString
// List of schema names, e.g., column names, which are modified in the query.
schemaList []string
// Schema change query.
query string
// Function to check existing schema.
schemaExistsFn func(catalog.TableDescriptor, catalog.TableDescriptor, string) (bool, error)
}
// waitForJobStatement is the statement used to wait for an ongoing job to
// complete.
const waitForJobStatement = "SHOW JOBS WHEN COMPLETE VALUES ($1)"
// migrateTable is run during an upgrade to a new version and changes an existing
// table's schema based on schemaChangeQuery. The schema-change is ignored if the
// table already has the required changes.
//
// This function reads the existing table descriptor from storage and passes it
// to schemaExists function to verify whether the schema-change already exists or
// not. If the change is already done, the function does not perform the change
// again, which makes migrateTable idempotent.
//
// schemaExists function should be customized based on the table being modified,
// ignoring the fields that do not matter while comparing with an existing descriptor.
//
// If multiple changes are done in the same query, e.g., if multiple columns are
// added, the function should check all changes to exist or absent, returning
// an error if changes exist partially.
func migrateTable(
ctx context.Context,
_ clusterversion.ClusterVersion,
d upgrade.TenantDeps,
op operation,
storedTableID descpb.ID,
expectedTable catalog.TableDescriptor,
) error {
for {
// - Fetch the table, reading its descriptor from storage.
// - Check if any mutation jobs exist for the table. These mutations can
// belong to a previous upgrade attempt that failed.
// - If any mutation job exists:
// - Wait for the ongoing mutations to complete.
// - Continue to the beginning of the loop to cater for the mutations
// that may have started while waiting for existing mutations to complete.
// - Check if the intended schema-changes already exist.
// - If the changes already exist, skip the schema-change and return as
// the changes are already done in a previous upgrade attempt.
// - Otherwise, perform the schema-change and return.
log.Infof(ctx, "performing table migration operation %v", op.name)
// Retrieve the table.
storedTable, err := readTableDescriptor(ctx, d, storedTableID)
if err != nil {
return err
}
// Wait for any in-flight schema changes to complete.
if mutations := storedTable.GetMutationJobs(); len(mutations) > 0 {
for _, mutation := range mutations {
log.Infof(ctx, "waiting for the mutation job %v to complete", mutation.JobID)
if _, err := d.InternalExecutor.Exec(ctx, "migration-mutations-wait",
nil, waitForJobStatement, mutation.JobID); err != nil {
return err
}
}
continue
}
// Ignore the schema change if the table already has the required schema.
// Expect all or none.
var exists bool
for i, schemaName := range op.schemaList {
hasSchema, err := op.schemaExistsFn(storedTable, expectedTable, schemaName)
if err != nil {
return errors.Wrapf(err, "error while validating descriptors during"+
" operation %s", op.name)
}
if i > 0 && exists != hasSchema {
return errors.Errorf("error while validating descriptors. observed"+
" partial schema exists while performing %v", op.name)
}
exists = hasSchema
}
if exists {
log.Infof(ctx, "skipping %s operation as the schema change already exists.", op.name)
return nil
}
// Modify the table.
log.Infof(ctx, "performing operation: %s", op.name)
if _, err := d.InternalExecutor.ExecEx(
ctx,
fmt.Sprintf("migration-alter-table-%d", storedTableID),
nil, /* txn */
sessiondata.InternalExecutorOverride{User: username.NodeUserName()},
op.query); err != nil {
return err
}
return nil
}
}
func readTableDescriptor(
ctx context.Context, d upgrade.TenantDeps, tableID descpb.ID,
) (catalog.TableDescriptor, error) {
var t catalog.TableDescriptor
if err := d.InternalExecutorFactory.DescsTxn(ctx, d.DB, func(
ctx context.Context, txn *kv.Txn, descriptors *descs.Collection,
) (err error) {
t, err = descriptors.GetImmutableTableByID(ctx, txn, tableID, tree.ObjectLookupFlags{
CommonLookupFlags: tree.CommonLookupFlags{
AvoidLeased: true,
Required: true,
},
})
return err
}); err != nil {
return nil, err
}
return t, nil
}
// ensureProtoMessagesAreEqual verifies whether the given protobufs are equal or
// not, returning an error if they are not equal.
func ensureProtoMessagesAreEqual(expected, found protoutil.Message) error {
expectedBytes, err := protoutil.Marshal(expected)
if err != nil {
return err
}
foundBytes, err := protoutil.Marshal(found)
if err != nil {
return err
}
if bytes.Equal(expectedBytes, foundBytes) {
return nil
}
return errors.Errorf("expected descriptor doesn't match "+
"with found descriptor: %s", strings.Join(pretty.Diff(expected, found), "\n"))
}
// hasColumn returns true if storedTable already has the given column, comparing
// with expectedTable.
// storedTable descriptor must be read from system storage as compared to reading
// from the systemschema package. On the contrary, expectedTable must be accessed
// directly from systemschema package.
// This function returns an error if the column exists but doesn't match with the
// expectedTable descriptor. The comparison is not strict as several descriptor
// fields are ignored.
func hasColumn(storedTable, expectedTable catalog.TableDescriptor, colName string) (bool, error) {
storedCol, err := storedTable.FindColumnWithName(tree.Name(colName))
if err != nil {
if strings.Contains(err.Error(), "does not exist") {
return false, nil
}
return false, err
}
expectedCol, err := expectedTable.FindColumnWithName(tree.Name(colName))
if err != nil {
return false, errors.Wrapf(err, "columns name %s is invalid.", colName)
}
expectedCopy := expectedCol.ColumnDescDeepCopy()
storedCopy := storedCol.ColumnDescDeepCopy()
storedCopy.ID = 0
expectedCopy.ID = 0
if err = ensureProtoMessagesAreEqual(&expectedCopy, &storedCopy); err != nil {
return false, err
}
return true, nil
}
// hasIndex returns true if storedTable already has the given index, comparing
// with expectedTable.
// storedTable descriptor must be read from system storage as compared to reading
// from the systemschema package. On the contrary, expectedTable must be accessed
// directly from systemschema package.
// This function returns an error if the index exists but doesn't match with the
// expectedTable descriptor. The comparison is not strict as several descriptor
// fields are ignored.
func hasIndex(storedTable, expectedTable catalog.TableDescriptor, indexName string) (bool, error) {
storedIdx, err := storedTable.FindIndexWithName(indexName)
if err != nil {
if strings.Contains(err.Error(), "does not exist") {
return false, nil
}
return false, err
}
expectedIdx, err := expectedTable.FindIndexWithName(indexName)
if err != nil {
return false, errors.Wrapf(err, "index name %s is invalid", indexName)
}
// Ignore the fields that don't matter in the comparison.
storedCopy := indexDescForComparison(storedIdx)
expectedCopy := indexDescForComparison(expectedIdx)
if err = ensureProtoMessagesAreEqual(expectedCopy, storedCopy); err != nil {
return false, err
}
return true, nil
}
// indexDescForComparison extracts an index descriptor from an index with
// numerical fields zeroed so that the meaning can be compared directly even
// if the numerical values differ.
func indexDescForComparison(idx catalog.Index) *descpb.IndexDescriptor {
desc := idx.IndexDescDeepCopy()
desc.ID = 0
desc.Version = 0
desc.ConstraintID = 0
// CreatedExplicitly is an ignored field because there exists an inconsistency
// between CREATE TABLE (... INDEX) and CREATE INDEX.
// See https://github.com/cockroachdb/cockroach/issues/65929.
desc.CreatedExplicitly = false
// Clear out the column IDs, but retain their length. Column IDs may
// change. Note that we retain the name slices. Those should match.
desc.StoreColumnIDs = nil
for i := range desc.StoreColumnIDs {
desc.StoreColumnIDs[i] = 0
}
for i := range desc.KeyColumnIDs {
desc.KeyColumnIDs[i] = 0
}
for i := range desc.KeySuffixColumnIDs {
desc.KeySuffixColumnIDs[i] = 0
}
desc.CreatedAtNanos = 0
return &desc
}
// doesNotHaveIndex returns true if storedTable does not have an index named indexName.
func doesNotHaveIndex(
storedTable, expectedTable catalog.TableDescriptor, indexName string,
) (bool, error) {
idx, _ := storedTable.FindIndexWithName(indexName)
return idx == nil, nil
}
// hasColumnFamily returns true if storedTable already has the given column
// family, comparing with expectedTable. storedTable descriptor must be read
// from system storage as compared to reading from the systemschema package. On
// the contrary, expectedTable must be accessed directly from systemschema
// package. This function returns an error if the column doesn't exist in the
// expectedTable descriptor.
func hasColumnFamily(
storedTable, expectedTable catalog.TableDescriptor, colFamily string,
) (bool, error) {
var storedFamily, expectedFamily *descpb.ColumnFamilyDescriptor
for _, fam := range storedTable.GetFamilies() {
if fam.Name == colFamily {
storedFamily = &fam
break
}
}
if storedFamily == nil {
return false, nil
}
for _, fam := range expectedTable.GetFamilies() {
if fam.Name == colFamily {
expectedFamily = &fam
break
}
}
if expectedFamily == nil {
return false, errors.Errorf("column family %s does not exist", colFamily)
}
// Check that columns match.
storedFamilyCols := storedFamily.ColumnNames
expectedFamilyCols := expectedFamily.ColumnNames
if len(storedFamilyCols) != len(expectedFamilyCols) {
return false, nil
}
for i, storedCol := range storedFamilyCols {
if storedCol != expectedFamilyCols[i] {
return false, nil
}
}
return true, nil
}