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 "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/cost.h"
#include "optimizer/pathnode.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/var.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 847 of file file_fdw.c.

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

Referenced by fileGetForeignPaths().

850 {
851  ForeignTable *table;
852  ListCell *lc;
853  Relation rel;
856  Bitmapset *attrs_used = NULL;
857  bool has_wholerow = false;
858  int numattrs;
859  int i;
860 
861  *columns = NIL; /* default result */
862 
863  /*
864  * Check format of the file. If binary format, this is irrelevant.
865  */
866  table = GetForeignTable(foreigntableid);
867  foreach(lc, table->options)
868  {
869  DefElem *def = (DefElem *) lfirst(lc);
870 
871  if (strcmp(def->defname, "format") == 0)
872  {
873  char *format = defGetString(def);
874 
875  if (strcmp(format, "binary") == 0)
876  return false;
877  break;
878  }
879  }
880 
881  /* Collect all the attributes needed for joins or final output. */
882  pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid,
883  &attrs_used);
884 
885  /* Add all the attributes used by restriction clauses. */
886  foreach(lc, baserel->baserestrictinfo)
887  {
888  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
889 
890  pull_varattnos((Node *) rinfo->clause, baserel->relid,
891  &attrs_used);
892  }
893 
894  /* Convert attribute numbers to column names. */
895  rel = heap_open(foreigntableid, AccessShareLock);
896  tupleDesc = RelationGetDescr(rel);
897 
898  while ((attnum = bms_first_member(attrs_used)) >= 0)
899  {
900  /* Adjust for system attributes. */
902 
903  if (attnum == 0)
904  {
905  has_wholerow = true;
906  break;
907  }
908 
909  /* Ignore system attributes. */
910  if (attnum < 0)
911  continue;
912 
913  /* Get user attributes. */
914  if (attnum > 0)
915  {
916  Form_pg_attribute attr = TupleDescAttr(tupleDesc, attnum - 1);
917  char *attname = NameStr(attr->attname);
918 
919  /* Skip dropped attributes (probably shouldn't see any here). */
920  if (attr->attisdropped)
921  continue;
922  *columns = lappend(*columns, makeString(pstrdup(attname)));
923  }
924  }
925 
926  /* Count non-dropped user attributes while we have the tupdesc. */
927  numattrs = 0;
928  for (i = 0; i < tupleDesc->natts; i++)
929  {
930  Form_pg_attribute attr = TupleDescAttr(tupleDesc, i);
931 
932  if (attr->attisdropped)
933  continue;
934  numattrs++;
935  }
936 
938 
939  /* If there's a whole-row reference, fail: we need all the columns. */
940  if (has_wholerow)
941  {
942  *columns = NIL;
943  return false;
944  }
945 
946  /* If all the user attributes are needed, fail. */
947  if (numattrs == list_length(*columns))
948  {
949  *columns = NIL;
950  return false;
951  }
952 
953  return true;
954 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
int bms_first_member(Bitmapset *a)
Definition: bitmapset.c:1023
#define RelationGetDescr(relation)
Definition: rel.h:433
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
char * pstrdup(const char *in)
Definition: mcxt.c:1161
List * baserestrictinfo
Definition: relation.h:672
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:517
ForeignTable * GetForeignTable(Oid relid)
Definition: foreign.c:216
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
#define heap_close(r, l)
Definition: heapam.h:97
int natts
Definition: tupdesc.h:82
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:197
Index relid
Definition: relation.h:640
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1880
List * exprs
Definition: relation.h:1008
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
int16 attnum
Definition: pg_attribute.h:79
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
List * options
Definition: foreign.h:68
int i
#define NameStr(name)
Definition: c.h:576
char * defname
Definition: parsenodes.h:730
static char format
Definition: pg_basebackup.c:83
struct PathTarget * reltarget
Definition: relation.h:623
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 1045 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().

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

◆ estimate_size()

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

Definition at line 964 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().

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

◆ 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 1088 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(), tupleDesc::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().

