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 "utils/varlena.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 875 of file file_fdw.c.

878 {
879  ForeignTable *table;
880  ListCell *lc;
881  Relation rel;
882  TupleDesc tupleDesc;
883  int attidx;
884  Bitmapset *attrs_used = NULL;
885  bool has_wholerow = false;
886  int numattrs;
887  int i;
888 
889  *columns = NIL; /* default result */
890 
891  /*
892  * Check format of the file. If binary format, this is irrelevant.
893  */
894  table = GetForeignTable(foreigntableid);
895  foreach(lc, table->options)
896  {
897  DefElem *def = (DefElem *) lfirst(lc);
898 
899  if (strcmp(def->defname, "format") == 0)
900  {
901  char *format = defGetString(def);
902 
903  if (strcmp(format, "binary") == 0)
904  return false;
905  break;
906  }
907  }
908 
909  /* Collect all the attributes needed for joins or final output. */
910  pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid,
911  &attrs_used);
912 
913  /* Add all the attributes used by restriction clauses. */
914  foreach(lc, baserel->baserestrictinfo)
915  {
916  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
917 
918  pull_varattnos((Node *) rinfo->clause, baserel->relid,
919  &attrs_used);
920  }
921 
922  /* Convert attribute numbers to column names. */
923  rel = table_open(foreigntableid, AccessShareLock);
924  tupleDesc = RelationGetDescr(rel);
925 
926  attidx = -1;
927  while ((attidx = bms_next_member(attrs_used, attidx)) >= 0)
928  {
929  /* attidx is zero-based, attnum is the normal attribute number */
931 
932  if (attnum == 0)
933  {
934  has_wholerow = true;
935  break;
936  }
937 
938  /* Ignore system attributes. */
939  if (attnum < 0)
940  continue;
941 
942  /* Get user attributes. */
943  if (attnum > 0)
944  {
945  Form_pg_attribute attr = TupleDescAttr(tupleDesc, attnum - 1);
946  char *attname = NameStr(attr->attname);
947 
948  /* Skip dropped attributes (probably shouldn't see any here). */
949  if (attr->attisdropped)
950  continue;
951 
952  /*
953  * Skip generated columns (COPY won't accept them in the column
954  * list)
955  */
956  if (attr->attgenerated)
957  continue;
958  *columns = lappend(*columns, makeString(pstrdup(attname)));
959  }
960  }
961 
962  /* Count non-dropped user attributes while we have the tupdesc. */
963  numattrs = 0;
964  for (i = 0; i < tupleDesc->natts; i++)
965  {
966  Form_pg_attribute attr = TupleDescAttr(tupleDesc, i);
967 
968  if (attr->attisdropped)
969  continue;
970  numattrs++;
971  }
972 
974 
975  /* If there's a whole-row reference, fail: we need all the columns. */
976  if (has_wholerow)
977  {
978  *columns = NIL;
979  return false;
980  }
981 
982  /* If all the user attributes are needed, fail. */
983  if (numattrs == list_length(*columns))
984  {
985  *columns = NIL;
986  return false;
987  }
988 
989  return true;
990 }
int16 AttrNumber
Definition: attnum.h:21
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1306
#define NameStr(name)
Definition: c.h:746
char * defGetString(DefElem *def)
Definition: define.c:48
ForeignTable * GetForeignTable(Oid relid)
Definition: foreign.c:254
int i
Definition: isn.c:73
List * lappend(List *list, void *datum)
Definition: list.c:339
#define AccessShareLock
Definition: lockdefs.h:36
char * pstrdup(const char *in)
Definition: mcxt.c:1696
NameData attname
Definition: pg_attribute.h:41
int16 attnum
Definition: pg_attribute.h:74
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
static char format
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
#define RelationGetDescr(relation)
Definition: rel.h:531
char * defname
Definition: parsenodes.h:817
List * options
Definition: foreign.h:57
Definition: nodes.h:129
List * exprs
Definition: pathnodes.h:1539
List * baserestrictinfo
Definition: pathnodes.h:985
struct PathTarget * reltarget
Definition: pathnodes.h:893
Index relid
Definition: pathnodes.h:918
Expr * clause
Definition: pathnodes.h:2571
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
String * makeString(char *str)
Definition: value.c:63
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:296

References AccessShareLock, attname, attnum, RelOptInfo::baserestrictinfo, bms_next_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().

◆ estimate_costs()

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

Definition at line 1081 of file file_fdw.c.

1084 {
1085  BlockNumber pages = fdw_private->pages;
1086  double ntuples = fdw_private->ntuples;
1087  Cost run_cost = 0;
1088  Cost cpu_per_tuple;
1089 
1090  /*
1091  * We estimate costs almost the same way as cost_seqscan(), thus assuming
1092  * that I/O costs are equivalent to a regular table file of the same size.
1093  * However, we take per-tuple CPU costs as 10x of a seqscan, to account
1094  * for the cost of parsing records.
1095  *
1096  * In the case of a program source, this calculation is even more divorced
1097  * from reality, but we have no good alternative; and it's not clear that
1098  * the numbers we produce here matter much anyway, since there's only one
1099  * access path for the rel.
1100  */
1101  run_cost += seq_page_cost * pages;
1102 
1103  *startup_cost = baserel->baserestrictcost.startup;
1104  cpu_per_tuple = cpu_tuple_cost * 10 + baserel->baserestrictcost.per_tuple;
1105  run_cost += cpu_per_tuple * ntuples;
1106  *total_cost = *startup_cost + run_cost;
1107 }
uint32 BlockNumber
Definition: block.h:31
double cpu_tuple_cost
Definition: costsize.c:132
double seq_page_cost
Definition: costsize.c:130
double Cost
Definition: nodes.h:251
double ntuples
Definition: file_fdw.c:98
BlockNumber pages
Definition: file_fdw.c:97
Cost per_tuple
Definition: pathnodes.h:48
Cost startup
Definition: pathnodes.h:47
QualCost baserestrictcost
Definition: pathnodes.h:987

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

