PostgreSQL Source Code  git master
file_fdw.c File Reference
#include "postgres.h"
#include <sys/stat.h>
#include <unistd.h>
#include "access/htup_details.h"
#include "access/reloptions.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_foreign_table.h"
#include "commands/copy.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "commands/vacuum.h"
#include "foreign/fdwapi.h"
#include "foreign/foreign.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "optimizer/optimizer.h"
#include "optimizer/pathnode.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "utils/acl.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/sampling.h"
Include dependency graph for file_fdw.c:

Go to the source code of this file.

Data Structures

struct  FileFdwOption
 
struct  FileFdwPlanState
 
struct  FileFdwExecutionState
 

Typedefs

typedef struct FileFdwPlanState FileFdwPlanState
 
typedef struct FileFdwExecutionState FileFdwExecutionState
 

Functions

 PG_FUNCTION_INFO_V1 (file_fdw_handler)
 
 PG_FUNCTION_INFO_V1 (file_fdw_validator)
 
static void fileGetForeignRelSize (PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
 
static void fileGetForeignPaths (PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
 
static ForeignScanfileGetForeignPlan (PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid, ForeignPath *best_path, List *tlist, List *scan_clauses, Plan *outer_plan)
 
static void fileExplainForeignScan (ForeignScanState *node, ExplainState *es)
 
static void fileBeginForeignScan (ForeignScanState *node, int eflags)
 
static TupleTableSlotfileIterateForeignScan (ForeignScanState *node)
 
static void fileReScanForeignScan (ForeignScanState *node)
 
static void fileEndForeignScan (ForeignScanState *node)
 
static bool fileAnalyzeForeignTable (Relation relation, AcquireSampleRowsFunc *func, BlockNumber *totalpages)
 
static bool fileIsForeignScanParallelSafe (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static bool is_valid_option (const char *option, Oid context)
 
static void fileGetOptions (Oid foreigntableid, char **filename, bool *is_program, List **other_options)
 
static Listget_file_fdw_attribute_options (Oid relid)
 
static bool check_selective_binary_conversion (RelOptInfo *baserel, Oid foreigntableid, List **columns)
 
static void estimate_size (PlannerInfo *root, RelOptInfo *baserel, FileFdwPlanState *fdw_private)
 
static void estimate_costs (PlannerInfo *root, RelOptInfo *baserel, FileFdwPlanState *fdw_private, Cost *startup_cost, Cost *total_cost)
 
static int file_acquire_sample_rows (Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
 
Datum file_fdw_handler (PG_FUNCTION_ARGS)
 
Datum file_fdw_validator (PG_FUNCTION_ARGS)
 

Variables

 PG_MODULE_MAGIC
 
static const struct FileFdwOption valid_options []
 

Typedef Documentation

◆ FileFdwExecutionState

◆ FileFdwPlanState

Function Documentation

◆ check_selective_binary_conversion()

static bool check_selective_binary_conversion ( RelOptInfo baserel,
Oid  foreigntableid,
List **  columns 
)
static

Definition at line 848 of file file_fdw.c.

References AccessShareLock, attname, attnum, RelOptInfo::baserestrictinfo, bms_first_member(), RestrictInfo::clause, defGetString(), DefElem::defname, PathTarget::exprs, FirstLowInvalidHeapAttributeNumber, format, GetForeignTable(), i, lappend(), lfirst, list_length(), makeString(), NameStr, TupleDescData::natts, NIL, ForeignTable::options, pstrdup(), pull_varattnos(), RelationGetDescr, RelOptInfo::relid, RelOptInfo::reltarget, table_close(), table_open(), and TupleDescAttr.

Referenced by fileGetForeignPaths().

851 {
852  ForeignTable *table;
853  ListCell *lc;
854  Relation rel;
855  TupleDesc tupleDesc;
857  Bitmapset *attrs_used = NULL;
858  bool has_wholerow = false;
859  int numattrs;
860  int i;
861 
862  *columns = NIL; /* default result */
863 
864  /*
865  * Check format of the file. If binary format, this is irrelevant.
866  */
867  table = GetForeignTable(foreigntableid);
868  foreach(lc, table->options)
869  {
870  DefElem *def = (DefElem *) lfirst(lc);
871 
872  if (strcmp(def->defname, "format") == 0)
873  {
874  char *format = defGetString(def);
875 
876  if (strcmp(format, "binary") == 0)
877  return false;
878  break;
879  }
880  }
881 
882  /* Collect all the attributes needed for joins or final output. */
883  pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid,
884  &attrs_used);
885 
886  /* Add all the attributes used by restriction clauses. */
887  foreach(lc, baserel->baserestrictinfo)
888  {
889  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
890 
891  pull_varattnos((Node *) rinfo->clause, baserel->relid,
892  &attrs_used);
893  }
894 
895  /* Convert attribute numbers to column names. */
896  rel = table_open(foreigntableid, AccessShareLock);
897  tupleDesc = RelationGetDescr(rel);
898 
899  while ((attnum = bms_first_member(attrs_used)) >= 0)
900  {
901  /* Adjust for system attributes. */
903 
904  if (attnum == 0)
905  {
906  has_wholerow = true;
907  break;
908  }
909 
910  /* Ignore system attributes. */
911  if (attnum < 0)
912  continue;
913 
914  /* Get user attributes. */
915  if (attnum > 0)
916  {
917  Form_pg_attribute attr = TupleDescAttr(tupleDesc, attnum - 1);
918  char *attname = NameStr(attr->attname);
919 
920  /* Skip dropped attributes (probably shouldn't see any here). */
921  if (attr->attisdropped)
922  continue;
923 
924  /*
925  * Skip generated columns (COPY won't accept them in the column
926  * list)
927  */
928  if (attr->attgenerated)
929  continue;
930  *columns = lappend(*columns, makeString(pstrdup(attname)));
931  }
932  }
933 
934  /* Count non-dropped user attributes while we have the tupdesc. */
935  numattrs = 0;
936  for (i = 0; i < tupleDesc->natts; i++)
937  {
938  Form_pg_attribute attr = TupleDescAttr(tupleDesc, i);
939 
940  if (attr->attisdropped)
941  continue;
942  numattrs++;
943  }
944 
946 
947  /* If there's a whole-row reference, fail: we need all the columns. */
948  if (has_wholerow)
949  {
950  *columns = NIL;
951  return false;
952  }
953 
954  /* If all the user attributes are needed, fail. */
955  if (numattrs == list_length(*columns))
956  {
957  *columns = NIL;
958  return false;
959  }
960 
961  return true;
962 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
int bms_first_member(Bitmapset *a)
Definition: bitmapset.c:996
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define RelationGetDescr(relation)
Definition: rel.h:482
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * pstrdup(const char *in)
Definition: mcxt.c:1186
List * baserestrictinfo
Definition: pathnodes.h:727
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:529
ForeignTable * GetForeignTable(Oid relid)
Definition: foreign.c:248
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:219
NameData attname
Definition: pg_attribute.h:40
char * defGetString(DefElem *def)
Definition: define.c:49
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
Index relid
Definition: pathnodes.h:693
List * lappend(List *list, void *datum)
Definition: list.c:321
Expr * clause
Definition: pathnodes.h:1985
List * exprs
Definition: pathnodes.h:1074
int16 attnum
Definition: pg_attribute.h:79
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
List * options
Definition: foreign.h:57
int i
#define NameStr(name)
Definition: c.h:615
char * defname
Definition: parsenodes.h:732
static char format
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
struct PathTarget * reltarget
Definition: pathnodes.h:676
int16 AttrNumber
Definition: attnum.h:21

◆ estimate_costs()

static void estimate_costs ( PlannerInfo root,
RelOptInfo baserel,
FileFdwPlanState fdw_private,
Cost startup_cost,
Cost total_cost 
)
static

Definition at line 1053 of file file_fdw.c.

References RelOptInfo::baserestrictcost, cpu_tuple_cost, FileFdwPlanState::ntuples, FileFdwPlanState::pages, QualCost::per_tuple, seq_page_cost, and QualCost::startup.

Referenced by fileGetForeignPaths().

1056 {
1057  BlockNumber pages = fdw_private->pages;
1058  double ntuples = fdw_private->ntuples;
1059  Cost run_cost = 0;
1060  Cost cpu_per_tuple;
1061 
1062  /*
1063  * We estimate costs almost the same way as cost_seqscan(), thus assuming
1064  * that I/O costs are equivalent to a regular table file of the same size.
1065  * However, we take per-tuple CPU costs as 10x of a seqscan, to account
1066  * for the cost of parsing records.
1067  *
1068  * In the case of a program source, this calculation is even more divorced
1069  * from reality, but we have no good alternative; and it's not clear that
1070  * the numbers we produce here matter much anyway, since there's only one
1071  * access path for the rel.
1072  */
1073  run_cost += seq_page_cost * pages;
1074 
1075  *startup_cost = baserel->baserestrictcost.startup;
1076  cpu_per_tuple = cpu_tuple_cost * 10 + baserel->baserestrictcost.per_tuple;
1077  run_cost += cpu_per_tuple * ntuples;
1078  *total_cost = *startup_cost + run_cost;
1079 }
BlockNumber pages
Definition: file_fdw.c:95
uint32 BlockNumber
Definition: block.h:31
Cost startup
Definition: pathnodes.h:45
double ntuples
Definition: file_fdw.c:96
Cost per_tuple
Definition: pathnodes.h:46
double cpu_tuple_cost
Definition: costsize.c:113
double seq_page_cost
Definition: costsize.c:111
QualCost baserestrictcost
Definition: pathnodes.h:728
double Cost
Definition: nodes.h:663

◆ estimate_size()

static void estimate_size ( PlannerInfo root,
RelOptInfo baserel,
FileFdwPlanState fdw_private 
)
static

Definition at line 972 of file file_fdw.c.

References RelOptInfo::baserestrictinfo, clamp_row_est(), clauselist_selectivity(), FileFdwPlanState::filename, FileFdwPlanState::is_program, JOIN_INNER, MAXALIGN, FileFdwPlanState::ntuples, FileFdwPlanState::pages, RelOptInfo::pages, RelOptInfo::reltarget, RelOptInfo::rows, SizeofHeapTupleHeader, stat, RelOptInfo::tuples, and PathTarget::width.

Referenced by fileGetForeignRelSize().

974 {
975  struct stat stat_buf;
976  BlockNumber pages;
977  double ntuples;
978  double nrows;
979 
980  /*
981  * Get size of the file. It might not be there at plan time, though, in
982  * which case we have to use a default estimate. We also have to fall
983  * back to the default if using a program as the input.
984  */
985  if (fdw_private->is_program || stat(fdw_private->filename, &stat_buf) < 0)
986  stat_buf.st_size = 10 * BLCKSZ;
987 
988  /*
989  * Convert size to pages for use in I/O cost estimate later.
990  */
991  pages = (stat_buf.st_size + (BLCKSZ - 1)) / BLCKSZ;
992  if (pages < 1)
993  pages = 1;
994  fdw_private->pages = pages;
995 
996  /*
997  * Estimate the number of tuples in the file.
998  */
999  if (baserel->pages > 0)
1000  {
1001  /*
1002  * We have # of pages and # of tuples from pg_class (that is, from a
1003  * previous ANALYZE), so compute a tuples-per-page estimate and scale
1004  * that by the current file size.
1005  */
1006  double density;
1007 
1008  density = baserel->tuples / (double) baserel->pages;
1009  ntuples = clamp_row_est(density * (double) pages);
1010  }
1011  else
1012  {
1013  /*
1014  * Otherwise we have to fake it. We back into this estimate using the
1015  * planner's idea of the relation width; which is bogus if not all
1016  * columns are being read, not to mention that the text representation
1017  * of a row probably isn't the same size as its internal
1018  * representation. Possibly we could do something better, but the
1019  * real answer to anyone who complains is "ANALYZE" ...
1020  */
1021  int tuple_width;
1022 
1023  tuple_width = MAXALIGN(baserel->reltarget->width) +
1025  ntuples = clamp_row_est((double) stat_buf.st_size /
1026  (double) tuple_width);
1027  }
1028  fdw_private->ntuples = ntuples;
1029 
1030  /*
1031  * Now estimate the number of rows returned by the scan after applying the
1032  * baserestrictinfo quals.
1033  */
1034  nrows = ntuples *
1036  baserel->baserestrictinfo,
1037  0,
1038  JOIN_INNER,
1039  NULL);
1040 
1041  nrows = clamp_row_est(nrows);
1042 
1043  /* Save the output-rows estimate for the planner */
1044  baserel->rows = nrows;
1045 }
#define SizeofHeapTupleHeader
Definition: htup_details.h:184
BlockNumber pages
Definition: file_fdw.c:95
double tuples
Definition: pathnodes.h:705
List * baserestrictinfo
Definition: pathnodes.h:727
uint32 BlockNumber
Definition: block.h:31
double ntuples
Definition: file_fdw.c:96
struct stat stat_buf
Definition: pg_standby.c:100
char * filename
Definition: file_fdw.c:91
#define stat(a, b)
Definition: win32_port.h:255
double rows
Definition: pathnodes.h:668
BlockNumber pages
Definition: pathnodes.h:704
#define MAXALIGN(LEN)
Definition: c.h:691
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
double clamp_row_est(double nrows)
Definition: costsize.c:191
struct PathTarget * reltarget
Definition: pathnodes.h:676

◆ file_acquire_sample_rows()

static int file_acquire_sample_rows ( Relation  onerel,
int  elevel,
HeapTuple rows,
int  targrows,
double *  totalrows,
double *  totaldeadrows 
)
static

Definition at line 1096 of file file_fdw.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ErrorContextCallback::arg, Assert, BeginCopyFrom(), ErrorContextCallback::callback, CopyFromErrorCallback(), CurrentMemoryContext, EndCopyFrom(), ereport, errmsg(), error_context_stack, fileGetOptions(), filename, heap_form_tuple(), heap_freetuple(), MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), TupleDescData::natts, NextCopyFrom(), NIL, options, palloc(), pfree(), ErrorContextCallback::previous, ReservoirStateData::randstate, RelationGetDescr, RelationGetRelationName, RelationGetRelid, reservoir_get_next_S(), reservoir_init_selection_state(), sampler_random_fract(), vacuum_delay_point(), and values.

Referenced by fileAnalyzeForeignTable().

1099 {
1100  int numrows = 0;
1101  double rowstoskip = -1; /* -1 means not set yet */
1102  ReservoirStateData rstate;
1103  TupleDesc tupDesc;
1104  Datum *values;
1105  bool *nulls;
1106  bool found;
1107  char *filename;
1108  bool is_program;
1109  List *options;
1110  CopyState cstate;
1111  ErrorContextCallback errcallback;
1112  MemoryContext oldcontext = CurrentMemoryContext;
1113  MemoryContext tupcontext;
1114 
1115  Assert(onerel);
1116  Assert(targrows > 0);
1117 
1118  tupDesc = RelationGetDescr(onerel);
1119  values = (Datum *) palloc(tupDesc->natts * sizeof(Datum));
1120  nulls = (bool *) palloc(tupDesc->natts * sizeof(bool));
1121 
1122  /* Fetch options of foreign table */
1123  fileGetOptions(RelationGetRelid(onerel), &filename, &is_program, &options);
1124 
1125  /*
1126  * Create CopyState from FDW options.
1127  */
1128  cstate = BeginCopyFrom(NULL, onerel, filename, is_program, NULL, NIL,
1129  options);
1130 
1131  /*
1132  * Use per-tuple memory context to prevent leak of memory used to read
1133  * rows from the file with Copy routines.
1134  */
1136  "file_fdw temporary context",
1138 
1139  /* Prepare for sampling rows */
1140  reservoir_init_selection_state(&rstate, targrows);
1141 
1142  /* Set up callback to identify error line number. */
1143  errcallback.callback = CopyFromErrorCallback;
1144  errcallback.arg = (void *) cstate;
1145  errcallback.previous = error_context_stack;
1146  error_context_stack = &errcallback;
1147 
1148  *totalrows = 0;
1149  *totaldeadrows = 0;
1150  for (;;)
1151  {
1152  /* Check for user-requested abort or sleep */
1154 
1155  /* Fetch next row */
1156  MemoryContextReset(tupcontext);
1157  MemoryContextSwitchTo(tupcontext);
1158 
1159  found = NextCopyFrom(cstate, NULL, values, nulls);
1160 
1161  MemoryContextSwitchTo(oldcontext);
1162 
1163  if (!found)
1164  break;
1165 
1166  /*
1167  * The first targrows sample rows are simply copied into the
1168  * reservoir. Then we start replacing tuples in the sample until we
1169  * reach the end of the relation. This algorithm is from Jeff Vitter's
1170  * paper (see more info in commands/analyze.c).
1171  */
1172  if (numrows < targrows)
1173  {
1174  rows[numrows++] = heap_form_tuple(tupDesc, values, nulls);
1175  }
1176  else
1177  {
1178  /*
1179  * t in Vitter's paper is the number of records already processed.
1180  * If we need to compute a new S value, we must use the
1181  * not-yet-incremented value of totalrows as t.
1182  */
1183  if (rowstoskip < 0)
1184  rowstoskip = reservoir_get_next_S(&rstate, *totalrows, targrows);
1185 
1186  if (rowstoskip <= 0)
1187  {
1188  /*
1189  * Found a suitable tuple, so save it, replacing one old tuple
1190  * at random
1191  */
1192  int k = (int) (targrows * sampler_random_fract(rstate.randstate));
1193 
1194  Assert(k >= 0 && k < targrows);
1195  heap_freetuple(rows[k]);
1196  rows[k] = heap_form_tuple(tupDesc, values, nulls);
1197  }
1198 
1199  rowstoskip -= 1;
1200  }
1201 
1202  *totalrows += 1;
1203  }
1204 
1205  /* Remove error callback. */
1206  error_context_stack = errcallback.previous;
1207 
1208  /* Clean up. */
1209  MemoryContextDelete(tupcontext);
1210 
1211  EndCopyFrom(cstate);
1212 
1213  pfree(values);
1214  pfree(nulls);
1215 
1216  /*
1217  * Emit some interesting relation info
1218  */
1219  ereport(elevel,
1220  (errmsg("\"%s\": file contains %.0f rows; "
1221  "%d rows in sample",
1222  RelationGetRelationName(onerel),
1223  *totalrows, numrows)));
1224 
1225  return numrows;
1226 }
#define NIL
Definition: pg_list.h:65
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
void CopyFromErrorCallback(void *arg)
Definition: copy.c:2234
#define RelationGetDescr(relation)
Definition: rel.h:482
CopyState BeginCopyFrom(ParseState *pstate, Relation rel, const char *filename, bool is_program, copy_data_source_cb data_source_cb, List *attnamelist, List *options)
Definition: copy.c:3334
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
double sampler_random_fract(SamplerRandomState randstate)
Definition: sampling.c:242
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:136
void reservoir_init_selection_state(ReservoirState rs, int n)
Definition: sampling.c:133
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void(* callback)(void *arg)
Definition: elog.h:229
struct ErrorContextCallback * previous
Definition: elog.h:228
ErrorContextCallback * error_context_stack
Definition: elog.c:92
void pfree(void *pointer)
Definition: mcxt.c:1056
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define RelationGetRelationName(relation)
Definition: rel.h:490
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
static void fileGetOptions(Oid foreigntableid, char **filename, bool *is_program, List **other_options)
Definition: file_fdw.c:357
static char ** options
static int elevel
Definition: vacuumlazy.c:323
uintptr_t Datum
Definition: postgres.h:367
#define ereport(elevel,...)
Definition: elog.h:144
void EndCopyFrom(CopyState cstate)
Definition: copy.c:3823
#define Assert(condition)
Definition: c.h:738
bool NextCopyFrom(CopyState cstate, ExprContext *econtext, Datum *values, bool *nulls)
Definition: copy.c:3635
static Datum values[MAXATTR]
Definition: bootstrap.c:167
static char * filename
Definition: pg_dumpall.c:90
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:824
void vacuum_delay_point(void)
Definition: vacuum.c:1995
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:456
SamplerRandomState randstate
Definition: sampling.h:50
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:146

◆ file_fdw_handler()

Datum file_fdw_handler ( PG_FUNCTION_ARGS  )

Definition at line 171 of file file_fdw.c.

References FdwRoutine::AnalyzeForeignTable, FdwRoutine::BeginForeignScan, FdwRoutine::EndForeignScan, FdwRoutine::ExplainForeignScan, fileAnalyzeForeignTable(), fileBeginForeignScan(), fileEndForeignScan(), fileExplainForeignScan(), fileGetForeignPaths(), fileGetForeignPlan(), fileGetForeignRelSize(), fileIsForeignScanParallelSafe(), fileIterateForeignScan(), fileReScanForeignScan(), FdwRoutine::GetForeignPaths, FdwRoutine::GetForeignPlan, FdwRoutine::GetForeignRelSize, FdwRoutine::IsForeignScanParallelSafe, FdwRoutine::IterateForeignScan, makeNode, PG_RETURN_POINTER, and FdwRoutine::ReScanForeignScan.

172 {
173  FdwRoutine *fdwroutine = makeNode(FdwRoutine);
174 
176  fdwroutine->GetForeignPaths = fileGetForeignPaths;
177  fdwroutine->GetForeignPlan = fileGetForeignPlan;
182  fdwroutine->EndForeignScan = fileEndForeignScan;
185 
186  PG_RETURN_POINTER(fdwroutine);
187 }
GetForeignPlan_function GetForeignPlan
Definition: fdwapi.h:190
BeginForeignScan_function BeginForeignScan
Definition: fdwapi.h:191
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:360
static bool fileIsForeignScanParallelSafe(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: file_fdw.c:832
static void fileEndForeignScan(ForeignScanState *node)
Definition: file_fdw.c:767
ExplainForeignScan_function ExplainForeignScan
Definition: fdwapi.h:229
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:234
IsForeignScanParallelSafe_function IsForeignScanParallelSafe
Definition: fdwapi.h:240
static TupleTableSlot * fileIterateForeignScan(ForeignScanState *node)
Definition: file_fdw.c:705
GetForeignRelSize_function GetForeignRelSize
Definition: fdwapi.h:188
EndForeignScan_function EndForeignScan
Definition: fdwapi.h:194
static bool fileAnalyzeForeignTable(Relation relation, AcquireSampleRowsFunc *func, BlockNumber *totalpages)
Definition: file_fdw.c:781
static void fileBeginForeignScan(ForeignScanState *node, int eflags)
Definition: file_fdw.c:652
GetForeignPaths_function GetForeignPaths
Definition: fdwapi.h:189
static void fileGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
Definition: file_fdw.c:532
#define makeNode(_type_)
Definition: nodes.h:577
static void fileGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
Definition: file_fdw.c:501
ReScanForeignScan_function ReScanForeignScan
Definition: fdwapi.h:193
IterateForeignScan_function IterateForeignScan
Definition: fdwapi.h:192
static void fileExplainForeignScan(ForeignScanState *node, ExplainState *es)
Definition: file_fdw.c:620
static void fileReScanForeignScan(ForeignScanState *node)
Definition: file_fdw.c:747
static ForeignScan * fileGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid, ForeignPath *best_path, List *tlist, List *scan_clauses, Plan *outer_plan)
Definition: file_fdw.c:585

◆ file_fdw_validator()

Datum file_fdw_validator ( PG_FUNCTION_ARGS  )

Definition at line 196 of file file_fdw.c.

References appendStringInfo(), buf, StringInfoData::data, defGetBoolean(), defGetString(), DefElem::defname, ereport, errcode(), errhint(), errmsg(), ERROR, filename, GetUserId(), initStringInfo(), is_member_of_role(), is_valid_option(), lappend(), StringInfoData::len, lfirst, NIL, FileFdwOption::optcontext, FileFdwOption::optname, PG_GETARG_DATUM, PG_GETARG_OID, PG_RETURN_VOID, ProcessCopyOptions(), and untransformRelOptions().

197 {
198  List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
199  Oid catalog = PG_GETARG_OID(1);
200  char *filename = NULL;
201  DefElem *force_not_null = NULL;
202  DefElem *force_null = NULL;
203  List *other_options = NIL;
204  ListCell *cell;
205 
206  /*
207  * Check that only options supported by file_fdw, and allowed for the
208  * current object type, are given.
209  */
210  foreach(cell, options_list)
211  {
212  DefElem *def = (DefElem *) lfirst(cell);
213 
214  if (!is_valid_option(def->defname, catalog))
215  {
216  const struct FileFdwOption *opt;
218 
219  /*
220  * Unknown option specified, complain about it. Provide a hint
221  * with list of valid options for the object.
222  */
223  initStringInfo(&buf);
224  for (opt = valid_options; opt->optname; opt++)
225  {
226  if (catalog == opt->optcontext)
227  appendStringInfo(&buf, "%s%s", (buf.len > 0) ? ", " : "",
228  opt->optname);
229  }
230 
231  ereport(ERROR,
232  (errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
233  errmsg("invalid option \"%s\"", def->defname),
234  buf.len > 0
235  ? errhint("Valid options in this context are: %s",
236  buf.data)
237  : errhint("There are no valid options in this context.")));
238  }
239 
240  /*
241  * Separate out filename, program, and column-specific options, since
242  * ProcessCopyOptions won't accept them.
243  */
244  if (strcmp(def->defname, "filename") == 0 ||
245  strcmp(def->defname, "program") == 0)
246  {
247  if (filename)
248  ereport(ERROR,
249  (errcode(ERRCODE_SYNTAX_ERROR),
250  errmsg("conflicting or redundant options")));
251 
252  /*
253  * Check permissions for changing which file or program is used by
254  * the file_fdw.
255  *
256  * Only members of the role 'pg_read_server_files' are allowed to
257  * set the 'filename' option of a file_fdw foreign table, while
258  * only members of the role 'pg_execute_server_program' are
259  * allowed to set the 'program' option. This is because we don't
260  * want regular users to be able to control which file gets read
261  * or which program gets executed.
262  *
263  * Putting this sort of permissions check in a validator is a bit
264  * of a crock, but there doesn't seem to be any other place that
265  * can enforce the check more cleanly.
266  *
267  * Note that the valid_options[] array disallows setting filename
268  * and program at any options level other than foreign table ---
269  * otherwise there'd still be a security hole.
270  */
271  if (strcmp(def->defname, "filename") == 0 &&
272  !is_member_of_role(GetUserId(), DEFAULT_ROLE_READ_SERVER_FILES))
273  ereport(ERROR,
274  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
275  errmsg("only superuser or a member of the pg_read_server_files role may specify the filename option of a file_fdw foreign table")));
276 
277  if (strcmp(def->defname, "program") == 0 &&
278  !is_member_of_role(GetUserId(), DEFAULT_ROLE_EXECUTE_SERVER_PROGRAM))
279  ereport(ERROR,
280  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
281  errmsg("only superuser or a member of the pg_execute_server_program role may specify the program option of a file_fdw foreign table")));
282 
283  filename = defGetString(def);
284  }
285 
286  /*
287  * force_not_null is a boolean option; after validation we can discard
288  * it - it will be retrieved later in get_file_fdw_attribute_options()
289  */
290  else if (strcmp(def->defname, "force_not_null") == 0)
291  {
292  if (force_not_null)
293  ereport(ERROR,
294  (errcode(ERRCODE_SYNTAX_ERROR),
295  errmsg("conflicting or redundant options"),
296  errhint("Option \"force_not_null\" supplied more than once for a column.")));
297  force_not_null = def;
298  /* Don't care what the value is, as long as it's a legal boolean */
299  (void) defGetBoolean(def);
300  }
301  /* See comments for force_not_null above */
302  else if (strcmp(def->defname, "force_null") == 0)
303  {
304  if (force_null)
305  ereport(ERROR,
306  (errcode(ERRCODE_SYNTAX_ERROR),
307  errmsg("conflicting or redundant options"),
308  errhint("Option \"force_null\" supplied more than once for a column.")));
309  force_null = def;
310  (void) defGetBoolean(def);
311  }
312  else
313  other_options = lappend(other_options, def);
314  }
315 
316  /*
317  * Now apply the core COPY code's validation logic for more checks.
318  */
319  ProcessCopyOptions(NULL, NULL, true, other_options);
320 
321  /*
322  * Either filename or program option is required for file_fdw foreign
323  * tables.
324  */
325  if (catalog == ForeignTableRelationId && filename == NULL)
326  ereport(ERROR,
327  (errcode(ERRCODE_FDW_DYNAMIC_PARAMETER_VALUE_NEEDED),
328  errmsg("either filename or program is required for file_fdw foreign tables")));
329 
330  PG_RETURN_VOID();
331 }
#define NIL
Definition: pg_list.h:65
Oid optcontext
Definition: file_fdw.c:49
int errhint(const char *fmt,...)
Definition: elog.c:1071
static const struct FileFdwOption valid_options[]
Definition: file_fdw.c:61
Oid GetUserId(void)
Definition: miscinit.c:448
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
void ProcessCopyOptions(ParseState *pstate, CopyState cstate, bool is_from, List *options)
Definition: copy.c:1106
int errcode(int sqlerrcode)
Definition: elog.c:610
unsigned int Oid
Definition: postgres_ext.h:31
bool defGetBoolean(DefElem *def)
Definition: define.c:111
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:43
char * defGetString(DefElem *def)
Definition: define.c:49
static char * buf
Definition: pg_test_fsync.c:67
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
List * lappend(List *list, void *datum)
Definition: list.c:321
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
const char * optname
Definition: file_fdw.c:48
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1308
#define ereport(elevel,...)
Definition: elog.h:144
#define PG_RETURN_VOID()
Definition: fmgr.h:348
bool is_member_of_role(Oid member, Oid role)
Definition: acl.c:4916
#define lfirst(lc)
Definition: pg_list.h:190
static bool is_valid_option(const char *option, Oid context)
Definition: file_fdw.c:338
static char * filename
Definition: pg_dumpall.c:90
int errmsg(const char *fmt,...)
Definition: elog.c:824
char * defname
Definition: parsenodes.h:732
Definition: pg_list.h:50