1091 {
1092  int numrows = 0;
1093  double rowstoskip = -1; /* -1 means not set yet */
1094  ReservoirStateData rstate;
1095  TupleDesc tupDesc;
1096  Datum *values;
1097  bool *nulls;
1098  bool found;
1099  char *filename;
1100  bool is_program;
1101  List *options;
1102  CopyState cstate;
1103  ErrorContextCallback errcallback;
1104  MemoryContext oldcontext = CurrentMemoryContext;
1105  MemoryContext tupcontext;
1106 
1107  Assert(onerel);
1108  Assert(targrows > 0);
1109 
1110  tupDesc = RelationGetDescr(onerel);
1111  values = (Datum *) palloc(tupDesc->natts * sizeof(Datum));
1112  nulls = (bool *) palloc(tupDesc->natts * sizeof(bool));
1113 
1114  /* Fetch options of foreign table */
1115  fileGetOptions(RelationGetRelid(onerel), &filename, &is_program, &options);
1116 
1117  /*
1118  * Create CopyState from FDW options.
1119  */
1120  cstate = BeginCopyFrom(NULL, onerel, filename, is_program, NULL, NIL,
1121  options);
1122 
1123  /*
1124  * Use per-tuple memory context to prevent leak of memory used to read
1125  * rows from the file with Copy routines.
1126  */
1128  "file_fdw temporary context",
1130 
1131  /* Prepare for sampling rows */
1132  reservoir_init_selection_state(&rstate, targrows);
1133 
1134  /* Set up callback to identify error line number. */
1135  errcallback.callback = CopyFromErrorCallback;
1136  errcallback.arg = (void *) cstate;
1137  errcallback.previous = error_context_stack;
1138  error_context_stack = &errcallback;
1139 
1140  *totalrows = 0;
1141  *totaldeadrows = 0;
1142  for (;;)
1143  {
1144  /* Check for user-requested abort or sleep */
1146 
1147  /* Fetch next row */
1148  MemoryContextReset(tupcontext);
1149  MemoryContextSwitchTo(tupcontext);
1150 
1151  found = NextCopyFrom(cstate, NULL, values, nulls, NULL);
1152 
1153  MemoryContextSwitchTo(oldcontext);
1154 
1155  if (!found)
1156  break;
1157 
1158  /*
1159  * The first targrows sample rows are simply copied into the
1160  * reservoir. Then we start replacing tuples in the sample until we
1161  * reach the end of the relation. This algorithm is from Jeff Vitter's
1162  * paper (see more info in commands/analyze.c).
1163  */
1164  if (numrows < targrows)
1165  {
1166  rows[numrows++] = heap_form_tuple(tupDesc, values, nulls);
1167  }
1168  else
1169  {
1170  /*
1171  * t in Vitter's paper is the number of records already processed.
1172  * If we need to compute a new S value, we must use the
1173  * not-yet-incremented value of totalrows as t.
1174  */
1175  if (rowstoskip < 0)
1176  rowstoskip = reservoir_get_next_S(&rstate, *totalrows, targrows);
1177 
1178  if (rowstoskip <= 0)
1179  {
1180  /*
1181  * Found a suitable tuple, so save it, replacing one old tuple
1182  * at random
1183  */
1184  int k = (int) (targrows * sampler_random_fract(rstate.randstate));
1185 
1186  Assert(k >= 0 && k < targrows);
1187  heap_freetuple(rows[k]);
1188  rows[k] = heap_form_tuple(tupDesc, values, nulls);
1189  }
1190 
1191  rowstoskip -= 1;
1192  }
1193 
1194  *totalrows += 1;
1195  }
1196 
1197  /* Remove error callback. */
1198  error_context_stack = errcallback.previous;
1199 
1200  /* Clean up. */
1201  MemoryContextDelete(tupcontext);
1202 
1203  EndCopyFrom(cstate);
1204 
1205  pfree(values);
1206  pfree(nulls);
1207 
1208  /*
1209  * Emit some interesting relation info
1210  */
1211  ereport(elevel,
1212  (errmsg("\"%s\": file contains %.0f rows; "
1213  "%d rows in sample",
1214  RelationGetRelationName(onerel),
1215  *totalrows, numrows)));
1216 
1217  return numrows;
1218 }
#define NIL
Definition: pg_list.h:69
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
void CopyFromErrorCallback(void *arg)
Definition: copy.c:2192
#define RelationGetDescr(relation)
Definition: rel.h:433
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:2986
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
double sampler_random_fract(SamplerRandomState randstate)
Definition: sampling.c:238
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:136
void reservoir_init_selection_state(ReservoirState rs, int n)
Definition: sampling.c:129
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1074
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1773
void(* callback)(void *arg)
Definition: elog.h:239
struct ErrorContextCallback * previous
Definition: elog.h:238
int natts
Definition: tupdesc.h:82
ErrorContextCallback * error_context_stack
Definition: elog.c:88
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define RelationGetRelationName(relation)
Definition: rel.h:441
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define ereport(elevel, rest)
Definition: elog.h:122
static void fileGetOptions(Oid foreigntableid, char **filename, bool *is_program, List **other_options)
Definition: file_fdw.c:356
static char ** options
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:170
static int elevel
Definition: vacuumlazy.c:144
uintptr_t Datum
Definition: postgres.h:365
void EndCopyFrom(CopyState cstate)
Definition: copy.c:3538
#define Assert(condition)
Definition: c.h:699
static Datum values[MAXATTR]
Definition: bootstrap.c:164
static char * filename
Definition: pg_dumpall.c:87
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool NextCopyFrom(CopyState cstate, ExprContext *econtext, Datum *values, bool *nulls, Oid *tupleOid)
Definition: copy.c:3297
void vacuum_delay_point(void)
Definition: vacuum.c:1672
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:407
SamplerRandomState randstate
Definition: sampling.h:50
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:142