Referenced by fileGetForeignPaths().

◆ estimate_size()

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

Definition at line 1000 of file file_fdw.c.

1002 {
1003  struct stat stat_buf;
1004  BlockNumber pages;
1005  double ntuples;
1006  double nrows;
1007 
1008  /*
1009  * Get size of the file. It might not be there at plan time, though, in
1010  * which case we have to use a default estimate. We also have to fall
1011  * back to the default if using a program as the input.
1012  */
1013  if (fdw_private->is_program || stat(fdw_private->filename, &stat_buf) < 0)
1014  stat_buf.st_size = 10 * BLCKSZ;
1015 
1016  /*
1017  * Convert size to pages for use in I/O cost estimate later.
1018  */
1019  pages = (stat_buf.st_size + (BLCKSZ - 1)) / BLCKSZ;
1020  if (pages < 1)
1021  pages = 1;
1022  fdw_private->pages = pages;
1023 
1024  /*
1025  * Estimate the number of tuples in the file.
1026  */
1027  if (baserel->tuples >= 0 && baserel->pages > 0)
1028  {
1029  /*
1030  * We have # of pages and # of tuples from pg_class (that is, from a
1031  * previous ANALYZE), so compute a tuples-per-page estimate and scale
1032  * that by the current file size.
1033  */
1034  double density;
1035 
1036  density = baserel->tuples / (double) baserel->pages;
1037  ntuples = clamp_row_est(density * (double) pages);
1038  }
1039  else
1040  {
1041  /*
1042  * Otherwise we have to fake it. We back into this estimate using the
1043  * planner's idea of the relation width; which is bogus if not all
1044  * columns are being read, not to mention that the text representation
1045  * of a row probably isn't the same size as its internal
1046  * representation. Possibly we could do something better, but the
1047  * real answer to anyone who complains is "ANALYZE" ...
1048  */
1049  int tuple_width;
1050 
1051  tuple_width = MAXALIGN(baserel->reltarget->width) +
1053  ntuples = clamp_row_est((double) stat_buf.st_size /
1054  (double) tuple_width);
1055  }
1056  fdw_private->ntuples = ntuples;
1057 
1058  /*
1059  * Now estimate the number of rows returned by the scan after applying the
1060  * baserestrictinfo quals.
1061  */
1062  nrows = ntuples *
1064  baserel->baserestrictinfo,
1065  0,
1066  JOIN_INNER,
1067  NULL);
1068 
1069  nrows = clamp_row_est(nrows);
1070 
1071  /* Save the output-rows estimate for the planner */
1072  baserel->rows = nrows;
1073 }
#define MAXALIGN(LEN)
Definition: c.h:811
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:100
double clamp_row_est(double nrows)
Definition: costsize.c:213
#define SizeofHeapTupleHeader
Definition: htup_details.h:185
@ JOIN_INNER
Definition: nodes.h:293
tree ctl root
Definition: radixtree.h:1886
char * filename
Definition: file_fdw.c:93
Cardinality tuples
Definition: pathnodes.h:949
BlockNumber pages
Definition: pathnodes.h:948
Cardinality rows
Definition: pathnodes.h:877
__int64 st_size
Definition: win32_port.h:273

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

Referenced by fileGetForeignRelSize().

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