◆ fileAnalyzeForeignTable()

static bool fileAnalyzeForeignTable ( Relation  relation,
AcquireSampleRowsFunc func,
BlockNumber totalpages 
)
static

Definition at line 781 of file file_fdw.c.

References ereport, errcode_for_file_access(), errmsg(), ERROR, file_acquire_sample_rows(), fileGetOptions(), filename, options, RelationGetRelid, and stat.

Referenced by file_fdw_handler().

784 {
785  char *filename;
786  bool is_program;
787  List *options;
788  struct stat stat_buf;
789 
790  /* Fetch options of foreign table */
791  fileGetOptions(RelationGetRelid(relation), &filename, &is_program, &options);
792 
793  /*
794  * If this is a program instead of a file, just return false to skip
795  * analyzing the table. We could run the program and collect stats on
796  * whatever it currently returns, but it seems likely that in such cases
797  * the output would be too volatile for the stats to be useful. Maybe
798  * there should be an option to enable doing this?
799  */
800  if (is_program)
801  return false;
802 
803  /*
804  * Get size of the file. (XXX if we fail here, would it be better to just
805  * return false to skip analyzing the table?)
806  */
807  if (stat(filename, &stat_buf) < 0)
808  ereport(ERROR,
810  errmsg("could not stat file \"%s\": %m",
811  filename)));
812 
813  /*
814  * Convert size to pages. Must return at least 1 so that we can tell
815  * later on that pg_class.relpages is not default.
816  */
817  *totalpages = (stat_buf.st_size + (BLCKSZ - 1)) / BLCKSZ;
818  if (*totalpages < 1)
819  *totalpages = 1;
820 
821  *func = file_acquire_sample_rows;
822 
823  return true;
824 }
static int file_acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: file_fdw.c:1096
#define ERROR
Definition: elog.h:43
struct stat stat_buf
Definition: pg_standby.c:100
int errcode_for_file_access(void)
Definition: elog.c:633
static void fileGetOptions(Oid foreigntableid, char **filename, bool *is_program, List **other_options)
Definition: file_fdw.c:357
static char ** options
#define stat(a, b)
Definition: win32_port.h:255
#define ereport(elevel,...)
Definition: elog.h:144
static char * filename
Definition: pg_dumpall.c:90
int errmsg(const char *fmt,...)
Definition: elog.c:824
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:456