◆ file_fdw_handler()

Datum file_fdw_handler ( PG_FUNCTION_ARGS  )

Definition at line 170 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.

171 {
172  FdwRoutine *fdwroutine = makeNode(FdwRoutine);
173 
175  fdwroutine->GetForeignPaths = fileGetForeignPaths;
176  fdwroutine->GetForeignPlan = fileGetForeignPlan;
181  fdwroutine->EndForeignScan = fileEndForeignScan;
184 
185  PG_RETURN_POINTER(fdwroutine);
186 }
GetForeignPlan_function GetForeignPlan
Definition: fdwapi.h:189
BeginForeignScan_function BeginForeignScan
Definition: fdwapi.h:190
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:326
static bool fileIsForeignScanParallelSafe(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: file_fdw.c:831
static void fileEndForeignScan(ForeignScanState *node)
Definition: file_fdw.c:766
ExplainForeignScan_function ExplainForeignScan
Definition: fdwapi.h:228
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:233
IsForeignScanParallelSafe_function IsForeignScanParallelSafe
Definition: fdwapi.h:239
static TupleTableSlot * fileIterateForeignScan(ForeignScanState *node)
Definition: file_fdw.c:703
GetForeignRelSize_function GetForeignRelSize
Definition: fdwapi.h:187
EndForeignScan_function EndForeignScan
Definition: fdwapi.h:193
static bool fileAnalyzeForeignTable(Relation relation, AcquireSampleRowsFunc *func, BlockNumber *totalpages)
Definition: file_fdw.c:780
static void fileBeginForeignScan(ForeignScanState *node, int eflags)
Definition: file_fdw.c:650
GetForeignPaths_function GetForeignPaths
Definition: fdwapi.h:188
static void fileGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
Definition: file_fdw.c:534
#define makeNode(_type_)
Definition: nodes.h:565
static void fileGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
Definition: file_fdw.c:503
ReScanForeignScan_function ReScanForeignScan
Definition: fdwapi.h:192
IterateForeignScan_function IterateForeignScan
Definition: fdwapi.h:191
static void fileExplainForeignScan(ForeignScanState *node, ExplainState *es)
Definition: file_fdw.c:618
static void fileReScanForeignScan(ForeignScanState *node)
Definition: file_fdw.c:746
static ForeignScan * fileGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid, ForeignPath *best_path, List *tlist, List *scan_clauses, Plan *outer_plan)
Definition: file_fdw.c:583

◆ file_fdw_validator()

Datum file_fdw_validator ( PG_FUNCTION_ARGS  )

Definition at line 195 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().

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

◆ fileAnalyzeForeignTable()

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

Definition at line 780 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().

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

◆ fileBeginForeignScan()

static void fileBeginForeignScan ( ForeignScanState node,
int  eflags 
)
static

Definition at line 650 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().

651 {
652  ForeignScan *plan = (ForeignScan *) node->ss.ps.plan;
653  char *filename;
654  bool is_program;
655  List *options;
656  CopyState cstate;
657  FileFdwExecutionState *festate;
658 
659  /*
660  * Do nothing in EXPLAIN (no ANALYZE) case. node->fdw_state stays NULL.
661  */
662  if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
663  return;
664 
665  /* Fetch options of foreign table */
667  &filename, &is_program, &options);
668 
669  /* Add any options from the plan (currently only convert_selectively) */
671 
672  /*
673  * Create CopyState from FDW options. We always acquire all columns, so
674  * as to match the expected ScanTupleSlot signature.
675  */
676  cstate = BeginCopyFrom(NULL,
677  node->ss.ss_currentRelation,
678  filename,
679  is_program,
680  NULL,
681  NIL,
682  options);
683 
684  /*
685  * Save state in node->fdw_state. We must save enough information to call
686  * BeginCopyFrom() again.
687  */
688  festate = (FileFdwExecutionState *) palloc(sizeof(FileFdwExecutionState));
689  festate->filename = filename;
690  festate->is_program = is_program;
691  festate->options = options;
692  festate->cstate = cstate;
693 
694  node->fdw_state = (void *) festate;
695 }
#define NIL
Definition: pg_list.h:69
ScanState ss
Definition: execnodes.h:1640
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:2986
List * fdw_private
Definition: plannodes.h:615
List * list_concat(List *list1, List *list2)
Definition: list.c:321
Relation ss_currentRelation
Definition: execnodes.h:1192
PlanState ps
Definition: execnodes.h:1191
static void fileGetOptions(Oid foreigntableid, char **filename, bool *is_program, List **other_options)
Definition: file_fdw.c:356
static char ** options
Plan * plan
Definition: execnodes.h:911
static char * filename
Definition: pg_dumpall.c:87
void * palloc(Size size)
Definition: mcxt.c:924
Definition: pg_list.h:45
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:58
#define RelationGetRelid(relation)
Definition: rel.h:407

