-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathdrop.go
272 lines (245 loc) · 8.19 KB
/
drop.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
// Copyright 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: XisiHuang (cockhuangxh@163.com)
package sql
import (
"github.com/cockroachdb/cockroach/client"
"github.com/cockroachdb/cockroach/config"
"github.com/cockroachdb/cockroach/roachpb"
"github.com/cockroachdb/cockroach/sql/parser"
"github.com/cockroachdb/cockroach/sql/privilege"
"github.com/cockroachdb/cockroach/util"
)
// DropDatabase drops a database.
// Privileges: DROP on database.
// Notes: postgres allows only the database owner to DROP a database.
// mysql requires the DROP privileges on the database.
// TODO(XisiHuang): our DROP DATABASE is like the postgres DROP SCHEMA
// (cockroach database == postgres schema). the postgres default of not
// dropping the schema if there are dependent objects is more sensible
// (see the RESTRICT and CASCADE options).
func (p *planner) DropDatabase(n *parser.DropDatabase) (planNode, *roachpb.Error) {
if n.Name == "" {
return nil, roachpb.NewError(errEmptyDatabaseName)
}
// Check that the database exists.
dbDesc, pErr := p.getDatabaseDescEx(string(n.Name))
if dbDesc == nil {
if n.IfExists {
// Noop.
return &emptyNode{}, nil
}
return nil, databaseDoesntExistUErr(string(n.Name))
}
if err := p.checkPrivilege(dbDesc, privilege.DROP); err != nil {
return nil, roachpb.NewError(err)
}
tbNames, pErr := p.getTableNames(dbDesc)
if pErr != nil {
return nil, pErr
}
tbNameStrings := make([]string, len(tbNames))
for i := range tbNames {
tbDesc, err := p.dropTableImpl(tbNames[i])
if err != nil {
return nil, err
}
if tbDesc == nil {
// Database claims to have this table, but it does not exist.
return nil, roachpb.NewErrorf("table %q was described by database %q, but does not exist",
tbNames[i].String())
}
tbNameStrings[i] = tbDesc.Name
}
zoneKey, nameKey, descKey := getKeysForDatabaseDescriptor(dbDesc)
b := &client.Batch{}
b.Del(descKey)
b.Del(nameKey)
// Delete the zone config entry for this database.
b.Del(zoneKey)
p.setTestingVerifyMetadata(func(systemConfig config.SystemConfig) error {
for _, key := range [...]roachpb.Key{descKey, nameKey, zoneKey} {
if err := expectDeleted(systemConfig, key); err != nil {
return err
}
}
return nil
})
if pErr := p.txn.Run(b); pErr != nil {
return nil, pErr
}
// Log Drop Database event.
if pErr := MakeEventLogger(p.leaseMgr).InsertEventRecord(p.txn,
EventLogDropDatabase,
int32(dbDesc.ID),
int32(p.evalCtx.NodeID),
struct {
DatabaseName string
Statement string
User string
DroppedTables []string
}{n.Name.String(), n.String(), p.session.User, tbNameStrings},
); pErr != nil {
return nil, pErr
}
return &emptyNode{}, nil
}
// DropIndex drops an index.
// Privileges: CREATE on table.
// Notes: postgres allows only the index owner to DROP an index.
// mysql requires the INDEX privilege on the table.
func (p *planner) DropIndex(n *parser.DropIndex) (planNode, *roachpb.Error) {
for _, indexQualifiedName := range n.Names {
if err := indexQualifiedName.NormalizeTableName(p.session.Database); err != nil {
return nil, roachpb.NewError(err)
}
tableDesc, pErr := p.getTableDesc(indexQualifiedName)
if pErr != nil {
return nil, pErr
}
if err := p.checkPrivilege(&tableDesc, privilege.CREATE); err != nil {
return nil, roachpb.NewError(err)
}
idxName := indexQualifiedName.Index()
status, i, err := tableDesc.FindIndexByName(idxName)
if err != nil {
if n.IfExists {
// Noop.
return &emptyNode{}, nil
}
// Index does not exist, but we want it to: error out.
return nil, roachpb.NewError(err)
}
// Queue the mutation.
switch status {
case DescriptorActive:
tableDesc.addIndexMutation(tableDesc.Indexes[i], DescriptorMutation_DROP)
tableDesc.Indexes = append(tableDesc.Indexes[:i], tableDesc.Indexes[i+1:]...)
case DescriptorIncomplete:
switch tableDesc.Mutations[i].Direction {
case DescriptorMutation_ADD:
return nil, roachpb.NewUErrorf("index %q in the middle of being added, try again later", idxName)
case DescriptorMutation_DROP:
return &emptyNode{}, nil
}
}
mutationID := tableDesc.setUpVersion()
if err := tableDesc.Validate(); pErr != nil {
return nil, roachpb.NewError(err)
}
if pErr := p.writeTableDesc(&tableDesc); pErr != nil {
return nil, pErr
}
p.notifySchemaChange(tableDesc.ID, mutationID)
}
return &emptyNode{}, nil
}
// DropTable drops a table.
// Privileges: DROP on table.
// Notes: postgres allows only the table owner to DROP a table.
// mysql requires the DROP privilege on the table.
func (p *planner) DropTable(n *parser.DropTable) (planNode, *roachpb.Error) {
for i := range n.Names {
droppedDesc, err := p.dropTableImpl(n.Names[i])
if err != nil {
return nil, err
}
if droppedDesc == nil {
if n.IfExists {
continue
}
// Table does not exist, but we want it to: error out.
return nil, tableDoesntExistUErr(n.Names[i].Table())
}
// Log a Drop Table event for this table.
if pErr := MakeEventLogger(p.leaseMgr).InsertEventRecord(p.txn,
EventLogDropTable,
int32(droppedDesc.ID),
int32(p.evalCtx.NodeID),
struct {
TableName string
Statement string
User string
}{droppedDesc.Name, n.String(), p.session.User},
); pErr != nil {
return nil, pErr
}
}
return &emptyNode{}, nil
}
// dropTableImpl is used to drop a single table by name, which can result from
// either a DROP TABLE or DROP DATABASE statement. This method returns the
// dropped table descriptor, to be used for the purpose of logging the event.
// The table is not actually truncated or deleted synchronously. Instead, it is
// marked as deleted (meaning up_version is set and deleted is set) and the
// actual deletion happens async in a schema changer. Note that, courtesy of
// up_version, the actual truncation and dropping will only happen once every
// node ACKs the version of the descriptor with the deleted bit set, meaning the
// lease manager will not hand out new leases for it).
// If the table does not exist, this function returns a nil descriptor.
func (p *planner) dropTableImpl(name *parser.QualifiedName) (
*TableDescriptor, *roachpb.Error) {
tableDesc, pErr := p.getTableDescEx(name)
if pErr != nil {
return nil, pErr
}
if tableDesc == nil {
return nil, pErr
}
if pErr := p.checkPrivilege(tableDesc, privilege.DROP); pErr != nil {
return nil, roachpb.NewError(pErr)
}
tableDesc.Deleted = true
tableDesc.addDropTableMutation()
mutationID := tableDesc.setUpVersion()
if pErr = p.writeTableDesc(tableDesc); pErr != nil {
return nil, pErr
}
p.notifySchemaChange(tableDesc.ID, mutationID)
verifyMetadataCallback := func(systemConfig config.SystemConfig, tableID ID) error {
desc, err := GetTableDesc(systemConfig, tableID)
if err != nil {
return err
}
if desc == nil {
return util.Errorf("table %d missing", tableID)
}
if desc.Deleted {
return nil
}
return util.Errorf("expected table %d to be marked as deleted", tableID)
}
p.setTestingVerifyMetadata(func(systemConfig config.SystemConfig) error {
return verifyMetadataCallback(systemConfig, tableDesc.ID)
})
return tableDesc, nil
}
// truncateAndDropTable batches all the commands required for truncating and deleting the
// table descriptor.
// It is called from a mutation, async wrt the DROP statement.
func (p *planner) truncateAndDropTable(
tableDesc *TableDescriptor) *roachpb.Error {
if pErr := p.TruncateImpl(tableDesc); pErr != nil {
return pErr
}
zoneKey, nameKey, descKey := getKeysForTableDescriptor(tableDesc)
// Delete table descriptor
b := client.Batch{}
b.Del(descKey)
b.Del(nameKey)
// Delete the zone config entry for this table.
b.Del(zoneKey)
return p.txn.Run(&b)
}