◆ fileBeginForeignScan()

static void fileBeginForeignScan ( ForeignScanState node,
int  eflags 
)
static

Definition at line 652 of file file_fdw.c.

References BeginCopyFrom(), EXEC_FLAG_EXPLAIN_ONLY, ForeignScan::fdw_private, ForeignScanState::fdw_state, fileGetOptions(), filename, list_concat(), NIL, options, palloc(), PlanState::plan, ScanState::ps, RelationGetRelid, ForeignScanState::ss, and ScanState::ss_currentRelation.

Referenced by file_fdw_handler().

653 {
654  ForeignScan *plan = (ForeignScan *) node->ss.ps.plan;
655  char *filename;
656  bool is_program;
657  List *options;
658  CopyState cstate;
659  FileFdwExecutionState *festate;
660 
661  /*
662  * Do nothing in EXPLAIN (no ANALYZE) case. node->fdw_state stays NULL.
663  */
664  if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
665  return;
666 
667  /* Fetch options of foreign table */
669  &filename, &is_program, &options);
670 
671  /* Add any options from the plan (currently only convert_selectively) */
673 
674  /*
675  * Create CopyState from FDW options. We always acquire all columns, so
676  * as to match the expected ScanTupleSlot signature.
677  */
678  cstate = BeginCopyFrom(NULL,
679  node->ss.ss_currentRelation,
680  filename,
681  is_program,
682  NULL,
683  NIL,
684  options);
685 
686  /*
687  * Save state in node->fdw_state. We must save enough information to call
688  * BeginCopyFrom() again.
689  */
690  festate = (FileFdwExecutionState *) palloc(sizeof(FileFdwExecutionState));
691  festate->filename = filename;
692  festate->is_program = is_program;
693  festate->options = options;
694  festate->cstate = cstate;
695 
696  node->fdw_state = (void *) festate;
697 }
#define NIL
Definition: pg_list.h:65
ScanState ss
Definition: execnodes.h:1794
CopyState BeginCopyFrom(ParseState *pstate, Relation rel, const char *filename, bool is_program, copy_data_source_cb data_source_cb, List *attnamelist, List *options)
Definition: copy.c:3334
List * fdw_private
Definition: plannodes.h:618
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
Relation ss_currentRelation
Definition: execnodes.h:1333
PlanState ps
Definition: execnodes.h:1332
static void fileGetOptions(Oid foreigntableid, char **filename, bool *is_program, List **other_options)
Definition: file_fdw.c:357
static char ** options
Plan * plan
Definition: execnodes.h:945
static char * filename
Definition: pg_dumpall.c:90
void * palloc(Size size)
Definition: mcxt.c:949
Definition: pg_list.h:50
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:56
#define RelationGetRelid(relation)
Definition: rel.h:456