◆ fileEndForeignScan()

static void fileEndForeignScan ( ForeignScanState node)
static

Definition at line 766 of file file_fdw.c.

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

Referenced by file_fdw_handler().

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

◆ fileExplainForeignScan()

static void fileExplainForeignScan ( ForeignScanState node,
ExplainState es 
)
static

Definition at line 618 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().

619 {
620  char *filename;
621  bool is_program;
622  List *options;
623 
624  /* Fetch options --- we only need filename and is_program at this point */
626  &filename, &is_program, &options);
627 
628  if (is_program)
629  ExplainPropertyText("Foreign Program", filename, es);
630  else
631  ExplainPropertyText("Foreign File", filename, es);
632 
633  /* Suppress file size if we're not showing cost details */
634  if (es->costs)
635  {
636  struct stat stat_buf;
637 
638  if (!is_program &&
639  stat(filename, &stat_buf) == 0)
640  ExplainPropertyInteger("Foreign File Size", "b",
641  (int64) stat_buf.st_size, es);
642  }
643 }
ScanState ss
Definition: execnodes.h:1640
void ExplainPropertyInteger(const char *qlabel, const char *unit, int64 value, ExplainState *es)
Definition: explain.c:3411
Relation ss_currentRelation
Definition: execnodes.h:1192
bool costs
Definition: explain.h:34
void ExplainPropertyText(const char *qlabel, const char *value, ExplainState *es)
Definition: explain.c:3402
struct stat stat_buf
Definition: pg_standby.c:103
static void fileGetOptions(Oid foreigntableid, char **filename, bool *is_program, List **other_options)
Definition: file_fdw.c:356
static char ** options
#define stat(a, b)
Definition: win32_port.h:266
static char * filename
Definition: pg_dumpall.c:87
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:407

◆ fileGetForeignPaths()

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

Definition at line 534 of file file_fdw.c.

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

Referenced by file_fdw_handler().

537 {
538  FileFdwPlanState *fdw_private = (FileFdwPlanState *) baserel->fdw_private;
539  Cost startup_cost;
540  Cost total_cost;
541  List *columns;
542  List *coptions = NIL;
543 
544  /* Decide whether to selectively perform binary conversion */
546  foreigntableid,
547  &columns))
548  coptions = list_make1(makeDefElem("convert_selectively",
549  (Node *) columns, -1));
550 
551  /* Estimate costs */
552  estimate_costs(root, baserel, fdw_private,
553  &startup_cost, &total_cost);
554 
555  /*
556  * Create a ForeignPath node and add it as only possible path. We use the
557  * fdw_private list of the path to carry the convert_selectively option;
558  * it will be propagated into the fdw_private list of the Plan node.
559  */
560  add_path(baserel, (Path *)
561  create_foreignscan_path(root, baserel,
562  NULL, /* default pathtarget */
563  baserel->rows,
564  startup_cost,
565  total_cost,
566  NIL, /* no pathkeys */
567  NULL, /* no outer rel either */
568  NULL, /* no extra plan */
569  coptions));
570 
571  /*
572  * If data file was sorted, and we knew it somehow, we could insert
573  * appropriate pathkeys into the ForeignPath node to tell the planner
574  * that.
575  */
576 }
#define NIL
Definition: pg_list.h:69
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
Definition: nodes.h:517
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
#define list_make1(x1)
Definition: pg_list.h:139
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:2056
double rows
Definition: relation.h:615
void * fdw_private
Definition: relation.h:664
static bool check_selective_binary_conversion(RelOptInfo *baserel, Oid foreigntableid, List **columns)
Definition: file_fdw.c:847
static void estimate_costs(PlannerInfo *root, RelOptInfo *baserel, FileFdwPlanState *fdw_private, Cost *startup_cost, Cost *total_cost)
Definition: file_fdw.c:1045
Definition: pg_list.h:45
double Cost
Definition: nodes.h:648

