forked from pgspider/sqlite_fdw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlite_fdw.c
More file actions
2202 lines (1841 loc) · 59.7 KB
/
sqlite_fdw.c
File metadata and controls
2202 lines (1841 loc) · 59.7 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
/*-------------------------------------------------------------------------
*
* 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 <stdio.h>
#include "access/reloptions.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "foreign/fdwapi.h"
#include "foreign/foreign.h"
#include "optimizer/pathnode.h"
#include "optimizer/planmain.h"
#include "optimizer/cost.h"
#include "optimizer/clauses.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/paths.h"
#include "optimizer/prep.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/var.h"
#include "optimizer/tlist.h"
#include "funcapi.h"
#include "utils/builtins.h"
#include "utils/formatting.h"
#include "utils/rel.h"
#include "utils/lsyscache.h"
#include "utils/array.h"
#include "utils/date.h"
#include "utils/hsearch.h"
#include "utils/timestamp.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_user_mapping.h"
#include "catalog/pg_aggregate.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "commands/vacuum.h"
#include "storage/ipc.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "parser/parsetree.h"
#include "utils/typcache.h"
#include "utils/selfuncs.h"
extern PGDLLEXPORT void _PG_init(void);
bool sqlite_load_library(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(((Value *)(A->arg))->val.str, "true") == 0))
extern Datum sqlite_fdw_handler(PG_FUNCTION_ARGS);
extern Datum sqlite_fdw_validator(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(sqlite_fdw_handler);
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(Query *parsetree,
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);
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);
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 sqliteAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
static List *sqliteImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void sqliteGetForeignUpperPaths(PlannerInfo *root,
UpperRelationKind stage,
RelOptInfo *input_rel,
RelOptInfo *output_rel);
static void sqlite_prepare_wrapper(sqlite3 * db, char *query, sqlite3_stmt * *result, const char **pzTail);
static int get_estimate(Oid foreigntableid);
static void sqlite_to_pg_type(StringInfo str, char *typname);
static void 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 process_query_params(ExprContext *econtext,
FmgrInfo *param_flinfo,
List *param_exprs,
const char **param_values,
sqlite3_stmt * *stmt,
Oid *param_types);
static void create_cursor(ForeignScanState *node);
static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel);
static void add_foreign_grouping_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *grouped_rel);
/*
* 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->AddForeignUpdateTargets = sqliteAddForeignUpdateTargets;
fdwroutine->PlanForeignModify = sqlitePlanForeignModify;
fdwroutine->BeginForeignModify = sqliteBeginForeignModify;
fdwroutine->ExecForeignInsert = sqliteExecForeignInsert;
fdwroutine->ExecForeignUpdate = sqliteExecForeignUpdate;
fdwroutine->ExecForeignDelete = sqliteExecForeignDelete;
fdwroutine->EndForeignModify = sqliteEndForeignModify;
/* support for EXPLAIN */
fdwroutine->ExplainForeignScan = sqliteExplainForeignScan;
fdwroutine->ExplainForeignModify = sqliteExplainForeignModify;
/* support for ANALYSE */
fdwroutine->AnalyzeForeignTable = sqliteAnalyzeForeignTable;
/* support for IMPORT FOREIGN SCHEMA */
fdwroutine->ImportForeignSchema = sqliteImportForeignSchema;
#if (PG_VERSION_NUM >= 100000)
/* Support functions for upper relation push-down */
fdwroutine->GetForeignUpperPaths = sqliteGetForeignUpperPaths;
#endif
PG_RETURN_POINTER(fdwroutine);
}
/* Wrapper for sqlite3_prepare */
static void
sqlite_prepare_wrapper(sqlite3 * db, char *query, sqlite3_stmt * *stmt,
const char **pzTail)
{
int rc;
elog(DEBUG1, "sqlite_fdw : %s %s\n", __func__, query);
rc = sqlite3_prepare(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)
));
}
}
/*
* sqliteGetForeignRelSize: Create a FdwPlan for a scan on the foreign table
*/
static void
sqliteGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
{
double rows = 0;
SqliteFdwRelationInfo *fpinfo;
ListCell *lc;
RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
const char *namespace;
const char *relname;
const char *refname;
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);
/*
* Identify which baserestrictinfo clauses can be sent to the remote
* server and which can't.
*/
foreach(lc, baserel->baserestrictinfo)
{
RestrictInfo *ri = (RestrictInfo *) lfirst(lc);
if (sqlite_is_foreign_expr(root, baserel, ri->clause))
fpinfo->remote_conds = lappend(fpinfo->remote_conds, ri);
else
fpinfo->local_conds = lappend(fpinfo->local_conds, ri);
}
/*
* Identify which attributes will need to be retrieved from the remote
* server.
*/
#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);
}
rows = get_estimate(foreigntableid);
baserel->rows = rows;
baserel->tuples = rows;
/*
* 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 = makeStringInfo();
namespace = get_namespace_name(get_rel_namespace(foreigntableid));
relname = get_rel_name(foreigntableid);
refname = rte->eref->aliasname;
appendStringInfo(fpinfo->relation_name, "%s.%s",
quote_identifier(namespace),
quote_identifier(relname));
if (*refname && strcmp(refname, relname) != 0)
appendStringInfo(fpinfo->relation_name, " %s",
quote_identifier(rte->eref->aliasname));
}
/*
* 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;
elog(DEBUG1, "sqlite_fdw : %s", __func__);
/* Estimate costs */
total_cost = baserel->rows;
/* 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 */
NULL, /* no outer rel either */
NULL, /* no extra plan */
NULL)); /* no fdw_private data */
}
/*
* 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;
List *retrieved_attrs;
ListCell *lc;
List *fdw_recheck_quals = NIL;
int for_update;
elog(DEBUG1, "sqlite_fdw : %s", __func__);
/*
* 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 classifyConditions 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.
* Note however that we only strip the RestrictInfo nodes from the
* local_exprs list, since appendWhereClause expects a list of
* RestrictInfos.
*/
if (baserel->reloptkind == RELOPT_BASEREL ||
baserel->reloptkind == RELOPT_OTHER_MEMBER_REL)
{
foreach(lc, scan_clauses)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
Assert(IsA(rinfo, RestrictInfo));
/* Ignore any pseudoconstants, they're dealt with elsewhere */
if (rinfo->pseudoconstant)
continue;
if (list_member_ptr(fpinfo->remote_conds, rinfo))
{
remote_conds = lappend(remote_conds, rinfo);
remote_exprs = lappend(remote_exprs, rinfo->clause);
}
else if (list_member_ptr(fpinfo->local_conds, rinfo))
local_exprs = lappend(local_exprs, rinfo->clause);
else if (sqlite_is_foreign_expr(root, baserel, rinfo->clause))
{
remote_conds = lappend(remote_conds, rinfo);
remote_exprs = lappend(remote_exprs, rinfo->clause);
}
else
local_exprs = lappend(local_exprs, rinfo->clause);
/*
* For a base-relation scan, we have to support EPQ recheck, which
* should recheck all the remote quals.
*/
fdw_recheck_quals = remote_exprs;
}
}
else
{
/*
* Join relation or upper relation - set scan_relid to 0.
*/
scan_relid = 0;
/*
* For a join rel, baserestrictinfo is NIL and we are not considering
* parameterization right now, so there should be no scan_clauses for
* a joinrel or an upper rel either.
*/
Assert(!scan_clauses);
/*
* Instead we get the conditions to apply from the fdw_private
* structure.
*/
remote_exprs = extract_actual_clauses(fpinfo->remote_conds, false);
local_exprs = extract_actual_clauses(fpinfo->local_conds, false);
/*
* We leave fdw_recheck_quals empty in this case, since we never need
* to apply EPQ recheck clauses. In the case of a joinrel, EPQ
* recheck is handled elsewhere --- see sqliteGetForeignJoinPaths().
* If we're planning an upperrel (ie, remote grouping or aggregation)
* then there's no EPQ to do because SELECT FOR UPDATE wouldn't be
* allowed, and indeed we *can't* put the remote clauses into
* fdw_recheck_quals because the unaggregated Vars won't be available
* locally.
*/
/* Build the list of columns to be fetched from the foreign server. */
fdw_scan_tlist = sqlite_build_tlist_to_deparse(baserel);
/*
* Ensure that the outer plan produces a tuple whose descriptor
* matches our scan tuple slot. This is safe because all scans and
* joins support projection, so we never need to insert a Result node.
* Also, remove the local conditions from outer plan's quals, lest
* they will be evaluated twice, once by the local plan and once by
* the scan.
*/
if (outer_plan)
{
ListCell *lc;
/*
* Right now, we only consider grouping and aggregation beyond
* joins. Queries involving aggregates or grouping do not require
* EPQ mechanism, hence should not have an outer plan here.
*/
Assert(baserel->reloptkind != RELOPT_UPPER_REL);
outer_plan->targetlist = fdw_scan_tlist;
foreach(lc, local_exprs)
{
Join *join_plan = (Join *) outer_plan;
Node *qual = lfirst(lc);
outer_plan->qual = list_delete(outer_plan->qual, qual);
/*
* For an inner join the local conditions of foreign scan plan
* can be part of the joinquals as well.
*/
if (join_plan->jointype == JOIN_INNER)
join_plan->joinqual = list_delete(join_plan->joinqual,
qual);
}
}
}
/*
* Build the query string to be sent for execution, and identify
* expressions to be sent as parameters.
*/
initStringInfo(&sql);
sqliteDeparseSelectStmtForRel(&sql, root, baserel, fdw_scan_tlist,
remote_exprs, best_path->path.pathkeys,
false, &retrieved_attrs, ¶ms_list);
for_update = false;
if (baserel->relid == root->parse->resultRelation &&
(root->parse->commandType == CMD_UPDATE ||
root->parse->commandType == CMD_DELETE))
{
/* Relation is UPDATE/DELETE target, so use FOR UPDATE */
for_update = true;
}
/*
* Build the fdw_private list that will be available to the executor.
* Items in the list must match enum FdwScanPrivateIndex, above.
*/
fdw_private = list_make3(makeString(sql.data), retrieved_attrs, makeInteger(for_update));
if (baserel->reloptkind == RELOPT_JOINREL ||
baserel->reloptkind == RELOPT_UPPER_REL)
fdw_private = lappend(fdw_private,
makeString(fpinfo->relation_name->data));
/*
* Create the ForeignScan node from target list, local filtering
* expressions, remote parameter expressions, and FDW private information.
*
* Note that the remote parameter expressions are stored in the fdw_exprs
* field of the finished plan node; we can't keep them in private state
* because then they wouldn't be subject to later planner processing.
*/
return make_foreignscan(tlist, local_exprs, scan_relid, params_list, fdw_private,
fdw_scan_tlist, fdw_recheck_quals, outer_plan
);
}
/*
* sqliteBeginForeignScan: Initiate access to the database
*/
static void
sqliteBeginForeignScan(ForeignScanState *node, int eflags)
{
sqlite3 *conn = NULL;
SqliteFdwExecState *festate = NULL;
EState *estate = node->ss.ps.state;
ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
int numParams;
ForeignTable *table;
ForeignServer *server;
RangeTblEntry *rte;
int rtindex;
elog(DEBUG1, "sqlite_fdw : %s", __func__);
/*
* We'll save private state in node->fdw_state.
*/
festate = (SqliteFdwExecState *) palloc(sizeof(SqliteFdwExecState));
node->fdw_state = (void *) festate;
festate->rowidx = 0;
/*
* Identify which user to do the remote access as. This should match what
* ExecCheckRTEPerms() does. In case of a join or aggregate, use the
* lowest-numbered member RTE as a representative; we would get the same
* result from any.
*/
if (fsplan->scan.scanrelid > 0)
rtindex = fsplan->scan.scanrelid;
else
rtindex = bms_next_member(fsplan->fs_relids, -1);
rte = rt_fetch(rtindex, estate->es_range_table);
/* Get info about foreign table. */
table = GetForeignTable(rte->relid);
server = GetForeignServer(table->serverid);
/*
* Get the already connected connection, otherwise connect and get the
* connection handle.
*/
conn = sqlite_get_connection(server);
/* Stash away the state info we have already */
festate->query = strVal(list_nth(fsplan->fdw_private, 0));
festate->retrieved_attrs = list_nth(fsplan->fdw_private, 1);
festate->for_update = intVal(list_nth(fsplan->fdw_private, 2)) ? true : false;
festate->conn = conn;
festate->cursor_exists = false;
festate->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
"sqlite_fdw temporary data",
ALLOCSET_SMALL_MINSIZE,
ALLOCSET_SMALL_INITSIZE,
ALLOCSET_SMALL_MAXSIZE);
/* Initialize the Sqlite statement */
festate->stmt = NULL;
/* Prepare Sqlite statement */
sqlite_prepare_wrapper(festate->conn, festate->query, &festate->stmt, NULL);
/* Prepare for output conversion of parameters used in remote query. */
numParams = list_length(fsplan->fdw_exprs);
festate->numParams = numParams;
if (numParams > 0)
prepare_query_params((PlanState *) node,
fsplan->fdw_exprs,
numParams,
&festate->param_flinfo,
&festate->param_exprs,
&festate->param_values,
&festate->param_types);
}
static void
make_tuple_from_result_row(sqlite3_stmt * stmt,
TupleDesc tupleDescriptor,
List *retrieved_attrs,
Datum *row,
bool *is_null)
{
ListCell *lc = NULL;
int attid = 0;
memset(row, 0, sizeof(Datum) * tupleDescriptor->natts);
memset(is_null, true, sizeof(bool) * tupleDescriptor->natts);
foreach(lc, retrieved_attrs)
{
int attnum = lfirst_int(lc) - 1;
Oid pgtype = tupleDescriptor->attrs[attnum]->atttypid;
int32 pgtypmod = tupleDescriptor->attrs[attnum]->atttypmod;
if (sqlite3_column_type(stmt, attid) != SQLITE_NULL)
{
is_null[attnum] = false;
row[attnum] = sqlite_convert_to_pg(pgtype, pgtypmod,
stmt, attid);
}
attid++;
}
}
/*
* sqliteIterateForeignScan: Iterate and get the rows one by one from
* Sqlite and placed in tuple slot
*/
static TupleTableSlot *
sqliteIterateForeignScan(ForeignScanState *node)
{
SqliteFdwExecState *festate = (SqliteFdwExecState *) node->fdw_state;
TupleTableSlot *tupleSlot = node->ss.ss_ScanTupleSlot;
EState *estate = node->ss.ps.state;
TupleDesc tupleDescriptor = tupleSlot->tts_tupleDescriptor;
int rc = 0;
elog(DEBUG1, "sqlite_fdw : %s", __func__);
/*
* If this is the first call after Begin or ReScan, we need to create the
* cursor on the remote side. Binding parameters is done in this function.
*/
if (!festate->cursor_exists)
create_cursor(node);
ExecClearTuple(tupleSlot);
/*
* We get all rows before starting update if this scan is for update
* because there is no isolation between update and select on the same
* database connections. Please see for details:
* https://sqlite.org/isolation.html
*/
if (festate->for_update && festate->rowidx == 0)
{
int size = 0;
/* festate->rows need longer context than per tuple */
MemoryContext oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
festate->row_nums = 0;
festate->rowidx = 0;
while (1)
{
rc = sqlite3_step(festate->stmt);
if (rc == SQLITE_ROW)
{
if (size == 0)
{
size = 1;
festate->rows = palloc(sizeof(Datum *) * size);
festate->rows_isnull = palloc(sizeof(bool *) * size);
}
else if (festate->row_nums >= size)
{
/* expand array */
size = size * 2;
festate->rows = repalloc(festate->rows, sizeof(Datum *) * size);
festate->rows_isnull = repalloc(festate->rows_isnull, sizeof(bool *) * size);
}
festate->rows[festate->row_nums] = palloc(sizeof(Datum) * tupleDescriptor->natts);
festate->rows_isnull[festate->row_nums] = palloc(sizeof(bool) * tupleDescriptor->natts);
make_tuple_from_result_row(festate->stmt,
tupleDescriptor, festate->retrieved_attrs,
festate->rows[festate->row_nums],
festate->rows_isnull[festate->row_nums]);
festate->row_nums++;
}
else if (SQLITE_DONE == rc)
{
/* No more rows/data exists */
break;
}
else
{
sqlitefdw_report_error(ERROR, festate->stmt, festate->conn, NULL, rc);
}
}
MemoryContextSwitchTo(oldcontext);
}
if (festate->for_update)
{
if (festate->rowidx < festate->row_nums)
{
memcpy(tupleSlot->tts_values, festate->rows[festate->rowidx], sizeof(Datum) * tupleDescriptor->natts);
memcpy(tupleSlot->tts_isnull, festate->rows_isnull[festate->rowidx], sizeof(bool) * tupleDescriptor->natts);
ExecStoreVirtualTuple(tupleSlot);
festate->rowidx++;
}
}
else
{
rc = sqlite3_step(festate->stmt);
if (SQLITE_ROW == rc)
{
make_tuple_from_result_row(festate->stmt,
tupleDescriptor, festate->retrieved_attrs,
tupleSlot->tts_values, tupleSlot->tts_isnull);
ExecStoreVirtualTuple(tupleSlot);
}
else if (SQLITE_DONE == rc)
{
/* No more rows/data exists */
}
else
{
sqlitefdw_report_error(ERROR, festate->stmt, festate->conn, NULL, rc);
}
}
return tupleSlot;
}
/*
* sqliteEndForeignScan: Finish scanning foreign table and dispose
* objects used for this scan
*/
static void
sqliteEndForeignScan(ForeignScanState *node)
{
SqliteFdwExecState *festate = (SqliteFdwExecState *) node->fdw_state;
elog(DEBUG1, "sqlite_fdw : %s", __func__);
if (festate->stmt)
{
sqlite3_finalize(festate->stmt);
festate->stmt = NULL;
}
}
/*
* Restart the scan from the beginning. Note that any parameters the scan
* depends on may have changed value, so the new scan does not necessarily
* return exactly the same rows.
*/
static void
sqliteReScanForeignScan(ForeignScanState *node)
{
SqliteFdwExecState *festate = (SqliteFdwExecState *) node->fdw_state;
elog(DEBUG1, "sqlite_fdw : %s", __func__);
if (festate->stmt)
{
sqlite3_reset(festate->stmt);
}
festate->cursor_exists = false;
festate->rowidx = 0;
}
/*
* sqliteAddForeignUpdateTargets: Add column(s) needed for update/delete on a foreign table,
* we are using first column as row identification column, so we are adding that into target
* list.
*/
static void
sqliteAddForeignUpdateTargets(Query *parsetree,
RangeTblEntry *target_rte,
Relation target_relation)
{
Oid relid = RelationGetRelid(target_relation);
TupleDesc tupdesc = target_relation->rd_att;
int i;
bool has_key = false;
/* loop through all columns of the foreign table */
for (i = 0; i < tupdesc->natts; ++i)
{
Form_pg_attribute att = TupleDescAttr(tupdesc, i);
AttrNumber attrno = att->attnum;
List *options;
ListCell *option;
/* look for the "key" option on this column */
options = GetForeignColumnOptions(relid, attrno);
foreach(option, options)
{
DefElem *def = (DefElem *) lfirst(option);
/* if "key" is set, add a resjunk for this column */
if (IS_KEY_COLUMN(def))
{
Var *var;
TargetEntry *tle;
/* Make a Var representing the desired value */
var = makeVar(parsetree->resultRelation,
attrno,
att->atttypid,
att->atttypmod,
att->attcollation,
0);
/* Wrap it in a resjunk TLE with the right name ... */
tle = makeTargetEntry((Expr *) var,
list_length(parsetree->targetList) + 1,
pstrdup(NameStr(att->attname)),
true);
/* ... and add it to the query's targetlist */
parsetree->targetList = lappend(parsetree->targetList, tle);
has_key = true;
}
else
{
elog(ERROR, "impossible column option \"%s\"", def->defname);
}
}
}
if (!has_key)
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("no primary key column specified for foreign table"),
errdetail("For UPDATE or DELETE, at least one foreign table column must be marked as primary key column."),
errhint("Set the option \"%s\" on the columns that belong to the primary key.", "key")));
}
static List *
sqlitePlanForeignModify(PlannerInfo *root,
ModifyTable *plan,
Index resultRelation,
int subplan_index)
{
CmdType operation = plan->operation;
RangeTblEntry *rte = planner_rt_fetch(resultRelation, root);
Relation rel;
List *targetAttrs = NULL;
StringInfoData sql;
char *attname;
Oid foreignTableId;
TupleDesc tupdesc;
int i;
List *condAttr = NULL;
elog(DEBUG1, "sqlite_fdw : %s", __func__);
initStringInfo(&sql);
/*
* Core code already has some lock on each rel being planned, so we can
* use NoLock here.
*/
rel = heap_open(rte->relid, NoLock);
foreignTableId = RelationGetRelid(rel);
tupdesc = RelationGetDescr(rel);
if (operation == CMD_INSERT)
{
int attnum;
for (attnum = 1; attnum <= tupdesc->natts; attnum++)
{
Form_pg_attribute attr = tupdesc->attrs[attnum - 1];
if (!attr->attisdropped)
targetAttrs = lappend_int(targetAttrs, attnum);
}
}
else if (operation == CMD_UPDATE)
{
Bitmapset *tmpset = bms_copy(rte->updatedCols);
AttrNumber col;
while ((col = bms_first_member(tmpset)) >= 0)
{
col += FirstLowInvalidHeapAttributeNumber;
if (col <= InvalidAttrNumber) /* shouldn't happen */
elog(ERROR, "system-column update is not supported");
targetAttrs = lappend_int(targetAttrs, col);
}
}
if (plan->returningLists)
elog(ERROR, "RETURNING is not supported by this FDW");
if (plan->onConflictAction != ONCONFLICT_NONE)
elog(ERROR, "not suport ON CONFLICT: %d",
(int) plan->onConflictAction);
/*
* Add all primary key attribute names to condAttr used in where clause of
* update
*/
for (i = 0; i < tupdesc->natts; ++i)
{
Form_pg_attribute att = TupleDescAttr(tupdesc, i);
AttrNumber attrno = att->attnum;