◆ fileEndForeignScan()

static void fileEndForeignScan ( ForeignScanState node)
static

Definition at line 767 of file file_fdw.c.

References FileFdwExecutionState::cstate, EndCopyFrom(), and ForeignScanState::fdw_state.

Referenced by file_fdw_handler().

768 {
770 
771  /* if festate is NULL, we are in EXPLAIN; nothing to do */
772  if (festate)
773  EndCopyFrom(festate->cstate);
774 }
void EndCopyFrom(CopyState cstate)
Definition: copy.c:3823

◆ fileExplainForeignScan()

static void fileExplainForeignScan ( ForeignScanState node,
ExplainState es 
)
static

Definition at line 620 of file file_fdw.c.

References ExplainState::costs, ExplainPropertyInteger(), ExplainPropertyText(), fileGetOptions(), filename, options, RelationGetRelid, ForeignScanState::ss, ScanState::ss_currentRelation, and stat.

Referenced by file_fdw_handler().

621 {
622  char *filename;
623  bool is_program;
624  List *options;
625 
626  /* Fetch options --- we only need filename and is_program at this point */
628  &filename, &is_program, &options);
629 
630  if (is_program)
631  ExplainPropertyText("Foreign Program", filename, es);
632  else
633  ExplainPropertyText("Foreign File", filename, es);
634 
635  /* Suppress file size if we're not showing cost details */
636  if (es->costs)
637  {
638  struct stat stat_buf;
639 
640  if (!is_program &&
641  stat(filename, &stat_buf) == 0)
642  ExplainPropertyInteger("Foreign File Size", "b",
643  (int64) stat_buf.st_size, es);
644  }
645 }
ScanState ss
Definition: execnodes.h:1794
void ExplainPropertyInteger(const char *qlabel, const char *unit, int64 value, ExplainState *es)
Definition: explain.c:4146
Relation ss_currentRelation
Definition: execnodes.h:1333
bool costs
Definition: explain.h:43
void ExplainPropertyText(const char *qlabel, const char *value, ExplainState *es)
Definition: explain.c:4137
struct stat stat_buf
Definition: pg_standby.c:100
static void fileGetOptions(Oid foreigntableid, char **filename, bool *is_program, List **other_options)
Definition: file_fdw.c:357
static char ** options
#define stat(a, b)
Definition: win32_port.h:255
static char * filename
Definition: pg_dumpall.c:90
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:456

