-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpgquery.v
More file actions
630 lines (572 loc) · 15 KB
/
Copy pathpgquery.v
File metadata and controls
630 lines (572 loc) · 15 KB
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
module pg_query
import json
pub struct ParseResult {
pub:
parse_tree string
stderr_buffer string
}
pub struct ParseResultProtobuf {
pub:
parse_tree Protobuf
stderr_buffer string
}
pub struct Protobuf {
pub:
len usize
data string
}
pub fn (pb Protobuf) hex() string {
if pb.len == 0 {
return ''
}
mut out := ''
for i in 0 .. int(pb.len) {
out += pb.data[i].hex()
}
return out
}
pub fn (pb Protobuf) bytes() []u8 {
return pb.data.bytes()
}
// encode_ast serializes a ParseAstResult back to protobuf wire format.
// The returned Protobuf can be passed to deparse_protobuf() for SQL deparsing.
pub fn encode_ast(result ParseAstResult) Protobuf {
buf := encode_parse_result(result)
return protobuf_from_bytes(buf)
}
// encode_scan serializes a ScanResult back to protobuf wire format.
pub fn encode_scan(result ScanResult) Protobuf {
return protobuf_from_bytes(encode_scan_result(result))
}
// encode_summary serializes a SummaryResult back to protobuf wire format.
pub fn encode_summary(result SummaryResult) Protobuf {
return protobuf_from_bytes(encode_summary_result(result))
}
// deparse_ast encodes a ParseAstResult to protobuf and deparses it back to SQL.
// Returns the deparsed SQL string on success.
pub fn deparse_ast(result ParseAstResult) !string {
pb := encode_ast(result)
res := deparse_protobuf(pb) or { return err }
return res.query
}
fn protobuf_from_bytes(buf []u8) Protobuf {
return Protobuf{
len: usize(buf.len)
data: buf.bytestr()
}
}
pub struct NormalizeResult {
pub:
normalized_query string
}
pub struct FingerprintResult {
pub:
fingerprint u64
fingerprint_str string
stderr_buffer string
}
pub struct SplitStmt {
pub:
stmt_location int
stmt_len int
}
pub struct SplitResult {
pub:
stmts []SplitStmt
n_stmts int
stderr_buffer string
}
pub struct DeparseResult {
pub:
query string
}
pub struct DeparseComment {
pub:
match_location int
newlines_before_comment int
newlines_after_comment int
str string
}
pub struct DeparseOpts {
pub:
comments []DeparseComment
pretty_print bool
indent_size int
max_line_length int
trailing_newline bool
commas_start_of_line bool
}
pub struct DeparseCommentsResult {
pub:
comments []DeparseComment
}
pub struct PlpgsqlParseResult {
pub:
plpgsql_funcs string
}
pub struct IsUtilityResult {
pub:
length int
items []bool
}
pub struct PgError {
pub:
message string
funcname string
filename string
lineno int
cursorpos int
context string
}
pub fn (e PgError) msg() string {
return e.message
}
pub fn (e PgError) code() int {
return 0
}
fn cstring(s &char) string {
if s == unsafe { nil } {
return ''
}
return unsafe { cstring_to_vstring(s) }
}
fn pg_error_from(err &C.PgQueryError) ?PgError {
if err == unsafe { nil } {
return none
}
return PgError{
message: cstring(err.message)
funcname: cstring(err.funcname)
filename: cstring(err.filename)
lineno: err.lineno
cursorpos: err.cursorpos
context: cstring(err.context)
}
}
// Parse SQL and return JSON parse tree.
pub fn parse(input string) !ParseResult {
res := C.pg_query_parse(input.str)
if pe := pg_error_from(res.error) {
C.pg_query_free_parse_result(res)
return pe
}
pt := cstring(res.parse_tree)
sb := cstring(res.stderr_buffer)
C.pg_query_free_parse_result(res)
return ParseResult{
parse_tree: pt
stderr_buffer: sb
}
}
// Parse SQL with options and return JSON parse tree.
pub fn parse_opts(input string, parser_options int) !ParseResult {
res := C.pg_query_parse_opts(input.str, parser_options)
if pe := pg_error_from(res.error) {
C.pg_query_free_parse_result(res)
return pe
}
pt := cstring(res.parse_tree)
sb := cstring(res.stderr_buffer)
C.pg_query_free_parse_result(res)
return ParseResult{
parse_tree: pt
stderr_buffer: sb
}
}
// Parse SQL and return Protobuf parse tree.
pub fn parse_protobuf(input string) !ParseResultProtobuf {
res := C.pg_query_parse_protobuf(input.str)
if pe := pg_error_from(res.error) {
C.pg_query_free_protobuf_parse_result(res)
return pe
}
pb := protobuf_from_c(res.parse_tree)
sb := cstring(res.stderr_buffer)
C.pg_query_free_protobuf_parse_result(res)
return ParseResultProtobuf{
parse_tree: pb
stderr_buffer: sb
}
}
// Parse a JSON parse tree string into typed V AST structs.
// Unlike parse_ast() (which calls parse() internally), this accepts
// any JSON string produced by pg_query.parse() or an external source.
pub fn parse_json_ast(json_string string) !ParseAstResult {
json_res := json.decode(JsonParseResult, json_string) or { return err }
mut stmts := []AstRawStmt{}
for s in json_res.stmts {
stmts << AstRawStmt{
stmt_location: s.stmt_location
stmt_len: s.stmt_len
stmt: decode_node_json(s.stmt)
}
}
return ParseAstResult{
version: json_res.version
stmts: stmts
}
}
// Parse SQL and return a typed V AST (protobuf decode path, no JSON).
pub fn parse_protobuf_ast(input string) !ParseAstResult {
res := C.pg_query_parse_protobuf(input.str)
if pe := pg_error_from(res.error) {
C.pg_query_free_protobuf_parse_result(res)
return pe
}
buf := protobuf_to_bytes(res.parse_tree)
C.pg_query_free_protobuf_parse_result(res)
return decode_parse_result(buf)
}
// Parse SQL with options and return a typed V AST (protobuf decode path, no JSON).
pub fn parse_protobuf_ast_opts(input string, parser_options int) !ParseAstResult {
res := C.pg_query_parse_protobuf_opts(input.str, parser_options)
if pe := pg_error_from(res.error) {
C.pg_query_free_protobuf_parse_result(res)
return pe
}
buf := protobuf_to_bytes(res.parse_tree)
C.pg_query_free_protobuf_parse_result(res)
return decode_parse_result(buf)
}
// Parse SQL with options and return Protobuf parse tree.
pub fn parse_protobuf_opts(input string, parser_options int) !ParseResultProtobuf {
res := C.pg_query_parse_protobuf_opts(input.str, parser_options)
if pe := pg_error_from(res.error) {
C.pg_query_free_protobuf_parse_result(res)
return pe
}
pb := protobuf_from_c(res.parse_tree)
sb := cstring(res.stderr_buffer)
C.pg_query_free_protobuf_parse_result(res)
return ParseResultProtobuf{
parse_tree: pb
stderr_buffer: sb
}
}
// Parse PL/pgSQL and return function list.
pub fn parse_plpgsql(input string) !PlpgsqlParseResult {
res := C.pg_query_parse_plpgsql(input.str)
if pe := pg_error_from(res.error) {
C.pg_query_free_plpgsql_parse_result(res)
return pe
}
pf := cstring(res.plpgsql_funcs)
C.pg_query_free_plpgsql_parse_result(res)
return PlpgsqlParseResult{
plpgsql_funcs: pf
}
}
// Normalize a SQL query.
pub fn normalize(input string) !NormalizeResult {
res := C.pg_query_normalize(input.str)
if pe := pg_error_from(res.error) {
C.pg_query_free_normalize_result(res)
return pe
}
nq := cstring(res.normalized_query)
C.pg_query_free_normalize_result(res)
return NormalizeResult{
normalized_query: nq
}
}
// Normalize a utility SQL query.
pub fn normalize_utility(input string) !NormalizeResult {
res := C.pg_query_normalize_utility(input.str)
if pe := pg_error_from(res.error) {
C.pg_query_free_normalize_result(res)
return pe
}
nq := cstring(res.normalized_query)
C.pg_query_free_normalize_result(res)
return NormalizeResult{
normalized_query: nq
}
}
// Scan (tokenize) a SQL query.
pub fn scan(input string) !ScanResult {
res := C.pg_query_scan(input.str)
if pe := pg_error_from(res.error) {
C.pg_query_free_scan_result(res)
return pe
}
bytes := protobuf_to_bytes(res.pbuf)
C.pg_query_free_scan_result(res)
val, _ := decode_scan_result(bytes, max_decode_depth)
return val
}
// Fingerprint a SQL query.
pub fn fingerprint(input string) !FingerprintResult {
res := C.pg_query_fingerprint(input.str)
if pe := pg_error_from(res.error) {
C.pg_query_free_fingerprint_result(res)
return pe
}
fp := res.fingerprint
fps := cstring(res.fingerprint_str)
sb := cstring(res.stderr_buffer)
C.pg_query_free_fingerprint_result(res)
return FingerprintResult{
fingerprint: fp
fingerprint_str: fps
stderr_buffer: sb
}
}
// Fingerprint a SQL query with options.
pub fn fingerprint_opts(input string, parser_options int) !FingerprintResult {
res := C.pg_query_fingerprint_opts(input.str, parser_options)
if pe := pg_error_from(res.error) {
C.pg_query_free_fingerprint_result(res)
return pe
}
fp := res.fingerprint
fps := cstring(res.fingerprint_str)
sb := cstring(res.stderr_buffer)
C.pg_query_free_fingerprint_result(res)
return FingerprintResult{
fingerprint: fp
fingerprint_str: fps
stderr_buffer: sb
}
}
// Split SQL into statements using the scanner.
pub fn split_with_scanner(input string) !SplitResult {
res := C.pg_query_split_with_scanner(input.str)
if pe := pg_error_from(res.error) {
C.pg_query_free_split_result(res)
return pe
}
stmts := split_stmts_from_c(res)
sb := cstring(res.stderr_buffer)
n := res.n_stmts
C.pg_query_free_split_result(res)
return SplitResult{
stmts: stmts
n_stmts: n
stderr_buffer: sb
}
}
// Split SQL into statements using the parser.
pub fn split_with_parser(input string) !SplitResult {
res := C.pg_query_split_with_parser(input.str)
if pe := pg_error_from(res.error) {
C.pg_query_free_split_result(res)
return pe
}
stmts := split_stmts_from_c(res)
sb := cstring(res.stderr_buffer)
n := res.n_stmts
C.pg_query_free_split_result(res)
return SplitResult{
stmts: stmts
n_stmts: n
stderr_buffer: sb
}
}
// Deparse a Protobuf parse tree back to SQL.
pub fn deparse_protobuf(pb Protobuf) !DeparseResult {
c_pb := protobuf_to_c(pb)
res := C.pg_query_deparse_protobuf(c_pb)
if pe := pg_error_from(res.error) {
C.pg_query_free_deparse_result(res)
return pe
}
q := cstring(res.query)
C.pg_query_free_deparse_result(res)
return DeparseResult{
query: q
}
}
// Deparse a Protobuf parse tree with options back to SQL.
pub fn deparse_protobuf_opts(pb Protobuf, opts DeparseOpts) !DeparseResult {
c_pb := protobuf_to_c(pb)
c_opts := deparse_opts_to_c(opts)
defer {
if c_opts.comment_count > 0 {
unsafe {
n := int(c_opts.comment_count)
arr := &voidptr(c_opts.comments)
for i in 0 .. n {
C.free(arr[i])
}
C.free(c_opts.comments)
}
}
}
res := C.pg_query_deparse_protobuf_opts(c_pb, c_opts)
if pe := pg_error_from(res.error) {
C.pg_query_free_deparse_result(res)
return pe
}
q := cstring(res.query)
C.pg_query_free_deparse_result(res)
return DeparseResult{
query: q
}
}
// Deparse comments for a query.
pub fn deparse_comments_for_query(query string) !DeparseCommentsResult {
res := C.pg_query_deparse_comments_for_query(query.str)
if pe := pg_error_from(res.error) {
C.pg_query_free_deparse_comments_result(res)
return pe
}
comments := deparse_comments_from_c(res)
C.pg_query_free_deparse_comments_result(res)
return DeparseCommentsResult{
comments: comments
}
}
// Check if a query is a utility statement.
pub fn is_utility_stmt(query string) !IsUtilityResult {
res := C.pg_query_is_utility_stmt(query.str)
if pe := pg_error_from(res.error) {
C.pg_query_free_is_utility_result(res)
return pe
}
items := is_utility_items_from_c(res)
C.pg_query_free_is_utility_result(res)
return IsUtilityResult{
length: res.length
items: items
}
}
// Get a summary of a SQL query.
pub fn summary(input string, parser_options int, truncate_limit int) !SummaryResult {
res := C.pg_query_summary(input.str, parser_options, truncate_limit)
if pe := pg_error_from(res.error) {
C.pg_query_free_summary_parse_result(res)
return pe
}
bytes := protobuf_to_bytes(res.summary)
C.pg_query_free_summary_parse_result(res)
val, _ := decode_summary_result(bytes, max_decode_depth)
return val
}
// Clean up global memory contexts used by the C parser.
//
// The parser uses thread-local memory contexts internally and is
// safe to call concurrently from multiple threads. Do NOT call
// pg_query_exit() while other goroutines may be actively parsing,
// as it frees the memory context used by the current thread.
pub fn exit() {
C.pg_query_exit()
}
// Postgres version information.
pub fn pg_version() string {
return pg_version_str
}
pub fn pg_major_version() string {
return pg_major_version_str
}
pub fn pg_version_num() int {
return C.PG_VERSION_NUM
}
// --- internal helpers ---
fn protobuf_to_bytes(cpb C.PgQueryProtobuf) []u8 {
if cpb.len == 0 || cpb.data == unsafe { nil } {
return []
}
mut bytes := []u8{len: int(cpb.len)}
unsafe { C.memcpy(bytes.data, voidptr(cpb.data), usize(cpb.len)) }
return bytes
}
fn protobuf_from_c(cpb C.PgQueryProtobuf) Protobuf {
if cpb.len == 0 || cpb.data == unsafe { nil } {
return Protobuf{
len: 0
data: ''
}
}
mut bytes := []u8{len: int(cpb.len)}
unsafe { C.memcpy(bytes.data, voidptr(cpb.data), usize(cpb.len)) }
return Protobuf{
len: cpb.len
data: bytes.bytestr()
}
}
fn protobuf_to_c(pb Protobuf) C.PgQueryProtobuf {
if pb.data.len == 0 {
return C.PgQueryProtobuf{
len: 0
data: unsafe { nil }
}
}
return C.PgQueryProtobuf{
len: usize(pb.data.len)
data: pb.data.str
}
}
fn split_stmts_from_c(res C.PgQuerySplitResult) []SplitStmt {
if res.n_stmts == 0 || res.stmts == unsafe { nil } {
return []
}
mut stmts := []SplitStmt{len: res.n_stmts}
unsafe {
for i in 0 .. res.n_stmts {
c_stmt := res.stmts[i]
stmts[i] = SplitStmt{
stmt_location: c_stmt.stmt_location
stmt_len: c_stmt.stmt_len
}
}
}
return stmts
}
fn deparse_opts_to_c(opts DeparseOpts) C.PostgresDeparseOpts {
mut c_opts := C.PostgresDeparseOpts{
comments: unsafe { nil }
comment_count: usize(0)
pretty_print: opts.pretty_print
indent_size: opts.indent_size
max_line_length: opts.max_line_length
trailing_newline: opts.trailing_newline
commas_start_of_line: opts.commas_start_of_line
}
if opts.comments.len > 0 {
unsafe {
n := opts.comments.len
raw := C.calloc(usize(n), usize(8))
arr := &voidptr(raw)
for i in 0 .. n {
c := &C.PostgresDeparseComment(C.calloc(1, usize(sizeof(C.PostgresDeparseComment))))
c.match_location = opts.comments[i].match_location
c.newlines_before_comment = opts.comments[i].newlines_before_comment
c.newlines_after_comment = opts.comments[i].newlines_after_comment
c.str = opts.comments[i].str.str
arr[i] = voidptr(c)
}
c_opts.comments = raw
c_opts.comment_count = usize(n)
}
}
return c_opts
}
fn deparse_comments_from_c(res C.PgQueryDeparseCommentsResult) []DeparseComment {
if res.comment_count == 0 || res.comments == unsafe { nil } {
return []
}
mut comments := []DeparseComment{len: int(res.comment_count)}
unsafe {
for i in 0 .. res.comment_count {
c := res.comments[i]
comments[i] = DeparseComment{
match_location: c.match_location
newlines_before_comment: c.newlines_before_comment
newlines_after_comment: c.newlines_after_comment
str: cstring(c.str)
}
}
}
return comments
}
fn is_utility_items_from_c(res C.PgQueryIsUtilityResult) []bool {
if res.length == 0 || res.items == unsafe { nil } {
return []
}
mut items := []bool{len: res.length}
ptr := unsafe { &u8(voidptr(res.items)) }
for i in 0 .. res.length {
items[i] = unsafe { ptr[i] } != 0
}
return items
}