1127 {
1128  int numrows = 0;
1129  double rowstoskip = -1; /* -1 means not set yet */
1130  ReservoirStateData rstate;
1131  TupleDesc tupDesc;
1132  Datum *values;
1133  bool *nulls;
1134  bool found;
1135  char *filename;
1136  bool is_program;
1137  List *options;
1138  CopyFromState cstate;
1139  ErrorContextCallback errcallback;
1140  MemoryContext oldcontext = CurrentMemoryContext;
1141  MemoryContext tupcontext;
1142 
1143  Assert(onerel);
1144  Assert(targrows > 0);
1145 
1146  tupDesc = RelationGetDescr(onerel);
1147  values = (Datum *) palloc(tupDesc->natts * sizeof(Datum));
1148  nulls = (bool *) palloc(tupDesc->natts * sizeof(bool));
1149 
1150  /* Fetch options of foreign table */
1151  fileGetOptions(RelationGetRelid(onerel), &filename, &is_program, &options);
1152 
1153  /*
1154  * Create CopyState from FDW options.
1155  */
1156  cstate = BeginCopyFrom(NULL, onerel, NULL, filename, is_program, NULL, NIL,
1157  options);
1158 
1159  /*
1160  * Use per-tuple memory context to prevent leak of memory used to read
1161  * rows from the file with Copy routines.
1162  */
1164  "file_fdw temporary context",
1166 
1167  /* Prepare for sampling rows */
1168  reservoir_init_selection_state(&rstate, targrows);
1169 
1170  /* Set up callback to identify error line number. */
1171  errcallback.callback = CopyFromErrorCallback;
1172  errcallback.arg = (void *) cstate;
1173  errcallback.previous = error_context_stack;
1174  error_context_stack = &errcallback;
1175 
1176  *totalrows = 0;
1177  *totaldeadrows = 0;
1178  for (;;)
1179  {
1180  /* Check for user-requested abort or sleep */
1182 
1183  /* Fetch next row */
1184  MemoryContextReset(tupcontext);
1185  MemoryContextSwitchTo(tupcontext);
1186 
1187  found = NextCopyFrom(cstate, NULL, values, nulls);
1188 
1189  MemoryContextSwitchTo(oldcontext);
1190 
1191  if (!found)
1192  break;
1193 
1194  /*
1195  * The first targrows sample rows are simply copied into the
1196  * reservoir. Then we start replacing tuples in the sample until we
1197  * reach the end of the relation. This algorithm is from Jeff Vitter's
1198  * paper (see more info in commands/analyze.c).
1199  */
1200  if (numrows < targrows)
1201  {
1202  rows[numrows++] = heap_form_tuple(tupDesc, values, nulls);
1203  }
1204  else
1205  {
1206  /*
1207  * t in Vitter's paper is the number of records already processed.
1208  * If we need to compute a new S value, we must use the
1209  * not-yet-incremented value of totalrows as t.
1210  */
1211  if (rowstoskip < 0)
1212  rowstoskip = reservoir_get_next_S(&rstate, *totalrows, targrows);
1213 
1214  if (rowstoskip <= 0)
1215  {
1216  /*
1217  * Found a suitable tuple, so save it, replacing one old tuple
1218  * at random
1219  */
1220  int k = (int) (targrows * sampler_random_fract(&rstate.randstate));
1221 
1222  Assert(k >= 0 && k < targrows);
1223  heap_freetuple(rows[k]);
1224  rows[k] = heap_form_tuple(tupDesc, values, nulls);
1225  }
1226 
1227  rowstoskip -= 1;
1228  }
1229 
1230  *totalrows += 1;
1231  }
1232 
1233  /* Remove error callback. */
1234  error_context_stack = errcallback.previous;
1235 
1236  /* Clean up. */
1237  MemoryContextDelete(tupcontext);
1238 
1239  EndCopyFrom(cstate);
1240 
1241  pfree(values);
1242  pfree(nulls);
1243 
1244  /*
1245  * Emit some interesting relation info
1246  */
1247  ereport(elevel,
1248  (errmsg("\"%s\": file contains %.0f rows; "
1249  "%d rows in sample",
1250  RelationGetRelationName(onerel),
1251  *totalrows, numrows)));
1252 
1253  return numrows;
1254 }
static Datum values[MAXATTR]
Definition: bootstrap.c:150
#define Assert(condition)
Definition: c.h:858
CopyFromState BeginCopyFrom(ParseState *pstate, Relation rel, Node *whereClause, const char *filename, bool is_program, copy_data_source_cb data_source_cb, List *attnamelist, List *options)
Definition: copyfrom.c:1380
void EndCopyFrom(CopyFromState cstate)
Definition: copyfrom.c:1799
void CopyFromErrorCallback(void *arg)
Definition: copyfrom.c:115
bool NextCopyFrom(CopyFromState cstate, ExprContext *econtext, Datum *values, bool *nulls)
ErrorContextCallback * error_context_stack
Definition: elog.c:94
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ereport(elevel,...)
Definition: elog.h:149
static void fileGetOptions(Oid foreigntableid, char **filename, bool *is_program, List **other_options)
Definition: file_fdw.c:370
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1116
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:383
void pfree(void *pointer)
Definition: mcxt.c:1521
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
void * palloc(Size size)
Definition: mcxt.c:1317
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
static char * filename
Definition: pg_dumpall.c:119
static char ** options
uintptr_t Datum
Definition: postgres.h:64
MemoryContextSwitchTo(old_ctx)
#define RelationGetRelid(relation)
Definition: rel.h:505
#define RelationGetRelationName(relation)
Definition: rel.h:539
void reservoir_init_selection_state(ReservoirState rs, int n)
Definition: sampling.c:133
double sampler_random_fract(pg_prng_state *randstate)
Definition: sampling.c:241
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:147
struct ErrorContextCallback * previous
Definition: elog.h:296
void(* callback)(void *arg)
Definition: elog.h:297
Definition: pg_list.h:54
pg_prng_state randstate
Definition: sampling.h:49
void vacuum_delay_point(void)
Definition: vacuum.c:2337

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().

◆ file_fdw_handler()

Datum file_fdw_handler ( PG_FUNCTION_ARGS  )

Definition at line 173 of file file_fdw.c.

