-
Notifications
You must be signed in to change notification settings - Fork 39
/
sqlite_fdw.c
5717 lines (5050 loc) · 165 KB
/
sqlite_fdw.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
/*-------------------------------------------------------------------------
*
* SQLite Foreign Data Wrapper for PostgreSQL
*
* Portions Copyright (c) 2018, TOSHIBA CORPORATION
*
* IDENTIFICATION
* sqlite_fdw.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "sqlite_fdw.h"
#include <sqlite3.h>
#include "catalog/pg_collation.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#if (PG_VERSION_NUM < 140000)
#include "optimizer/clauses.h"
#endif
#include "optimizer/pathnode.h"
#if PG_VERSION_NUM >= 120000
#include "optimizer/appendinfo.h"
#endif
#include "optimizer/planmain.h"
#include "optimizer/planner.h"
#include "optimizer/cost.h"
#if (PG_VERSION_NUM >= 130010 && PG_VERSION_NUM < 140000) || \
(PG_VERSION_NUM >= 140007 && PG_VERSION_NUM < 150000) || \
(PG_VERSION_NUM >= 150002)
#include "optimizer/inherit.h"
#endif
#include "optimizer/paths.h"
#include "optimizer/prep.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/tlist.h"
#include "parser/parsetree.h"
#include "parser/parse_type.h"
#include "storage/ipc.h"
#include "utils/builtins.h"
#include "utils/formatting.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/selfuncs.h"
extern PGDLLEXPORT void _PG_init(void);
static void sqlite_fdw_exit(int code, Datum arg);
PG_MODULE_MAGIC;
/* The number of default estimated rows for table which does not exist in sqlite1_stat1
* See sqlite3ResultSetOfSelect in select.c of SQLite
*/
#define DEFAULT_ROW_ESTIMATE 1000000
#define DEFAULTE_NUM_ROWS 1000
#define IS_KEY_COLUMN(A) ((strcmp(A->defname, "key") == 0) && \
(strcmp(strVal(A->arg), "true") == 0))
/* Default CPU cost to start up a foreign query. */
#define DEFAULT_FDW_STARTUP_COST 100.0
/* Default CPU cost to process 1 row (above and beyond cpu_tuple_cost). */
#if PG_VERSION_NUM >= 170000
#define DEFAULT_FDW_TUPLE_COST 0.2
#else
#define DEFAULT_FDW_TUPLE_COST 0.01
#endif
/* If no remote estimates, assume a sort costs 20% extra */
#define DEFAULT_FDW_SORT_MULTIPLIER 1.2
/*
* This enum describes what's kept in the fdw_private list for a ForeignPath.
* We store:
*
* 1) Boolean flag showing if the remote query has the final sort
* 2) Boolean flag showing if the remote query has the LIMIT clause
*/
enum FdwPathPrivateIndex
{
/* has-final-sort flag (as an integer Value node) */
FdwPathPrivateHasFinalSort,
/* has-limit flag (as an integer Value node) */
FdwPathPrivateHasLimit,
};
/*
* Indexes of FDW-private information stored in fdw_private lists.
*
* These items are indexed with the enum FdwScanPrivateIndex, so an item
* can be fetched with list_nth(). For example, to get the SELECT statement:
* sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
*/
enum FdwScanPrivateIndex
{
/* SQL statement to execute remotely (as a String node) */
FdwScanPrivateSelectSql,
/* Integer list of attribute numbers retrieved by the SELECT */
FdwScanPrivateRetrievedAttrs,
/* Integer representing UPDATE/DELETE target */
FdwScanPrivateForUpdate,
#if (PG_VERSION_NUM < 100000)
/* rtindex */
FdwScanPrivateRtIndex,
#endif
/*
* String describing join i.e. names of relations being joined and types
* of join, added when the scan is join
*/
FdwScanPrivateRelations,
};
/*
* Similarly, this enum describes what's kept in the fdw_private list for
* a ModifyTable node referencing a sqlite_fdw foreign table. We store:
*
* 1) INSERT/UPDATE/DELETE statement text to be sent to the remote server
* 2) Integer list of target attribute numbers for INSERT/UPDATE
* (NIL for a DELETE)
* 3) Length till the end of VALUES clause for INSERT
* (-1 for a DELETE/UPDATE)
*/
enum FdwModifyPrivateIndex
{
/* SQL statement to execute remotely (as a String node) */
FdwModifyPrivateUpdateSql,
/* Integer list of target attribute numbers for INSERT/UPDATE */
FdwModifyPrivateTargetAttnums,
/* Length till the end of VALUES clause (as an Integer node) */
FdwModifyPrivateLen,
};
/*
* Similarly, this enum describes what's kept in the fdw_private list for
* a ForeignScan node that modifies a foreign table directly. We store:
*
* 1) UPDATE/DELETE statement text to be sent to the remote server
* 2) Boolean flag showing if the remote query has a RETURNING clause
* 3) Integer list of attribute numbers retrieved by RETURNING, if any
* 4) Boolean flag showing if we set the command es_processed
*/
enum FdwDirectModifyPrivateIndex
{
/* SQL statement to execute remotely (as a String node) */
FdwDirectModifyPrivateUpdateSql,
/* has-returning flag (as a Boolean node) */
FdwDirectModifyPrivateHasReturning,
/* Integer list of attribute numbers retrieved by RETURNING */
FdwDirectModifyPrivateRetrievedAttrs,
/* set-processed flag (as a Boolean node) */
FdwDirectModifyPrivateSetProcessed,
};
extern PGDLLEXPORT Datum sqlite_fdw_handler(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(sqlite_fdw_handler);
PG_FUNCTION_INFO_V1(sqlite_fdw_version);
static void sqliteGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
static void sqliteGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
static ForeignScan *sqliteGetForeignPlan(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses,
Plan *outer_plan);
static void sqliteBeginForeignScan(ForeignScanState *node,
int eflags);
static TupleTableSlot *sqliteIterateForeignScan(ForeignScanState *node);
static void sqliteReScanForeignScan(ForeignScanState *node);
static void sqliteEndForeignScan(ForeignScanState *node);
static void sqliteAddForeignUpdateTargets(
#if (PG_VERSION_NUM >= 140000)
PlannerInfo *root,
Index rtindex,
#else
Query *parsetree,
#endif
RangeTblEntry *target_rte,
Relation target_relation);
static List *sqlitePlanForeignModify(PlannerInfo *root,
ModifyTable *plan,
Index resultRelation,
int subplan_index);
static void sqliteBeginForeignModify(ModifyTableState *mtstate,
ResultRelInfo *rinfo,
List *fdw_private,
int subplan_index,
int eflags);
static TupleTableSlot *sqliteExecForeignInsert(EState *estate,
ResultRelInfo *rinfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
#if PG_VERSION_NUM >= 140000
static TupleTableSlot **sqliteExecForeignBatchInsert(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot **slots,
TupleTableSlot **planSlots,
int *numSlots);
static int sqliteGetForeignModifyBatchSize(ResultRelInfo *resultRelInfo);
#endif
static TupleTableSlot *sqliteExecForeignUpdate(EState *estate,
ResultRelInfo *rinfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static TupleTableSlot *sqliteExecForeignDelete(EState *estate,
ResultRelInfo *rinfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static void sqliteEndForeignModify(EState *estate,
ResultRelInfo *rinfo);
#if (PG_VERSION_NUM >= 110000)
static void sqliteEndForeignInsert(EState *estate,
ResultRelInfo *resultRelInfo);
static void sqliteBeginForeignInsert(ModifyTableState *mtstate,
ResultRelInfo *resultRelInfo);
#endif
static void sqliteExplainForeignScan(ForeignScanState *node,
struct ExplainState *es);
static void sqliteExplainForeignModify(ModifyTableState *mtstate,
ResultRelInfo *rinfo,
List *fdw_private,
int subplan_index,
struct ExplainState *es);
static bool sqlitePlanDirectModify(PlannerInfo *root,
ModifyTable *plan,
Index resultRelation,
int subplan_index);
static void sqliteBeginDirectModify(ForeignScanState *node, int eflags);
static TupleTableSlot *sqliteIterateDirectModify(ForeignScanState *node);
static void sqliteEndDirectModify(ForeignScanState *node);
static void sqliteExplainDirectModify(ForeignScanState *node,
struct ExplainState *es);
#if PG_VERSION_NUM >= 140000
static void sqliteExecForeignTruncate(List *rels,
DropBehavior behavior,
bool restart_seqs);
#endif
static bool sqliteAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
static int sqliteIsForeignRelUpdatable(Relation rel);
static List *sqliteImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void sqliteGetForeignJoinPaths(PlannerInfo *root,
RelOptInfo *joinrel,
RelOptInfo *outerrel,
RelOptInfo *innerrel,
JoinType jointype,
JoinPathExtraData *extra);
static void
sqliteGetForeignUpperPaths(PlannerInfo *root,
UpperRelationKind stage,
RelOptInfo *input_rel,
RelOptInfo *output_rel
#if (PG_VERSION_NUM >= 110000)
,void *extra
#endif
);
static void sqlite_prepare_wrapper(ForeignServer *server,
sqlite3 * db, char *query,
sqlite3_stmt * *result,
const char **pzTail,
bool is_cache);
static void sqlite_to_pg_type(StringInfo str, char *typname);
static TupleTableSlot **sqlite_execute_insert(EState *estate,
ResultRelInfo *resultRelInfo,
CmdType operation,
TupleTableSlot **slots,
TupleTableSlot **planSlots,
int *numSlots);
static void sqlite_prepare_query_params(PlanState *node,
List *fdw_exprs,
int numParams,
FmgrInfo **param_flinfo,
List **param_exprs,
const char ***param_values,
Oid **param_types);
static void sqlite_process_query_params(ExprContext *econtext,
FmgrInfo *param_flinfo,
List *param_exprs,
const char **param_values,
sqlite3_stmt * *stmt,
Oid *param_types,
Oid foreignTableId);
static void sqlite_create_cursor(ForeignScanState *node);
static void sqlite_execute_dml_stmt(ForeignScanState *node);
static void sqlite_merge_fdw_options(SqliteFdwRelationInfo * fpinfo,
const SqliteFdwRelationInfo * fpinfo_o,
const SqliteFdwRelationInfo * fpinfo_i);
static bool sqlite_foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel);
static void sqlite_add_foreign_grouping_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *grouped_rel
#if (PG_VERSION_NUM >= 110000)
,GroupPathExtraData *extra
#endif
);
static void sqlite_add_foreign_ordered_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *ordered_rel);
static void sqlite_add_foreign_final_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *final_rel
#if (PG_VERSION_NUM >= 120000)
,FinalPathExtraData *extra
#endif
);
static void sqlite_estimate_path_cost_size(PlannerInfo *root,
RelOptInfo *foreignrel,
List *param_join_conds,
List *pathkeys,
SqliteFdwPathExtraData * fpextra,
double *p_rows, int *p_width,
Cost *p_startup_cost, Cost *p_total_cost);
static bool sqlite_foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel,
JoinType jointype, RelOptInfo *outerrel, RelOptInfo *innerrel,
JoinPathExtraData *extra);
#if PG_VERSION_NUM >= 170000
static bool sqlite_semijoin_target_ok(PlannerInfo *root,
RelOptInfo *joinrel,
RelOptInfo *outerrel,
RelOptInfo *innerrel);
#endif
static void sqlite_adjust_foreign_grouping_path_cost(PlannerInfo *root,
List *pathkeys,
double retrieved_rows,
double width,
double limit_tuples,
Cost *p_startup_cost,
Cost *p_run_cost);
static bool sqlite_all_baserels_are_foreign(PlannerInfo *root);
static void sqlite_add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel, List *fdw_private,
Path *epq_path
#if PG_VERSION_NUM >= 170000
, List *restrictlist
#endif
);
static List *sqlite_get_useful_pathkeys_for_relation(PlannerInfo *root,
RelOptInfo *rel);
#if PG_VERSION_NUM >= 140000
static int sqlite_get_batch_size_option(Relation rel);
#endif
static void conversion_error_callback(void *arg);
static int32 sqlite_affinity_eqv_to_pgtype(Oid type);
const char* sqlite_datatype(int t);
static const char *azType[] = { "?", "integer", "real", "text", "blob", "null" };
/*
* Identify the attribute where data conversion fails.
*/
typedef struct ConversionLocation
{
AttrNumber cur_attno; /* attribute number being processed, or 0 */
Relation rel; /* foreign table being processed, or NULL */
ForeignScanState *fsstate; /* plan node being processed, or NULL */
Form_pg_attribute att; /* PostgreSQL relation attribute */
sqlite3_value *val; /* abstract SQLite value to get affinity, length and text value */
} ConversionLocation;
/*
* Library load-time initialization, sets on_proc_exit() callback for
* backend shutdown.
*/
void
_PG_init(void)
{
on_proc_exit(&sqlite_fdw_exit, PointerGetDatum(NULL));
}
/*
* sqlite_fdw_exit: Exit callback function.
*/
static void
sqlite_fdw_exit(int code, Datum arg)
{
sqlite_cleanup_connection();
}
Datum
sqlite_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *fdwroutine = makeNode(FdwRoutine);
elog(DEBUG1, "sqlite_fdw : %s", __func__);
fdwroutine->GetForeignRelSize = sqliteGetForeignRelSize;
fdwroutine->GetForeignPaths = sqliteGetForeignPaths;
fdwroutine->GetForeignPlan = sqliteGetForeignPlan;
fdwroutine->BeginForeignScan = sqliteBeginForeignScan;
fdwroutine->IterateForeignScan = sqliteIterateForeignScan;
fdwroutine->ReScanForeignScan = sqliteReScanForeignScan;
fdwroutine->EndForeignScan = sqliteEndForeignScan;
fdwroutine->IsForeignRelUpdatable = sqliteIsForeignRelUpdatable;
fdwroutine->AddForeignUpdateTargets = sqliteAddForeignUpdateTargets;
fdwroutine->PlanForeignModify = sqlitePlanForeignModify;
fdwroutine->BeginForeignModify = sqliteBeginForeignModify;
fdwroutine->ExecForeignInsert = sqliteExecForeignInsert;
#if PG_VERSION_NUM >= 140000
fdwroutine->ExecForeignBatchInsert = sqliteExecForeignBatchInsert;
fdwroutine->GetForeignModifyBatchSize = sqliteGetForeignModifyBatchSize;
#endif
fdwroutine->ExecForeignUpdate = sqliteExecForeignUpdate;
fdwroutine->ExecForeignDelete = sqliteExecForeignDelete;
fdwroutine->EndForeignModify = sqliteEndForeignModify;
#if (PG_VERSION_NUM >= 110000)
fdwroutine->BeginForeignInsert = sqliteBeginForeignInsert;
fdwroutine->EndForeignInsert = sqliteEndForeignInsert;
#endif
/* Support functions for join push-down */
fdwroutine->GetForeignJoinPaths = sqliteGetForeignJoinPaths;
/* support for EXPLAIN */
fdwroutine->ExplainForeignScan = sqliteExplainForeignScan;
fdwroutine->ExplainForeignModify = sqliteExplainForeignModify;
fdwroutine->ExplainDirectModify = sqliteExplainDirectModify;
#if PG_VERSION_NUM >= 140000
/* Support function for TRUNCATE */
fdwroutine->ExecForeignTruncate = sqliteExecForeignTruncate;
#endif
/* suport for Direct Modification */
fdwroutine->PlanDirectModify = sqlitePlanDirectModify;
fdwroutine->BeginDirectModify = sqliteBeginDirectModify;
fdwroutine->IterateDirectModify = sqliteIterateDirectModify;
fdwroutine->EndDirectModify = sqliteEndDirectModify;
/* support for ANALYSE */
fdwroutine->AnalyzeForeignTable = sqliteAnalyzeForeignTable;
/* support for IMPORT FOREIGN SCHEMA */
fdwroutine->ImportForeignSchema = sqliteImportForeignSchema;
/* Support functions for upper relation push-down */
fdwroutine->GetForeignUpperPaths = sqliteGetForeignUpperPaths;
PG_RETURN_POINTER(fdwroutine);
}
Datum
sqlite_fdw_version(PG_FUNCTION_ARGS)
{
PG_RETURN_INT32(CODE_VERSION);
}
/* Wrapper for sqlite3_prepare */
static void
sqlite_prepare_wrapper(ForeignServer *server, sqlite3 * db, char *query, sqlite3_stmt * *stmt,
const char **pzTail, bool is_cache)
{
int rc;
elog(DEBUG1, "sqlite_fdw : %s %s\n", __func__, query);
rc = sqlite3_prepare_v2(db, query, -1, stmt, pzTail);
if (rc != SQLITE_OK)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("SQL error during prepare: %s %s", sqlite3_errmsg(db), query)
));
}
/* cache stmt to finalize at last */
if (is_cache)
sqlite_cache_stmt(server, stmt);
}
/*
* sqliteGetForeignRelSize: Create a FdwPlan for a scan on the foreign table
*/
static void
sqliteGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
{
SqliteFdwRelationInfo *fpinfo;
ListCell *lc;
elog(DEBUG1, "sqlite_fdw : %s", __func__);
fpinfo = (SqliteFdwRelationInfo *) palloc0(sizeof(SqliteFdwRelationInfo));
baserel->fdw_private = (void *) fpinfo;
/* Base foreign tables need to be pushed down always. */
fpinfo->pushdown_safe = true;
/* Look up foreign-table catalog info. */
fpinfo->table = GetForeignTable(foreigntableid);
fpinfo->server = GetForeignServer(fpinfo->table->serverid);
/*
* Extract user-settable option values.
*/
fpinfo->fdw_startup_cost = DEFAULT_FDW_STARTUP_COST;
fpinfo->fdw_tuple_cost = DEFAULT_FDW_TUPLE_COST;
/*
* Identify which baserestrictinfo clauses can be sent to the remote
* server and which can't.
*/
sqlite_classify_conditions(root, baserel, baserel->baserestrictinfo,
&fpinfo->remote_conds, &fpinfo->local_conds);
/*
* Identify which attributes will need to be retrieved from the remote
* server.
*/
fpinfo->attrs_used = NULL;
#if PG_VERSION_NUM >= 90600
pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid, &fpinfo->attrs_used);
#else
pull_varattnos((Node *) baserel->reltargetlist, baserel->relid, &fpinfo->attrs_used);
#endif
foreach(lc, fpinfo->local_conds)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
pull_varattnos((Node *) rinfo->clause, baserel->relid, &fpinfo->attrs_used);
}
/*
* Compute the selectivity and cost of the local_conds, so we don't have
* to do it over again for each path. The best we can do for these
* conditions is to estimate selectivity on the basis of local statistics.
*/
fpinfo->local_conds_sel = clauselist_selectivity(root,
fpinfo->local_conds,
baserel->relid,
JOIN_INNER,
NULL);
cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root);
/*
* Set # of retrieved rows and cached relation costs to some negative
* value, so that we can detect when they are set to some sensible values,
* during one (usually the first) of the calls to
* sqlite_estimate_path_cost_size.
*/
fpinfo->retrieved_rows = -1;
fpinfo->rel_startup_cost = -1;
fpinfo->rel_total_cost = -1;
/*
* If the foreign table has never been ANALYZEd, it will have relpages
* and reltuples equal to zero, which most likely has nothing to do
* with reality. We can't do a whole lot about that if we're not
* allowed to consult the remote server, but we can use a hack similar
* to plancat.c's treatment of empty relations: use a minimum size
* estimate of 10 pages, and divide by the column-datatype-based width
* estimate to get the corresponding number of tuples.
*/
#if (PG_VERSION_NUM >= 140000)
if (baserel->tuples < 0)
#else
if (baserel->pages == 0 && baserel->tuples == 0)
#endif
{
baserel->pages = 10;
baserel->tuples =
(10 * BLCKSZ) / (baserel->reltarget->width +
MAXALIGN(SizeofHeapTupleHeader));
}
/*
* Estimate baserel size as best we can with local statistics.
*/
set_baserel_size_estimates(root, baserel);
/* Fill in basically-bogus cost estimates for use later. */
sqlite_estimate_path_cost_size(root, baserel, NIL, NIL, NULL,
&fpinfo->rows, &fpinfo->width,
&fpinfo->startup_cost, &fpinfo->total_cost);
/*
* Set the name of relation in fpinfo, while we are constructing it here.
* It will be used to build the string describing the join relation in
* EXPLAIN output. We can't know whether VERBOSE option is specified or
* not, so always schema-qualify the foreign table name.
*/
fpinfo->relation_name = psprintf("%u", baserel->relid);
/* No outer and inner relations. */
fpinfo->make_outerrel_subquery = false;
fpinfo->make_innerrel_subquery = false;
fpinfo->lower_subquery_rels = NULL;
#if PG_VERSION_NUM >= 170000
fpinfo->hidden_subquery_rels = NULL;
#endif
/* Set the relation index. */
fpinfo->relation_index = baserel->relid;
}
/*
* sqlite_get_useful_pathkeys_for_relation
* Determine which orderings of a relation might be useful.
*
* Getting data in sorted order can be useful either because the requested
* order matches the final output ordering for the overall query we're
* planning, or because it enables an efficient merge join. Here, we try
* to figure out which pathkeys to consider.
*/
static List *
sqlite_get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel)
{
List *useful_pathkeys_list = NIL;
SqliteFdwRelationInfo *fpinfo = (SqliteFdwRelationInfo *) rel->fdw_private;
ListCell *lc;
/*
* Pushing the query_pathkeys to the remote server is always worth
* considering, because it might let us avoid a local sort.
*/
fpinfo->qp_is_pushdown_safe = false;
if (root->query_pathkeys)
{
bool query_pathkeys_ok = true;
foreach(lc, root->query_pathkeys)
{
PathKey *pathkey = (PathKey *) lfirst(lc);
/*
* The planner and executor don't have any clever strategy for
* taking data sorted by a prefix of the query's pathkeys and
* getting it to be sorted by all of those pathkeys. We'll just
* end up resorting the entire data set. So, unless we can push
* down all of the query pathkeys, forget it.
*/
if (!sqlite_is_foreign_pathkey(root, rel, pathkey))
{
query_pathkeys_ok = false;
break;
}
}
if (query_pathkeys_ok)
{
useful_pathkeys_list = list_make1(list_copy(root->query_pathkeys));
fpinfo->qp_is_pushdown_safe = true;
}
}
return useful_pathkeys_list;
}
static void
sqlite_add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel, List *fdw_private,
Path *epq_path
#if PG_VERSION_NUM >= 170000
, List *restrictlist
#endif
)
{
List *useful_pathkeys_list = NIL; /* List of all pathkeys */
ListCell *lc;
double rows;
Cost startup_cost;
Cost total_cost;
/* Use small cost to avoid calculating real cost size in SQLite */
rows = startup_cost = total_cost = 10;
useful_pathkeys_list = sqlite_get_useful_pathkeys_for_relation(root, rel);
#if PG_VERSION_NUM >= 150000
/*
* Before creating sorted paths, arrange for the passed-in EPQ path, if
* any, to return columns needed by the parent ForeignScan node so that
* they will propagate up through Sort nodes injected below, if necessary.
*/
if (epq_path != NULL && useful_pathkeys_list != NIL)
{
SqliteFdwRelationInfo *fpinfo = (SqliteFdwRelationInfo *) rel->fdw_private;
PathTarget *target = copy_pathtarget(epq_path->pathtarget);
/* Include columns required for evaluating PHVs in the tlist. */
add_new_columns_to_pathtarget(target,
pull_var_clause((Node *) target->exprs,
PVC_RECURSE_PLACEHOLDERS));
/* Include columns required for evaluating the local conditions. */
foreach(lc, fpinfo->local_conds)
{
RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
add_new_columns_to_pathtarget(target,
pull_var_clause((Node *) rinfo->clause,
PVC_RECURSE_PLACEHOLDERS));
}
/*
* If we have added any new columns, adjust the tlist of the EPQ path.
*
* Note: the plan created using this path will only be used to execute
* EPQ checks, where accuracy of the plan cost and width estimates
* would not be important, so we do not do set_pathtarget_cost_width()
* for the new pathtarget here. See also postgresGetForeignPlan().
*/
if (list_length(target->exprs) > list_length(epq_path->pathtarget->exprs))
{
/* The EPQ path is a join path, so it is projection-capable. */
Assert(is_projection_capable_path(epq_path));
/*
* Use create_projection_path() here, so as to avoid modifying it
* in place.
*/
epq_path = (Path *) create_projection_path(root,
rel,
epq_path,
target);
}
}
#endif
/* Create one path for each set of pathkeys we found above. */
foreach(lc, useful_pathkeys_list)
{
List *useful_pathkeys = lfirst(lc);
Path *sorted_epq_path;
/*
* The EPQ path must be at least as well sorted as the path itself, in
* case it gets used as input to a mergejoin.
*/
sorted_epq_path = epq_path;
if (sorted_epq_path != NULL &&
!pathkeys_contained_in(useful_pathkeys,
sorted_epq_path->pathkeys))
sorted_epq_path = (Path *)
create_sort_path(root,
rel,
sorted_epq_path,
useful_pathkeys,
-1.0);
if (rel->reloptkind == RELOPT_BASEREL ||
rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
add_path(rel, (Path *)
create_foreignscan_path(root, rel,
NULL,
rows,
startup_cost,
total_cost,
useful_pathkeys,
#if (PG_VERSION_NUM >= 120000)
rel->lateral_relids,
#else
NULL, /* no outer rel either */
#endif
sorted_epq_path,
#if PG_VERSION_NUM >= 170000
NIL, /* no fdw_restrictinfo
* list */
#endif
fdw_private));
else
add_path(rel, (Path *)
#if PG_VERSION_NUM >= 120000
create_foreign_join_path(root, rel,
#else
create_foreignscan_path(root, rel,
#endif
NULL,
rows,
startup_cost,
total_cost,
useful_pathkeys,
#if (PG_VERSION_NUM >= 120000)
rel->lateral_relids,
#else
NULL, /* no outer rel either */
#endif
sorted_epq_path,
#if PG_VERSION_NUM >= 170000
restrictlist,
#endif
fdw_private));
}
}
/*
* Check if any of the tables queried aren't foreign tables.
* We use this function to add limit pushdownm fallback to sqlite
* because if theres any non-foreign table, GetForeignUpperPath its not called from planner.c
*/
static bool
sqlite_all_baserels_are_foreign(PlannerInfo *root)
{
bool allTablesQueriedAreForeign = true;
ListCell *l;
/*
* If there is no append_rel_list, we assume we're only consulting a
* foreign table, so default value it's true and we dont need to do more.
*/
foreach(l, root->append_rel_list)
{
AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, l);
int childRTindex;
RangeTblEntry *childRTE;
RelOptInfo *childrel;
/* Re-locate the child RTE and RelOptInfo */
childRTindex = appinfo->child_relid;
childRTE = root->simple_rte_array[childRTindex];
childrel = root->simple_rel_array[childRTindex];
if (!(IS_DUMMY_REL(childrel) || childRTE->inh))
{
if (!(childrel->rtekind == RTE_RELATION && childRTE->relkind == RELKIND_FOREIGN_TABLE))
{
allTablesQueriedAreForeign = false;
break;
}
}
}
return allTablesQueriedAreForeign;
}
/*
* sqliteGetForeignPaths
* Create possible scan paths for a scan on the foreign table
*/
static void
sqliteGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
{
Cost startup_cost = 10;
Cost total_cost = baserel->rows + startup_cost;
List *fdw_private = NIL;
elog(DEBUG1, "sqlite_fdw : %s", __func__);
/* Estimate costs */
total_cost = baserel->rows;
/*
* We add fdw_private with has_limit: true if these three conditions are
* true because we need to be able to pushdown limit in this case: - Query
* has LIMIT - Query don't have OFFSET because if we pusdown OFFSET and
* later, we re-applying offset with the "final result", and we would be
* "jumping/skipping" child results and losing registries that we wanted
* to show. - Some of the baserels are not a foreign table, so PostgreSQL
* is not calling GetForeignUpperPaths
*/
if (limit_needed(root->parse) && !root->parse->limitOffset && !sqlite_all_baserels_are_foreign(root))
#if PG_VERSION_NUM >= 150000
fdw_private = list_make2(makeBoolean(false), makeBoolean(true));
#else
fdw_private = list_make2(makeInteger(false), makeInteger(true));
#endif
/* Create a ForeignPath node and add it as only possible path */
add_path(baserel, (Path *)
create_foreignscan_path(root, baserel,
#if PG_VERSION_NUM >= 90600
NULL, /* default pathtarget */
#endif
baserel->rows,
startup_cost,
total_cost,
NIL, /* no pathkeys */
#if (PG_VERSION_NUM >= 120000)
baserel->lateral_relids,
#else
NULL, /* no outer rel either */
#endif
NULL, /* no extra plan */
#if PG_VERSION_NUM >= 170000
NIL, /* no fdw_restrictinfo list */
#endif
fdw_private));
/* Add paths with pathkeys */
sqlite_add_paths_with_pathkeys_for_rel(root, baserel, fdw_private, NULL
#if PG_VERSION_NUM >= 170000
, NIL
#endif
);
}
/*
* sqliteGetForeignPlan: Get a foreign scan plan node
*/
static ForeignScan *
sqliteGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid, ForeignPath *best_path, List *tlist, List *scan_clauses, Plan *outer_plan)
{
SqliteFdwRelationInfo *fpinfo = (SqliteFdwRelationInfo *) baserel->fdw_private;
Index scan_relid = baserel->relid;
List *fdw_private;
List *local_exprs = NULL;
List *remote_exprs = NULL;
List *params_list = NULL;
List *fdw_scan_tlist = NIL;
List *remote_conds = NIL;
StringInfoData sql;
bool has_final_sort = false;
bool has_limit = false;
List *retrieved_attrs;
ListCell *lc;
List *fdw_recheck_quals = NIL;
int for_update;
elog(DEBUG1, "sqlite_fdw : %s", __func__);
/* Decide to execute function pushdown support in the target list. */
fpinfo->is_tlist_func_pushdown = sqlite_is_foreign_function_tlist(root, baserel, tlist);
/*
* Get FDW private data created by sqliteGetForeignUpperPaths(), if any.
*/
if (best_path->fdw_private)
{
#if PG_VERSION_NUM >= 150000
has_final_sort = boolVal(list_nth(best_path->fdw_private, FdwPathPrivateHasFinalSort));
has_limit = boolVal(list_nth(best_path->fdw_private, FdwPathPrivateHasLimit));
#else
has_final_sort = intVal(list_nth(best_path->fdw_private, FdwPathPrivateHasFinalSort));
has_limit = intVal(list_nth(best_path->fdw_private, FdwPathPrivateHasLimit));
#endif
}
/*
* Build the query string to be sent for execution, and identify
* expressions to be sent as parameters.
*/
/* Build the query */
initStringInfo(&sql);
/*
* Separate the scan_clauses into those that can be executed remotely and
* those that can't. baserestrictinfo clauses that were previously
* determined to be safe or unsafe by sqlite_classify_conditions are shown
* in fpinfo->remote_conds and fpinfo->local_conds. Anything else in the
* scan_clauses list will be a join clause, which we have to check for
* remote-safety.
*
* Note: the join clauses we see here should be the exact same ones
* previously examined by sqliteGetForeignPaths. Possibly it'd be worth
* passing forward the classification work done then, rather than
* repeating it here.
*
* This code must match "extract_actual_clauses(scan_clauses, false)"
* except for the additional decision about remote versus local execution.