forked from citusdata/pg_shard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pg_shard.c
2108 lines (1784 loc) · 61.8 KB
/
pg_shard.c
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
/*-------------------------------------------------------------------------
*
* pg_shard.c
*
* This file contains functions to perform distributed planning and execution of
* distributed tables.
*
* Copyright (c) 2014, Citus Data, Inc.
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "c.h"
#include "fmgr.h"
#include "funcapi.h"
#include "libpq-fe.h"
#include "miscadmin.h"
#include "postgres_ext.h"
#include "pg_shard.h"
#include "connection.h"
#include "create_shards.h"
#include "distribution_metadata.h"
#include "prune_shard_list.h"
#include "ruleutils.h"
#include <stddef.h>
#include <string.h>
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/htup.h"
#include "access/sdir.h"
#include "access/skey.h"
#include "access/tupdesc.h"
#include "access/xact.h"
#include "catalog/namespace.h"
#include "catalog/pg_class.h"
#include "catalog/pg_type.h"
#include "catalog/objectaddress.h"
#include "commands/extension.h"
#include "executor/execdesc.h"
#include "executor/executor.h"
#include "executor/instrument.h"
#include "executor/tuptable.h"
#include "nodes/execnodes.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/nodes.h"
#include "nodes/params.h"
#include "nodes/parsenodes.h"
#include "nodes/pg_list.h"
#include "nodes/plannodes.h"
#include "nodes/primnodes.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/planner.h"
#include "optimizer/var.h"
#include "parser/analyze.h"
#include "parser/parse_node.h"
#include "parser/parsetree.h"
#include "parser/parse_type.h"
#include "storage/lock.h"
#include "tcop/dest.h"
#include "tcop/tcopprot.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/elog.h"
#include "utils/errcodes.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/palloc.h"
#include "utils/rel.h"
#include "utils/relcache.h"
#include "utils/snapmgr.h"
#include "utils/tuplestore.h"
/* controls use of locks to enforce safe commutativity */
bool AllModificationsCommutative = false;
/* informs pg_shard to use the CitusDB planner */
bool UseCitusDBSelectLogic = false;
/* logs each statement used in a distributed plan */
bool LogDistributedStatements = false;
/* planner functions forward declarations */
static PlannedStmt * PgShardPlanner(Query *parse, int cursorOptions,
ParamListInfo boundParams);
static PlannerType DeterminePlannerType(Query *query);
static void ErrorIfQueryNotSupported(Query *queryTree);
static Oid ExtractFirstDistributedTableId(Query *query);
static bool ExtractRangeTableEntryWalker(Node *node, List **rangeTableList);
static List * DistributedQueryShardList(Query *query);
static bool SelectFromMultipleShards(Query *query, List *queryShardList);
static void ClassifyRestrictions(List *queryRestrictList, List **remoteRestrictList,
List **localRestrictList);
static Query * RowAndColumnFilterQuery(Query *query, List *remoteRestrictList,
List *localRestrictList);
static Query * BuildLocalQuery(Query *query, List *localRestrictList);
static PlannedStmt * PlanSequentialScan(Query *query, int cursorOptions,
ParamListInfo boundParams);
static List * QueryRestrictList(Query *query);
static Const * ExtractPartitionValue(Query *query, Var *partitionColumn);
static bool ExtractFromExpressionWalker(Node *node, List **qualifierList);
static List * QueryFromList(List *rangeTableList);
static List * TargetEntryList(List *expressionList);
static CreateStmt * CreateTemporaryTableLikeStmt(Oid sourceRelationId);
static DistributedPlan * BuildDistributedPlan(Query *query, List *shardIntervalList);
/* executor functions forward declarations */
static void PgShardExecutorStart(QueryDesc *queryDesc, int eflags);
static bool IsPgShardPlan(PlannedStmt *plannedStmt);
static void NextExecutorStartHook(QueryDesc *queryDesc, int eflags);
static LOCKMODE CommutativityRuleToLockMode(CmdType commandType);
static void AcquireExecutorShardLocks(List *taskList, LOCKMODE lockMode);
static int CompareTasksByShardId(const void *leftElement, const void *rightElement);
static void ExecuteMultipleShardSelect(DistributedPlan *distributedPlan,
RangeVar *intermediateTable);
static bool ExecuteTaskAndStoreResults(Task *task, TupleDesc tupleDescriptor,
Tuplestorestate *tupleStore);
static bool SendQueryInSingleRowMode(PGconn *connection, StringInfo query);
static bool StoreQueryResult(PGconn *connection, TupleDesc tupleDescriptor,
Tuplestorestate *tupleStore);
static void TupleStoreToTable(RangeVar *tableRangeVar, List *remoteTargetList,
TupleDesc storeTupleDescriptor, Tuplestorestate *store);
static void PgShardExecutorRun(QueryDesc *queryDesc, ScanDirection direction, long count);
static int32 ExecuteDistributedModify(DistributedPlan *distributedPlan);
static void ExecuteSingleShardSelect(DistributedPlan *distributedPlan,
EState *executorState, TupleDesc tupleDescriptor,
DestReceiver *destination);
static void PgShardExecutorFinish(QueryDesc *queryDesc);
static void PgShardExecutorEnd(QueryDesc *queryDesc);
static void PgShardProcessUtility(Node *parsetree, const char *queryString,
ProcessUtilityContext context, ParamListInfo params,
DestReceiver *dest, char *completionTag);
static void ErrorOnDropIfDistributedTablesExist(DropStmt *dropStatement);
/* declarations for dynamic loading */
PG_MODULE_MAGIC;
/* saved hook values in case of unload */
static planner_hook_type PreviousPlannerHook = NULL;
static ExecutorStart_hook_type PreviousExecutorStartHook = NULL;
static ExecutorRun_hook_type PreviousExecutorRunHook = NULL;
static ExecutorFinish_hook_type PreviousExecutorFinishHook = NULL;
static ExecutorEnd_hook_type PreviousExecutorEndHook = NULL;
static ProcessUtility_hook_type PreviousProcessUtilityHook = NULL;
/*
* _PG_init is called when the module is loaded. In this function we save the
* previous utility hook, and then install our hook to pre-intercept calls to
* the copy command.
*/
void
_PG_init(void)
{
PreviousPlannerHook = planner_hook;
planner_hook = PgShardPlanner;
PreviousExecutorStartHook = ExecutorStart_hook;
ExecutorStart_hook = PgShardExecutorStart;
PreviousExecutorRunHook = ExecutorRun_hook;
ExecutorRun_hook = PgShardExecutorRun;
PreviousExecutorFinishHook = ExecutorFinish_hook;
ExecutorFinish_hook = PgShardExecutorFinish;
PreviousExecutorEndHook = ExecutorEnd_hook;
ExecutorEnd_hook = PgShardExecutorEnd;
PreviousProcessUtilityHook = ProcessUtility_hook;
ProcessUtility_hook = PgShardProcessUtility;
DefineCustomBoolVariable("pg_shard.all_modifications_commutative",
"Bypasses commutativity checks when enabled", NULL,
&AllModificationsCommutative, false, PGC_USERSET, 0, NULL,
NULL, NULL);
DefineCustomBoolVariable("pg_shard.use_citusdb_select_logic",
"Informs pg_shard to use CitusDB's select logic", NULL,
&UseCitusDBSelectLogic, false, PGC_USERSET, 0, NULL,
NULL, NULL);
DefineCustomBoolVariable("pg_shard.log_distributed_statements",
"Logs each statement used in a distributed plan", NULL,
&LogDistributedStatements, false, PGC_USERSET, 0, NULL,
NULL, NULL);
EmitWarningsOnPlaceholders("pg_shard");
}
/*
* _PG_fini is called when the module is unloaded. This function uninstalls the
* extension's hooks.
*/
void
_PG_fini(void)
{
ProcessUtility_hook = PreviousProcessUtilityHook;
ExecutorRun_hook = PreviousExecutorRunHook;
ExecutorStart_hook = PreviousExecutorStartHook;
ExecutorFinish_hook = PreviousExecutorFinishHook;
ExecutorEnd_hook = PreviousExecutorEndHook;
planner_hook = PreviousPlannerHook;
}
/*
* PgShardPlanner implements custom planner logic to plan queries involving
* distributed tables. It first calls the standard planner to perform common
* mutations and normalizations on the query and retrieve the "normal" planned
* statement for the query. Further functions actually produce the distributed
* plan should one be necessary.
*/
static PlannedStmt *
PgShardPlanner(Query *query, int cursorOptions, ParamListInfo boundParams)
{
PlannedStmt *plannedStatement = NULL;
PlannerType plannerType = DeterminePlannerType(query);
if (plannerType == PLANNER_TYPE_PG_SHARD)
{
DistributedPlan *distributedPlan = NULL;
Query *distributedQuery = copyObject(query);
List *queryShardList = NIL;
bool selectFromMultipleShards = false;
CreateStmt *createTemporaryTableStmt = NULL;
/* call standard planner first to have Query transformations performed */
plannedStatement = standard_planner(distributedQuery, cursorOptions,
boundParams);
ErrorIfQueryNotSupported(distributedQuery);
/*
* Compute the list of shards this query needs to access.
* Error out if there are no existing shards for the table.
*/
queryShardList = DistributedQueryShardList(distributedQuery);
/*
* If a select query touches multiple shards, we don't push down the
* query as-is, and instead only push down the filter clauses and select
* needed columns. We then copy those results to a local temporary table
* and then modify the original PostgreSQL plan to perform a sequential
* scan on that temporary table.
* XXX: This approach is limited as we cannot handle index or foreign
* scans. We will revisit this by potentially using another type of scan
* node instead of a sequential scan.
*/
selectFromMultipleShards = SelectFromMultipleShards(query, queryShardList);
if (selectFromMultipleShards)
{
Oid distributedTableId = InvalidOid;
Query *localQuery = NULL;
List *queryRestrictList = QueryRestrictList(distributedQuery);
List *remoteRestrictList = NIL;
List *localRestrictList = NIL;
/* partition restrictions into remote and local lists */
ClassifyRestrictions(queryRestrictList, &remoteRestrictList,
&localRestrictList);
/* build local and distributed query */
distributedQuery = RowAndColumnFilterQuery(distributedQuery,
remoteRestrictList,
localRestrictList);
localQuery = BuildLocalQuery(query, localRestrictList);
/*
* Force a sequential scan as we change the underlying table to
* point to our intermediate temporary table which contains the
* fetched data.
*/
plannedStatement = PlanSequentialScan(localQuery, cursorOptions, boundParams);
/* construct a CreateStmt to clone the existing table */
distributedTableId = ExtractFirstDistributedTableId(distributedQuery);
createTemporaryTableStmt = CreateTemporaryTableLikeStmt(distributedTableId);
}
distributedPlan = BuildDistributedPlan(distributedQuery, queryShardList);
distributedPlan->originalPlan = plannedStatement->planTree;
distributedPlan->selectFromMultipleShards = selectFromMultipleShards;
distributedPlan->createTemporaryTableStmt = createTemporaryTableStmt;
plannedStatement->planTree = (Plan *) distributedPlan;
}
else if (plannerType == PLANNER_TYPE_CITUSDB)
{
if (PreviousPlannerHook == NULL)
{
ereport(ERROR, (errmsg("could not plan SELECT query"),
errdetail("Configured to use CitusDB's SELECT "
"logic, but CitusDB is not installed."),
errhint("Install CitusDB or set the "
"\"use_citusdb_select_logic\" "
"configuration parameter to \"false\".")));
}
plannedStatement = PreviousPlannerHook(query, cursorOptions, boundParams);
}
else if (plannerType == PLANNER_TYPE_POSTGRES)
{
if (PreviousPlannerHook != NULL)
{
plannedStatement = PreviousPlannerHook(query, cursorOptions, boundParams);
}
else
{
plannedStatement = standard_planner(query, cursorOptions, boundParams);
}
}
else
{
ereport(ERROR, (errmsg("unknown planner type: %d", plannerType)));
}
return plannedStatement;
}
/*
* DeterminePlannerType chooses the appropriate planner to use in order to plan
* the given query.
*/
static PlannerType
DeterminePlannerType(Query *query)
{
PlannerType plannerType = PLANNER_INVALID_FIRST;
CmdType commandType = query->commandType;
/* if the extension isn't created, we always use the postgres planner */
bool missingOK = true;
Oid extensionOid = get_extension_oid(PG_SHARD_EXTENSION_NAME, missingOK);
if (extensionOid == InvalidOid)
{
return PLANNER_TYPE_POSTGRES;
}
if (commandType == CMD_SELECT && UseCitusDBSelectLogic)
{
plannerType = PLANNER_TYPE_CITUSDB;
}
else if (commandType == CMD_SELECT || commandType == CMD_INSERT ||
commandType == CMD_UPDATE || commandType == CMD_DELETE)
{
Oid distributedTableId = ExtractFirstDistributedTableId(query);
if (OidIsValid(distributedTableId))
{
plannerType = PLANNER_TYPE_PG_SHARD;
}
else
{
plannerType = PLANNER_TYPE_POSTGRES;
}
}
else
{
/*
* For utility statements, we need to detect if they are operating on
* distributed tables. If they are, we need to warn or error out
* accordingly.
*/
plannerType = PLANNER_TYPE_POSTGRES;
}
return plannerType;
}
/*
* ErrorIfQueryNotSupported checks if the query contains unsupported features,
* and errors out if it does.
*/
static void
ErrorIfQueryNotSupported(Query *queryTree)
{
Oid distributedTableId = ExtractFirstDistributedTableId(queryTree);
Var *partitionColumn = PartitionColumn(distributedTableId);
List *rangeTableList = NIL;
ListCell *rangeTableCell = NULL;
bool hasValuesScan = false;
uint32 queryTableCount = 0;
bool hasNonConstTargetEntryExprs = false;
bool specifiesPartitionValue = false;
CmdType commandType = queryTree->commandType;
Assert(commandType == CMD_SELECT || commandType == CMD_INSERT ||
commandType == CMD_UPDATE || commandType == CMD_DELETE);
/* prevent utility statements like DECLARE CURSOR attached to selects */
if (commandType == CMD_SELECT && queryTree->utilityStmt != NULL)
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("unsupported utility statement")));
}
/*
* Reject subqueries which are in SELECT or WHERE clause.
* Queries which include subqueries in FROM clauses are rejected below.
*/
if (queryTree->hasSubLinks == true)
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot perform distributed planning for the given"
" query"),
errdetail("Subqueries are not supported in distributed"
" queries.")));
}
/* reject queries which include CommonTableExpr */
if (queryTree->cteList != NIL)
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot perform distributed planning for the given"
" query"),
errdetail("Common table expressions are not supported in"
" distributed queries.")));
}
/* extract range table entries */
ExtractRangeTableEntryWalker((Node *) queryTree, &rangeTableList);
foreach(rangeTableCell, rangeTableList)
{
RangeTblEntry *rangeTableEntry = (RangeTblEntry *) lfirst(rangeTableCell);
if (rangeTableEntry->rtekind == RTE_RELATION)
{
queryTableCount++;
}
else if (rangeTableEntry->rtekind == RTE_VALUES)
{
hasValuesScan = true;
}
else
{
/*
* Error out for rangeTableEntries that we do not support.
* We do not explicitly specify "in FROM clause" in the error detail
* for the features that we do not support at all (SUBQUERY, JOIN).
* We do not need to check for RTE_CTE because all common table expressions
* are rejected above with queryTree->cteList check.
*/
char *rangeTableEntryErrorDetail = NULL;
if (rangeTableEntry->rtekind == RTE_SUBQUERY)
{
rangeTableEntryErrorDetail = "Subqueries are not supported in"
" distributed queries.";
}
else if (rangeTableEntry->rtekind == RTE_JOIN)
{
rangeTableEntryErrorDetail = "Joins are not supported in distributed"
" queries.";
}
else if (rangeTableEntry->rtekind == RTE_FUNCTION)
{
rangeTableEntryErrorDetail = "Functions must not appear in the FROM"
" clause of a distributed query.";
}
else
{
rangeTableEntryErrorDetail = "Unrecognized range table entry.";
}
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot perform distributed planning for the given"
" query"),
errdetail("%s", rangeTableEntryErrorDetail)));
}
}
/* reject queries which involve joins */
if (queryTableCount != 1)
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot perform distributed planning for the given"
" query"),
errdetail("Joins are not supported in distributed queries.")));
}
/* reject queries which involve multi-row inserts */
if (hasValuesScan)
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("multi-row INSERTs to distributed tables "
"are not supported")));
}
/* reject queries with a returning list */
if (list_length(queryTree->returningList) > 0)
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot plan sharded modification that uses a "
"RETURNING clause")));
}
if (commandType == CMD_INSERT || commandType == CMD_UPDATE ||
commandType == CMD_DELETE)
{
ListCell *targetEntryCell = NULL;
foreach(targetEntryCell, queryTree->targetList)
{
TargetEntry *targetEntry = (TargetEntry *) lfirst(targetEntryCell);
/* skip resjunk entries: UPDATE adds some for ctid, etc. */
if (targetEntry->resjunk)
{
continue;
}
if (!IsA(targetEntry->expr, Const))
{
hasNonConstTargetEntryExprs = true;
}
if (targetEntry->resno == partitionColumn->varattno)
{
specifiesPartitionValue = true;
}
}
}
if (hasNonConstTargetEntryExprs)
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot plan sharded modification containing values "
"which are not constants or constant expressions")));
}
if (specifiesPartitionValue && (commandType == CMD_UPDATE))
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("modifying the partition value of rows is not allowed")));
}
}
/*
* ExtractFirstDistributedTableId takes a given query, and finds the relationId
* for the first distributed table in that query. If the function cannot find a
* distributed table, it returns InvalidOid.
*/
static Oid
ExtractFirstDistributedTableId(Query *query)
{
List *rangeTableList = NIL;
ListCell *rangeTableCell = NULL;
Oid distributedTableId = InvalidOid;
/* extract range table entries */
ExtractRangeTableEntryWalker((Node *) query, &rangeTableList);
foreach(rangeTableCell, rangeTableList)
{
RangeTblEntry *rangeTableEntry = (RangeTblEntry *) lfirst(rangeTableCell);
if (IsDistributedTable(rangeTableEntry->relid))
{
distributedTableId = rangeTableEntry->relid;
break;
}
}
return distributedTableId;
}
/*
* ExtractRangeTableEntryWalker walks over a query tree, and finds all range
* table entries. For recursing into the query tree, this function uses the
* query tree walker since the expression tree walker doesn't recurse into
* sub-queries.
*/
static bool
ExtractRangeTableEntryWalker(Node *node, List **rangeTableList)
{
bool walkIsComplete = false;
if (node == NULL)
{
return false;
}
if (IsA(node, RangeTblEntry))
{
RangeTblEntry *rangeTable = (RangeTblEntry *) node;
(*rangeTableList) = lappend(*rangeTableList, rangeTable);
}
else if (IsA(node, Query))
{
walkIsComplete = query_tree_walker((Query *) node, ExtractRangeTableEntryWalker,
rangeTableList, QTW_EXAMINE_RTES);
}
else
{
walkIsComplete = expression_tree_walker(node, ExtractRangeTableEntryWalker,
rangeTableList);
}
return walkIsComplete;
}
/*
* DistributedQueryShardList prunes the shards for the table in the query based
* on the query's restriction qualifiers, and returns this list. It is possible
* that all shards will be pruned if a query's restrictions are unsatisfiable.
* In that case, this function can return an empty list; however, if the table
* being queried has no shards created whatsoever, this function errors out.
*/
static List *
DistributedQueryShardList(Query *query)
{
List *restrictClauseList = NIL;
List *prunedShardList = NIL;
Oid distributedTableId = ExtractFirstDistributedTableId(query);
List *shardIntervalList = LookupShardIntervalList(distributedTableId);
/* error out if no shards exists for the table */
if (shardIntervalList == NIL)
{
char *relationName = get_rel_name(distributedTableId);
ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("could not find any shards for query"),
errdetail("No shards exist for distributed table \"%s\".",
relationName),
errhint("Run master_create_worker_shards to create shards "
"and try again.")));
}
restrictClauseList = QueryRestrictList(query);
prunedShardList = PruneShardList(distributedTableId, restrictClauseList,
shardIntervalList);
return prunedShardList;
}
/* Returns true if the query is a select query that reads data from multiple shards. */
static bool
SelectFromMultipleShards(Query *query, List *queryShardList)
{
if ((query->commandType == CMD_SELECT) && (list_length(queryShardList) > 1))
{
return true;
}
else
{
return false;
}
}
/*
* ClassifyRestrictions divides a query's restriction list in two: the subset
* of restrictions safe for remote evaluation and the subset of restrictions
* that must be evaluated locally. remoteRestrictList and localRestrictList are
* output parameters to receive these two subsets.
*
* Currently places all restrictions in the remote list and leaves the local
* one totally empty.
*/
static void
ClassifyRestrictions(List *queryRestrictList, List **remoteRestrictList,
List **localRestrictList)
{
ListCell *restrictCell = NULL;
*remoteRestrictList = NIL;
*localRestrictList = NIL;
foreach(restrictCell, queryRestrictList)
{
Node *restriction = (Node *) lfirst(restrictCell);
bool restrictionSafeToSend = true;
if (restrictionSafeToSend)
{
*remoteRestrictList = lappend(*remoteRestrictList, restriction);
}
else
{
*localRestrictList = lappend(*localRestrictList, restriction);
}
}
}
/*
* RowAndColumnFilterQuery builds a query which contains the filter clauses from
* the original query and also only selects columns needed for the original
* query. This new query can then be pushed down to the worker nodes.
*/
static Query *
RowAndColumnFilterQuery(Query *query, List *remoteRestrictList, List *localRestrictList)
{
Query *filterQuery = NULL;
List *rangeTableList = NIL;
List *whereColumnList = NIL;
List *projectColumnList = NIL;
List *havingClauseColumnList = NIL;
List *requiredColumnList = NIL;
ListCell *columnCell = NULL;
List *uniqueColumnList = NIL;
List *targetList = NIL;
FromExpr *fromExpr = NULL;
PVCAggregateBehavior aggregateBehavior = PVC_RECURSE_AGGREGATES;
PVCPlaceHolderBehavior placeHolderBehavior = PVC_REJECT_PLACEHOLDERS;
ExtractRangeTableEntryWalker((Node *) query, &rangeTableList);
Assert(list_length(rangeTableList) == 1);
/* build the expression to supply FROM/WHERE for the remote query */
fromExpr = makeNode(FromExpr);
fromExpr->quals = (Node *) make_ands_explicit((List *) remoteRestrictList);
fromExpr->fromlist = QueryFromList(rangeTableList);
/* must retrieve all columns referenced by local WHERE clauses... */
whereColumnList = pull_var_clause((Node *) localRestrictList, aggregateBehavior,
placeHolderBehavior);
/* as well as any used in projections (GROUP BY, etc.) */
projectColumnList = pull_var_clause((Node *) query->targetList, aggregateBehavior,
placeHolderBehavior);
/* finally, need those used in any HAVING quals */
havingClauseColumnList = pull_var_clause(query->havingQual, aggregateBehavior,
placeHolderBehavior);
/* put them together to get list of required columns for query */
requiredColumnList = list_concat(requiredColumnList, whereColumnList);
requiredColumnList = list_concat(requiredColumnList, projectColumnList);
requiredColumnList = list_concat(requiredColumnList, havingClauseColumnList);
/* ensure there are no duplicates in the list */
foreach(columnCell, requiredColumnList)
{
Var *column = (Var *) lfirst(columnCell);
uniqueColumnList = list_append_unique(uniqueColumnList, column);
}
/*
* If we still have no columns, possible in a query like "SELECT count(*)",
* add a NULL constant. This constant results in "SELECT NULL FROM ...".
* postgres_fdw generates a similar string when no columns are selected.
*/
if (uniqueColumnList == NIL)
{
/* values for NULL const taken from parse_node.c */
Const *nullConst = makeConst(UNKNOWNOID, -1, InvalidOid, -2,
(Datum) 0, true, false);
uniqueColumnList = lappend(uniqueColumnList, nullConst);
}
targetList = TargetEntryList(uniqueColumnList);
filterQuery = makeNode(Query);
filterQuery->commandType = CMD_SELECT;
filterQuery->rtable = rangeTableList;
filterQuery->jointree = fromExpr;
filterQuery->targetList = targetList;
return filterQuery;
}
/*
* BuildLocalQuery returns a copy of query with its quals replaced by those
* in localRestrictList. Expects queries with a single entry in their FROM
* list.
*/
static Query *
BuildLocalQuery(Query *query, List *localRestrictList)
{
Query *localQuery = copyObject(query);
FromExpr *joinTree = localQuery->jointree;
Assert(joinTree != NULL);
Assert(list_length(joinTree->fromlist) == 1);
joinTree->quals = (Node *) make_ands_explicit((List *) localRestrictList);
return localQuery;
}
/*
* PlanSequentialScan attempts to plan the given query using only a sequential
* scan of the underlying table. The function disables index scan types and
* plans the query. If the plan still contains a non-sequential scan plan node,
* the function errors out. Note this function modifies the query parameter, so
* make a copy before calling PlanSequentialScan if that is unacceptable.
*/
static PlannedStmt *
PlanSequentialScan(Query *query, int cursorOptions, ParamListInfo boundParams)
{
PlannedStmt *sequentialScanPlan = NULL;
bool indexScanEnabledOldValue = false;
bool bitmapScanEnabledOldValue = false;
List *rangeTableList = NIL;
ListCell *rangeTableCell = NULL;
/* error out if the table is a foreign table */
ExtractRangeTableEntryWalker((Node *) query, &rangeTableList);
foreach(rangeTableCell, rangeTableList)
{
RangeTblEntry *rangeTableEntry = (RangeTblEntry *) lfirst(rangeTableCell);
if (rangeTableEntry->rtekind == RTE_RELATION)
{
if (rangeTableEntry->relkind == RELKIND_FOREIGN_TABLE)
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("select from multiple shards is unsupported "
"for foreign tables")));
}
}
}
/* disable index scan types */
indexScanEnabledOldValue = enable_indexscan;
bitmapScanEnabledOldValue = enable_bitmapscan;
enable_indexscan = false;
enable_bitmapscan = false;
sequentialScanPlan = standard_planner(query, cursorOptions, boundParams);
enable_indexscan = indexScanEnabledOldValue;
enable_bitmapscan = bitmapScanEnabledOldValue;
return sequentialScanPlan;
}
/*
* QueryRestrictList returns the restriction clauses for the query. For a SELECT
* statement these are the where-clause expressions. For INSERT statements we
* build an equality clause based on the partition-column and its supplied
* insert value.
*/
static List *
QueryRestrictList(Query *query)
{
List *queryRestrictList = NIL;
CmdType commandType = query->commandType;
if (commandType == CMD_INSERT)
{
/* build equality expression based on partition column value for row */
Oid distributedTableId = ExtractFirstDistributedTableId(query);
Var *partitionColumn = PartitionColumn(distributedTableId);
Const *partitionValue = ExtractPartitionValue(query, partitionColumn);
OpExpr *equalityExpr = MakeOpExpression(partitionColumn, BTEqualStrategyNumber);
Node *rightOp = get_rightop((Expr *) equalityExpr);
Const *rightConst = (Const *) rightOp;
Assert(IsA(rightOp, Const));
rightConst->constvalue = partitionValue->constvalue;
rightConst->constisnull = partitionValue->constisnull;
rightConst->constbyval = partitionValue->constbyval;
queryRestrictList = list_make1(equalityExpr);
}
else if (commandType == CMD_SELECT || commandType == CMD_UPDATE ||
commandType == CMD_DELETE)
{
query_tree_walker(query, ExtractFromExpressionWalker, &queryRestrictList, 0);
}
return queryRestrictList;
}
/*
* ExtractPartitionValue extracts the partition column value from a the target
* of a modification command. If a partition value is not a constant, is NULL,
* or is missing altogether, this function throws an error.
*/
static Const *
ExtractPartitionValue(Query *query, Var *partitionColumn)
{
Const *partitionValue = NULL;
TargetEntry *targetEntry = get_tle_by_resno(query->targetList,
partitionColumn->varattno);
if (targetEntry != NULL)
{
if (!IsA(targetEntry->expr, Const))
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot plan INSERT to a distributed table "
"using a non-constant partition column value")));
}
partitionValue = (Const *) targetEntry->expr;
}
if (partitionValue == NULL || partitionValue->constisnull)
{
ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("cannot plan INSERT using row with NULL value "
"in partition column")));
}
return partitionValue;
}
/*
* ExtractFromExpressionWalker walks over a FROM expression, and finds all
* explicit qualifiers in the expression.
*/
static bool
ExtractFromExpressionWalker(Node *node, List **qualifierList)
{
bool walkIsComplete = false;
if (node == NULL)
{
return false;
}
if (IsA(node, FromExpr))
{
FromExpr *fromExpression = (FromExpr *) node;
List *fromQualifierList = (List *) fromExpression->quals;
(*qualifierList) = list_concat(*qualifierList, fromQualifierList);
}
walkIsComplete = expression_tree_walker(node, ExtractFromExpressionWalker,
(void *) qualifierList);
return walkIsComplete;
}
/*
* QueryFromList creates the from list construct that is used for building the
* query's join tree. The function creates the from list by making a range table
* reference for each entry in the given range table list.
*/
static List *
QueryFromList(List *rangeTableList)
{
List *fromList = NIL;
Index rangeTableIndex = 1;
uint32 rangeTableCount = (uint32) list_length(rangeTableList);
for (rangeTableIndex = 1; rangeTableIndex <= rangeTableCount; rangeTableIndex++)
{
RangeTblRef *rangeTableReference = makeNode(RangeTblRef);
rangeTableReference->rtindex = rangeTableIndex;
fromList = lappend(fromList, rangeTableReference);
}
return fromList;
}
/*
* TargetEntryList creates a target entry for each expression in the given list,
* and returns the newly created target entries in a list.
*/
static List *
TargetEntryList(List *expressionList)
{
List *targetEntryList = NIL;
ListCell *expressionCell = NULL;
foreach(expressionCell, expressionList)
{
Expr *expression = (Expr *) lfirst(expressionCell);
TargetEntry *targetEntry = makeTargetEntry(expression, -1, NULL, false);
targetEntryList = lappend(targetEntryList, targetEntry);
}
return targetEntryList;
}
/*
* CreateTemporaryTableLikeStmt returns a CreateStmt node which will create a
* clone of the given relation using the CREATE TEMPORARY TABLE LIKE option.
* Note that the function only creates the table, and doesn't copy over indexes,