◆ fileGetForeignPaths()

static void fileGetForeignPaths ( PlannerInfo root,
RelOptInfo baserel,
Oid  foreigntableid 
)
static

Definition at line 532 of file file_fdw.c.

References add_path(), check_selective_binary_conversion(), create_foreignscan_path(), estimate_costs(), RelOptInfo::fdw_private, RelOptInfo::lateral_relids, list_make1, makeDefElem(), NIL, and RelOptInfo::rows.

Referenced by file_fdw_handler().

535 {
536  FileFdwPlanState *fdw_private = (FileFdwPlanState *) baserel->fdw_private;
537  Cost startup_cost;
538  Cost total_cost;
539  List *columns;
540  List *coptions = NIL;
541 
542  /* Decide whether to selectively perform binary conversion */
544  foreigntableid,
545  &columns))
546  coptions = list_make1(makeDefElem("convert_selectively",
547  (Node *) columns, -1));
548 
549  /* Estimate costs */
550  estimate_costs(root, baserel, fdw_private,
551  &startup_cost, &total_cost);
552 
553  /*
554  * Create a ForeignPath node and add it as only possible path. We use the
555  * fdw_private list of the path to carry the convert_selectively option;
556  * it will be propagated into the fdw_private list of the Plan node.
557  *
558  * We don't support pushing join clauses into the quals of this path, but
559  * it could still have required parameterization due to LATERAL refs in
560  * its tlist.
561  */
562  add_path(baserel, (Path *)
563  create_foreignscan_path(root, baserel,
564  NULL, /* default pathtarget */
565  baserel->rows,
566  startup_cost,
567  total_cost,
568  NIL, /* no pathkeys */
569  baserel->lateral_relids,
570  NULL, /* no extra plan */
571  coptions));
572 
573  /*
574  * If data file was sorted, and we knew it somehow, we could insert
575  * appropriate pathkeys into the ForeignPath node to tell the planner
576  * that.
577  */
578 }
#define NIL
Definition: pg_list.h:65
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
Definition: nodes.h:529
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:544
#define list_make1(x1)
Definition: pg_list.h:227
Relids lateral_relids
Definition: pathnodes.h:690
ForeignPath * create_foreignscan_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, double rows, Cost startup_cost, Cost total_cost, List *pathkeys, Relids required_outer, Path *fdw_outerpath, List *fdw_private)
Definition: pathnode.c:2100
double rows
Definition: pathnodes.h:668
void * fdw_private
Definition: pathnodes.h:719
static bool check_selective_binary_conversion(RelOptInfo *baserel, Oid foreigntableid, List **columns)
Definition: file_fdw.c:848
static void estimate_costs(PlannerInfo *root, RelOptInfo *baserel, FileFdwPlanState *fdw_private, Cost *startup_cost, Cost *total_cost)
Definition: file_fdw.c:1053
Definition: pg_list.h:50
double Cost
Definition: nodes.h:663

