forked from cockroachdb/cockroach
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn_executor_prepare.go
509 lines (458 loc) · 16.1 KB
/
conn_executor_prepare.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
// Copyright 2018 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.
package sql
import (
"context"
"fmt"
"strconv"
"unsafe"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgwirebase"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/util/fsm"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/lib/pq/oid"
"github.com/pkg/errors"
)
func (ex *connExecutor) execPrepare(
ctx context.Context, parseCmd PrepareStmt,
) (fsm.Event, fsm.EventPayload) {
retErr := func(err error) (fsm.Event, fsm.EventPayload) {
return eventNonRetriableErr{IsCommit: fsm.False}, eventNonRetriableErrPayload{err: err}
}
// The anonymous statement can be overwritter.
if parseCmd.Name != "" {
if _, ok := ex.prepStmtsNamespace.prepStmts[parseCmd.Name]; ok {
err := pgerror.NewErrorf(
pgerror.CodeDuplicatePreparedStatementError,
"prepared statement %q already exists", parseCmd.Name,
)
return retErr(err)
}
} else {
// Deallocate the unnamed statement, if it exists.
ex.deletePreparedStmt(ctx, "")
}
ps, err := ex.addPreparedStmt(
ctx, parseCmd.Name, Statement{AST: parseCmd.Stmt}, parseCmd.TypeHints,
)
if err != nil {
return retErr(err)
}
// Convert the inferred SQL types back to an array of pgwire Oids.
inTypes := make([]oid.Oid, 0, len(ps.TypeHints))
if len(ps.TypeHints) > pgwirebase.MaxPreparedStatementArgs {
return retErr(
pgwirebase.NewProtocolViolationErrorf(
"more than %d arguments to prepared statement: %d",
pgwirebase.MaxPreparedStatementArgs, len(ps.TypeHints)))
}
for k, t := range ps.TypeHints {
i, err := strconv.Atoi(k)
if err != nil || i < 1 {
return retErr(pgerror.NewErrorf(
pgerror.CodeUndefinedParameterError, "invalid placeholder name: $%s", k))
}
// Placeholder names are 1-indexed; the arrays in the protocol are
// 0-indexed.
i--
// Grow inTypes to be at least as large as i. Prepopulate all
// slots with the hints provided, if any.
for j := len(inTypes); j <= i; j++ {
inTypes = append(inTypes, 0)
if j < len(parseCmd.RawTypeHints) {
inTypes[j] = parseCmd.RawTypeHints[j]
}
}
// OID to Datum is not a 1-1 mapping (for example, int4 and int8
// both map to TypeInt), so we need to maintain the types sent by
// the client.
if inTypes[i] != 0 {
continue
}
inTypes[i] = t.Oid()
}
for i, t := range inTypes {
if t == 0 {
return retErr(pgerror.NewErrorf(
pgerror.CodeIndeterminateDatatypeError,
"could not determine data type of placeholder $%d", i+1))
}
}
// Remember the inferred placeholder types so they can be reported on
// Describe.
ps.InTypes = inTypes
return nil, nil
}
// addPreparedStmt creates a new PreparedStatement with the provided name using
// the given query. The new prepared statement is added to the connExecutor and
// also returned. It is illegal to call this when a statement with that name
// already exists (even for anonymous prepared statements).
//
// placeholderHints are used to assist in inferring placeholder types.
func (ex *connExecutor) addPreparedStmt(
ctx context.Context, name string, stmt Statement, placeholderHints tree.PlaceholderTypes,
) (*PreparedStatement, error) {
if _, ok := ex.prepStmtsNamespace.prepStmts[name]; ok {
panic(fmt.Sprintf("prepared statement already exists: %q", name))
}
// Prepare the query. This completes the typing of placeholders.
prepared, err := ex.prepare(ctx, stmt, placeholderHints)
if err != nil {
return nil, err
}
if err := prepared.memAcc.Grow(ctx, int64(len(name))); err != nil {
return nil, err
}
ex.prepStmtsNamespace.prepStmts[name] = prepStmtEntry{
PreparedStatement: prepared,
portals: make(map[string]struct{}),
}
return prepared, nil
}
// prepare prepares the given statement.
//
// placeholderHints may contain partial type information for placeholders.
// prepare will populate the missing types. It can be nil.
//
// The PreparedStatement is returned (or nil if there are no results). The
// returned PreparedStatement needs to be close()d once its no longer in use.
func (ex *connExecutor) prepare(
ctx context.Context, stmt Statement, placeholderHints tree.PlaceholderTypes,
) (*PreparedStatement, error) {
if placeholderHints == nil {
placeholderHints = make(tree.PlaceholderTypes)
}
prepared := &PreparedStatement{
TypeHints: placeholderHints,
memAcc: ex.sessionMon.MakeBoundAccount(),
}
// NB: if we start caching the plan, we'll want to keep around the memory
// account used for the plan, rather than clearing it.
defer prepared.memAcc.Clear(ctx)
if stmt.AST == nil {
return prepared, nil
}
prepared.Str = stmt.String()
prepared.Statement = stmt.AST
prepared.AnonymizedStr = anonymizeStmt(stmt)
if err := placeholderHints.ProcessPlaceholderAnnotations(stmt.AST); err != nil {
return nil, err
}
// Preparing needs a transaction because it needs to retrieve db/table
// descriptors for type checking.
// TODO(andrei): Needing a transaction for preparing seems non-sensical, as
// the prepared statement outlives the txn. I hope that it's not used for
// anything other than getting a timestamp.
txn := client.NewTxn(ex.server.cfg.DB, ex.server.cfg.NodeID.Get(), client.RootTxn)
// Create a plan for the statement to figure out the typing, then close the
// plan.
if err := func() error {
p := &ex.planner
ex.resetPlanner(ctx, p, txn, ex.server.cfg.Clock.PhysicalTime() /* stmtTimestamp */)
p.semaCtx.Placeholders.SetTypeHints(placeholderHints)
p.extendedEvalCtx.PrepareOnly = true
p.extendedEvalCtx.ActiveMemAcc = &prepared.memAcc
// constantMemAcc accounts for all constant folded values that are computed
// prior to any rows being computed.
constantMemAcc := p.extendedEvalCtx.Mon.MakeBoundAccount()
p.extendedEvalCtx.ActiveMemAcc = &constantMemAcc
defer constantMemAcc.Close(ctx)
protoTS, err := p.isAsOf(stmt.AST, ex.server.cfg.Clock.Now() /* max */)
if err != nil {
return err
}
if protoTS != nil {
p.asOfSystemTime = true
// We can't use cached descriptors anywhere in this query, because
// we want the descriptors at the timestamp given, not the latest
// known to the cache.
p.avoidCachedDescriptors = true
txn.SetFixedTimestamp(ctx, *protoTS)
}
// PREPARE has a limited subset of statements it can be run with. Postgres
// only allows SELECT, INSERT, UPDATE, DELETE and VALUES statements to be
// prepared.
// See: https://www.postgresql.org/docs/current/static/sql-prepare.html
// However, we allow a large number of additional statements.
// As of right now, the optimizer only works on SELECT statements and will
// fallback for all others, so this should be safe for the foreseeable
// future.
if optimizerPlanned, err := p.optionallyUseOptimizer(ctx, ex.sessionData, stmt); err != nil {
return err
} else if !optimizerPlanned {
isCorrelated := p.curPlan.isCorrelated
log.VEventf(ctx, 1, "query is correlated: %v", isCorrelated)
// Fallback if the optimizer was not enabled or used.
if err := p.prepare(ctx, stmt.AST); err != nil {
enhanceErrWithCorrelation(err, isCorrelated)
return err
}
}
if p.curPlan.plan == nil {
// The statement cannot be prepared. Nothing to do.
return nil
}
defer p.curPlan.close(ctx)
prepared.Columns = p.curPlan.columns()
for _, c := range prepared.Columns {
if err := checkResultType(c.Typ); err != nil {
return err
}
}
prepared.Types = p.semaCtx.Placeholders.Types
return nil
}(); err != nil {
txn.CleanupOnError(ctx, err)
return nil, err
}
if err := txn.CommitOrCleanup(ctx); err != nil {
return nil, err
}
// Account for the memory used by this prepared statement: for now we are just
// counting the size of the query string (we'll account for the statement name
// at a higher layer). When we start storing the prepared query plan during
// prepare, this should be tallied up to the monitor as well.
if err := prepared.memAcc.Grow(ctx,
int64(len(prepared.Str)+int(unsafe.Sizeof(*prepared))),
); err != nil {
return nil, err
}
return prepared, nil
}
func (ex *connExecutor) execBind(
ctx context.Context, bindCmd BindStmt,
) (fsm.Event, fsm.EventPayload) {
retErr := func(err error) (fsm.Event, fsm.EventPayload) {
return eventNonRetriableErr{IsCommit: fsm.False}, eventNonRetriableErrPayload{err: err}
}
portalName := bindCmd.PortalName
// The unnamed portal can be freely overwritten.
if portalName != "" {
if _, ok := ex.prepStmtsNamespace.portals[portalName]; ok {
return retErr(pgerror.NewErrorf(
pgerror.CodeDuplicateCursorError, "portal %q already exists", portalName))
}
} else {
// Deallocate the unnamed portal, if it exists.
ex.deletePortal(ctx, "")
}
ps, ok := ex.prepStmtsNamespace.prepStmts[bindCmd.PreparedStatementName]
if !ok {
return retErr(pgerror.NewErrorf(
pgerror.CodeInvalidSQLStatementNameError,
"unknown prepared statement %q", bindCmd.PreparedStatementName))
}
numQArgs := uint16(len(ps.InTypes))
// Decode the arguments, except for internal queries for which we just verify
// that the arguments match what's expected.
qargs := tree.QueryArguments{}
if bindCmd.internalArgs != nil {
if len(bindCmd.internalArgs) != int(numQArgs) {
return retErr(
pgwirebase.NewProtocolViolationErrorf(
"expected %d arguments, got %d", numQArgs, len(bindCmd.internalArgs)))
}
for i, datum := range bindCmd.internalArgs {
t := ps.InTypes[i]
if oid := datum.ResolvedType().Oid(); datum != tree.DNull && oid != t {
return retErr(
pgwirebase.NewProtocolViolationErrorf(
"for argument %d expected OID %d, got %d", i, t, oid))
}
k := strconv.Itoa(i + 1)
qargs[k] = datum
}
} else {
qArgFormatCodes := bindCmd.ArgFormatCodes
// If a single code is specified, it is applied to all arguments.
if len(qArgFormatCodes) != 1 && len(qArgFormatCodes) != int(numQArgs) {
return retErr(pgwirebase.NewProtocolViolationErrorf(
"wrong number of format codes specified: %d for %d arguments",
len(qArgFormatCodes), numQArgs))
}
// If a single format code was specified, it applies to all the arguments.
if len(qArgFormatCodes) == 1 {
fmtCode := qArgFormatCodes[0]
qArgFormatCodes = make([]pgwirebase.FormatCode, numQArgs)
for i := range qArgFormatCodes {
qArgFormatCodes[i] = fmtCode
}
}
if len(bindCmd.Args) != int(numQArgs) {
return retErr(
pgwirebase.NewProtocolViolationErrorf(
"expected %d arguments, got %d", numQArgs, len(bindCmd.Args)))
}
for i, arg := range bindCmd.Args {
k := strconv.Itoa(i + 1)
t := ps.InTypes[i]
if arg == nil {
// nil indicates a NULL argument value.
qargs[k] = tree.DNull
} else {
d, err := pgwirebase.DecodeOidDatum(t, qArgFormatCodes[i], arg)
if err != nil {
if _, ok := err.(*pgerror.Error); ok {
return retErr(err)
}
return retErr(pgwirebase.NewProtocolViolationErrorf(
"error in argument for $%d: %s", i+1, err.Error()))
}
qargs[k] = d
}
}
}
numCols := len(ps.Columns)
if (len(bindCmd.OutFormats) > 1) && (len(bindCmd.OutFormats) != numCols) {
return retErr(pgwirebase.NewProtocolViolationErrorf(
"expected 1 or %d for number of format codes, got %d",
numCols, len(bindCmd.OutFormats)))
}
columnFormatCodes := bindCmd.OutFormats
if len(bindCmd.OutFormats) == 1 {
// Apply the format code to every column.
columnFormatCodes = make([]pgwirebase.FormatCode, numCols)
for i := 0; i < numCols; i++ {
columnFormatCodes[i] = bindCmd.OutFormats[0]
}
}
// Create the new PreparedPortal.
if err := ex.addPortal(
ctx, portalName, bindCmd.PreparedStatementName, ps.PreparedStatement, qargs, columnFormatCodes,
); err != nil {
return retErr(err)
}
if log.V(2) {
log.Infof(ctx, "portal: %q for %q, args %q, formats %q",
portalName, ps.Statement, qargs, columnFormatCodes)
}
return nil, nil
}
// addPortal creates a new PreparedPortal on the connExecutor.
//
// It is illegal to call this when a portal with that name already exists (even
// for anonymous portals).
func (ex *connExecutor) addPortal(
ctx context.Context,
portalName string,
psName string,
stmt *PreparedStatement,
qargs tree.QueryArguments,
outFormats []pgwirebase.FormatCode,
) error {
if _, ok := ex.prepStmtsNamespace.portals[portalName]; ok {
panic(fmt.Sprintf("portal already exists: %q", portalName))
}
portal, err := ex.newPreparedPortal(ctx, portalName, stmt, qargs, outFormats)
if err != nil {
return err
}
ex.prepStmtsNamespace.portals[portalName] = portalEntry{
PreparedPortal: portal,
psName: psName,
}
ex.prepStmtsNamespace.prepStmts[psName].portals[portalName] = struct{}{}
return nil
}
func (ex *connExecutor) deletePreparedStmt(ctx context.Context, name string) {
psEntry, ok := ex.prepStmtsNamespace.prepStmts[name]
if !ok {
return
}
// If the prepared statement only exists in prepStmtsNamespace, it's up to us
// to close it.
baseP, inBase := ex.extraTxnState.prepStmtsNamespaceAtTxnRewindPos.prepStmts[name]
if !inBase || (baseP.PreparedStatement != psEntry.PreparedStatement) {
psEntry.close(ctx)
}
for portalName := range psEntry.portals {
ex.deletePortal(ctx, portalName)
}
delete(ex.prepStmtsNamespace.prepStmts, name)
}
func (ex *connExecutor) deletePortal(ctx context.Context, name string) {
portalEntry, ok := ex.prepStmtsNamespace.portals[name]
if !ok {
return
}
// If the portal only exists in prepStmtsNamespace, it's up to us to close it.
baseP, inBase := ex.extraTxnState.prepStmtsNamespaceAtTxnRewindPos.portals[name]
if !inBase || (baseP.PreparedPortal != portalEntry.PreparedPortal) {
portalEntry.close(ctx)
}
delete(ex.prepStmtsNamespace.portals, name)
delete(ex.prepStmtsNamespace.prepStmts[portalEntry.psName].portals, name)
}
func (ex *connExecutor) execDelPrepStmt(
ctx context.Context, delCmd DeletePreparedStmt,
) (fsm.Event, fsm.EventPayload) {
switch delCmd.Type {
case pgwirebase.PrepareStatement:
_, ok := ex.prepStmtsNamespace.prepStmts[delCmd.Name]
if !ok {
// The spec says "It is not an error to issue Close against a nonexistent
// statement or portal name". See
// https://www.postgresql.org/docs/current/static/protocol-flow.html.
break
}
ex.deletePreparedStmt(ctx, delCmd.Name)
case pgwirebase.PreparePortal:
_, ok := ex.prepStmtsNamespace.portals[delCmd.Name]
if !ok {
break
}
ex.deletePortal(ctx, delCmd.Name)
default:
panic(fmt.Sprintf("unknown del type: %s", delCmd.Type))
}
return nil, nil
}
func (ex *connExecutor) execDescribe(
ctx context.Context, descCmd DescribeStmt, res DescribeResult,
) (fsm.Event, fsm.EventPayload) {
retErr := func(err error) (fsm.Event, fsm.EventPayload) {
return eventNonRetriableErr{IsCommit: fsm.False}, eventNonRetriableErrPayload{err: err}
}
switch descCmd.Type {
case pgwirebase.PrepareStatement:
ps, ok := ex.prepStmtsNamespace.prepStmts[descCmd.Name]
if !ok {
return retErr(pgerror.NewErrorf(
pgerror.CodeInvalidSQLStatementNameError,
"unknown prepared statement %q", descCmd.Name))
}
res.SetInTypes(ps.InTypes)
if stmtHasNoData(ps.Statement) {
res.SetNoDataRowDescription()
} else {
res.SetPrepStmtOutput(ctx, ps.Columns)
}
case pgwirebase.PreparePortal:
portal, ok := ex.prepStmtsNamespace.portals[descCmd.Name]
if !ok {
return retErr(pgerror.NewErrorf(
pgerror.CodeInvalidCursorNameError, "unknown portal %q", descCmd.Name))
}
if stmtHasNoData(portal.Stmt.Statement) {
res.SetNoDataRowDescription()
} else {
res.SetPortalOutput(ctx, portal.Stmt.Columns, portal.OutFormats)
}
default:
return retErr(errors.Errorf("unknown describe type: %s", descCmd.Type))
}
return nil, nil
}