-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathshow_create.go
270 lines (248 loc) · 8.38 KB
/
show_create.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
// Copyright 2017 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 sql
import (
"bytes"
"context"
"fmt"
"strings"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catformat"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemaexpr"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
)
type shouldOmitFKClausesFromCreate int
const (
_ shouldOmitFKClausesFromCreate = iota
// OmitFKClausesFromCreate will not include any foreign key information in the
// create statement.
OmitFKClausesFromCreate
// IncludeFkClausesInCreate will include foreign key information in the create
// statement, and error if a FK cannot be resolved.
IncludeFkClausesInCreate
// OmitMissingFKClausesFromCreate will include foreign key information only if they
// can be resolved. If not, it will ignore those constraints.
// This is used in the case when showing the create statement for
// tables stored in backups. Not all relevant tables may have been
// included in the back up, so some foreign key information may be
// impossible to retrieve.
OmitMissingFKClausesFromCreate
)
// ShowCreateDisplayOptions is a container struct holding the options that
// ShowCreate uses to determine how much information should be included in the
// CREATE statement.
type ShowCreateDisplayOptions struct {
FKDisplayMode shouldOmitFKClausesFromCreate
// Comment resolution requires looking up table data from system.comments
// table. This is sometimes not possible. For example, in the context of a
// SHOW BACKUP which may resolve the create statement, there is no mechanism
// to read any table data from the backup (nor is there a guarantee that the
// system.comments table is included in the backup at all).
IgnoreComments bool
}
// ShowCreateTable returns a valid SQL representation of the CREATE
// TABLE statement used to create the given table.
//
// The names of the tables referenced by foreign keys are prefixed by their own
// database name unless it is equal to the given dbPrefix. This allows us to
// elide the prefix when the given table references other tables in the
// current database.
func ShowCreateTable(
ctx context.Context,
p PlanHookState,
tn *tree.TableName,
dbPrefix string,
desc catalog.TableDescriptor,
lCtx simpleSchemaResolver,
displayOptions ShowCreateDisplayOptions,
) (string, error) {
a := &tree.DatumAlloc{}
f := p.ExtendedEvalContext().FmtCtx(tree.FmtSimple)
f.WriteString("CREATE ")
if desc.IsTemporary() {
f.WriteString("TEMP ")
}
f.WriteString("TABLE ")
f.FormatNode(tn)
f.WriteString(" (")
// Inaccessible columns are not displayed in SHOW CREATE TABLE.
for i, col := range desc.AccessibleColumns() {
if i != 0 {
f.WriteString(",")
}
f.WriteString("\n\t")
colstr, err := schemaexpr.FormatColumnForDisplay(
ctx, desc, col, &p.RunParams(ctx).p.semaCtx, p.RunParams(ctx).p.SessionData(),
)
if err != nil {
return "", err
}
f.WriteString(colstr)
}
if desc.IsPhysicalTable() {
f.WriteString(",\n\tCONSTRAINT ")
formatQuoteNames(&f.Buffer, desc.GetPrimaryIndex().GetName())
f.WriteString(" ")
f.WriteString(tabledesc.PrimaryKeyString(desc))
}
// TODO (lucy): Possibly include FKs in the mutations list here, or else
// exclude check mutations below, for consistency.
if displayOptions.FKDisplayMode != OmitFKClausesFromCreate {
if err := desc.ForeachOutboundFK(func(fk *descpb.ForeignKeyConstraint) error {
fkCtx := tree.NewFmtCtx(tree.FmtSimple)
fkCtx.WriteString(",\n\tCONSTRAINT ")
fkCtx.FormatNameP(&fk.Name)
fkCtx.WriteString(" ")
// Passing in EmptySearchPath causes the schema name to show up in the
// constraint definition, which we need for `cockroach dump` output to be
// usable.
if err := showForeignKeyConstraint(
&fkCtx.Buffer,
dbPrefix,
desc,
fk,
lCtx,
sessiondata.EmptySearchPath,
); err != nil {
if displayOptions.FKDisplayMode == OmitMissingFKClausesFromCreate {
return nil
}
// When FKDisplayMode == IncludeFkClausesInCreate.
return err
}
f.WriteString(fkCtx.String())
return nil
}); err != nil {
return "", err
}
}
for _, idx := range desc.PublicNonPrimaryIndexes() {
// Showing the primary index is handled above.
// Build the PARTITION BY clause.
var partitionBuf bytes.Buffer
if err := ShowCreatePartitioning(
a, p.ExecCfg().Codec, desc, idx, idx.GetPartitioning(), &partitionBuf, 1 /* indent */, 0, /* colOffset */
); err != nil {
return "", err
}
f.WriteString(",\n\t")
idxStr, err := catformat.IndexForDisplay(
ctx,
desc,
&descpb.AnonymousTable,
idx,
partitionBuf.String(),
tree.FmtSimple,
p.RunParams(ctx).p.SemaCtx(),
p.RunParams(ctx).p.SessionData(),
catformat.IndexDisplayDefOnly,
)
if err != nil {
return "", err
}
f.WriteString(idxStr)
}
// Create the FAMILY and CONSTRAINTs of the CREATE statement
showFamilyClause(desc, f)
if err := showConstraintClause(ctx, desc, &p.RunParams(ctx).p.semaCtx, p.RunParams(ctx).p.SessionData(), f); err != nil {
return "", err
}
if err := ShowCreatePartitioning(
a, p.ExecCfg().Codec, desc, desc.GetPrimaryIndex(), desc.GetPrimaryIndex().GetPartitioning(), &f.Buffer, 0 /* indent */, 0, /* colOffset */
); err != nil {
return "", err
}
var storageParams []string
if ttl := desc.GetRowLevelTTL(); ttl != nil {
storageParams = append(
storageParams,
`ttl = 'on'`,
`ttl_automatic_column = 'on'`,
fmt.Sprintf(`ttl_expire_after = %s`, ttl.DurationExpr),
)
if bs := ttl.SelectBatchSize; bs != 0 {
storageParams = append(storageParams, fmt.Sprintf(`ttl_select_batch_size = %d`, bs))
}
if bs := ttl.DeleteBatchSize; bs != 0 {
storageParams = append(storageParams, fmt.Sprintf(`ttl_delete_batch_size = %d`, bs))
}
if cron := ttl.DeletionCron; cron != "" {
storageParams = append(storageParams, fmt.Sprintf(`ttl_delete_batch_size = '%s'`, cron))
}
}
if exclude := desc.GetExcludeDataFromBackup(); exclude {
storageParams = append(storageParams, `exclude_data_from_backup = true`)
}
if len(storageParams) > 0 {
f.Buffer.WriteString(` WITH (`)
f.Buffer.WriteString(strings.Join(storageParams, ", "))
f.Buffer.WriteString(`)`)
}
if err := showCreateLocality(desc, f); err != nil {
return "", err
}
if !displayOptions.IgnoreComments {
if err := showComments(tn, desc, selectComment(ctx, p, desc.GetID()), &f.Buffer); err != nil {
return "", err
}
}
return f.CloseAndGetString(), nil
}
// formatQuoteNames quotes and adds commas between names.
func formatQuoteNames(buf *bytes.Buffer, names ...string) {
f := tree.NewFmtCtx(tree.FmtSimple)
for i := range names {
if i > 0 {
f.WriteString(", ")
}
f.FormatNameP(&names[i])
}
buf.WriteString(f.CloseAndGetString())
}
// ShowCreate returns a valid SQL representation of the CREATE
// statement used to create the descriptor passed in.
//
// The names of the tables references by foreign keys are prefixed by their own
// database name unless it is equal to the given dbPrefix. This allows us to
// elide the prefix when the given table references other tables in the current
// database.
func (p *planner) ShowCreate(
ctx context.Context,
dbPrefix string,
allDescs []descpb.Descriptor,
desc catalog.TableDescriptor,
displayOptions ShowCreateDisplayOptions,
) (string, error) {
var stmt string
var err error
tn := tree.MakeUnqualifiedTableName(tree.Name(desc.GetName()))
if desc.IsView() {
stmt, err = ShowCreateView(ctx, &p.RunParams(ctx).p.semaCtx, p.RunParams(ctx).p.SessionData(), &tn, desc)
} else if desc.IsSequence() {
stmt, err = ShowCreateSequence(ctx, &tn, desc)
} else {
lCtx, lErr := newInternalLookupCtxFromDescriptorProtos(
ctx, allDescs, nil, /* want all tables */
)
if lErr != nil {
return "", lErr
}
// Overwrite desc with hydrated descriptor.
desc, err = lCtx.getTableByID(desc.GetID())
if err != nil {
return "", err
}
stmt, err = ShowCreateTable(ctx, p, &tn, dbPrefix, desc, lCtx, displayOptions)
}
return stmt, err
}