174 {
175  FdwRoutine *fdwroutine = makeNode(FdwRoutine);
176 
178  fdwroutine->GetForeignPaths = fileGetForeignPaths;
179  fdwroutine->GetForeignPlan = fileGetForeignPlan;
184  fdwroutine->EndForeignScan = fileEndForeignScan;
187 
188  PG_RETURN_POINTER(fdwroutine);
189 }
static ForeignScan * fileGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid, ForeignPath *best_path, List *tlist, List *scan_clauses, Plan *outer_plan)
Definition: file_fdw.c:600
static void fileEndForeignScan(ForeignScanState *node)
Definition: file_fdw.c:794
static void fileGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
Definition: file_fdw.c:514
static void fileExplainForeignScan(ForeignScanState *node, ExplainState *es)
Definition: file_fdw.c:635
static bool fileAnalyzeForeignTable(Relation relation, AcquireSampleRowsFunc *func, BlockNumber *totalpages)
Definition: file_fdw.c:808
static void fileReScanForeignScan(ForeignScanState *node)
Definition: file_fdw.c:773
static bool fileIsForeignScanParallelSafe(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: file_fdw.c:859
static void fileGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
Definition: file_fdw.c:545
static void fileBeginForeignScan(ForeignScanState *node, int eflags)
Definition: file_fdw.c:667
static TupleTableSlot * fileIterateForeignScan(ForeignScanState *node)
Definition: file_fdw.c:721
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:361
#define makeNode(_type_)
Definition: nodes.h:155
ReScanForeignScan_function ReScanForeignScan
Definition: fdwapi.h:214
BeginForeignScan_function BeginForeignScan
Definition: fdwapi.h:212
IsForeignScanParallelSafe_function IsForeignScanParallelSafe
Definition: fdwapi.h:266
GetForeignPaths_function GetForeignPaths
Definition: fdwapi.h:210
GetForeignRelSize_function GetForeignRelSize
Definition: fdwapi.h:209
ExplainForeignScan_function ExplainForeignScan
Definition: fdwapi.h:252
EndForeignScan_function EndForeignScan
Definition: fdwapi.h:215
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:257
IterateForeignScan_function IterateForeignScan
Definition: fdwapi.h:213
GetForeignPlan_function GetForeignPlan
Definition: fdwapi.h:211

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.

◆ file_fdw_validator()

Datum file_fdw_validator ( PG_FUNCTION_ARGS  )

Definition at line 198 of file file_fdw.c.

199 {
200  List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
201  Oid catalog = PG_GETARG_OID(1);
202  char *filename = NULL;
203  DefElem *force_not_null = NULL;
204  DefElem *force_null = NULL;
205  List *other_options = NIL;
206  ListCell *cell;
207 
208  /*
209  * Check that only options supported by file_fdw, and allowed for the
210  * current object type, are given.
211  */
212  foreach(cell, options_list)
213  {
214  DefElem *def = (DefElem *) lfirst(cell);
215 
216  if (!is_valid_option(def->defname, catalog))
217  {
218  const struct FileFdwOption *opt;
219  const char *closest_match;
221  bool has_valid_options = false;
222 
223  /*
224  * Unknown option specified, complain about it. Provide a hint
225  * with a valid option that looks similar, if there is one.
226  */
228  for (opt = valid_options; opt->optname; opt++)
229  {
230  if (catalog == opt->optcontext)
231  {
232  has_valid_options = true;
234  }
235  }
236 
237  closest_match = getClosestMatch(&match_state);
238  ereport(ERROR,
239  (errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
240  errmsg("invalid option \"%s\"", def->defname),
241  has_valid_options ? closest_match ?
242  errhint("Perhaps you meant the option \"%s\".",
243  closest_match) : 0 :
244  errhint("There are no valid options in this context.")));
245  }
246 
247  /*
248  * Separate out filename, program, and column-specific options, since
249  * ProcessCopyOptions won't accept them.
250  */
251  if (strcmp(def->defname, "filename") == 0 ||
252  strcmp(def->defname, "program") == 0)
253  {
254  if (filename)
255  ereport(ERROR,
256  (errcode(ERRCODE_SYNTAX_ERROR),
257  errmsg("conflicting or redundant options")));
258 
259  /*
260  * Check permissions for changing which file or program is used by
261  * the file_fdw.
262  *
263  * Only members of the role 'pg_read_server_files' are allowed to
264  * set the 'filename' option of a file_fdw foreign table, while
265  * only members of the role 'pg_execute_server_program' are
266  * allowed to set the 'program' option. This is because we don't
267  * want regular users to be able to control which file gets read
268  * or which program gets executed.
269  *
270  * Putting this sort of permissions check in a validator is a bit
271  * of a crock, but there doesn't seem to be any other place that
272  * can enforce the check more cleanly.
273  *
274  * Note that the valid_options[] array disallows setting filename
275  * and program at any options level other than foreign table ---
276  * otherwise there'd still be a security hole.
277  */
278  if (strcmp(def->defname, "filename") == 0 &&
279  !has_privs_of_role(GetUserId(), ROLE_PG_READ_SERVER_FILES))
280  ereport(ERROR,
281  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
282  errmsg("permission denied to set the \"%s\" option of a file_fdw foreign table",
283  "filename"),
284  errdetail("Only roles with privileges of the \"%s\" role may set this option.",
285  "pg_read_server_files")));
286 
287  if (strcmp(def->defname, "program") == 0 &&
288  !has_privs_of_role(GetUserId(), ROLE_PG_EXECUTE_SERVER_PROGRAM))
289  ereport(ERROR,
290  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
291  errmsg("permission denied to set the \"%s\" option of a file_fdw foreign table",
292  "program"),
293  errdetail("Only roles with privileges of the \"%s\" role may set this option.",
294  "pg_execute_server_program")));
295 
296  filename = defGetString(def);
297  }
298 
299  /*
300  * force_not_null is a boolean option; after validation we can discard
301  * it - it will be retrieved later in get_file_fdw_attribute_options()
302  */
303  else if (strcmp(def->defname, "force_not_null") == 0)
304  {
305  if (force_not_null)
306  ereport(ERROR,
307  (errcode(ERRCODE_SYNTAX_ERROR),
308  errmsg("conflicting or redundant options"),
309  errhint("Option \"force_not_null\" supplied more than once for a column.")));
310  force_not_null = def;
311  /* Don't care what the value is, as long as it's a legal boolean */
312  (void) defGetBoolean(def);
313  }
314  /* See comments for force_not_null above */
315  else if (strcmp(def->defname, "force_null") == 0)
316  {
317  if (force_null)
318  ereport(ERROR,
319  (errcode(ERRCODE_SYNTAX_ERROR),
320  errmsg("conflicting or redundant options"),
321  errhint("Option \"force_null\" supplied more than once for a column.")));
322  force_null = def;
323  (void) defGetBoolean(def);
324  }
325  else
326  other_options = lappend(other_options, def);
327  }
328 
329  /*
330  * Now apply the core COPY code's validation logic for more checks.
331  */
332  ProcessCopyOptions(NULL, NULL, true, other_options);
333 
334  /*
335  * Either filename or program option is required for file_fdw foreign
336  * tables.
337  */
338  if (catalog == ForeignTableRelationId && filename == NULL)
339  ereport(ERROR,
340  (errcode(ERRCODE_FDW_DYNAMIC_PARAMETER_VALUE_NEEDED),
341  errmsg("either filename or program is required for file_fdw foreign tables")));
342 
343  PG_RETURN_VOID();
344 }
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:5268
void ProcessCopyOptions(ParseState *pstate, CopyFormatOptions *opts_out, bool is_from, List *options)
Definition: copy.c:463
bool defGetBoolean(DefElem *def)
Definition: define.c:107
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:853
#define ERROR
Definition: elog.h:39
static const struct FileFdwOption valid_options[]
Definition: file_fdw.c:62
static bool is_valid_option(const char *option, Oid context)
Definition: file_fdw.c:351
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
struct parser_state match_state[5]
Oid GetUserId(void)
Definition: miscinit.c:514
unsigned int Oid
Definition: postgres_ext.h:31
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1331
Oid optcontext
Definition: file_fdw.c:50
const char * optname
Definition: file_fdw.c:49
const char * getClosestMatch(ClosestMatchState *state)
Definition: varlena.c:6218
void initClosestMatch(ClosestMatchState *state, const char *source, int max_d)
Definition: varlena.c:6163
void updateClosestMatch(ClosestMatchState *state, const char *candidate)
Definition: varlena.c:6183