◆ fileGetForeignPlan()

static ForeignScan * fileGetForeignPlan ( PlannerInfo root,
RelOptInfo baserel,
Oid  foreigntableid,
ForeignPath best_path,
List tlist,
List scan_clauses,
Plan outer_plan 
)
static

Definition at line 585 of file file_fdw.c.

References extract_actual_clauses(), ForeignPath::fdw_private, make_foreignscan(), NIL, and RelOptInfo::relid.

Referenced by file_fdw_handler().

592 {
593  Index scan_relid = baserel->relid;
594 
595  /*
596  * We have no native ability to evaluate restriction clauses, so we just
597  * put all the scan_clauses into the plan node's qual list for the
598  * executor to check. So all we have to do here is strip RestrictInfo
599  * nodes from the clauses and ignore pseudoconstants (which will be
600  * handled elsewhere).
601  */
602  scan_clauses = extract_actual_clauses(scan_clauses, false);
603 
604  /* Create the ForeignScan node */
605  return make_foreignscan(tlist,
606  scan_clauses,
607  scan_relid,
608  NIL, /* no expressions to evaluate */
609  best_path->fdw_private,
610  NIL, /* no custom tlist */
611  NIL, /* no remote quals */
612  outer_plan);
613 }
#define NIL
Definition: pg_list.h:65
Index relid
Definition: pathnodes.h:693
unsigned int Index
Definition: c.h:475
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:422
ForeignScan * make_foreignscan(List *qptlist, List *qpqual, Index scanrelid, List *fdw_exprs, List *fdw_private, List *fdw_scan_tlist, List *fdw_recheck_quals, Plan *outer_plan)
Definition: createplan.c:5533
List * fdw_private
Definition: pathnodes.h:1350