◆ 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 583 of file file_fdw.c.

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

Referenced by file_fdw_handler().

590 {
591  Index scan_relid = baserel->relid;
592 
593  /*
594  * We have no native ability to evaluate restriction clauses, so we just
595  * put all the scan_clauses into the plan node's qual list for the
596  * executor to check. So all we have to do here is strip RestrictInfo
597  * nodes from the clauses and ignore pseudoconstants (which will be
598  * handled elsewhere).
599  */
600  scan_clauses = extract_actual_clauses(scan_clauses, false);
601 
602  /* Create the ForeignScan node */
603  return make_foreignscan(tlist,
604  scan_clauses,
605  scan_relid,
606  NIL, /* no expressions to evaluate */
607  best_path->fdw_private,
608  NIL, /* no custom tlist */
609  NIL, /* no remote quals */
610  outer_plan);
611 }
#define NIL
Definition: pg_list.h:69
Index relid
Definition: relation.h:640
unsigned int Index
Definition: c.h:442
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:356
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:5383
List * fdw_private
Definition: relation.h:1256

◆ fileGetForeignRelSize()

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

Definition at line 503 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().

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

◆ fileGetOptions()

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

Definition at line 356 of file file_fdw.c.

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

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

358 {
359  ForeignTable *table;
360  ForeignServer *server;
361  ForeignDataWrapper *wrapper;
362  List *options;
363  ListCell *lc,
364  *prev;
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  prev = NULL;
391  foreach(lc, options)
392  {
393  DefElem *def = (DefElem *) lfirst(lc);
394 
395  if (strcmp(def->defname, "filename") == 0)
396  {
397  *filename = defGetString(def);
398  options = list_delete_cell(options, lc, prev);
399  break;
400  }
401  else if (strcmp(def->defname, "program") == 0)
402  {
403  *filename = defGetString(def);
404  *is_program = true;
405  options = list_delete_cell(options, lc, prev);
406  break;
407  }
408  prev = lc;
409  }
410 
411  /*
412  * The validator should have checked that filename or program was included
413  * in the options, but check again, just in case.
414  */
415  if (*filename == NULL)
416  elog(ERROR, "either filename or program is required for file_fdw foreign tables");
417 
418  *other_options = options;
419 }
#define NIL
Definition: pg_list.h:69
static List * get_file_fdw_attribute_options(Oid relid)
Definition: file_fdw.c:430
ForeignTable * GetForeignTable(Oid relid)
Definition: foreign.c:216
List * list_concat(List *list1, List *list2)
Definition: list.c:321
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:42
List * list_delete_cell(List *list, ListCell *cell, ListCell *prev)
Definition: list.c:528
ForeignServer * GetForeignServer(Oid serverid)
Definition: foreign.c:93
#define lfirst(lc)
Definition: pg_list.h:106
Oid serverid
Definition: foreign.h:67
List * options
Definition: foreign.h:68
static char * filename
Definition: pg_dumpall.c:87
char * defname
Definition: parsenodes.h:730
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
List * options
Definition: foreign.h:53

◆ fileIsForeignScanParallelSafe()

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

Definition at line 831 of file file_fdw.c.

Referenced by file_fdw_handler().

833 {
834  return true;
835 }

◆ fileIterateForeignScan()

static TupleTableSlot * fileIterateForeignScan ( ForeignScanState node)
static

Definition at line 703 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().

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

◆ fileReScanForeignScan()

static void fileReScanForeignScan ( ForeignScanState node)
static

Definition at line 746 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().

747 {
749 
750  EndCopyFrom(festate->cstate);
751 
752  festate->cstate = BeginCopyFrom(NULL,
753  node->ss.ss_currentRelation,
754  festate->filename,
755  festate->is_program,
756  NULL,
757  NIL,
758  festate->options);
759 }
#define NIL
Definition: pg_list.h:69
ScanState ss
Definition: execnodes.h:1640
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:2986
Relation ss_currentRelation
Definition: execnodes.h:1192
void EndCopyFrom(CopyState cstate)
Definition: copy.c:3538

◆ get_file_fdw_attribute_options()

static List * get_file_fdw_attribute_options ( Oid  relid)
static

Definition at line 430 of file file_fdw.c.

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

Referenced by fileGetOptions().

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

◆ is_valid_option()

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

Definition at line 337 of file file_fdw.c.

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

Referenced by file_fdw_validator().

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

◆ 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 40 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 60 of file file_fdw.c.