References defGetBoolean(), defGetString(), DefElem::defname, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, filename, getClosestMatch(), GetUserId(), has_privs_of_role(), initClosestMatch(), is_valid_option(), lappend(), lfirst, match_state, NIL, FileFdwOption::optcontext, FileFdwOption::optname, PG_GETARG_DATUM, PG_GETARG_OID, PG_RETURN_VOID, ProcessCopyOptions(), untransformRelOptions(), updateClosestMatch(), and valid_options.

◆ fileAnalyzeForeignTable()

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

Definition at line 808 of file file_fdw.c.

811 {
812  char *filename;
813  bool is_program;
814  List *options;
815  struct stat stat_buf;
816 
817  /* Fetch options of foreign table */
818  fileGetOptions(RelationGetRelid(relation), &filename, &is_program, &options);
819 
820  /*
821  * If this is a program instead of a file, just return false to skip
822  * analyzing the table. We could run the program and collect stats on
823  * whatever it currently returns, but it seems likely that in such cases
824  * the output would be too volatile for the stats to be useful. Maybe
825  * there should be an option to enable doing this?
826  */
827  if (is_program)
828  return false;
829 
830  /*
831  * Get size of the file. (XXX if we fail here, would it be better to just
832  * return false to skip analyzing the table?)
833  */
834  if (stat(filename, &stat_buf) < 0)
835  ereport(ERROR,
837  errmsg("could not stat file \"%s\": %m",
838  filename)));
839 
840  /*
841  * Convert size to pages. Must return at least 1 so that we can tell
842  * later on that pg_class.relpages is not default.
843  */
844  *totalpages = (stat_buf.st_size + (BLCKSZ - 1)) / BLCKSZ;
845  if (*totalpages < 1)
846  *totalpages = 1;
847 
848  *func = file_acquire_sample_rows;
849 
850  return true;
851 }
int errcode_for_file_access(void)
Definition: elog.c:876
static int file_acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: file_fdw.c:1124
#define stat
Definition: win32_port.h:284

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

Referenced by file_fdw_handler().

◆ fileBeginForeignScan()

static void fileBeginForeignScan ( ForeignScanState node,
int  eflags 
)
static

Definition at line 667 of file file_fdw.c.