◆ fileGetForeignRelSize()

static void fileGetForeignRelSize ( PlannerInfo root,
RelOptInfo baserel,
Oid  foreigntableid 
)
static

Definition at line 501 of file file_fdw.c.

References estimate_size(), RelOptInfo::fdw_private, fileGetOptions(), FileFdwPlanState::filename, FileFdwPlanState::is_program, FileFdwPlanState::options, and palloc().

Referenced by file_fdw_handler().

504 {
505  FileFdwPlanState *fdw_private;
506 
507  /*
508  * Fetch options. We only need filename (or program) at this point, but
509  * we might as well get everything and not need to re-fetch it later in
510  * planning.
511  */
512  fdw_private = (FileFdwPlanState *) palloc(sizeof(FileFdwPlanState));
513  fileGetOptions(foreigntableid,
514  &fdw_private->filename,
515  &fdw_private->is_program,
516  &fdw_private->options);
517  baserel->fdw_private = (void *) fdw_private;
518 
519  /* Estimate relation size */
520  estimate_size(root, baserel, fdw_private);
521 }
List * options
Definition: file_fdw.c:93
static void estimate_size(PlannerInfo *root, RelOptInfo *baserel, FileFdwPlanState *fdw_private)
Definition: file_fdw.c:972
char * filename
Definition: file_fdw.c:91
static void fileGetOptions(Oid foreigntableid, char **filename, bool *is_program, List **other_options)
Definition: file_fdw.c:357
void * fdw_private
Definition: pathnodes.h:719
void * palloc(Size size)
Definition: mcxt.c:949

◆ fileGetOptions()

static void fileGetOptions ( Oid  foreigntableid,
char **  filename,
bool is_program,
List **  other_options 
)
static

Definition at line 357 of file file_fdw.c.

References defGetString(), DefElem::defname, elog, ERROR, ForeignServer::fdwid, foreach_delete_current, get_file_fdw_attribute_options(), GetForeignDataWrapper(), GetForeignServer(), GetForeignTable(), lfirst, list_concat(), NIL, ForeignDataWrapper::options, ForeignServer::options, options, ForeignTable::options, and ForeignTable::serverid.

Referenced by file_acquire_sample_rows(), fileAnalyzeForeignTable(), fileBeginForeignScan(), fileExplainForeignScan(), and fileGetForeignRelSize().

359 {
360  ForeignTable *table;
361  ForeignServer *server;
362  ForeignDataWrapper *wrapper;
363  List *options;
364  ListCell *lc;
365 
366  /*
367  * Extract options from FDW objects. We ignore user mappings because
368  * file_fdw doesn't have any options that can be specified there.
369  *
370  * (XXX Actually, given the current contents of valid_options[], there's
371  * no point in examining anything except the foreign table's own options.
372  * Simplify?)
373  */
374  table = GetForeignTable(foreigntableid);
375  server = GetForeignServer(table->serverid);
376  wrapper = GetForeignDataWrapper(server->fdwid);
377 
378  options = NIL;
379  options = list_concat(options, wrapper->options);
380  options = list_concat(options, server->options);
381  options = list_concat(options, table->options);
382  options = list_concat(options, get_file_fdw_attribute_options(foreigntableid));
383 
384  /*
385  * Separate out the filename or program option (we assume there is only
386  * one).
387  */
388  *filename = NULL;
389  *is_program = false;
390  foreach(lc, options)
391  {
392  DefElem *def = (DefElem *) lfirst(lc);
393 
394  if (strcmp(def->defname, "filename") == 0)
395  {
396  *filename = defGetString(def);
397  options = foreach_delete_current(options, lc);
398  break;
399  }
400  else if (strcmp(def->defname, "program") == 0)
401  {
402  *filename = defGetString(def);
403  *is_program = true;
404  options = foreach_delete_current(options, lc);
405  break;
406  }
407  }
408 
409  /*
410  * The validator should have checked that filename or program was included
411  * in the options, but check again, just in case.
412  */
413  if (*filename == NULL)
414  elog(ERROR, "either filename or program is required for file_fdw foreign tables");
415 
416  *other_options = options;
417 }
#define NIL
Definition: pg_list.h:65
static List * get_file_fdw_attribute_options(Oid relid)
Definition: file_fdw.c:428
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
ForeignTable * GetForeignTable(Oid relid)
Definition: foreign.c:248
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:368
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:35
#define ERROR
Definition: elog.h:43
char * defGetString(DefElem *def)
Definition: define.c:49
static char ** options
List * options
Definition: foreign.h:31
ForeignServer * GetForeignServer(Oid serverid)
Definition: foreign.c:109
#define lfirst(lc)
Definition: pg_list.h:190
Oid serverid
Definition: foreign.h:56
List * options
Definition: foreign.h:57
static char * filename
Definition: pg_dumpall.c:90
#define elog(elevel,...)
Definition: elog.h:214
char * defname
Definition: parsenodes.h:732
Definition: pg_list.h:50
List * options
Definition: foreign.h:42

◆ fileIsForeignScanParallelSafe()

static bool fileIsForeignScanParallelSafe ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 832 of file file_fdw.c.

Referenced by file_fdw_handler().

834 {
835  return true;
836 }

◆ fileIterateForeignScan()

static TupleTableSlot * fileIterateForeignScan ( ForeignScanState node)
static

Definition at line 705 of file file_fdw.c.

References ErrorContextCallback::callback, CopyFromErrorCallback(), FileFdwExecutionState::cstate, error_context_stack, ExecClearTuple(), ExecStoreVirtualTuple(), ForeignScanState::fdw_state, NextCopyFrom(), ErrorContextCallback::previous, ForeignScanState::ss, and ScanState::ss_ScanTupleSlot.

Referenced by file_fdw_handler().

