-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
rules.go
448 lines (403 loc) · 12.6 KB
/
rules.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
// Copyright 2022 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 comprules
import (
"context"
"fmt"
"regexp"
"github.com/cockroachdb/cockroach/pkg/sql/compengine"
"github.com/cockroachdb/cockroach/pkg/sql/lexbase"
"github.com/cockroachdb/cockroach/pkg/sql/scanner"
)
// GetCompMethods exposes the completion heuristics defined in this
// package.
func GetCompMethods() []compengine.Method {
return []compengine.Method{
method("keywords", completeKeyword),
method("functions", completeFunction),
method("objects", completeObjectInCurrentDatabase),
method("schemas", completeSchemaInCurrentDatabase),
method("dbs", completeDatabase),
method("xobjs", completeObjectInOtherDatabase),
method("xsch", completeSchemaInOtherDatabase),
}
}
var compIdentAfterPeriod = regexp.MustCompile(`\.(i'|_)`)
func completeKeyword(ctx context.Context, c compengine.Context) (compengine.Rows, error) {
// We complete a keyword in the following cases:
//
// - cursor not after a period (.), and EITHER:
// - cursor in whitespace, i.e. in-between other tokens; OR
// - cursor inside a non-quoted identifier-like token.
//
// In all other cases, there's no keyword to be found.
//
// Note how in particular we do not complete after a period.
// This is because in SQL only object names can appear after
// a period, so it's never expected to find a keyword there.
//
// We also do not complete inside quoted identifiers: if the user
// types {"sel} and then tries to autocomplete, we should understand
// they are interested in an object/name starting with "sel", not a
// keyword, because keywords can never be quoted.
curTok := c.RelToken(0)
sketch := c.Sketch()
var prefix string
var start, end int
switch {
case compIdentAfterPeriod.MatchString(sketch):
c.Trace("not completing after period")
return nil, nil
case c.CursorInSpace():
start = c.QueryPos()
end = start
case c.AtWordOrInSpaceFollowingWord() && !curTok.Quoted:
prefix = curTok.Str
start = int(curTok.Start)
end = int(curTok.End)
default:
c.Trace("not completing")
return nil, nil
}
c.Trace("completing for %q (%d,%d)", prefix, start, end)
const query = `
SELECT upper(word),
'keyword' AS category,
COALESCE(catdesc,'') AS description,
$2:::INT AS start,
$3:::INT AS end
FROM pg_catalog.pg_get_keywords()
WHERE left(word, length($1:::STRING)) = $1:::STRING`
iter, err := c.Query(ctx, query, prefix, start, end)
return iter, err
}
// A surely not qualified possible function name.
// Also, function names cannot appear directly after a semicolon.
var compNotQualProcRe = regexp.MustCompile(`[^.;](i'|_)`)
// A schema-qualified possible builtin name.
// Also, function names cannot appear directly after a semicolon.
var compMaybeQualProcRe = regexp.MustCompile(`[^.;]i\.(['_]|i')`)
func completeFunction(ctx context.Context, c compengine.Context) (compengine.Rows, error) {
// Complete function names:
//
// - at whitespace after keywords.
// - after a period.
//
var prefix string
var start, end int
var schemaName string
atWord := c.AtWordOrInSpaceFollowingWord()
sketch := c.Sketch()
switch {
case compMaybeQualProcRe.MatchString(sketch):
start = int(c.RelToken(-1).Start)
schemaName = c.RelToken(-1).Str
if atWord {
start = int(c.RelToken(-2).Start)
schemaName = c.RelToken(-2).Str
prefix = c.RelToken(0).Str
}
end = int(c.RelToken(0).End)
case compNotQualProcRe.MatchString(sketch):
switch {
case c.CursorInToken() && atWord:
curTok := c.RelToken(0)
prefix = curTok.Str
start = int(curTok.Start)
end = int(curTok.End)
default:
start = c.QueryPos()
end = start
}
default:
c.Trace("not completing")
return nil, nil
}
c.Trace("completing for %q (%d,%d) with schema %q", prefix, start, end, schemaName)
// Note: we use min(p.oid) ... GROUP BY p.proname to cover the case
// there are multiple overloads. This ensures we have only one entry
// in the completion results for that function. Its reported
// description will also be the description for the first overload.
// Separately, we GROUP BY n.nspname to ensure that a UDF with
// the same name as a pg_catalog function gets reported as a
// separate completion entry.
const query = `
WITH p AS (
SELECT min(p.oid) AS oid, p.proname, n.nspname
FROM pg_catalog.pg_proc p
JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
WHERE left(p.proname, length($1:::STRING)) = $1:::STRING
AND ((length($4) > 0 AND $4 = n.nspname)
OR (length($4) = 0 AND n.nspname = ANY current_schemas(true)))
GROUP BY p.proname, n.nspname
)
SELECT DISTINCT
IF(length($4) > 0, pg_catalog.quote_ident($4:::STRING) || '.', '') ||
pg_catalog.quote_ident(proname) || '(' AS completion,
'functions' AS category,
IF(length($4) = 0, '(from schema '||nspname||') ', '') ||
substr(COALESCE(pg_catalog.obj_description(oid, 'pg_proc'),''), e'[^.\n]{0,80}') AS description,
$2:::INT AS start,
$3:::INT AS end
FROM p
ORDER BY 1,3,4,5
`
iter, err := c.Query(ctx, query, prefix, start, end, schemaName)
return iter, err
}
// A database name can only occur after a keyword or a comma (,).
var compDbRe = regexp.MustCompile(`[i,](i'|_)`)
func completeDatabase(ctx context.Context, c compengine.Context) (compengine.Rows, error) {
var prefix string
var start, end int
sketch := c.Sketch()
switch {
case !compDbRe.MatchString(sketch):
c.Trace("not completing")
return nil, nil
case c.CursorInToken() && c.AtWordOrInSpaceFollowingWord():
curTok := c.RelToken(0)
prefix = curTok.Str
start = int(curTok.Start)
end = int(curTok.End)
default:
// Not inside an identifier (e.g inside a comma, or at space).
start = c.QueryPos()
end = start
}
c.Trace("completing for %q (%d,%d)", prefix, start, end)
const query = `
WITH d AS (SELECT oid, datname FROM pg_catalog.pg_database)
SELECT datname AS completion,
'database' AS category,
substr(COALESCE(sc.comment, ''), e'[^\n]{0,80}') as description,
$2:::INT AS start,
$3:::INT AS end
FROM d
LEFT OUTER JOIN system.public.comments sc
ON d.oid = sc.object_id
AND sc.type = 0
WHERE left(datname, length($1:::STRING)) = $1::STRING
ORDER BY 1,3,4,5
`
iter, err := c.Query(ctx, query, prefix, start, end)
return iter, err
}
// A local (current schema) object can only occur after non-period.
var compLocalTableRe = regexp.MustCompile(`[^.;](i'|_)`)
// A schema-qualified object in the current db, or a db
// qualified object.
var compOneQualPrefixRe = regexp.MustCompile(`[^.;]i\.(['_]|i')`)
func completeObjectInCurrentDatabase(
ctx context.Context, c compengine.Context,
) (compengine.Rows, error) {
var schema string
atWord := c.AtWordOrInSpaceFollowingWord()
sketch := c.Sketch()
hasSchemaPrefix := false
switch {
case compLocalTableRe.MatchString(sketch):
schema = "IN (TABLE unnest(current_schemas(true)))"
case compOneQualPrefixRe.MatchString(sketch):
schemaTok := c.RelToken(-1)
if atWord {
schemaTok = c.RelToken(-2)
}
schema = "= " + lexbase.EscapeSQLString(schemaTok.Str)
hasSchemaPrefix = true
default:
c.Trace("not completing")
return nil, nil
}
var prefix string
var start, end int
switch {
case c.CursorInToken() && atWord:
curTok := c.RelToken(0)
prefix = curTok.Str
start = int(curTok.Start)
end = int(curTok.End)
default:
start = c.QueryPos()
end = start
}
c.Trace("completing for %q (%d,%d), schema: %s", prefix, start, end, schema)
// We only include pg_catalog relations in the following cases:
//
// - when the cursor is position after an explicit schema qualification;
// in which case we're going to filter to that schema anyway.
// - when the completion prefix already includes the `pg_` prefix,
// in which case we can assume the user wants to see these tables.
const queryT = `
WITH n AS (SELECT oid, nspname FROM pg_catalog.pg_namespace WHERE nspname %s),
t AS (SELECT c.oid, relname FROM pg_catalog.pg_class c
JOIN n ON n.oid = c.relnamespace
WHERE reltype != 0
AND left(relname, length($1:::STRING)) = $1::STRING
AND (nspname != 'pg_catalog' OR $4:::BOOL OR left($1:::STRING, 3) = 'pg_'))
SELECT relname AS completion,
'relation' AS category,
substr(COALESCE(cc.comment, ''), e'[^\n]{0,80}') as description,
$2:::INT AS start,
$3:::INT AS end
FROM t
LEFT OUTER JOIN "".crdb_internal.kv_catalog_comments cc
ON t.oid = cc.object_id AND cc.type = 'TableCommentType'
ORDER BY 1,3,4,5
`
query := fmt.Sprintf(queryT, schema)
iter, err := c.Query(ctx, query, prefix, start, end, hasSchemaPrefix)
return iter, err
}
func completeSchemaInCurrentDatabase(
ctx context.Context, c compengine.Context,
) (compengine.Rows, error) {
switch {
case compLocalTableRe.MatchString(c.Sketch()):
default:
c.Trace("not completing")
return nil, nil
}
var prefix string
var start, end int
switch {
case c.CursorInToken() && c.AtWordOrInSpaceFollowingWord():
curTok := c.RelToken(0)
prefix = curTok.Str
start = int(curTok.Start)
end = int(curTok.End)
default:
start = c.QueryPos()
end = start
}
c.Trace("completing for %q (%d,%d)", prefix, start, end)
const query = `
SELECT nspname AS completion,
'schema' AS category,
substr(COALESCE(cc.comment, ''), e'[^\n]{0,80}') as description,
$2:::INT AS start,
$3:::INT AS end
FROM pg_catalog.pg_namespace t
LEFT OUTER JOIN "".crdb_internal.kv_catalog_comments cc
ON t.oid = cc.object_id AND cc.type = 'SchemaCommentType'
WHERE left(nspname, length($1:::STRING)) = $1::STRING
ORDER BY 1,3,4,5
`
iter, err := c.Query(ctx, query, prefix, start, end)
return iter, err
}
func completeSchemaInOtherDatabase(
ctx context.Context, c compengine.Context,
) (compengine.Rows, error) {
var dbname string
atWord := c.AtWordOrInSpaceFollowingWord()
switch {
case compOneQualPrefixRe.MatchString(c.Sketch()):
dbTok := c.RelToken(-1)
if atWord {
dbTok = c.RelToken(-2)
}
dbname = dbTok.Str
default:
c.Trace("not completing")
return nil, nil
}
var prefix string
var start, end int
switch {
case atWord:
curTok := c.RelToken(0)
prefix = curTok.Str
start = int(curTok.Start)
end = int(curTok.End)
default:
start = c.QueryPos()
end = start
}
c.Trace("completing for %q (%d,%d) in db %q",
prefix, start, end, dbname)
// TODO(knz): also pull comments.
const query = `
SELECT schema_name AS completion,
'schema' AS category,
'' as description,
$2:::INT AS start,
$3:::INT AS end
FROM "".information_schema.schemata
WHERE catalog_name = $4:::STRING
AND left(schema_name, length($1:::STRING)) = $1:::STRING
ORDER BY 1,3,4,5
`
iter, err := c.Query(ctx, query, prefix, start, end, dbname)
return iter, err
}
// An object name with two prefix qualifications.
var compTwoQualPrefixRe = regexp.MustCompile(`[^.;]i\.i\.(['_]|i')`)
func completeObjectInOtherDatabase(
ctx context.Context, c compengine.Context,
) (compengine.Rows, error) {
var schema string
atWord := c.AtWordOrInSpaceFollowingWord()
sketch := c.Sketch()
var dbTok scanner.InspectToken
switch {
case compOneQualPrefixRe.MatchString(sketch):
schema = "public"
dbTok = c.RelToken(-1)
if atWord {
dbTok = c.RelToken(-2)
}
case compTwoQualPrefixRe.MatchString(sketch):
schemaTok := c.RelToken(-1)
dbTok = c.RelToken(-3)
if atWord {
schemaTok = c.RelToken(-2)
dbTok = c.RelToken(-4)
}
schema = schemaTok.Str
default:
c.Trace("not completing")
return nil, nil
}
dbname := dbTok.Str
var prefix string
var start, end int
switch {
case c.CursorInToken() && atWord:
curTok := c.RelToken(0)
prefix = curTok.Str
start = int(curTok.Start)
end = int(curTok.End)
default:
start = c.QueryPos()
end = start
}
c.Trace("completing for %q (%d,%d), schema: %q, db: %q", prefix, start, end, schema, dbname)
const query = `
WITH t AS (
SELECT name, table_id
FROM "".crdb_internal.tables
WHERE database_name = $4:::STRING
AND schema_name = $5:::STRING
AND left(name, length($1:::STRING)) = $1:::STRING
)
SELECT name AS completion,
'relation' AS category,
substr(COALESCE(cc.comment, ''), e'[^\n]{0,80}') as description,
$2:::INT AS start,
$3:::INT AS end
FROM t
LEFT OUTER JOIN "".crdb_internal.kv_catalog_comments cc
ON t.table_id = cc.object_id AND cc.type = 'TableCommentType'
ORDER BY 1,3,4,5
`
iter, err := c.Query(ctx, query, prefix, start, end, dbname, schema)
return iter, err
}