668 {
669  ForeignScan *plan = (ForeignScan *) node->ss.ps.plan;
670  char *filename;
671  bool is_program;
672  List *options;
673  CopyFromState cstate;
674  FileFdwExecutionState *festate;
675 
676  /*
677  * Do nothing in EXPLAIN (no ANALYZE) case. node->fdw_state stays NULL.
678  */
679  if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
680  return;
681 
682  /* Fetch options of foreign table */
684  &filename, &is_program, &options);
685 
686  /* Add any options from the plan (currently only convert_selectively) */
687  options = list_concat(options, plan->fdw_private);
688 
689  /*
690  * Create CopyState from FDW options. We always acquire all columns, so
691  * as to match the expected ScanTupleSlot signature.
692  */
693  cstate = BeginCopyFrom(NULL,
694  node->ss.ss_currentRelation,
695  NULL,
696  filename,
697  is_program,
698  NULL,
699  NIL,
700  options);
701 
702  /*
703  * Save state in node->fdw_state. We must save enough information to call
704  * BeginCopyFrom() again.
705  */
706  festate = (FileFdwExecutionState *) palloc(sizeof(FileFdwExecutionState));
707  festate->filename = filename;
708  festate->is_program = is_program;
709  festate->options = options;
710  festate->cstate = cstate;
711 
712  node->fdw_state = (void *) festate;
713 }
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:65
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
#define plan(x)
Definition: pg_regress.c:162
ScanState ss
Definition: execnodes.h:2068
Plan * plan
Definition: execnodes.h:1120
Relation ss_currentRelation
Definition: execnodes.h:1568
PlanState ps
Definition: execnodes.h:1567

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

Referenced by file_fdw_handler().

◆ fileEndForeignScan()

static void fileEndForeignScan ( ForeignScanState node)
static

Definition at line 794 of file file_fdw.c.

795 {
797 
798  /* if festate is NULL, we are in EXPLAIN; nothing to do */
799  if (festate)
800  EndCopyFrom(festate->cstate);
801 }
CopyFromState cstate
Definition: file_fdw.c:110

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

Referenced by file_fdw_handler().

◆ fileExplainForeignScan()

static void fileExplainForeignScan ( ForeignScanState node,
ExplainState es 
)
static

Definition at line 635 of file file_fdw.c.

636 {
637  char *filename;
638  bool is_program;
639  List *options;
640 
641  /* Fetch options --- we only need filename and is_program at this point */
643  &filename, &is_program, &options);
644 
645  if (is_program)
646  ExplainPropertyText("Foreign Program", filename, es);
647  else
648  ExplainPropertyText("Foreign File", filename, es);
649 
650  /* Suppress file size if we're not showing cost details */
651  if (es->costs)
652  {
653  struct stat stat_buf;
654 
655  if (!is_program &&
656  stat(filename, &stat_buf) == 0)
657  ExplainPropertyInteger("Foreign File Size", "b",
658  (int64) stat_buf.st_size, es);
659  }
660 }
void ExplainPropertyText(const char *qlabel, const char *value, ExplainState *es)
Definition: explain.c:4932
void ExplainPropertyInteger(const char *qlabel, const char *unit, int64 value, ExplainState *es)
Definition: explain.c:4941
bool costs
Definition: explain.h:50

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

Referenced by file_fdw_handler().

◆ fileGetForeignPaths()

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

Definition at line 545 of file file_fdw.c.

548 {
549  FileFdwPlanState *fdw_private = (FileFdwPlanState *) baserel->fdw_private;
550  Cost startup_cost;
551  Cost total_cost;
552  List *columns;
553  List *coptions = NIL;
554 
555  /* Decide whether to selectively perform binary conversion */
557  foreigntableid,
558  &columns))
559  coptions = list_make1(makeDefElem("convert_selectively",
560  (Node *) columns, -1));
561 
562  /* Estimate costs */
563  estimate_costs(root, baserel, fdw_private,
564  &startup_cost, &total_cost);
565 
566  /*
567  * Create a ForeignPath node and add it as only possible path. We use the
568  * fdw_private list of the path to carry the convert_selectively option;
569  * it will be propagated into the fdw_private list of the Plan node.
570  *
571  * We don't support pushing join clauses into the quals of this path, but
572  * it could still have required parameterization due to LATERAL refs in
573  * its tlist.
574  */
575  add_path(baserel, (Path *)
576  create_foreignscan_path(root, baserel,
577  NULL, /* default pathtarget */
578  baserel->rows,
579  0,
580  startup_cost,
581  total_cost,
582  NIL, /* no pathkeys */
583  baserel->lateral_relids,
584  NULL, /* no extra plan */
585  NIL, /* no fdw_restrictinfo list */
586  coptions));
587 
588  /*
589  * If data file was sorted, and we knew it somehow, we could insert
590  * appropriate pathkeys into the ForeignPath node to tell the planner
591  * that.
592  */
593 }
static bool check_selective_binary_conversion(RelOptInfo *baserel, Oid foreigntableid, List **columns)
Definition: file_fdw.c:875
static void estimate_costs(PlannerInfo *root, RelOptInfo *baserel, FileFdwPlanState *fdw_private, Cost *startup_cost, Cost *total_cost)
Definition: file_fdw.c:1081
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:564
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:461
ForeignPath * create_foreignscan_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, double rows, int disabled_nodes, Cost startup_cost, Cost total_cost, List *pathkeys, Relids required_outer, Path *fdw_outerpath, List *fdw_restrictinfo, List *fdw_private)
Definition: pathnode.c:2307
#define list_make1(x1)
Definition: pg_list.h:212
Relids lateral_relids
Definition: pathnodes.h:913

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