706 {
708  TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
709  bool found;
710  ErrorContextCallback errcallback;
711 
712  /* Set up callback to identify error line number. */
713  errcallback.callback = CopyFromErrorCallback;
714  errcallback.arg = (void *) festate->cstate;
715  errcallback.previous = error_context_stack;
716  error_context_stack = &errcallback;
717 
718  /*
719  * The protocol for loading a virtual tuple into a slot is first
720  * ExecClearTuple, then fill the values/isnull arrays, then
721  * ExecStoreVirtualTuple. If we don't find another row in the file, we
722  * just skip the last step, leaving the slot empty as required.
723  *
724  * We can pass ExprContext = NULL because we read all columns from the
725  * file, so no need to evaluate default expressions.
726  *
727  * We can also pass tupleOid = NULL because we don't allow oids for
728  * foreign tables.
729  */
730  ExecClearTuple(slot);
731  found = NextCopyFrom(festate->cstate, NULL,
732  slot->tts_values, slot->tts_isnull);
733  if (found)
734  ExecStoreVirtualTuple(slot);
735 
736  /* Remove error callback. */
737  error_context_stack = errcallback.previous;
738 
739  return slot;
740 }
ScanState ss
Definition: execnodes.h:1794
void CopyFromErrorCallback(void *arg)
Definition: copy.c:2234
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1335
void(* callback)(void *arg)
Definition: elog.h:229
struct ErrorContextCallback * previous
Definition: elog.h:228
ErrorContextCallback * error_context_stack
Definition: elog.c:92
bool NextCopyFrom(CopyState cstate, ExprContext *econtext, Datum *values, bool *nulls)
Definition: copy.c:3635
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1522

◆ fileReScanForeignScan()

static void fileReScanForeignScan ( ForeignScanState node)
static

Definition at line 747 of file file_fdw.c.

References BeginCopyFrom(), FileFdwExecutionState::cstate, EndCopyFrom(), ForeignScanState::fdw_state, FileFdwExecutionState::filename, FileFdwExecutionState::is_program, NIL, FileFdwExecutionState::options, ForeignScanState::ss, and ScanState::ss_currentRelation.

Referenced by file_fdw_handler().

748 {
750 
751  EndCopyFrom(festate->cstate);
752 
753  festate->cstate = BeginCopyFrom(NULL,
754  node->ss.ss_currentRelation,
755  festate->filename,
756  festate->is_program,
757  NULL,
758  NIL,
759  festate->options);
760 }
#define NIL
Definition: pg_list.h:65
ScanState ss
Definition: execnodes.h:1794
CopyState BeginCopyFrom(ParseState *pstate, Relation rel, const char *filename, bool is_program, copy_data_source_cb data_source_cb, List *attnamelist, List *options)
Definition: copy.c:3334
Relation ss_currentRelation
Definition: execnodes.h:1333
void EndCopyFrom(CopyState cstate)
Definition: copy.c:3823

◆ get_file_fdw_attribute_options()

static List * get_file_fdw_attribute_options ( Oid  relid)
static

Definition at line 428 of file file_fdw.c.

References AccessShareLock, attname, attnum, defGetBoolean(), DefElem::defname, GetForeignColumnOptions(), lappend(), lfirst, makeDefElem(), makeString(), NameStr, TupleDescData::natts, NIL, options, pstrdup(), RelationGetDescr, table_close(), table_open(), and TupleDescAttr.

Referenced by fileGetOptions().

429 {
430  Relation rel;
431  TupleDesc tupleDesc;
432  AttrNumber natts;
434  List *fnncolumns = NIL;
435  List *fncolumns = NIL;
436 
437  List *options = NIL;
438 
439  rel = table_open(relid, AccessShareLock);
440  tupleDesc = RelationGetDescr(rel);
441  natts = tupleDesc->natts;
442 
443  /* Retrieve FDW options for all user-defined attributes. */
444  for (attnum = 1; attnum <= natts; attnum++)
445  {
446  Form_pg_attribute attr = TupleDescAttr(tupleDesc, attnum - 1);
447  List *options;
448  ListCell *lc;
449 
450  /* Skip dropped attributes. */
451  if (attr->attisdropped)
452  continue;
453 
454  options = GetForeignColumnOptions(relid, attnum);
455  foreach(lc, options)
456  {
457  DefElem *def = (DefElem *) lfirst(lc);
458 
459  if (strcmp(def->defname, "force_not_null") == 0)
460  {
461  if (defGetBoolean(def))
462  {
463  char *attname = pstrdup(NameStr(attr->attname));
464 
465  fnncolumns = lappend(fnncolumns, makeString(attname));
466  }
467  }
468  else if (strcmp(def->defname, "force_null") == 0)
469  {
470  if (defGetBoolean(def))
471  {
472  char *attname = pstrdup(NameStr(attr->attname));
473 
474  fncolumns = lappend(fncolumns, makeString(attname));
475  }
476  }
477  /* maybe in future handle other options here */
478  }
479  }
480 
482 
483  /*
484  * Return DefElem only when some column(s) have force_not_null /
485  * force_null options set
486  */
487  if (fnncolumns != NIL)
488  options = lappend(options, makeDefElem("force_not_null", (Node *) fnncolumns, -1));
489 
490  if (fncolumns != NIL)
491  options = lappend(options, makeDefElem("force_null", (Node *) fncolumns, -1));
492 
493  return options;
494 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define RelationGetDescr(relation)
Definition: rel.h:482
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:529
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:544
bool defGetBoolean(DefElem *def)
Definition: define.c:111
List * GetForeignColumnOptions(Oid relid, AttrNumber attnum)
Definition: foreign.c:286
NameData attname
Definition: pg_attribute.h:40
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
List * lappend(List *list, void *datum)
Definition: list.c:321
static char ** options
int16 attnum
Definition: pg_attribute.h:79
#define lfirst(lc)
Definition: pg_list.h:190
#define NameStr(name)
Definition: c.h:615
char * defname
Definition: parsenodes.h:732
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21

◆ is_valid_option()

static bool is_valid_option ( const char *  option,
Oid  context 
)
static

Definition at line 338 of file file_fdw.c.

References FileFdwOption::optcontext, and FileFdwOption::optname.

Referenced by file_fdw_validator().

339 {
340  const struct FileFdwOption *opt;
341 
342  for (opt = valid_options; opt->optname; opt++)
343  {
344  if (context == opt->optcontext && strcmp(opt->optname, option) == 0)
345  return true;
346  }
347  return false;
348 }
Oid optcontext
Definition: file_fdw.c:49
static const struct FileFdwOption valid_options[]
Definition: file_fdw.c:61
const char * optname
Definition: file_fdw.c:48

◆ PG_FUNCTION_INFO_V1() [1/2]

PG_FUNCTION_INFO_V1 ( file_fdw_handler  )

◆ PG_FUNCTION_INFO_V1() [2/2]

PG_FUNCTION_INFO_V1 ( file_fdw_validator  )

Variable Documentation

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 41 of file file_fdw.c.

◆ valid_options

const struct FileFdwOption valid_options[]
static
Initial value:
= {
{"filename", ForeignTableRelationId},
{"program", ForeignTableRelationId},
{"format", ForeignTableRelationId},
{"header", ForeignTableRelationId},
{"delimiter", ForeignTableRelationId},
{"quote", ForeignTableRelationId},
{"escape", ForeignTableRelationId},
{"null", ForeignTableRelationId},
{"encoding", ForeignTableRelationId},
{"force_not_null", AttributeRelationId},
{"force_null", AttributeRelationId},
{NULL, InvalidOid}
}
#define InvalidOid
Definition: postgres_ext.h:36

Definition at line 61 of file file_fdw.c.