-
Notifications
You must be signed in to change notification settings - Fork 486
Expand file tree
/
Copy pathcypher_clause.c
More file actions
7641 lines (6549 loc) · 259 KB
/
cypher_clause.c
File metadata and controls
7641 lines (6549 loc) · 259 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
/*
* For PostgreSQL Database Management System:
* (formerly known as Postgres, then as Postgres95)
*
* Portions Copyright (c) 1996-2010, The PostgreSQL Global Development Group
*
* Portions Copyright (c) 1994, The Regents of the University of California
*
* Permission to use, copy, modify, and distribute this software and its documentation for any purpose,
* without fee, and without a written agreement is hereby granted, provided that the above copyright notice
* and this paragraph and the following two paragraphs appear in all copies.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
* OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA
* HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#include "postgres.h"
#include "access/heapam.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_func.h"
#include "parser/parse_oper.h"
#include "parser/parse_target.h"
#include "parser/parsetree.h"
#include "parser/parse_relation.h"
#include "rewrite/rewriteHandler.h"
#include "catalog/ag_graph.h"
#include "catalog/ag_label.h"
#include "commands/label_commands.h"
#include "common/hashfn.h"
#include "parser/cypher_analyze.h"
#include "parser/cypher_clause.h"
#include "parser/cypher_expr.h"
#include "parser/cypher_item.h"
#include "parser/cypher_parse_agg.h"
#include "parser/cypher_transform_entity.h"
#include "storage/lock.h"
#include "utils/ag_cache.h"
#include "utils/ag_func.h"
#include "utils/ag_guc.h"
/*
* Variable string names for makeTargetEntry. As they are going to be variable
* names that will be hidden from the user, we need to do our best to make sure
* they won't be picked by mistake. Additionally, their form needs to be easily
* determined as ours. For now, prefix them as follows -
*
* #define AGE_VARNAME_SOMETHING AGE_DEFAULT_VARNAME_PREFIX"something"
*
* We should probably make an automated variable generator, like for aliases,
* for this.
*
* Also, keep these here as nothing outside of this file needs to know these.
*/
#define AGE_VARNAME_CREATE_CLAUSE AGE_DEFAULT_VARNAME_PREFIX"create_clause"
#define AGE_VARNAME_CREATE_NULL_VALUE AGE_DEFAULT_VARNAME_PREFIX"create_null_value"
#define AGE_VARNAME_DELETE_CLAUSE AGE_DEFAULT_VARNAME_PREFIX"delete_clause"
#define AGE_VARNAME_MERGE_CLAUSE AGE_DEFAULT_VARNAME_PREFIX"merge_clause"
#define AGE_VARNAME_ID AGE_DEFAULT_VARNAME_PREFIX"id"
#define AGE_VARNAME_SET_CLAUSE AGE_DEFAULT_VARNAME_PREFIX"set_clause"
/*
* In the transformation stage, we need to track
* where a variable came from. When moving between
* clauses, Postgres parsestate and Query data structures
* are insufficient for some of the information we
* need.
*/
/*
* Rules to determine if a node must be included:
*
* 1. the node is in a path variable
* 2. the node is a variable
* 3. the node contains filter properties
*/
#define INCLUDE_NODE_IN_JOIN_TREE(path, node) \
(path->var_name || node->name || node->props)
typedef Query *(*transform_method)(cypher_parsestate *cpstate,
cypher_clause *clause);
/* projection */
static Query *transform_cypher_return(cypher_parsestate *cpstate,
cypher_clause *clause);
static List *transform_cypher_order_by(cypher_parsestate *cpstate,
List *sort_items, List **target_list,
ParseExprKind expr_kind);
static TargetEntry *find_target_list_entry(cypher_parsestate *cpstate,
Node *node, List **target_list,
ParseExprKind expr_kind);
static Node *transform_cypher_limit(cypher_parsestate *cpstate, Node *node,
ParseExprKind expr_kind,
const char *construct_name);
static Query *transform_cypher_with(cypher_parsestate *cpstate,
cypher_clause *clause);
static Query *transform_cypher_clause_with_where(cypher_parsestate *cpstate,
transform_method transform,
cypher_clause *clause,
Node *where);
/* match clause */
static Query *transform_cypher_match(cypher_parsestate *cpstate,
cypher_clause *clause);
static Query *transform_cypher_match_pattern(cypher_parsestate *cpstate,
cypher_clause *clause);
static List *transform_match_entities(cypher_parsestate *cpstate, Query *query,
cypher_path *path);
static void transform_match_pattern(cypher_parsestate *cpstate, Query *query,
List *pattern, Node *where);
static List *transform_match_path(cypher_parsestate *cpstate, Query *query,
cypher_path *path);
static Expr *transform_cypher_edge(cypher_parsestate *cpstate,
cypher_relationship *rel,
List **target_list, bool valid_label);
static Expr *transform_cypher_node(cypher_parsestate *cpstate,
cypher_node *node, List **target_list,
bool output_node, bool valid_label);
static bool match_check_valid_label(cypher_match *match,
cypher_parsestate *cpstate);
static Node *make_vertex_expr(cypher_parsestate *cpstate,
ParseNamespaceItem *pnsi);
static Node *make_edge_expr(cypher_parsestate *cpstate,
ParseNamespaceItem *pnsi);
static Node *make_qual(cypher_parsestate *cpstate,
transform_entity *entity, char *name);
static TargetEntry *
transform_match_create_path_variable(cypher_parsestate *cpstate,
cypher_path *path, List *entities);
static List *make_path_join_quals(cypher_parsestate *cpstate, List *entities);
static List *make_directed_edge_join_conditions(
cypher_parsestate *cpstate, transform_entity *prev_entity,
transform_entity *next_entity, Node *prev_qual, Node *next_qual,
char *prev_node_label, char *next_node_label);
static List *join_to_entity(cypher_parsestate *cpstate,
transform_entity *entity, Node *qual,
enum transform_entity_join_side side);
static List *make_join_condition_for_edge(cypher_parsestate *cpstate,
transform_entity *prev_edge,
transform_entity *prev_node,
transform_entity *entity,
transform_entity *next_node,
transform_entity *next_edge);
static List *make_edge_quals(cypher_parsestate *cpstate,
transform_entity *edge,
enum transform_entity_join_side side);
static A_Expr *filter_vertices_on_label_id(cypher_parsestate *cpstate,
Node *id_field, char *label);
static Node *transform_map_to_ind(cypher_parsestate *cpstate,
transform_entity *entity, cypher_map *map);
static List *transform_map_to_ind_recursive(cypher_parsestate *cpstate,
transform_entity *entity,
cypher_map *map,
List *parent_fields);
static List *transform_map_to_ind_top_level(cypher_parsestate *cpstate,
transform_entity *entity,
cypher_map *map);
static Node *create_property_constraints(cypher_parsestate *cpstate,
transform_entity *entity,
Node *property_constraints,
Node *prop_expr);
static TargetEntry *findTarget(List *targetList, char *resname);
static transform_entity *transform_VLE_edge_entity(cypher_parsestate *cpstate,
cypher_relationship *rel,
Query *query);
/* create clause */
static Query *transform_cypher_create(cypher_parsestate *cpstate,
cypher_clause *clause);
static List *transform_cypher_create_pattern(cypher_parsestate *cpstate,
Query *query, List *pattern);
static cypher_create_path *
transform_cypher_create_path(cypher_parsestate *cpstate, List **target_list,
cypher_path *cp);
static cypher_target_node *
transform_create_cypher_node(cypher_parsestate *cpstate, List **target_list,
cypher_node *node, bool has_edge);
static cypher_target_node *
transform_create_cypher_new_node(cypher_parsestate *cpstate,
List **target_list, cypher_node *node);
static cypher_target_node *transform_create_cypher_existing_node(
cypher_parsestate *cpstate, List **target_list, bool declared_in_current_clause,
cypher_node *node);
static cypher_target_node *
transform_create_cypher_edge(cypher_parsestate *cpstate, List **target_list,
cypher_relationship *edge);
static Expr *cypher_create_properties(cypher_parsestate *cpstate,
cypher_target_node *rel,
Relation label_relation, Node *props,
enum transform_entity_type type);
static Expr *add_volatile_wrapper(Expr *node);
static bool variable_exists(cypher_parsestate *cpstate, char *name);
static void add_volatile_wrapper_to_target_entry(List *target_list, int resno);
static int get_target_entry_resno(List *target_list, char *name);
static void handle_prev_clause(cypher_parsestate *cpstate, Query *query,
cypher_clause *clause, bool first_rte);
static TargetEntry *placeholder_target_entry(cypher_parsestate *cpstate,
char *name);
static Query *transform_cypher_sub_pattern(cypher_parsestate *cpstate,
cypher_clause *clause);
static Query *transform_cypher_sub_query(cypher_parsestate *cpstate,
cypher_clause *clause);
/* set and remove clause */
static Query *transform_cypher_set(cypher_parsestate *cpstate,
cypher_clause *clause);
static cypher_update_information *transform_cypher_set_item_list(cypher_parsestate *cpstate,
List *set_item_list,
Query *query);
static cypher_update_information *transform_cypher_remove_item_list(cypher_parsestate *cpstate,
List *remove_item_list,
Query *query);
/* delete */
static Query *transform_cypher_delete(cypher_parsestate *cpstate,
cypher_clause *clause);
static List *transform_cypher_delete_item_list(cypher_parsestate *cpstate,
List *delete_item_list,
Query *query);
/* set operators */
static cypher_clause *make_cypher_clause(List *stmt);
static Query *transform_cypher_union(cypher_parsestate *cpstate,
cypher_clause *clause);
static Node * transform_cypher_union_tree(cypher_parsestate *cpstate,
cypher_clause *clause,
bool isTopLevel,
List **targetlist);
Query *cypher_parse_sub_analyze_union(cypher_clause *clause,
cypher_parsestate *cpstate,
CommonTableExpr *parentCTE,
bool locked_from_parent,
bool resolve_unknowns);
static void get_res_cols(ParseState *pstate, ParseNamespaceItem *l_pnsi,
ParseNamespaceItem *r_pnsi, List **res_colnames,
List **res_colvars);
/* unwind */
static Query *transform_cypher_unwind(cypher_parsestate *cpstate,
cypher_clause *clause);
/* merge */
static Query *transform_cypher_merge(cypher_parsestate *cpstate,
cypher_clause *clause);
static cypher_create_path *
transform_merge_make_lateral_join(cypher_parsestate *cpstate, Query *query,
cypher_clause *clause,
cypher_clause *isolated_merge_clause);
static cypher_create_path *
transform_cypher_merge_path(cypher_parsestate *cpstate, List **target_list,
cypher_path *path);
static cypher_target_node *
transform_merge_cypher_edge(cypher_parsestate *cpstate, List **target_list,
cypher_relationship *edge);
static cypher_target_node *
transform_merge_cypher_node(cypher_parsestate *cpstate, List **target_list,
cypher_node *node, bool has_edge);
static Node *transform_clause_for_join(cypher_parsestate *cpstate,
cypher_clause *clause,
RangeTblEntry **rte,
ParseNamespaceItem **nsitem,
Alias* alias);
static cypher_clause *convert_merge_to_match(cypher_merge *merge);
static void
transform_cypher_merge_mark_tuple_position(cypher_parsestate *cpstate,
List *target_list,
cypher_create_path *path);
static cypher_target_node *get_referenced_variable(ParseState *pstate,
Node *node,
List *transformed_path);
/* call...[yield] */
static Query *transform_cypher_call_stmt(cypher_parsestate *cpstate,
cypher_clause *clause);
static Query *transform_cypher_call_subquery(cypher_parsestate *cpstate,
cypher_clause *clause);
/* transform */
#define PREV_CYPHER_CLAUSE_ALIAS AGE_DEFAULT_ALIAS_PREFIX"previous_cypher_clause"
#define CYPHER_OPT_RIGHT_ALIAS AGE_DEFAULT_ALIAS_PREFIX"cypher_optional_right"
#define transform_prev_cypher_clause(cpstate, prev_clause, add_rte_to_query) \
transform_cypher_clause_as_subquery(cpstate, transform_cypher_clause, \
prev_clause, NULL, add_rte_to_query)
ParseNamespaceItem
*transform_cypher_clause_as_subquery(cypher_parsestate *cpstate,
transform_method transform,
cypher_clause *clause,
Alias *alias,
bool add_rte_to_query);
static Query *analyze_cypher_clause(transform_method transform,
cypher_clause *clause,
cypher_parsestate *parent_cpstate);
static List *transform_group_clause(cypher_parsestate *cpstate,
List *grouplist, List **groupingSets,
List **targetlist, List *sortClause,
ParseExprKind exprKind);
static Node *flatten_grouping_sets(Node *expr, bool toplevel,
bool *hasGroupingSets);
static Index transform_group_clause_expr(List **flatresult,
Bitmapset *seen_local,
cypher_parsestate *cpstate,
Node *gexpr, List **targetlist,
List *sortClause,
ParseExprKind exprKind,
bool toplevel);
static List *add_target_to_group_list(cypher_parsestate *cpstate,
TargetEntry *tle, List *grouplist,
List *targetlist, int location);
static void advance_transform_entities_to_next_clause(List *entities);
static ParseNamespaceItem *get_namespace_item(ParseState *pstate,
RangeTblEntry *rte);
static List *make_target_list_from_join(ParseState *pstate,
RangeTblEntry *rte);
static FuncExpr *make_clause_func_expr(char *function_name,
Node *clause_information);
static void markRelsAsNulledBy(ParseState *pstate, Node *n, int jindex);
/* for VLE support */
static ParseNamespaceItem *transform_RangeFunction(cypher_parsestate *cpstate,
RangeFunction *r);
static Node *transform_VLE_Function(cypher_parsestate *cpstate, Node *n,
RangeTblEntry **top_rte, int *top_rti,
List **namespace);
static ParseNamespaceItem *append_VLE_Func_to_FromClause(cypher_parsestate *cpstate,
Node *n);
static void setNamespaceLateralState(List *namespace, bool lateral_only,
bool lateral_ok);
static bool isa_special_VLE_case(cypher_path *path);
static ParseNamespaceItem *find_pnsi(cypher_parsestate *cpstate, char *varname);
/*
* transform a cypher_clause
*/
Query *transform_cypher_clause(cypher_parsestate *cpstate,
cypher_clause *clause)
{
Node *self = clause->self;
Query *result;
/* examine the type of clause and call the transform logic for it */
if (is_ag_node(self, cypher_return))
{
cypher_return *n = (cypher_return *) self;
if (n->op == SETOP_NONE)
{
result = transform_cypher_return(cpstate, clause);
}
else if (n->op == SETOP_UNION)
{
result = transform_cypher_union(cpstate, clause);
}
else
{
ereport(ERROR, (errmsg_internal("unexpected Node for cypher_return")));
}
}
else if (is_ag_node(self, cypher_with))
{
result = transform_cypher_with(cpstate, clause);
}
else if (is_ag_node(self, cypher_match))
{
result = transform_cypher_match(cpstate, clause);
}
else if (is_ag_node(self, cypher_create))
{
result = transform_cypher_create(cpstate, clause);
}
else if (is_ag_node(self, cypher_set))
{
result = transform_cypher_set(cpstate, clause);
}
else if (is_ag_node(self, cypher_delete))
{
result = transform_cypher_delete(cpstate, clause);
}
else if (is_ag_node(self, cypher_merge))
{
result = transform_cypher_merge(cpstate, clause);
}
else if (is_ag_node(self, cypher_sub_pattern))
{
result = transform_cypher_sub_pattern(cpstate, clause);
}
else if (is_ag_node(self, cypher_sub_query))
{
result = transform_cypher_sub_query(cpstate, clause);
}
else if (is_ag_node(self, cypher_unwind))
{
cypher_unwind *n = (cypher_unwind *) self;
if (n->collect != NULL)
{
cpstate->p_list_comp = true;
}
result = transform_cypher_clause_with_where(cpstate,
transform_cypher_unwind,
clause, n->where);
}
else if (is_ag_node(self, cypher_call))
{
result = transform_cypher_call_stmt(cpstate, clause);
}
else
{
ereport(ERROR, (errmsg_internal("unexpected Node for cypher_clause")));
}
result->querySource = QSRC_ORIGINAL;
result->canSetTag = true;
return result;
}
/*
* Makes a cypher_clause from a list of nodes. Used by union
* and subquery procedures to generate a subquery to transform.
*/
static cypher_clause *make_cypher_clause(List *stmt)
{
cypher_clause *clause;
ListCell *lc;
/*
* Since the first clause in stmt is the innermost subquery, the order of
* the clauses is inverted.
*/
clause = NULL;
foreach (lc, stmt)
{
cypher_clause *next;
next = palloc(sizeof(*next));
next->next = NULL;
next->self = lfirst(lc);
next->prev = clause;
/* check for subqueries in match */
if (is_ag_node(next->self, cypher_match))
{
cypher_match *match = (cypher_match *)next->self;
if (match->where != NULL && expr_contains_node(expr_has_subquery, match->where))
{
/* advance the clause iterator to the intermediate clause position */
clause = build_subquery_node(next);
/* set the next of the match to the where_container_clause */
match->where = NULL;
next->next = clause;
continue;
}
}
if (clause != NULL)
{
clause->next = next;
}
clause = next;
}
return clause;
}
/*
* transform_cypher_union -
* transforms a union tree, derived from postgresql's
* transformSetOperationStmt. A lot of the general logic is similar,
* with adjustments made for AGE.
*
* A union tree is just a return, but with UNION structure to it.
* We must transform each leaf SELECT and build up a top-level Query
* that contains the leaf SELECTs as subqueries in its rangetable.
* The tree of unions is converted into the setOperations field of
* the top-level Query.
*/
static Query *transform_cypher_union(cypher_parsestate *cpstate,
cypher_clause *clause)
{
ParseState *pstate = (ParseState *)cpstate;
Query *qry = makeNode(Query);
int leftmostRTI;
Query *leftmostQuery;
SetOperationStmt *cypher_union_statement;
Node *skip = NULL; /* equivalent to postgres limitOffset */
Node *limit = NULL; /* equivalent to postgres limitCount */
List *order_by = NIL;
Node *node;
cypher_return *self = (cypher_return *)clause->self;
ListCell *left_tlist, *lct, *lcm, *lcc;
List *targetvars, *targetnames, *sv_namespace;
int sv_rtable_length;
int tllen;
ParseNamespaceItem *nsitem;
ParseNamespaceColumn *sortnscolumns;
int sortcolindex;
qry->commandType = CMD_SELECT;
/*
* Union is a node that should never have a previous node because
* of where it is used in the parse logic. The query parts around it
* are children located in larg or rarg. Something went wrong if the
* previous clause field is not null.
*/
if (clause->prev)
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("Union is a parent node, there are no previous"),
parser_errposition(&cpstate->pstate, 0)));
}
order_by = self->order_by;
skip = self->skip;
limit = self->limit;
self->order_by = NIL;
self->skip = NULL;
self->limit = NULL;
/*
* Recursively transform the components of the tree.
*/
cypher_union_statement = (SetOperationStmt *) transform_cypher_union_tree(cpstate,
clause, true, NULL);
Assert(cypher_union_statement);
qry->setOperations = (Node *) cypher_union_statement;
/*
* Re-find leftmost return (now it's a sub-query in rangetable)
*/
node = cypher_union_statement->larg;
while (node && IsA(node, SetOperationStmt))
{
node = ((SetOperationStmt *) node)->larg;
}
Assert(node && IsA(node, RangeTblRef));
leftmostRTI = ((RangeTblRef *) node)->rtindex;
leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
Assert(leftmostQuery != NULL);
/*
* Generate dummy targetlist for outer query using column names of
* leftmost return and common datatypes/collations of topmost set
* operation. Also make lists of the dummy vars and their names for use
* in parsing ORDER BY.
*
* Note: we use leftmostRTI as the varno of the dummy variables. It
* shouldn't matter too much which RT index they have, as long as they
* have one that corresponds to a real RT entry; else funny things may
* happen when the tree is mashed by rule rewriting.
*/
qry->targetList = NIL;
targetvars = NIL;
targetnames = NIL;
sortnscolumns = (ParseNamespaceColumn *)
palloc0(list_length(cypher_union_statement->colTypes) * sizeof(ParseNamespaceColumn));
sortcolindex = 0;
forfour(lct, cypher_union_statement->colTypes,
lcm, cypher_union_statement->colTypmods,
lcc, cypher_union_statement->colCollations,
left_tlist, leftmostQuery->targetList)
{
Oid colType = lfirst_oid(lct);
int32 colTypmod = lfirst_int(lcm);
Oid colCollation = lfirst_oid(lcc);
TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
char *colName;
TargetEntry *tle;
Var *var;
Assert(!lefttle->resjunk);
colName = pstrdup(lefttle->resname);
var = makeVar(leftmostRTI,
lefttle->resno,
colType,
colTypmod,
colCollation,
0);
var->location = exprLocation((Node *) lefttle->expr);
tle = makeTargetEntry((Expr *) var,
(AttrNumber) pstate->p_next_resno++,
colName,
false);
qry->targetList = lappend(qry->targetList, tle);
targetvars = lappend(targetvars, var);
targetnames = lappend(targetnames, makeString(colName));
sortnscolumns[sortcolindex].p_varno = leftmostRTI;
sortnscolumns[sortcolindex].p_varattno = lefttle->resno;
sortnscolumns[sortcolindex].p_vartype = colType;
sortnscolumns[sortcolindex].p_vartypmod = colTypmod;
sortnscolumns[sortcolindex].p_varcollid = colCollation;
sortnscolumns[sortcolindex].p_varnosyn = leftmostRTI;
sortnscolumns[sortcolindex].p_varattnosyn = lefttle->resno;
sortcolindex++;
}
/*
* As a first step towards supporting sort clauses that are expressions
* using the output columns, generate a namespace entry that makes the
* output columns visible. A Join RTE node is handy for this, since we
* can easily control the Vars generated upon matches.
*
* Note: we don't yet do anything useful with such cases, but at least
* "ORDER BY upper(foo)" will draw the right error message rather than
* "foo not found".
*/
sv_rtable_length = list_length(pstate->p_rtable);
nsitem = addRangeTableEntryForJoin(pstate, targetnames, sortnscolumns,
JOIN_INNER, 0, targetvars, NIL, NIL,
NULL, NULL, false);
sv_namespace = pstate->p_namespace;
pstate->p_namespace = NIL;
/* add jrte to column namespace only */
addNSItemToQuery(pstate, nsitem, false, false, true);
tllen = list_length(qry->targetList);
qry->sortClause = transformSortClause(pstate,
order_by,
&qry->targetList,
EXPR_KIND_ORDER_BY,
false /* allow SQL92 rules */ );
/* restore namespace, remove jrte from rtable */
pstate->p_namespace = sv_namespace;
pstate->p_rtable = list_truncate(pstate->p_rtable, sv_rtable_length);
if (tllen != list_length(qry->targetList))
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("invalid UNION ORDER BY clause"),
errdetail("Only result column names can be used, not expressions or functions."),
parser_errposition(pstate,
exprLocation(list_nth(qry->targetList, tllen)))));
}
qry->limitOffset = transform_cypher_limit(cpstate, skip,
EXPR_KIND_OFFSET, "OFFSET");
qry->limitCount = transform_cypher_limit(cpstate, limit,
EXPR_KIND_LIMIT, "LIMIT");
qry->rtable = pstate->p_rtable;
qry->rteperminfos = pstate->p_rteperminfos;
qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
qry->hasAggs = pstate->p_hasAggs;
assign_query_collations(pstate, qry);
/* this must be done after collations, for reliable comparison of exprs */
if (pstate->p_hasAggs ||
qry->groupClause || qry->groupingSets || qry->havingQual)
{
parse_check_aggregates(pstate, qry);
}
return qry;
}
/*
* transform_cypher_union_tree
* Recursively transform leaves and internal nodes of a set-op tree,
* derived from postgresql's transformSetOperationTree. A lot of
* the general logic is similar, with adjustments made for AGE.
*
* In addition to returning the transformed node, if targetlist isn't NULL
* then we return a list of its non-resjunk TargetEntry nodes. For a leaf
* set-op node these are the actual targetlist entries; otherwise they are
* dummy entries created to carry the type, typmod, collation, and location
* (for error messages) of each output column of the set-op node. This info
* is needed only during the internal recursion of this function, so outside
* callers pass NULL for targetlist. Note: the reason for passing the
* actual targetlist entries of a leaf node is so that upper levels can
* replace UNKNOWN Consts with properly-coerced constants.
*/
static Node *
transform_cypher_union_tree(cypher_parsestate *cpstate, cypher_clause *clause,
bool isTopLevel, List **targetlist)
{
bool isLeaf;
ParseState *pstate = (ParseState *)cpstate;
cypher_return *cmp;
ParseNamespaceItem *pnsi;
/* Guard against stack overflow due to overly complex set-expressions */
check_stack_depth();
if (IsA(clause, List))
{
clause = make_cypher_clause((List *)clause);
}
if (is_ag_node(clause->self, cypher_return))
{
cmp = (cypher_return *) clause->self;
}
else
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("Cypher found an unsupported node"),
parser_errposition(pstate, 0)));
}
if (cmp->op == SETOP_NONE)
{
Assert(cmp->larg == NULL && cmp->rarg == NULL);
isLeaf = true;
}
else if (cmp->op == SETOP_UNION)
{
Assert(cmp->larg != NULL && cmp->rarg != NULL);
if (cmp->order_by || cmp->limit || cmp->skip)
{
isLeaf = true;
}
else
{
isLeaf = false;
}
}
else
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("Cypher found an unsupported SETOP"),
parser_errposition(pstate, 0)));
}
if (isLeaf)
{
/*process leaf return */
Query *returnQuery;
char returnName[32];
RangeTblEntry *rte PG_USED_FOR_ASSERTS_ONLY;
RangeTblRef *rtr;
ListCell *tl;
/*
* Transform SelectStmt into a Query.
*
* This works the same as RETURN transformation normally would, except
* that we prevent resolving unknown-type outputs as TEXT. This does
* not change the subquery's semantics since if the column type
* matters semantically, it would have been resolved to something else
* anyway. Doing this lets us resolve such outputs using
* select_common_type(), below.
*
* Note: previously transformed sub-queries don't affect the parsing
* of this sub-query, because they are not in the toplevel pstate's
* namespace list.
*/
/*
* Convert the List * that the grammar gave us to a cypher_clause.
* cypher_analyze doesn't do this because the cypher_union clause
* is hiding it.
*/
returnQuery = cypher_parse_sub_analyze_union((cypher_clause *) clause, cpstate,
NULL, false, false);
/*
* Check for bogus references to Vars on the current query level (but
* upper-level references are okay). Normally this can't happen
* because the namespace will be empty, but it could happen if we are
* inside a rule.
*/
if (pstate->p_namespace)
{
if (contain_vars_of_level((Node *) returnQuery, 1))
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
errmsg("UNION member statement cannot refer to other relations of same query level"),
parser_errposition(pstate,
locate_var_of_level((Node *) returnQuery, 1))));
}
}
/*
* Extract a list of the non-junk TLEs for upper-level processing.
*/
/* mechanism to check for top level query list items here? */
if (targetlist)
{
*targetlist = NIL;
foreach(tl, returnQuery->targetList)
{
TargetEntry *tle = (TargetEntry *) lfirst(tl);
if (!tle->resjunk)
{
*targetlist = lappend(*targetlist, tle);
}
}
}
/*
* Make the leaf query be a subquery in the top-level rangetable.
*/
snprintf(returnName, sizeof(returnName), "*SELECT* %d ",
list_length(pstate->p_rtable) + 1);
pnsi = addRangeTableEntryForSubquery(pstate,
returnQuery,
makeAlias(returnName, NIL),
false,
false);
rte = pnsi->p_rte;
rtr = makeNode(RangeTblRef);
/* assume new rte is at end */
rtr->rtindex = list_length(pstate->p_rtable);
Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
return (Node *) rtr;
}
else /*is not a leaf */
{
/* Process an internal node (set operation node) */
SetOperationStmt *op = makeNode(SetOperationStmt);
List *ltargetlist;
List *rtargetlist;
ListCell *ltl;
ListCell *rtl;
cypher_return *self = (cypher_return *) clause->self;
const char *context;
context = "UNION";
op->op = self->op;
op->all = self->all_or_distinct;
/*
* Recursively transform the left child node.
*/
op->larg = transform_cypher_union_tree(cpstate,
(cypher_clause *) self->larg,
false,
<argetlist);
/*
* If we find ourselves processing a recursive CTE here something
* went horribly wrong. That is an SQL construct with no parallel in
* cypher.
*/
if (isTopLevel &&
pstate->p_parent_cte &&
pstate->p_parent_cte->cterecursive)
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("Cypher does not support recursive CTEs"),
parser_errposition(pstate, 0)));
}
/*
* Recursively transform the right child node.
*/
op->rarg = transform_cypher_union_tree(cpstate,
(cypher_clause *) self->rarg,
false,
&rtargetlist);
/*
* Verify that the two children have the same number of non-junk
* columns, and determine the types of the merged output columns.
* If we are in a returnless subquery, we do not care about the columns
* matching, because they are not relevant to the end result.
*/
if (list_length(ltargetlist) != list_length(rtargetlist) &&
self->returnless_union == false)
{
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("each %s query must have the same number of columns",
context),
parser_errposition(pstate,
exprLocation((Node *) rtargetlist))));
}
if (targetlist)
{
*targetlist = NIL;
}
op->colTypes = NIL;
op->colTypmods = NIL;
op->colCollations = NIL;
op->groupClauses = NIL;
forboth(ltl, ltargetlist, rtl, rtargetlist)
{
TargetEntry *ltle = (TargetEntry *) lfirst(ltl);
TargetEntry *rtle = (TargetEntry *) lfirst(rtl);
Node *lcolnode = (Node *) ltle->expr;
Node *rcolnode = (Node *) rtle->expr;
Oid lcoltype = exprType(lcolnode);
Oid rcoltype = exprType(rcolnode);
int32 lcoltypmod = exprTypmod(lcolnode);
int32 rcoltypmod = exprTypmod(rcolnode);
Node *bestexpr;
int bestlocation;
Oid rescoltype;
int32 rescoltypmod;
Oid rescolcoll;
/* select common type, same as CASE et al */
rescoltype = select_common_type(pstate,
list_make2(lcolnode, rcolnode),
context,
&bestexpr);
bestlocation = exprLocation(bestexpr);
/* if same type and same typmod, use typmod; else default */
if (lcoltype == rcoltype && lcoltypmod == rcoltypmod)
{
rescoltypmod = lcoltypmod;
}
else
{
rescoltypmod = -1;
}
/*
* Verify the coercions are actually possible. If not, we'd fail
* later anyway, but we want to fail now while we have sufficient
* context to produce an error cursor position.
*
* For all non-UNKNOWN-type cases, we verify coercibility but we
* don't modify the child's expression, for fear of changing the
* child query's semantics.
*
* If a child expression is an UNKNOWN-type Const or Param, we
* want to replace it with the coerced expression. This can only
* happen when the child is a leaf set-op node. It's safe to
* replace the expression because if the child query's semantics
* depended on the type of this output column, it'd have already
* coerced the UNKNOWN to something else. We want to do this
* because (a) we want to verify that a Const is valid for the
* target type, or resolve the actual type of an UNKNOWN Param,
* and (b) we want to avoid unnecessary discrepancies between the
* output type of the child query and the resolved target type.
* Such a discrepancy would disable optimization in the planner.
*
* If it's some other UNKNOWN-type node, eg a Var, we do nothing
* (knowing that coerce_to_common_type would fail). The planner
* is sometimes able to fold an UNKNOWN Var to a constant before
* it has to coerce the type, so failing now would just break
* cases that might work.
*/
if (lcoltype != UNKNOWNOID)
{
lcolnode = coerce_to_common_type(pstate, lcolnode,
rescoltype, context);
}
else if (IsA(lcolnode, Const) || IsA(lcolnode, Param))
{
lcolnode = coerce_to_common_type(pstate, lcolnode,
rescoltype, context);
ltle->expr = (Expr *) lcolnode;
}
if (rcoltype != UNKNOWNOID)
{
rcolnode = coerce_to_common_type(pstate, rcolnode,
rescoltype, context);
}
else if (IsA(rcolnode, Const) || IsA(rcolnode, Param))
{
rcolnode = coerce_to_common_type(pstate, rcolnode,
rescoltype, context);
rtle->expr = (Expr *) rcolnode;
}
/*
* Select common collation. A common collation is required for
* all set operators except UNION ALL; see SQL:2008 7.13 <query
* expression> Syntax Rule 15c. (If we fail to identify a common
* collation for a UNION ALL column, the curCollations element
* will be set to InvalidOid, which may result in a runtime error
* if something at a higher query level wants to use the column's