Referenced by file_fdw_handler().

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

607 {
608  Index scan_relid = baserel->relid;
609 
610  /*
611  * We have no native ability to evaluate restriction clauses, so we just
612  * put all the scan_clauses into the plan node's qual list for the
613  * executor to check. So all we have to do here is strip RestrictInfo
614  * nodes from the clauses and ignore pseudoconstants (which will be
615  * handled elsewhere).
616  */
617  scan_clauses = extract_actual_clauses(scan_clauses, false);
618 
619  /* Create the ForeignScan node */
620  return make_foreignscan(tlist,
621  scan_clauses,
622  scan_relid,
623  NIL, /* no expressions to evaluate */
624  best_path->fdw_private,
625  NIL, /* no custom tlist */
626  NIL, /* no remote quals */
627  outer_plan);
628 }
unsigned int Index
Definition: c.h:614
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:5822
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:494
List * fdw_private
Definition: pathnodes.h:1879

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

Referenced by file_fdw_handler().

◆ fileGetForeignRelSize()

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

Definition at line 514 of file file_fdw.c.

517 {
518  FileFdwPlanState *fdw_private;
519 
520  /*
521  * Fetch options. We only need filename (or program) at this point, but
522  * we might as well get everything and not need to re-fetch it later in
523  * planning.
524  */
525  fdw_private = (FileFdwPlanState *) palloc(sizeof(FileFdwPlanState));
526  fileGetOptions(foreigntableid,
527  &fdw_private->filename,
528  &fdw_private->is_program,
529  &fdw_private->options);
530  baserel->fdw_private = (void *) fdw_private;
531 
532  /* Estimate relation size */
533  estimate_size(root, baserel, fdw_private);
534 }
static void estimate_size(PlannerInfo *root, RelOptInfo *baserel, FileFdwPlanState *fdw_private)
Definition: file_fdw.c:1000
List * options
Definition: file_fdw.c:95

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

Referenced by file_fdw_handler().

◆ fileGetOptions()

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

Definition at line 370 of file file_fdw.c.

372 {
373  ForeignTable *table;
374  ForeignServer *server;
375  ForeignDataWrapper *wrapper;
376  List *options;
377  ListCell *lc;
378 
379  /*
380  * Extract options from FDW objects. We ignore user mappings because
381  * file_fdw doesn't have any options that can be specified there.
382  *
383  * (XXX Actually, given the current contents of valid_options[], there's
384  * no point in examining anything except the foreign table's own options.
385  * Simplify?)
386  */
387  table = GetForeignTable(foreigntableid);
388  server = GetForeignServer(table->serverid);
389  wrapper = GetForeignDataWrapper(server->fdwid);
390 
391  options = NIL;
392  options = list_concat(options, wrapper->options);
393  options = list_concat(options, server->options);
394  options = list_concat(options, table->options);
396 
397  /*
398  * Separate out the filename or program option (we assume there is only
399  * one).
400  */
401  *filename = NULL;
402  *is_program = false;
403  foreach(lc, options)
404  {
405  DefElem *def = (DefElem *) lfirst(lc);
406 
407  if (strcmp(def->defname, "filename") == 0)
408  {
409  *filename = defGetString(def);
411  break;
412  }
413  else if (strcmp(def->defname, "program") == 0)
414  {
415  *filename = defGetString(def);
416  *is_program = true;
418  break;
419  }
420  }
421 
422  /*
423  * The validator should have checked that filename or program was included
424  * in the options, but check again, just in case.
425  */
426  if (*filename == NULL)
427  elog(ERROR, "either filename or program is required for file_fdw foreign tables");
428 
429  *other_options = options;
430 }
#define elog(elevel,...)
Definition: elog.h:225
static List * get_file_fdw_attribute_options(Oid relid)
Definition: file_fdw.c:441
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:37
ForeignServer * GetForeignServer(Oid serverid)
Definition: foreign.c:111
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
List * options
Definition: foreign.h:31
List * options
Definition: foreign.h:42
Oid serverid
Definition: foreign.h:56

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

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

◆ fileIsForeignScanParallelSafe()

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

Definition at line 859 of file file_fdw.c.

861 {
862  return true;
863 }

Referenced by file_fdw_handler().

◆ fileIterateForeignScan()

static TupleTableSlot * fileIterateForeignScan ( ForeignScanState node)
static

Definition at line 721 of file file_fdw.c.

