forked from babelfish-for-postgresql/babelfish_extensions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtsqlIface.cpp
More file actions
9969 lines (8681 loc) · 359 KB
/
tsqlIface.cpp
File metadata and controls
9969 lines (8681 loc) · 359 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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <algorithm>
#include <functional>
#include <iostream>
#include <strstream>
#include <string>
#include <string_view>
#include <unordered_map>
#pragma GCC diagnostic ignored "-Wattributes"
#include "antlr4-runtime.h" // antlr4-cpp-runtime
#include "tree/ParseTreeWalker.h" // antlr4-cpp-runtime
#include "tree/ParseTreeProperty.h" // antlr4-cpp-runtime
#include "support/Utf8.h"
#include "../antlr/antlr4cpp_generated_src/TSqlLexer/TSqlLexer.h"
#include "../antlr/antlr4cpp_generated_src/TSqlParser/TSqlParser.h"
#include "../antlr/antlr4cpp_generated_src/TSqlParser/TSqlParserBaseListener.h"
#include "tsqlIface.hpp"
#define LOOP_JOIN_HINT 0
#define HASH_JOIN_HINT 1
#define MERGE_JOIN_HINT 2
#define LOOP_QUERY_HINT 3
#define HASH_QUERY_HINT 4
#define MERGE_QUERY_HINT 5
#define JOIN_HINTS_INFO_VECTOR_SIZE 6
#define RAISE_ERROR_PARAMS_LIMIT 20
#define PUBLIC_ROLE_NAME "public"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wregister"
extern "C" {
#if 0
#include "tsqlNodes.h"
#else
#include "pltsql.h"
#include "pltsql-2.h"
#include "pl_explain.h"
#include "session.h"
#include "multidb.h"
#include "catalog/namespace.h"
#include "catalog/pg_proc.h"
#include "parser/scansup.h"
#include "utils/builtins.h"
#include "guc.h"
#endif
#ifdef LOG // maybe already defined in elog.h, which is conflicted with grammar token LOG
#undef LOG
#endif
}
#pragma GCC diagnostic pop
using namespace std;
using namespace antlr4;
using namespace tree;
extern "C"
{
ANTLR_result antlr_parser_cpp(const char *sourceText);
void report_antlr_error(ANTLR_result result);
extern PLtsql_type *parse_datatype(const char *string, int location);
extern bool is_tsql_text_ntext_or_image_datatype(Oid oid);
extern int CurrentLineNumber;
extern int pltsql_curr_compile_body_position;
extern int pltsql_curr_compile_body_lineno;
extern bool pltsql_dump_antlr_query_graph;
extern bool pltsql_enable_antlr_detailed_log;
extern bool pltsql_enable_sll_parse_mode;
extern bool pltsql_enable_tsql_information_schema;
extern char *column_names_to_be_delimited[];
extern char *pg_reserved_keywords_to_be_delimited[];
extern size_t get_num_column_names_to_be_delimited();
extern size_t get_num_pg_reserved_keywords_to_be_delimited();
extern char * construct_unique_index_name(char *index_name, char *relation_name);
extern bool enable_hint_mapping;
extern bool check_fulltext_exist(const char *schema_name, const char *table_name, const List *column_name);
extern int escape_hatch_showplan_all;
/* To store the time spent in ANTLR parsing for the current batch */
extern instr_time antlr_parse_time;
extern bool is_classic_catalog(const char *name);
}
static void toDotRecursive(ParseTree *t, const std::vector<std::string> &ruleNames, const std::string &sourceText);
class tsqlBuilder;
class PLtsql_expr_query_mutator;
class tsqlSelectStatementMutator;
// helper template function to get certain token from given context.
// use template here because there is no mid-level base class for similar contexts.
template <class T>
using GetTokenFunc = std::function <antlr4::tree::TerminalNode * (T)>;
template <class T>
using GetCtxFunc = std::function <ParserRuleContext * (T)>;
void handleBatchLevelStatement(TSqlParser::Batch_level_statementContext *ctx, tsqlSelectStatementMutator *ssm, const char *originalQuery);
bool handleITVFBody(TSqlParser::Func_body_return_select_bodyContext *body);
PLtsql_stmt_block *makeEmptyBlockStmt(int lineno);
PLtsql_stmt *makeCfl(TSqlParser::Cfl_statementContext *ctx, tsqlBuilder &builder);
PLtsql_stmt *makeSQL(ParserRuleContext *ctx);
std::vector<PLtsql_stmt *> makeAnother(TSqlParser::Another_statementContext *ctx, tsqlBuilder &builder);
PLtsql_stmt *makeExecBodyBatch(TSqlParser::Execute_body_batchContext *ctx);
PLtsql_stmt *makeExecuteProcedure(ParserRuleContext *ctx, std::string call_type);
PLtsql_stmt *makeInsertBulkStatement(TSqlParser::Dml_statementContext *ctx);
PLtsql_stmt *makeDbccCheckidentStatement(TSqlParser::Dbcc_statementContext *ctx);
PLtsql_stmt *makeSetExplainModeStatement(TSqlParser::Set_statementContext *ctx, bool is_explain_only);
PLtsql_expr *makeTsqlExpr(const std::string &fragment, bool addSelect);
PLtsql_expr *makeTsqlExpr(ParserRuleContext *ctx, bool addSelect);
PLtsql_stmt *makeCreateFulltextIndexStmt(TSqlParser::Create_fulltext_indexContext *ctx);
PLtsql_stmt *makeCreatePartitionFunction(TSqlParser::Create_partition_functionContext *ctx);
PLtsql_stmt *makeDropPartitionFunction(TSqlParser::Drop_partition_functionContext *ctx);
PLtsql_stmt *makeCreatePartitionScheme(TSqlParser::Create_partition_schemeContext *ctx);
PLtsql_stmt *makeDropPartitionScheme(TSqlParser::Drop_partition_schemeContext *ctx);
PLtsql_stmt *makeDropFulltextIndexStmt(TSqlParser::Drop_fulltext_indexContext *ctx);
std::tuple<std::string, std::string, std::string> getDatabaseSchemaAndTableName(TSqlParser::Table_nameContext* tctx);
void * makeBlockStmt(ParserRuleContext *ctx, tsqlBuilder &builder);
void replaceTokenStringFromQuery(PLtsql_expr* expr, TerminalNode* tokenNode, const char* repl, ParserRuleContext *baseCtx);
void replaceCtxStringFromQuery(PLtsql_expr* expr, ParserRuleContext *ctx, const char *repl, ParserRuleContext *baseCtx);
void removeTokenStringFromQuery(PLtsql_expr* expr, TerminalNode* tokenNode, ParserRuleContext *baseCtx);
void removeCtxStringFromQuery(PLtsql_expr* expr, ParserRuleContext *ctx, ParserRuleContext *baseCtx);
void extractQueryHintsFromOptionClause(TSqlParser::Option_clauseContext *octx);
void extractTableHints(TSqlParser::With_table_hintsContext *tctx, std::string table_name);
std::string extractTableName(TSqlParser::Ddl_objectContext *ctx, TSqlParser::Table_source_itemContext *tctx);
std::string extractSchemaName(TSqlParser::Ddl_objectContext *ctx, TSqlParser::Table_source_itemContext *tctx);
void extractTableHint(TSqlParser::Table_hintContext *table_hint, std::string table_name);
void extractJoinHint(TSqlParser::Join_hintContext *join_hint, std::string table_name1, std::string table_names);
void extractJoinHintFromOption(TSqlParser::OptionContext *option);
std::string extractIndexValues(std::vector<TSqlParser::Index_valueContext *> index_valuesCtx, std::string table_name);
static void *makeBatch(TSqlParser::Tsql_fileContext *ctx, tsqlBuilder &builder);
static void process_execsql_destination(TSqlParser::Dml_statementContext *ctx, PLtsql_stmt_execsql *stmt);
static void process_execsql_remove_unsupported_tokens(TSqlParser::Dml_statementContext *ctx, PLtsql_expr_query_mutator *exprMutator);
static bool post_process_create_table(TSqlParser::Create_tableContext *ctx, PLtsql_stmt_execsql *stmt, TSqlParser::Ddl_statementContext *baseCtx);
static bool post_process_alter_table(TSqlParser::Alter_tableContext *ctx, PLtsql_stmt_execsql *stmt, TSqlParser::Ddl_statementContext *baseCtx);
static bool post_process_create_index(TSqlParser::Create_indexContext *ctx, PLtsql_stmt_execsql *stmt, TSqlParser::Ddl_statementContext *baseCtx);
static bool post_process_create_database(TSqlParser::Create_databaseContext *ctx, PLtsql_stmt_execsql *stmt, TSqlParser::Ddl_statementContext *baseCtx);
static bool post_process_create_type(TSqlParser::Create_typeContext *ctx, PLtsql_stmt_execsql *stmt, TSqlParser::Ddl_statementContext *baseCtx);
static void post_process_table_source(TSqlParser::Table_source_itemContext *ctx, PLtsql_expr *expr, ParserRuleContext *baseCtx, List *column_name = NULL, bool is_freetext_predicate = false);
static void post_process_declare_cursor_statement(PLtsql_stmt_decl_cursor *stmt, TSqlParser::Declare_cursorContext *ctx, tsqlBuilder &builder);
static void post_process_declare_table_statement(PLtsql_stmt_decl_table *stmt, TSqlParser::Table_type_definitionContext *ctx);
static bool check_freetext_predicate(TSqlParser::Search_conditionContext *ctx, List **column_name);
static PLtsql_var *lookup_cursor_variable(const char *varname);
static PLtsql_var *build_cursor_variable(const char *curname, int lineno);
static int read_extended_cursor_option(TSqlParser::Declare_cursor_optionsContext *ctx, int current_cursor_option);
static PLtsql_stmt *makeDeclTableStmt(PLtsql_variable *var, PLtsql_type *type, int lineno);
static void *makeReturnQueryStmt(TSqlParser::Select_statement_standaloneContext *ctx, bool itvf);
static PLtsql_stmt *makeSpStatement(const std::string& sp_name, TSqlParser::Execute_statement_argContext *sp_args, int lineno, int return_code_dno);
static void makeSpParams(TSqlParser::Execute_statement_argContext *ctx, std::vector<tsql_exec_param *> ¶ms);
static tsql_exec_param *makeSpParam(TSqlParser::Execute_statement_arg_namedContext *ctx);
static tsql_exec_param *makeSpParam(TSqlParser::Execute_statement_arg_unnamedContext *ctx);
static int getVarno(tree::TerminalNode *localID);
static int check_assignable(tree::TerminalNode *localID);
static void check_dup_declare(const char *name);
static bool is_sp_proc(const std::string& func_proc_name);
static bool string_matches(const char *str, const char *pattern);
static void check_param_type(tsql_exec_param *param, bool is_output, Oid typoid, const char *param_str);
static PLtsql_expr *getNthParamExpr(std::vector<tsql_exec_param *> ¶ms, size_t n);
static const char* rewrite_assign_operator(tree::TerminalNode *aop);
TSqlParser::Query_specificationContext *get_query_specification(TSqlParser::Select_statementContext *sctx);
static bool is_top_level_query_specification(TSqlParser::Query_specificationContext *ctx);
static bool is_quotation_needed_for_column_alias(TSqlParser::Column_aliasContext *ctx);
static bool is_compiling_create_function();
static void process_query_specification(TSqlParser::Query_specificationContext *qctx, PLtsql_expr_query_mutator *mutator, bool process_local_id_assignment);
static void process_select_statement(TSqlParser::Select_statementContext *selectCtx, PLtsql_expr_query_mutator *mutator);
static void process_select_statement_standalone(TSqlParser::Select_statement_standaloneContext *standaloneCtx, PLtsql_expr_query_mutator *mutator, tsqlBuilder &builder);
template <class T> static std::string rewrite_object_name_with_omitted_db_and_schema_name(T ctx, GetCtxFunc<T> getDatabase, GetCtxFunc<T> getSchema, GetCtxFunc<T> getObject);
template <class T> static std::string rewrite_information_schema_to_information_schema_tsql(T ctx, GetCtxFunc<T> getSchema);
template <class T> static std::string rewrite_column_name_with_omitted_schema_name(T ctx, GetCtxFunc<T> getSchema, GetCtxFunc<T> getTableName);
template <class T> static void rewrite_geospatial_query_helper(T ctx, TSqlParser::Method_callContext *method, size_t geospatial_start_index);
template <class T> static void rewrite_geospatial_col_ref_query_helper(T ctx, TSqlParser::Method_callContext *method, size_t geospatial_start_index);
template <class T> static void rewrite_geospatial_func_ref_no_arg_query_helper(T ctx, TSqlParser::Method_callContext *method, size_t geospatial_start_index);
template <class T> static void rewrite_dot_func_ref_args_query_helper(T ctx, TSqlParser::Method_callContext *method, size_t start_index, size_t arg_list_start_index, size_t arg_list_stop_index);
template <class T> static void rewrite_function_call_dot_func_ref_args(T ctx);
template <class T> static void rewrite_function_call_geospatial_func_ref_no_arg(T ctx);
static void handleGeospatialFunctionsInFunctionCall(TSqlParser::Function_callContext *ctx);
static void handleXMLFunctionsInFunctionCall(TSqlParser::Function_callContext *ctx);
static void handleClrUdtFuncCall(TSqlParser::Clr_udt_func_callContext *ctx);
static void handleFullColumnNameCtx(TSqlParser::Full_column_nameContext *ctx);
template <class T> static void handleLocalIdQuotingFuncRefNoArg(T ctx, size_t geospatial_start_index, int &offset1, std::string &expr, std::vector<size_t> keysToRemove);
static bool does_object_name_need_delimiter(TSqlParser::IdContext *id);
static std::string delimit_identifier(TSqlParser::IdContext *id);
static bool does_msg_exceeds_params_limit(const std::string& msg);
static std::string getIDName(TerminalNode *dq, TerminalNode *sb, TerminalNode *id);
static ANTLR_result antlr_parse_query(const char *sourceText, bool useSSLParsing);
std::string rewriteDoubleQuotedString(const std::string strDoubleQuoted);
std::string escapeDoubleQuotes(const std::string strWithDoubleQuote);
static bool in_execute_body_batch = false;
static bool in_execute_body_batch_parameter = false;
static const std::string fragment_SELECT_prefix = "SELECT "; // fragment prefix for expressions
static const std::string fragment_EXEC_prefix = "EXEC "; // fragment prefix for execute_body_batch
static PLtsql_stmt *makeChangeDbOwnerStatement(TSqlParser::Alter_authorizationContext *ctx);
static PLtsql_stmt *makeAlterDatabaseStatement(TSqlParser::Alter_databaseContext *ctx);
static void handleFloatWithoutExponent(TSqlParser::ConstantContext *ctx);
static void handleTableConstraintWithoutComma(TSqlParser::Column_def_table_constraintsContext *ctx);
static void handleBitNotOperator(TSqlParser::Unary_op_exprContext *ctx);
static void handleBitOperators(TSqlParser::Plus_minus_bit_exprContext *ctx);
static void handleModuloOperator(TSqlParser::Mult_div_percent_exprContext *ctx);
static void handleAtAtVarInPredicate(TSqlParser::PredicateContext *ctx);
static void handleOrderByOffsetFetch(TSqlParser::Order_by_clauseContext *ctx);
static void rewrite_string_agg_query(TSqlParser::STRING_AGGContext *ctx);
static bool setSysSchema = false;
static void rewrite_function_trim_to_sys_trim(TSqlParser::TRIMContext *ctx);
static bool isAtAtUserVarName(const std::string name);
static bool isDelimitedAtAtUserVarName(const std::string name);
static void handleLocal_id(TSqlParser::Local_idContext *ctx, bool inSqlObject);
static std::string delimitIfAtAtUserVarName(const std::string name);
static void CheckDeclareAtAtGlobalVarName(const std::string name, int lineNr);
static antlr4::tree::TerminalNode *getTokenFromFunctionOption(TSqlParser::Function_optionContext* o);
/*
* Structure / Utility function for general purpose of query string modification
*
* The difficulty of query string modification is that, upper-level general grammar (i.e. dml_clause, ddl_clause, ...)
* actually creates PLtsql_stmt but logic of query modification is available in low-level fine-grained grammar (i.e. full_object_name, select_list, ...)
* We can't modify the query string in enter/exit function of low-level grammar because it may append query string in middle of query
* so it may lead to inconsistency between query string and token index information obtained from ANTLR parser.
* (i.e. if we rewrite "SELECT 'a'=1 from T" to "SELECT 1 as 'a' FROM T", T appears poisition 22 after rewriting but ANTLR token still keeps position 19)
*
* To resolve this issue, each low-level grammar just register rewritten-query-fragement to a map (rewritten_query_fragment)
* and all the rewriting will be done by upper-level grammar rule at once by using PLtsql_expr_query_mutator
*
* Here is general code snippet (but different patterns in specific query statement like itvf, batch-level statement)
*
* void enterUpperLevelGrammar() { // DML, DDL, ...
* ...
* clear_rewritten_query_fragment(); // clean-up before collecting rewriting information
* }
*
* void exitLowLevelGrammar() { // fine-grained grammar needs actual rewirting
* ...
* // register rewritten query
* rewritten_query_fragment.emplace(std::make_pair(original_string_position, std::make_pair(original_string, rewritten_string));
* }
*
* void exitUpperLevelGrammar() {
* ...
* PLtsql_expr* expr = ...; acutal payload query string for PLtsql_stmt;
* PLtsql_expr_query_mutator mutator(expr, ctx);
*
* add_rewritten_query_fragment_to_mutator(&mutator); // move information of rewritten_query_fragment to mutator.
*
* mutator.run(); // expr->query will be rewitten here
* clear_rewritten_query_fragment();
* }
*/
// general-purpose map to store query fragement which needs to be rewritten
// intentionally use std::map to access positions by sorted order.
// global object is enough because no nesting is expected.
static std::map<size_t, pair<std::string, std::string>> rewritten_query_fragment;
// Keeping positions of local_ids to quote them.
// local_id can be rewritten in different ways in some cases (itvf), don't use rewritten_query_fragment.
// TODO: incorporate local_id_positions with rewritten_query_fragment
static std::map<size_t, std::string> local_id_positions;
// For user-defined variables like @@var or @var# in the RETURN clause of an ITVF
static std::map<size_t, std::string> local_id_positions_atatuservar;
// should be called before visiting subclause to make PLtsql_stmt.
static void clear_rewritten_query_fragment();
// add information of rewritten_query_fragment information to mutator
static void add_rewritten_query_fragment_to_mutator(PLtsql_expr_query_mutator *mutator);
static std::unordered_map<std::string, std::string> alias_to_table_mapping;
static std::unordered_map<std::string, std::string> table_to_alias_mapping;
static std::vector<std::string> query_hints;
static std::vector<bool> join_hints_info(JOIN_HINTS_INFO_VECTOR_SIZE, false);
static bool isJoinHintInOptionClause = false;
static std::string table_names;
static int num_of_tables = 0;
static std::string leading_hint;
static void add_query_hints(PLtsql_expr_query_mutator *mutator, int contextOffset);
static void clear_query_hints();
static void clear_tables_info();
static std::string validate_and_stringify_hints();
static int find_hint_offset(const char * queryTxt);
static bool pltsql_parseonly = false;
bool has_identity_function = false;
static void
breakHere()
{
}
std::string
getFullText(ParserRuleContext *context, misc::Interval range)
{
if (context == nullptr)
return" ";
return context->start->getInputStream()->getText(range);
}
std::string
getFullText(ParserRuleContext *context)
{
if (context == nullptr)
return "";
if (context->start == nullptr || context->stop == nullptr || context->start->getStartIndex() < 0 || context->stop->getStopIndex() < 0)
return context->getText();
return getFullText(context, misc::Interval(context->start->getStartIndex(), context->stop->getStopIndex()));
}
template <class T>
std::string
getFullText(std::vector<T*> const &contexts)
{
auto beg = contexts[0];
auto end = contexts[contexts.size() - 1];
misc::Interval textRange(beg->start->getStartIndex(), end->stop->getStopIndex());
return getFullText(contexts[0], textRange);
}
std::string
getFullText(TerminalNode *node)
{
return node->getText();
}
std::string
getFullText(Token* token)
{
return token->getText();
}
std::string
stripQuoteFromId(TSqlParser::IdContext *ctx)
{
if (ctx->DOUBLE_QUOTE_ID())
{
std::string val = getFullText(ctx->DOUBLE_QUOTE_ID());
Assert(val.length() >= 2);
return val.substr(1, val.length()-2);
}
else if (ctx->SQUARE_BRACKET_ID())
{
std::string val = getFullText(ctx->SQUARE_BRACKET_ID());
Assert(val.length() >= 2);
return val.substr(1, val.length()-2);
}
return getFullText(ctx);
}
std::string
stripQuoteFromId(std::string s)
{
if (!s.empty() && s.front() == '[')
{
Assert(s.back() == ']');
return s.substr(1,s.length()-2);
}
else if (!s.empty() && s.front() == '"')
{
Assert(s.back() == '"');
return s.substr(1,s.length()-2);
}
return s;
}
static int
get_curr_compile_body_lineno_adjustment()
{
if (!pltsql_curr_compile || pltsql_curr_compile->fn_oid == InvalidOid) /* not in a func/proc body */
return 0;
if (pltsql_curr_compile_body_lineno == 0) /* not set */
return 0;
return pltsql_curr_compile_body_lineno - 1; /* minus 1 for correct adjustment */
}
int getLineNo(ParserRuleContext *ctx)
{
if (!ctx)
return 0;
/*
* in T-SQL, line number is relative to batch start of CREATE FUNCTION/PROCEDURE/...
* if we're running in CREATE FUNCTION/PROCEDURE/..., add a offset lineno.
*/
int lineno_offset = get_curr_compile_body_lineno_adjustment();
Token *startToken = ctx->getStart();
if (!startToken)
return 0;
return startToken->getLine() + lineno_offset;
}
int getLineNo(TerminalNode* node)
{
if (!node)
return 0;
/*
* in T-SQL, line number is relative to batch start of CREATE FUNCTION/PROCEDURE/...
* if we're running in CREATE FUNCTION/PROCEDURE/..., add a offset lineno.
*/
int lineno_offset = get_curr_compile_body_lineno_adjustment();
Token *symbol = node->getSymbol();
if (!symbol)
return 0;
return symbol->getLine() + lineno_offset;
}
static int
get_curr_compile_body_position_adjustment()
{
if (!pltsql_curr_compile || pltsql_curr_compile->fn_oid == InvalidOid) /* not in a func/proc body */
return 0;
if (pltsql_curr_compile_body_position == 0) /* not set */
return 0;
return pltsql_curr_compile_body_position - 1; /* minus 1 for correct adjustment */
}
int getPosition(ParserRuleContext *ctx)
{
if (!ctx)
return 0;
/* if we're running in CREATE FUNCTION/PROCEDURE/..., add a offset position. */
int position_offset = get_curr_compile_body_position_adjustment();
Token *startToken = ctx->getStart();
if (!startToken)
return 0;
return startToken->getStartIndex() + position_offset;
}
int getPosition(TerminalNode* node)
{
if (!node)
return 0;
/* if we're running in CREATE FUNCTION/PROCEDURE/..., add a offset position. */
int position_offset = get_curr_compile_body_position_adjustment();
Token *symbol = node->getSymbol();
if (!symbol)
return 0;
return symbol->getStartIndex() + position_offset;
}
std::pair<int,int> getLineAndPos(ParserRuleContext *ctx)
{
return std::make_pair(getLineNo(ctx), getPosition(ctx));
}
std::pair<int,int> getLineAndPos(TerminalNode *node)
{
return std::make_pair(getLineNo(node), getPosition(node));
}
static ParseTreeProperty<PLtsql_stmt *> fragments;
// Keeps track of location of expressions being rewritten into a fragment 'SELECT <expr>'
static std::map<ParseTree *, std::pair<int, std::pair<int, int>>> selectFragmentOffsets;
// Record the offsets for a 'SELECT <expr>' fragment
void
recordSelectFragmentOffsets(ParseTree *ctx, int ixStart, int ixEnd, int ixShift)
{
Assert(ctx);
selectFragmentOffsets.emplace(std::make_pair(ctx, std::make_pair(ixStart, std::make_pair(ixEnd, ixShift))));
}
void
recordSelectFragmentOffsets(ParseTree *ctx, ParserRuleContext *expr)
{
Assert(ctx);
Assert(expr);
recordSelectFragmentOffsets(ctx, expr->getStart()->getStartIndex(), expr->getStop()->getStopIndex(), 0);
}
void
attachPLtsql_fragment(ParseTree *node, PLtsql_stmt *fragment)
{
if (fragment)
{
if (pltsql_enable_antlr_detailed_log)
{
const char *tsqlDesc = pltsql_stmt_typename(fragment);
std::cout << " attachPLtsql_fragment(" << (void *) node << ", " << fragment << "[" << tsqlDesc << "])" << std::endl;
}
fragments.put(node, fragment);
}
else
{
if (pltsql_enable_antlr_detailed_log)
std::cout << " attachPLtsql_fragment(" << (void *) node << ", " << fragment << "<NULL>)" << std::endl;
}
}
PLtsql_stmt *
getPLtsql_fragment(ParseTree *node)
{
if (pltsql_enable_antlr_detailed_log)
std::cout << "getPLtsql_fragment(" << (void *) node << ") returns " << fragments.get(node) << std::endl;
return fragments.get(node);
}
static List *rootInitializers = NIL;
FormattedMessage
format_errmsg(const char *fmt, const char *arg0)
{
FormattedMessage fm;
fm.fmt = fmt;
MemoryContext oldContext = MemoryContextSwitchTo(CurTransactionContext);
fm.args.push_back(pstrdup(arg0));
MemoryContextSwitchTo(oldContext);
return fm;
}
FormattedMessage
format_errmsg(const char *fmt, int64_t arg0)
{
FormattedMessage fm;
fm.fmt = fmt;
fm.args.push_back(reinterpret_cast<void*>(arg0));
return fm;
}
template <typename... Types>
FormattedMessage
format_errmsg(const char *fmt, const char *arg1, Types... args)
{
FormattedMessage fm = format_errmsg(fmt, args...);
fm.args.insert(fm.args.begin(), pstrdup(arg1)); // push_front
return fm;
}
template <typename... Types>
FormattedMessage
format_errmsg(const char *fmt, int64_t arg1, Types... args)
{
FormattedMessage fm = format_errmsg(fmt, args...);
fm.args.insert(fm.args.begin(), reinterpret_cast<void*>(arg1)); // push_front
return fm;
}
// currently, format_errmsg with more than 1 args is not used in this file but tsqlUnsupportedHandler uses it.
// use explicit instantiation here to make compiler forcefully create that template functions.
template
FormattedMessage
format_errmsg(const char *fmt, const char *arg1, const char *arg2);
inline std::u32string utf8_to_utf32(const char* s)
{
return antlrcpp::Utf8::lenientDecode(std::string_view(s, strlen(s)));
}
class MyInputStream : public ANTLRInputStream
{
public:
MyInputStream(const char *src)
: ANTLRInputStream((string)src)
{
}
void setText(size_t pos, const char *newText)
{
std::u32string newText32 = utf8_to_utf32(newText);
_data.replace(pos, newText32.size(), newText32);
}
};
class PLtsql_expr_query_mutator
{
public:
PLtsql_expr_query_mutator(PLtsql_expr *expr, ParserRuleContext* baseCtx);
void add(int antlr_pos, std::string orig_text, std::string repl_text);
void markSelectFragment(ParserRuleContext *ctx);
void run();
PLtsql_expr *expr;
ParserRuleContext* ctx;
protected:
// intentionally use std::map to iterate it via sorted order.
std::map<int, std::pair<std::string, std::string>> m; // pos -> (orig_text, repl_text)
int base_idx;
// Indicate the fragment being processed is an expression that was prefixed with 'SELECT ',
// so that offsets can be adjusted when doing the rewriting
bool isSelectFragment = false;
int idxStart = 0;
int idxEnd = 0;
int idxStartShift = 0;
};
PLtsql_expr_query_mutator::PLtsql_expr_query_mutator(PLtsql_expr *e, ParserRuleContext* baseCtx)
: expr(e)
, ctx(baseCtx)
, base_idx(-1)
{
if (!e)
throw PGErrorWrapperException(ERROR, ERRCODE_INTERNAL_ERROR, "can't mutate an internal query. NULL expression", getLineAndPos(baseCtx));
size_t base_index = baseCtx->getStart()->getStartIndex();
if (base_index == INVALID_INDEX)
throw PGErrorWrapperException(ERROR, ERRCODE_INTERNAL_ERROR, "can't mutate an internal query. base index is invalid", getLineAndPos(baseCtx));
base_idx = base_index;
isSelectFragment = false;
}
void PLtsql_expr_query_mutator::markSelectFragment(ParserRuleContext *ctx)
{
Assert(ctx);
Assert(selectFragmentOffsets.count(ctx) > 0);
auto p = selectFragmentOffsets.at(ctx);
isSelectFragment = true;
idxStart = p.first;
idxEnd = p.second.first;
idxStartShift = p.second.second;
}
void PLtsql_expr_query_mutator::add(int antlr_pos, std::string orig_text, std::string repl_text)
{
int offset = antlr_pos - base_idx;
if (isSelectFragment)
{
// For SELECT fragments, only apply the item when antlr_pos is between idxStart and idxEnd:
// when there are multiple expressions per statement (only for DECLARE), the rewrites must be
// applied to the correct expression
if ((antlr_pos < idxStart) || (antlr_pos > idxEnd))
{
return;
}
// Adjust offset to reflect the fact that the expression in the fragment is now prefixed with only 'SELECT '
offset = antlr_pos - idxStart;
// Adjust offset once more if the expression was shifted left (for a compound SET @v operator)
if (idxStartShift > 0)
{
offset = offset + idxStartShift;
}
}
if (!orig_text.empty() && (orig_text.front() == '"') && (orig_text.back() == '"') && !repl_text.empty() && (repl_text.front() == '\'') && (repl_text.back() == '\''))
{
// Do not validate the positions of strings as these are not replaced by their positions
}
else {
/* validation check */
if (offset < 0)
throw PGErrorWrapperException(ERROR, ERRCODE_INTERNAL_ERROR, "can't mutate an internal query. offset value is negative", 0, 0);
if (offset > (int)strlen(expr->query))
throw PGErrorWrapperException(ERROR, ERRCODE_INTERNAL_ERROR, "can't mutate an internal query. offset value is too large", 0, 0);
}
m.emplace(std::make_pair(offset, std::make_pair(orig_text, repl_text)));
}
void PLtsql_expr_query_mutator::run()
{
/*
* ANTLR parser converts all input to std::u32string (utf-32 string) internally and runs the lexer/parser on that.
* This indicates that Token position is based on character position not a byte offset.
* To rewrite query based on token position, we have to convert a query string to std::u32string first
* so that offset should indicate a correct position to be replaced.
*/
if (m.size() == 0) return; // nothing to do
std::u32string query = utf8_to_utf32(expr->query);
std::u32string rewritten_query;
size_t cursor = 0; // cursor to expr->query where next copy should start
for (const auto &entry : m)
{
size_t offset = entry.first;
const std::u32string& orig_text = utf8_to_utf32(entry.second.first.c_str());
const std::u32string& repl_text = utf8_to_utf32(entry.second.second.c_str());
if (isSelectFragment) offset += fragment_SELECT_prefix.length(); // because this is an expression prefixed with 'SELECT '
if (orig_text.length() == 0 || orig_text.c_str(), query.substr(offset, orig_text.length()) == orig_text) // local_id maybe already deleted in some cases such as select-assignment. check here if it still exists)
{
/* detect multiple mutations on the same position */
if (offset < cursor)
{
throw PGErrorWrapperException(ERROR, ERRCODE_INTERNAL_ERROR,
"Can't mutate an internal query: detected multiple mutations on the same position", 0, 0);
}
if (offset - cursor > 0) // if offset==cursor, no need to copy
rewritten_query += query.substr(cursor, offset - cursor); // copy substring of expr->query. ranged [cursor, offset)
rewritten_query += repl_text;
cursor = offset + orig_text.length();
}
}
if (cursor < strlen(expr->query))
rewritten_query += query.substr(cursor); // copy remaining expr->query
// update query string
std::string new_query = antlrcpp::Utf8::lenientEncode(std::u32string_view(rewritten_query));
expr->query = pstrdup(new_query.c_str());
}
static void
clear_rewritten_query_fragment()
{
rewritten_query_fragment.clear();
local_id_positions.clear();
}
static void
add_rewritten_query_fragment_to_mutator(PLtsql_expr_query_mutator *mutator)
{
Assert(mutator);
for (auto &entry : rewritten_query_fragment)
mutator->add(entry.first, entry.second.first, entry.second.second);
}
static void
add_query_hints(PLtsql_expr_query_mutator *mutator, int contextOffset)
{
std::string hint = validate_and_stringify_hints();
int baseOffset = mutator->ctx->start->getStartIndex();
int queryOffset = contextOffset - baseOffset;
int initialTokenOffset = find_hint_offset(&mutator->expr->query[queryOffset]);
mutator->add(contextOffset + initialTokenOffset, "", hint);
}
static std::string
validate_and_stringify_hints()
{
ParserRuleContext* ctx = nullptr;
// If a query has both join hint and query hint which is a join hint, it should have all the join hints as the query hints as well
if (isJoinHintInOptionClause && ((join_hints_info[LOOP_JOIN_HINT] && !join_hints_info[LOOP_QUERY_HINT]) || (join_hints_info[HASH_JOIN_HINT] && !join_hints_info[HASH_QUERY_HINT]) || (join_hints_info[MERGE_JOIN_HINT] && !join_hints_info[MERGE_QUERY_HINT])))
{
clear_query_hints();
clear_tables_info();
throw PGErrorWrapperException(ERROR, ERRCODE_FEATURE_NOT_SUPPORTED, "Conflicting JOIN optimizer hints specified", getLineAndPos(ctx));
}
std::string hint = "/*+ ";
for (auto q_hint: query_hints)
{
hint += q_hint;
hint += " ";
}
if (!leading_hint.empty())
hint += leading_hint;
hint += "*/";
transform(hint.begin(), hint.end(), hint.begin(), ::tolower);
return hint;
}
static int
find_hint_offset(const char *query)
{
std::string queryString(query);
size_t spaceIdx = queryString.find_first_of(" \t\n\v\f\r");
size_t commentStartIdx = queryString.find("/*");
//if there is no space and no comment default to beginning of statement
if (commentStartIdx == std::string::npos && spaceIdx == std::string::npos)
return 0;
//if no comment return spaceIdx
if (commentStartIdx == std::string::npos && spaceIdx < INT_MAX)
return static_cast<int>(spaceIdx);
//if no space return comment
if (spaceIdx == std::string::npos && commentStartIdx < INT_MAX)
return static_cast<int>(commentStartIdx);
//if both comments and space return the index of the smaller.
if (commentStartIdx != std::string::npos && spaceIdx != std::string::npos) {
size_t smallest = min(spaceIdx, commentStartIdx);
if (smallest < INT_MAX)
return static_cast<int>(smallest);
}
return 0;
}
static void
clear_query_hints()
{
query_hints.clear();
leading_hint.clear();
for (size_t i=0; i<JOIN_HINTS_INFO_VECTOR_SIZE; i++)
join_hints_info[i] = false;
isJoinHintInOptionClause = false;
}
static void
clear_tables_info()
{
table_names.clear();
alias_to_table_mapping.clear();
table_to_alias_mapping.clear();
num_of_tables = 0;
}
/*
* NOTE: Currently there exist several similar mutator for historical reasons.
* tsqlMutator is the first invented one, which modifies input stream directly.
* However it has a limiation that rewritten fragment string should be shorter than
* original string.
* tsqlBuilder's main role is to create PLtsql_stmt_*. But, many query rewriting
* logic was also added here because it already had a listner implementation.
* To overcomse the limitation of tsqlBuilder, query fragment rewriting was invented
* (please see the comment on rewritten_query_fragment).
* tsqlSelectMuator was introduced to cover corner cases such as CREATE-VIEW and DECLARE-CURSOR
* which need to deal with inner SELECT statement.
* tsqlCommonMutator was added to cover a rewriting logic which needs to be applied in
* batch-level statement and normal statement.
*
* TODO:
* The plan is to incorporate all rewriting logics to tsqlCommonMutator. Other
* mutators will be deprecated and existing query rewriting logics in tsqlBuilder
* will be also moved. tsqlBuilder will focus on create Pltsql_stmt_* only.
*/
////////////////////////////////////////////////////////////////////////////////
// tsql Common Mutator
////////////////////////////////////////////////////////////////////////////////
class tsqlCommonMutator : public TSqlParserBaseListener
{
/* see comment above. */
public:
explicit tsqlCommonMutator() = default;
bool in_create_or_alter_function = false;
bool in_create_or_alter_procedure = false;
bool in_create_or_alter_trigger = false;
void enterCreate_or_alter_function(TSqlParser::Create_or_alter_functionContext *ctx) override {
in_create_or_alter_function = true;
}
void exitCreate_or_alter_function(TSqlParser::Create_or_alter_functionContext *ctx) override {
in_create_or_alter_function = false;
}
void enterCreate_or_alter_procedure(TSqlParser::Create_or_alter_procedureContext *ctx) override {
in_create_or_alter_procedure = true;
}
void exitCreate_or_alter_procedure(TSqlParser::Create_or_alter_procedureContext *ctx) override {
in_create_or_alter_procedure = false;
}
void enterCreate_or_alter_trigger(TSqlParser::Create_or_alter_triggerContext *ctx) override {
in_create_or_alter_trigger = true;
}
void exitCreate_or_alter_trigger(TSqlParser::Create_or_alter_triggerContext *ctx) override {
in_create_or_alter_trigger = false;
}
void enterTransaction_statement(TSqlParser::Transaction_statementContext *ctx) override {
if (in_create_or_alter_function && ctx->COMMIT()){
throw PGErrorWrapperException(ERROR, ERRCODE_FEATURE_NOT_SUPPORTED, "Invalid use of a side-effecting operator 'COMMIT TRANSACTION' within a function.", 0, 0);
}
if (in_create_or_alter_function && ctx->ROLLBACK()){
throw PGErrorWrapperException(ERROR, ERRCODE_FEATURE_NOT_SUPPORTED, "Invalid use of a side-effecting operator 'ROLLBACK TRANSACTION' within a function.", 0, 0);
}
if (in_create_or_alter_function && ctx->SAVE()){
throw PGErrorWrapperException(ERROR, ERRCODE_FEATURE_NOT_SUPPORTED, "Invalid use of a side-effecting operator 'SAVEPOINT' within a function.", 0, 0);
}
}
void enterPrint_statement(TSqlParser::Print_statementContext *ctx) override {
if (in_create_or_alter_function && ctx->PRINT()){
throw PGErrorWrapperException(ERROR, ERRCODE_FEATURE_NOT_SUPPORTED, "Invalid use of a side-effecting operator 'PRINT' within a function.", 0, 0);
}
}
void enterRaiseerror_statement(TSqlParser::Raiseerror_statementContext * ctx) override {
if (in_create_or_alter_function && ctx->RAISERROR()){
throw PGErrorWrapperException(ERROR, ERRCODE_FEATURE_NOT_SUPPORTED, "Invalid use of a side-effecting operator 'RAISERROR' within a function.", 0, 0);
}
}
void enterExecute_statement(TSqlParser::Execute_statementContext *ctx) override {
if (in_create_or_alter_function && (ctx->EXEC() || ctx->EXECUTE())){
TSqlParser::Execute_bodyContext *body = ctx->execute_body();
if (body->LR_BRACKET())
{
std::vector<TSqlParser::Execute_var_stringContext *> exec_strings = body->execute_var_string();
if (!exec_strings.empty())
{
throw PGErrorWrapperException(ERROR, ERRCODE_FEATURE_NOT_SUPPORTED, "Invalid use of a side-effecting operator 'EXECUTE STRING' within a function.", 0, 0);
}
}
}
}
void enterWaitfor_statement(TSqlParser::Waitfor_statementContext *ctx) override {
if (in_create_or_alter_function && ctx->WAITFOR()){
throw PGErrorWrapperException(ERROR, ERRCODE_FEATURE_NOT_SUPPORTED, "Invalid use of a side-effecting operator 'WAITFOR' within a function.", 0, 0);
}
}
void enterWaitfor_receive_statement(TSqlParser::Waitfor_receive_statementContext * ctx) override {
if (in_create_or_alter_function && ctx->WAITFOR()){
throw PGErrorWrapperException(ERROR, ERRCODE_FEATURE_NOT_SUPPORTED, "Invalid use of a side-effecting operator 'WAITFOR' within a function.", 0, 0);
}
}
void enterKill_statement(TSqlParser::Kill_statementContext *ctx) override {
if (in_create_or_alter_function){
throw PGErrorWrapperException(ERROR, ERRCODE_FEATURE_NOT_SUPPORTED, "Invalid use of a side-effecting operator 'KILL' within a function.", 0, 0);
}
}
void enterCreate_partition_function(TSqlParser::Create_partition_functionContext *ctx) override {
if (in_create_or_alter_function){
throw PGErrorWrapperException(ERROR, ERRCODE_FEATURE_NOT_SUPPORTED, "Invalid use of a side-effecting operator 'CREATE PARTITION FUNCTION' within a function.", 0, 0);
}
}
void enterDrop_partition_function(TSqlParser::Drop_partition_functionContext *ctx) override {
if (in_create_or_alter_function){
throw PGErrorWrapperException(ERROR, ERRCODE_FEATURE_NOT_SUPPORTED, "Invalid use of a side-effecting operator 'DROP PARTITION FUNCTION' within a function.", 0, 0);
}
}
void enterCreate_partition_scheme(TSqlParser::Create_partition_schemeContext *ctx) override {
if (in_create_or_alter_function){
throw PGErrorWrapperException(ERROR, ERRCODE_FEATURE_NOT_SUPPORTED, "Invalid use of a side-effecting operator 'CREATE PARTITION SCHEME' within a function.", 0, 0);
}
}
void enterDrop_partition_scheme(TSqlParser::Drop_partition_schemeContext *ctx) override {
if (in_create_or_alter_function){
throw PGErrorWrapperException(ERROR, ERRCODE_FEATURE_NOT_SUPPORTED, "Invalid use of a side-effecting operator 'DROP PARTITION SCHEME' within a function.", 0, 0);
}
}
/* Column Name */
void exitSimple_column_name(TSqlParser::Simple_column_nameContext *ctx) override
{
if (does_object_name_need_delimiter(ctx->id()))
rewritten_query_fragment.emplace(std::make_pair(ctx->id()->start->getStartIndex(), std::make_pair(::getFullText(ctx->id()), delimit_identifier(ctx->id()))));
}
void exitInsert_column_id(TSqlParser::Insert_column_idContext *ctx) override
{
// qualifier and DOT is totally ignored
for (auto dot : ctx->DOT())
rewritten_query_fragment.emplace(std::make_pair(dot->getSymbol()->getStartIndex(), std::make_pair(::getFullText(dot), ""))); // remove dot
for (auto ign : ctx->ignore)
rewritten_query_fragment.emplace(std::make_pair(ign->start->getStartIndex(), std::make_pair(::getFullText(ign), ""))); // remove ignore
// qualified identifier doesn't need delimiter
if (ctx->DOT().empty() && does_object_name_need_delimiter(ctx->id().back()))
rewritten_query_fragment.emplace(std::make_pair(ctx->id().back()->start->getStartIndex(), std::make_pair(::getFullText(ctx->id().back()), delimit_identifier(ctx->id().back()))));
}
void exitFunction_call(TSqlParser::Function_callContext *ctx) override
{
handleGeospatialFunctionsInFunctionCall(ctx);
handleXMLFunctionsInFunctionCall(ctx);
if (ctx->func_proc_name_server_database_schema())
{
auto fpnsds = ctx->func_proc_name_server_database_schema();
if (fpnsds->DOT().empty() && fpnsds->id().back()->keyword()) /* built-in functions */
{
auto id = fpnsds->id().back();
if (id->keyword()->NULLIF()) /* NULLIF */