-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
show_create.go
259 lines (242 loc) · 8.74 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
// 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"
"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/rowenc"
"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 references by foreign keys, and the
// interleaved parent if any, 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 := &rowenc.DatumAlloc{}
f := tree.NewFmtCtx(tree.FmtSimple)
f.WriteString("CREATE ")
if desc.IsTemporary() {
f.WriteString("TEMP ")
}
f.WriteString("TABLE ")
f.FormatNode(tn)
f.WriteString(" (")
primaryKeyIsOnVisibleColumn := false
// visibleCols := desc.VisibleColumns()
visibleCols := desc.AllNonDropColumns()
for i := range visibleCols {
col := &visibleCols[i]
if i != 0 {
f.WriteString(",")
}
f.WriteString("\n\t")
colstr, err := schemaexpr.FormatColumnForDisplay(ctx, desc, col, &p.RunParams(ctx).p.semaCtx)
if err != nil {
return "", err
}
f.WriteString(colstr)
if desc.IsPhysicalTable() && desc.GetPrimaryIndex().ColumnIDs[0] == col.ID {
// Only set primaryKeyIsOnVisibleColumn to true if the primary key
// is on a visible column (not rowid).
primaryKeyIsOnVisibleColumn = true
}
}
if primaryKeyIsOnVisibleColumn ||
(desc.IsPhysicalTable() && desc.GetPrimaryIndex().IsSharded()) {
f.WriteString(",\n\tCONSTRAINT ")
formatQuoteNames(&f.Buffer, desc.GetPrimaryIndex().Name)
f.WriteString(" ")
f.WriteString(desc.PrimaryKeyString())
}
// 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
}
}
allIdx := append(
append([]descpb.IndexDescriptor{}, desc.GetPublicNonPrimaryIndexes()...),
*desc.GetPrimaryIndex())
for i := range allIdx {
idx := &allIdx[i]
// Only add indexes to the create_statement column, and not to the
// create_nofks column if they are not associated with an INTERLEAVE
// statement.
// Initialize to false if Interleave has no ancestors, indicating that the
// index is not interleaved at all.
includeInterleaveClause := len(idx.Interleave.Ancestors) == 0
if displayOptions.FKDisplayMode != OmitFKClausesFromCreate {
// The caller is instructing us to not omit FK clauses from inside the CREATE.
// (i.e. the caller does not want them as separate DDL.)
// Since we're including FK clauses, we need to also include the PARTITION and INTERLEAVE
// clauses as well.
includeInterleaveClause = true
}
if idx.ID != desc.GetPrimaryIndex().ID && includeInterleaveClause {
// Showing the primary index is handled above.
f.WriteString(",\n\t")
idxStr, err := catformat.IndexForDisplay(ctx, desc, &descpb.AnonymousTable, idx, &p.RunParams(ctx).p.semaCtx)
if err != nil {
return "", err
}
f.WriteString(idxStr)
// Showing the INTERLEAVE and PARTITION BY for the primary index are
// handled last.
// Add interleave or Foreign Key indexes only to the create_table columns,
// and not the create_nofks column.
if includeInterleaveClause {
if err := showCreateInterleave(idx, &f.Buffer, dbPrefix, lCtx); err != nil {
return "", err
}
}
if err := ShowCreatePartitioning(
a, p.ExecCfg().Codec, desc, idx, &idx.Partitioning, &f.Buffer, 1 /* indent */, 0, /* colOffset */
); err != nil {
return "", err
}
}
}
// Create the FAMILY and CONSTRAINTs of the CREATE statement
showFamilyClause(desc, f)
if err := showConstraintClause(ctx, desc, &p.RunParams(ctx).p.semaCtx, f); err != nil {
return "", err
}
if err := showCreateInterleave(desc.GetPrimaryIndex(), &f.Buffer, dbPrefix, lCtx); err != nil {
return "", err
}
if err := ShowCreatePartitioning(
a, p.ExecCfg().Codec, desc, desc.GetPrimaryIndex(), &desc.GetPrimaryIndex().Partitioning, &f.Buffer, 0 /* indent */, 0, /* colOffset */
); err != nil {
return "", err
}
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, and the
// interleaved parent if any, 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 *tabledesc.Immutable,
displayOptions ShowCreateDisplayOptions,
) (string, error) {
var stmt string
var err error
tn := tree.MakeUnqualifiedTableName(tree.Name(desc.Name))
if desc.IsView() {
stmt, err = ShowCreateView(ctx, &tn, desc)
} else if desc.IsSequence() {
stmt, err = ShowCreateSequence(ctx, &tn, desc)
} else {
lCtx, lErr := newInternalLookupCtxFromDescriptors(ctx, allDescs, nil /* want all tables */)
if lErr != nil {
return "", lErr
}
stmt, err = ShowCreateTable(ctx, p, &tn, dbPrefix, desc, lCtx, displayOptions)
}
return stmt, err
}