722 {
724  EState *estate = CreateExecutorState();
725  ExprContext *econtext;
726  MemoryContext oldcontext;
727  TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
728  bool found;
729  ErrorContextCallback errcallback;
730 
731  /* Set up callback to identify error line number. */
732  errcallback.callback = CopyFromErrorCallback;
733  errcallback.arg = (void *) festate->cstate;
734  errcallback.previous = error_context_stack;
735  error_context_stack = &errcallback;
736 
737  /*
738  * The protocol for loading a virtual tuple into a slot is first
739  * ExecClearTuple, then fill the values/isnull arrays, then
740  * ExecStoreVirtualTuple. If we don't find another row in the file, we
741  * just skip the last step, leaving the slot empty as required.
742  *
743  * We pass ExprContext because there might be a use of the DEFAULT option
744  * in COPY FROM, so we may need to evaluate default expressions.
745  */
746  ExecClearTuple(slot);
747  econtext = GetPerTupleExprContext(estate);
748 
749  /*
750  * DEFAULT expressions need to be evaluated in a per-tuple context, so
751  * switch in case we are doing that.
752  */
753  oldcontext = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
754  found = NextCopyFrom(festate->cstate, econtext,
755  slot->tts_values, slot->tts_isnull);
756  if (found)
757  ExecStoreVirtualTuple(slot);
758 
759  /* Switch back to original memory context */
760  MemoryContextSwitchTo(oldcontext);
761 
762  /* Remove error callback. */
763  error_context_stack = errcallback.previous;
764 
765  return slot;
766 }
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1639
EState * CreateExecutorState(void)
Definition: execUtils.c:88
#define GetPerTupleExprContext(estate)
Definition: executor.h:561
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:566
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1570
bool * tts_isnull
Definition: tuptable.h:127
Datum * tts_values
Definition: tuptable.h:125
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:454

References ErrorContextCallback::arg, ErrorContextCallback::callback, CopyFromErrorCallback(), CreateExecutorState(), FileFdwExecutionState::cstate, error_context_stack, ExecClearTuple(), ExecStoreVirtualTuple(), ForeignScanState::fdw_state, GetPerTupleExprContext, GetPerTupleMemoryContext, MemoryContextSwitchTo(), NextCopyFrom(), ErrorContextCallback::previous, ForeignScanState::ss, ScanState::ss_ScanTupleSlot, TupleTableSlot::tts_isnull, and TupleTableSlot::tts_values.

Referenced by file_fdw_handler().

◆ fileReScanForeignScan()

static void fileReScanForeignScan ( ForeignScanState node)
static

Definition at line 773 of file file_fdw.c.

774 {
776 
777  EndCopyFrom(festate->cstate);
778 
779  festate->cstate = BeginCopyFrom(NULL,
780  node->ss.ss_currentRelation,
781  NULL,
782  festate->filename,
783  festate->is_program,
784  NULL,
785  NIL,
786  festate->options);
787 }

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().

◆ get_file_fdw_attribute_options()

static List * get_file_fdw_attribute_options ( Oid  relid)
static

Definition at line 441 of file file_fdw.c.

442 {
443  Relation rel;
444  TupleDesc tupleDesc;
445  AttrNumber natts;
447  List *fnncolumns = NIL;
448  List *fncolumns = NIL;
449 
450  List *options = NIL;
451 
452  rel = table_open(relid, AccessShareLock);
453  tupleDesc = RelationGetDescr(rel);
454  natts = tupleDesc->natts;
455 
456  /* Retrieve FDW options for all user-defined attributes. */
457  for (attnum = 1; attnum <= natts; attnum++)
458  {
459  Form_pg_attribute attr = TupleDescAttr(tupleDesc, attnum - 1);
460  List *column_options;
461  ListCell *lc;
462 
463  /* Skip dropped attributes. */
464  if (attr->attisdropped)
465  continue;
466 
467  column_options = GetForeignColumnOptions(relid, attnum);
468  foreach(lc, column_options)
469  {
470  DefElem *def = (DefElem *) lfirst(lc);
471 
472  if (strcmp(def->defname, "force_not_null") == 0)
473  {
474  if (defGetBoolean(def))
475  {
476  char *attname = pstrdup(NameStr(attr->attname));
477 
478  fnncolumns = lappend(fnncolumns, makeString(attname));
479  }
480  }
481  else if (strcmp(def->defname, "force_null") == 0)
482  {
483  if (defGetBoolean(def))
484  {
485  char *attname = pstrdup(NameStr(attr->attname));
486 
487  fncolumns = lappend(fncolumns, makeString(attname));
488  }
489  }
490  /* maybe in future handle other column options here */
491  }
492  }
493 
495 
496  /*
497  * Return DefElem only when some column(s) have force_not_null /
498  * force_null options set
499  */
500  if (fnncolumns != NIL)
501  options = lappend(options, makeDefElem("force_not_null", (Node *) fnncolumns, -1));
502 
503  if (fncolumns != NIL)
504  options = lappend(options, makeDefElem("force_null", (Node *) fncolumns, -1));
505 
506  return options;
507 }
List * GetForeignColumnOptions(Oid relid, AttrNumber attnum)
Definition: foreign.c:292

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().

◆ is_valid_option()

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

Definition at line 351 of file file_fdw.c.

352 {
353  const struct FileFdwOption *opt;
354 
355  for (opt = valid_options; opt->optname; opt++)
356  {
357  if (context == opt->optcontext && strcmp(opt->optname, option) == 0)
358  return true;
359  }
360  return false;
361 }
tree context
Definition: radixtree.h:1835

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

Referenced by file_fdw_validator().

◆ 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 42 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},
{"default", ForeignTableRelationId},
{"encoding", ForeignTableRelationId},
{"force_not_null", AttributeRelationId},
{"force_null", AttributeRelationId},
{NULL, InvalidOid}
}
#define InvalidOid
Definition: postgres_ext.h:36

Definition at line 42 of file file_fdw.c.

Referenced by file_fdw_validator(), and is_valid_option().