PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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_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

Function Documentation

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

Definition at line 832 of file file_fdw.c.

References AccessShareLock, tupleDesc::attrs, 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, NULL, ForeignTable::options, pstrdup(), pull_varattnos(), RelationGetDescr, RelOptInfo::relid, and RelOptInfo::reltarget.

Referenced by fileGetForeignPaths().

835 {
836  ForeignTable *table;
837  ListCell *lc;
838  Relation rel;
840  AttrNumber attnum;
841  Bitmapset *attrs_used = NULL;
842  bool has_wholerow = false;
843  int numattrs;
844  int i;
845 
846  *columns = NIL; /* default result */
847 
848  /*
849  * Check format of the file. If binary format, this is irrelevant.
850  */
851  table = GetForeignTable(foreigntableid);
852  foreach(lc, table->options)
853  {
854  DefElem *def = (DefElem *) lfirst(lc);
855 
856  if (strcmp(def->defname, "format") == 0)
857  {
858  char *format = defGetString(def);
859 
860  if (strcmp(format, "binary") == 0)
861  return false;
862  break;
863  }
864  }
865 
866  /* Collect all the attributes needed for joins or final output. */
867  pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid,
868  &attrs_used);
869 
870  /* Add all the attributes used by restriction clauses. */
871  foreach(lc, baserel->baserestrictinfo)
872  {
873  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
874 
875  pull_varattnos((Node *) rinfo->clause, baserel->relid,
876  &attrs_used);
877  }
878 
879  /* Convert attribute numbers to column names. */
880  rel = heap_open(foreigntableid, AccessShareLock);
881  tupleDesc = RelationGetDescr(rel);
882 
883  while ((attnum = bms_first_member(attrs_used)) >= 0)
884  {
885  /* Adjust for system attributes. */
887 
888  if (attnum == 0)
889  {
890  has_wholerow = true;
891  break;
892  }
893 
894  /* Ignore system attributes. */
895  if (attnum < 0)
896  continue;
897 
898  /* Get user attributes. */
899  if (attnum > 0)
900  {
901  Form_pg_attribute attr = tupleDesc->attrs[attnum - 1];
902  char *attname = NameStr(attr->attname);
903 
904  /* Skip dropped attributes (probably shouldn't see any here). */
905  if (attr->attisdropped)
906  continue;
907  *columns = lappend(*columns, makeString(pstrdup(attname)));
908  }
909  }
910 
911  /* Count non-dropped user attributes while we have the tupdesc. */
912  numattrs = 0;
913  for (i = 0; i < tupleDesc->natts; i++)
914  {
915  Form_pg_attribute attr = tupleDesc->attrs[i];
916 
917  if (attr->attisdropped)
918  continue;
919  numattrs++;
920  }
921 
923 
924  /* If there's a whole-row reference, fail: we need all the columns. */
925  if (has_wholerow)
926  {
927  *columns = NIL;
928  return false;
929  }
930 
931  /* If all the user attributes are needed, fail. */
932  if (numattrs == list_length(*columns))
933  {
934  *columns = NIL;
935  return false;
936  }
937 
938  return true;
939 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
int bms_first_member(Bitmapset *a)
Definition: bitmapset.c:885
#define RelationGetDescr(relation)
Definition: rel.h:429
char * pstrdup(const char *in)
Definition: mcxt.c:1077
List * baserestrictinfo
Definition: relation.h:549
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:506
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:73
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:219
char * defGetString(DefElem *def)
Definition: define.c:49
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
Index relid
Definition: relation.h:522
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1699
List * exprs
Definition: relation.h:847
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define NULL
Definition: c.h:229
#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:499
char * defname
Definition: parsenodes.h:708
static char format
Definition: pg_basebackup.c:80
struct PathTarget * reltarget
Definition: relation.h:505
int16 AttrNumber
Definition: attnum.h:21
static void estimate_costs ( PlannerInfo root,
RelOptInfo baserel,
FileFdwPlanState fdw_private,
Cost startup_cost,
Cost total_cost 
)
static

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

1033 {
1034  BlockNumber pages = fdw_private->pages;
1035  double ntuples = fdw_private->ntuples;
1036  Cost run_cost = 0;
1037  Cost cpu_per_tuple;
1038 
1039  /*
1040  * We estimate costs almost the same way as cost_seqscan(), thus assuming
1041  * that I/O costs are equivalent to a regular table file of the same size.
1042  * However, we take per-tuple CPU costs as 10x of a seqscan, to account
1043  * for the cost of parsing records.
1044  *
1045  * In the case of a program source, this calculation is even more divorced
1046  * from reality, but we have no good alternative; and it's not clear that
1047  * the numbers we produce here matter much anyway, since there's only one
1048  * access path for the rel.
1049  */
1050  run_cost += seq_page_cost * pages;
1051 
1052  *startup_cost = baserel->baserestrictcost.startup;
1053  cpu_per_tuple = cpu_tuple_cost * 10 + baserel->baserestrictcost.per_tuple;
1054  run_cost += cpu_per_tuple * ntuples;
1055  *total_cost = *startup_cost + run_cost;
1056 }
BlockNumber pages
Definition: file_fdw.c:93
uint32 BlockNumber
Definition: block.h:31
Cost startup
Definition: relation.h:45
double ntuples
Definition: file_fdw.c:94
Cost per_tuple
Definition: relation.h:46
double cpu_tuple_cost
Definition: costsize.c:106
double seq_page_cost
Definition: costsize.c:104
QualCost baserestrictcost
Definition: relation.h:551
double Cost
Definition: nodes.h:636
static void estimate_size ( PlannerInfo root,
RelOptInfo baserel,
FileFdwPlanState fdw_private 
)
static

Definition at line 949 of file file_fdw.c.

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

Referenced by fileGetForeignRelSize().

951 {
952  struct stat stat_buf;
953  BlockNumber pages;
954  double ntuples;
955  double nrows;
956 
957  /*
958  * Get size of the file. It might not be there at plan time, though, in
959  * which case we have to use a default estimate. We also have to fall
960  * back to the default if using a program as the input.
961  */
962  if (fdw_private->is_program || stat(fdw_private->filename, &stat_buf) < 0)
963  stat_buf.st_size = 10 * BLCKSZ;
964 
965  /*
966  * Convert size to pages for use in I/O cost estimate later.
967  */
968  pages = (stat_buf.st_size + (BLCKSZ - 1)) / BLCKSZ;
969  if (pages < 1)
970  pages = 1;
971  fdw_private->pages = pages;
972 
973  /*
974  * Estimate the number of tuples in the file.
975  */
976  if (baserel->pages > 0)
977  {
978  /*
979  * We have # of pages and # of tuples from pg_class (that is, from a
980  * previous ANALYZE), so compute a tuples-per-page estimate and scale
981  * that by the current file size.
982  */
983  double density;
984 
985  density = baserel->tuples / (double) baserel->pages;
986  ntuples = clamp_row_est(density * (double) pages);
987  }
988  else
989  {
990  /*
991  * Otherwise we have to fake it. We back into this estimate using the
992  * planner's idea of the relation width; which is bogus if not all
993  * columns are being read, not to mention that the text representation
994  * of a row probably isn't the same size as its internal
995  * representation. Possibly we could do something better, but the
996  * real answer to anyone who complains is "ANALYZE" ...
997  */
998  int tuple_width;
999 
1000  tuple_width = MAXALIGN(baserel->reltarget->width) +
1002  ntuples = clamp_row_est((double) stat_buf.st_size /
1003  (double) tuple_width);
1004  }
1005  fdw_private->ntuples = ntuples;
1006 
1007  /*
1008  * Now estimate the number of rows returned by the scan after applying the
1009  * baserestrictinfo quals.
1010  */
1011  nrows = ntuples *
1013  baserel->baserestrictinfo,
1014  0,
1015  JOIN_INNER,
1016  NULL);
1017 
1018  nrows = clamp_row_est(nrows);
1019 
1020  /* Save the output-rows estimate for the planner */
1021  baserel->rows = nrows;
1022 }
#define SizeofHeapTupleHeader
Definition: htup_details.h:170
BlockNumber pages
Definition: file_fdw.c:93
double tuples
Definition: relation.h:534
List * baserestrictinfo
Definition: relation.h:549
uint32 BlockNumber
Definition: block.h:31
double ntuples
Definition: file_fdw.c:94
struct stat stat_buf
Definition: pg_standby.c:101
char * filename
Definition: file_fdw.c:89
double rows
Definition: relation.h:497
BlockNumber pages
Definition: relation.h:533
#define NULL
Definition: c.h:229
#define MAXALIGN(LEN)
Definition: c.h:588
int width
Definition: relation.h:850
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:92
double clamp_row_est(double nrows)
Definition: costsize.c:173
struct PathTarget * reltarget
Definition: relation.h:505
static int file_acquire_sample_rows ( Relation  onerel,
int  elevel,
HeapTuple rows,
int  targrows,
double *  totalrows,
double *  totaldeadrows 
)
static

Definition at line 1073 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, NULL, 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().

1076 {
1077  int numrows = 0;
1078  double rowstoskip = -1; /* -1 means not set yet */
1079  ReservoirStateData rstate;
1080  TupleDesc tupDesc;
1081  Datum *values;
1082  bool *nulls;
1083  bool found;
1084  char *filename;
1085  bool is_program;
1086  List *options;
1087  CopyState cstate;
1088  ErrorContextCallback errcallback;
1089  MemoryContext oldcontext = CurrentMemoryContext;
1090  MemoryContext tupcontext;
1091 
1092  Assert(onerel);
1093  Assert(targrows > 0);
1094 
1095  tupDesc = RelationGetDescr(onerel);
1096  values = (Datum *) palloc(tupDesc->natts * sizeof(Datum));
1097  nulls = (bool *) palloc(tupDesc->natts * sizeof(bool));
1098 
1099  /* Fetch options of foreign table */
1100  fileGetOptions(RelationGetRelid(onerel), &filename, &is_program, &options);
1101 
1102  /*
1103  * Create CopyState from FDW options.
1104  */
1105  cstate = BeginCopyFrom(NULL, onerel, filename, is_program, NULL, NIL,
1106  options);
1107 
1108  /*
1109  * Use per-tuple memory context to prevent leak of memory used to read
1110  * rows from the file with Copy routines.
1111  */
1113  "file_fdw temporary context",
1115 
1116  /* Prepare for sampling rows */
1117  reservoir_init_selection_state(&rstate, targrows);
1118 
1119  /* Set up callback to identify error line number. */
1120  errcallback.callback = CopyFromErrorCallback;
1121  errcallback.arg = (void *) cstate;
1122  errcallback.previous = error_context_stack;
1123  error_context_stack = &errcallback;
1124 
1125  *totalrows = 0;
1126  *totaldeadrows = 0;
1127  for (;;)
1128  {
1129  /* Check for user-requested abort or sleep */
1131 
1132  /* Fetch next row */
1133  MemoryContextReset(tupcontext);
1134  MemoryContextSwitchTo(tupcontext);
1135 
1136  found = NextCopyFrom(cstate, NULL, values, nulls, NULL);
1137 
1138  MemoryContextSwitchTo(oldcontext);
1139 
1140  if (!found)
1141  break;
1142 
1143  /*
1144  * The first targrows sample rows are simply copied into the
1145  * reservoir. Then we start replacing tuples in the sample until we
1146  * reach the end of the relation. This algorithm is from Jeff Vitter's
1147  * paper (see more info in commands/analyze.c).
1148  */
1149  if (numrows < targrows)
1150  {
1151  rows[numrows++] = heap_form_tuple(tupDesc, values, nulls);
1152  }
1153  else
1154  {
1155  /*
1156  * t in Vitter's paper is the number of records already processed.
1157  * If we need to compute a new S value, we must use the
1158  * not-yet-incremented value of totalrows as t.
1159  */
1160  if (rowstoskip < 0)
1161  rowstoskip = reservoir_get_next_S(&rstate, *totalrows, targrows);
1162 
1163  if (rowstoskip <= 0)
1164  {
1165  /*
1166  * Found a suitable tuple, so save it, replacing one old tuple
1167  * at random
1168  */
1169  int k = (int) (targrows * sampler_random_fract(rstate.randstate));
1170 
1171  Assert(k >= 0 && k < targrows);
1172  heap_freetuple(rows[k]);
1173  rows[k] = heap_form_tuple(tupDesc, values, nulls);
1174  }
1175 
1176  rowstoskip -= 1;
1177  }
1178 
1179  *totalrows += 1;
1180  }
1181 
1182  /* Remove error callback. */
1183  error_context_stack = errcallback.previous;
1184 
1185  /* Clean up. */
1186  MemoryContextDelete(tupcontext);
1187 
1188  EndCopyFrom(cstate);
1189 
1190  pfree(values);
1191  pfree(nulls);
1192 
1193  /*
1194  * Emit some interesting relation info
1195  */
1196  ereport(elevel,
1197  (errmsg("\"%s\": file contains %.0f rows; "
1198  "%d rows in sample",
1199  RelationGetRelationName(onerel),
1200  *totalrows, numrows)));
1201 
1202  return numrows;
1203 }
#define NIL
Definition: pg_list.h:69
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
void CopyFromErrorCallback(void *arg)
Definition: copy.c:2192
#define RelationGetDescr(relation)
Definition: rel.h:429
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:2884
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:135
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:692
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
struct ErrorContextCallback * previous
Definition: elog.h:238
int natts
Definition: tupdesc.h:73
ErrorContextCallback * error_context_stack
Definition: elog.c:88
void pfree(void *pointer)
Definition: mcxt.c:950
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
#define RelationGetRelationName(relation)
Definition: rel.h:437
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#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:341
static char ** options
static int elevel
Definition: vacuumlazy.c:137
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
uintptr_t Datum
Definition: postgres.h:372
void EndCopyFrom(CopyState cstate)
Definition: copy.c:3432
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static Datum values[MAXATTR]
Definition: bootstrap.c:162
static char * filename
Definition: pg_dumpall.c:87
void(* callback)(void *arg)
Definition: elog.h:239
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool NextCopyFrom(CopyState cstate, ExprContext *econtext, Datum *values, bool *nulls, Oid *tupleOid)
Definition: copy.c:3191
void vacuum_delay_point(void)
Definition: vacuum.c:1560
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:417
SamplerRandomState randstate
Definition: sampling.h:50
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:142
Datum file_fdw_handler ( PG_FUNCTION_ARGS  )

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

170 {
171  FdwRoutine *fdwroutine = makeNode(FdwRoutine);
172 
174  fdwroutine->GetForeignPaths = fileGetForeignPaths;
175  fdwroutine->GetForeignPlan = fileGetForeignPlan;
180  fdwroutine->EndForeignScan = fileEndForeignScan;
183 
184  PG_RETURN_POINTER(fdwroutine);
185 }
GetForeignPlan_function GetForeignPlan
Definition: fdwapi.h:176
BeginForeignScan_function BeginForeignScan
Definition: fdwapi.h:177
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:321
static bool fileIsForeignScanParallelSafe(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: file_fdw.c:816
static void fileEndForeignScan(ForeignScanState *node)
Definition: file_fdw.c:751
ExplainForeignScan_function ExplainForeignScan
Definition: fdwapi.h:213
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:218
IsForeignScanParallelSafe_function IsForeignScanParallelSafe
Definition: fdwapi.h:224
static TupleTableSlot * fileIterateForeignScan(ForeignScanState *node)
Definition: file_fdw.c:688
GetForeignRelSize_function GetForeignRelSize
Definition: fdwapi.h:174
EndForeignScan_function EndForeignScan
Definition: fdwapi.h:180
static bool fileAnalyzeForeignTable(Relation relation, AcquireSampleRowsFunc *func, BlockNumber *totalpages)
Definition: file_fdw.c:765
static void fileBeginForeignScan(ForeignScanState *node, int eflags)
Definition: file_fdw.c:635
GetForeignPaths_function GetForeignPaths
Definition: fdwapi.h:175
static void fileGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
Definition: file_fdw.c:519
#define makeNode(_type_)
Definition: nodes.h:554
static void fileGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
Definition: file_fdw.c:488
ReScanForeignScan_function ReScanForeignScan
Definition: fdwapi.h:179
IterateForeignScan_function IterateForeignScan
Definition: fdwapi.h:178
static void fileExplainForeignScan(ForeignScanState *node, ExplainState *es)
Definition: file_fdw.c:603
static void fileReScanForeignScan(ForeignScanState *node)
Definition: file_fdw.c:731
static ForeignScan * fileGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid, ForeignPath *best_path, List *tlist, List *scan_clauses, Plan *outer_plan)
Definition: file_fdw.c:568
Datum file_fdw_validator ( PG_FUNCTION_ARGS  )

Definition at line 194 of file file_fdw.c.

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

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

Definition at line 765 of file file_fdw.c.

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

Referenced by file_fdw_handler().

768 {
769  char *filename;
770  bool is_program;
771  List *options;
772  struct stat stat_buf;
773 
774  /* Fetch options of foreign table */
775  fileGetOptions(RelationGetRelid(relation), &filename, &is_program, &options);
776 
777  /*
778  * If this is a program instead of a file, just return false to skip
779  * analyzing the table. We could run the program and collect stats on
780  * whatever it currently returns, but it seems likely that in such cases
781  * the output would be too volatile for the stats to be useful. Maybe
782  * there should be an option to enable doing this?
783  */
784  if (is_program)
785  return false;
786 
787  /*
788  * Get size of the file. (XXX if we fail here, would it be better to just
789  * return false to skip analyzing the table?)
790  */
791  if (stat(filename, &stat_buf) < 0)
792  ereport(ERROR,
794  errmsg("could not stat file \"%s\": %m",
795  filename)));
796 
797  /*
798  * Convert size to pages. Must return at least 1 so that we can tell
799  * later on that pg_class.relpages is not default.
800  */
801  *totalpages = (stat_buf.st_size + (BLCKSZ - 1)) / BLCKSZ;
802  if (*totalpages < 1)
803  *totalpages = 1;
804 
805  *func = file_acquire_sample_rows;
806 
807  return true;
808 }
static int file_acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: file_fdw.c:1073
#define ERROR
Definition: elog.h:43
struct stat stat_buf
Definition: pg_standby.c:101
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:341
static char ** options
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:417
static void fileBeginForeignScan ( ForeignScanState node,
int  eflags 
)
static

Definition at line 635 of file file_fdw.c.

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

Referenced by file_fdw_handler().

636 {
637  ForeignScan *plan = (ForeignScan *) node->ss.ps.plan;
638  char *filename;
639  bool is_program;
640  List *options;
641  CopyState cstate;
642  FileFdwExecutionState *festate;
643 
644  /*
645  * Do nothing in EXPLAIN (no ANALYZE) case. node->fdw_state stays NULL.
646  */
647  if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
648  return;
649 
650  /* Fetch options of foreign table */
652  &filename, &is_program, &options);
653 
654  /* Add any options from the plan (currently only convert_selectively) */
656 
657  /*
658  * Create CopyState from FDW options. We always acquire all columns, so
659  * as to match the expected ScanTupleSlot signature.
660  */
661  cstate = BeginCopyFrom(NULL,
662  node->ss.ss_currentRelation,
663  filename,
664  is_program,
665  NULL,
666  NIL,
667  options);
668 
669  /*
670  * Save state in node->fdw_state. We must save enough information to call
671  * BeginCopyFrom() again.
672  */
673  festate = (FileFdwExecutionState *) palloc(sizeof(FileFdwExecutionState));
674  festate->filename = filename;
675  festate->is_program = is_program;
676  festate->options = options;
677  festate->cstate = cstate;
678 
679  node->fdw_state = (void *) festate;
680 }
#define NIL
Definition: pg_list.h:69
ScanState ss
Definition: execnodes.h:1470
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:2884
List * fdw_private
Definition: plannodes.h:578
List * list_concat(List *list1, List *list2)
Definition: list.c:321
Relation ss_currentRelation
Definition: execnodes.h:1045
PlanState ps
Definition: execnodes.h:1044
static void fileGetOptions(Oid foreigntableid, char **filename, bool *is_program, List **other_options)
Definition: file_fdw.c:341
static char ** options
Plan * plan
Definition: execnodes.h:800
#define NULL
Definition: c.h:229
static char * filename
Definition: pg_dumpall.c:87
void * palloc(Size size)
Definition: mcxt.c:849
Definition: pg_list.h:45
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:58
#define RelationGetRelid(relation)
Definition: rel.h:417
static void fileEndForeignScan ( ForeignScanState node)
static

Definition at line 751 of file file_fdw.c.

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

Referenced by file_fdw_handler().

752 {
754 
755  /* if festate is NULL, we are in EXPLAIN; nothing to do */
756  if (festate)
757  EndCopyFrom(festate->cstate);
758 }
void EndCopyFrom(CopyState cstate)
Definition: copy.c:3432
static void fileExplainForeignScan ( ForeignScanState node,
ExplainState es 
)
static

Definition at line 603 of file file_fdw.c.

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

Referenced by file_fdw_handler().

604 {
605  char *filename;
606  bool is_program;
607  List *options;
608 
609  /* Fetch options --- we only need filename and is_program at this point */
611  &filename, &is_program, &options);
612 
613  if (is_program)
614  ExplainPropertyText("Foreign Program", filename, es);
615  else
616  ExplainPropertyText("Foreign File", filename, es);
617 
618  /* Suppress file size if we're not showing cost details */
619  if (es->costs)
620  {
621  struct stat stat_buf;
622 
623  if (!is_program &&
624  stat(filename, &stat_buf) == 0)
625  ExplainPropertyLong("Foreign File Size", (long) stat_buf.st_size,
626  es);
627  }
628 }
ScanState ss
Definition: execnodes.h:1470
void ExplainPropertyLong(const char *qlabel, long value, ExplainState *es)
Definition: explain.c:3143
Relation ss_currentRelation
Definition: execnodes.h:1045
bool costs
Definition: explain.h:34
void ExplainPropertyText(const char *qlabel, const char *value, ExplainState *es)
Definition: explain.c:3122
struct stat stat_buf
Definition: pg_standby.c:101
static void fileGetOptions(Oid foreigntableid, char **filename, bool *is_program, List **other_options)
Definition: file_fdw.c:341
static char ** options
static char * filename
Definition: pg_dumpall.c:87
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:417
static void fileGetForeignPaths ( PlannerInfo root,
RelOptInfo baserel,
Oid  foreigntableid 
)
static

Definition at line 519 of file file_fdw.c.

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

Referenced by file_fdw_handler().

522 {
523  FileFdwPlanState *fdw_private = (FileFdwPlanState *) baserel->fdw_private;
524  Cost startup_cost;
525  Cost total_cost;
526  List *columns;
527  List *coptions = NIL;
528 
529  /* Decide whether to selectively perform binary conversion */
531  foreigntableid,
532  &columns))
533  coptions = list_make1(makeDefElem("convert_selectively",
534  (Node *) columns, -1));
535 
536  /* Estimate costs */
537  estimate_costs(root, baserel, fdw_private,
538  &startup_cost, &total_cost);
539 
540  /*
541  * Create a ForeignPath node and add it as only possible path. We use the
542  * fdw_private list of the path to carry the convert_selectively option;
543  * it will be propagated into the fdw_private list of the Plan node.
544  */
545  add_path(baserel, (Path *)
546  create_foreignscan_path(root, baserel,
547  NULL, /* default pathtarget */
548  baserel->rows,
549  startup_cost,
550  total_cost,
551  NIL, /* no pathkeys */
552  NULL, /* no outer rel either */
553  NULL, /* no extra plan */
554  coptions));
555 
556  /*
557  * If data file was sorted, and we knew it somehow, we could insert
558  * appropriate pathkeys into the ForeignPath node to tell the planner
559  * that.
560  */
561 }
#define NIL
Definition: pg_list.h:69
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
Definition: nodes.h:506
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:543
#define list_make1(x1)
Definition: pg_list.h:133
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:1934
double rows
Definition: relation.h:497
void * fdw_private
Definition: relation.h:546
#define NULL
Definition: c.h:229
static bool check_selective_binary_conversion(RelOptInfo *baserel, Oid foreigntableid, List **columns)
Definition: file_fdw.c:832
static void estimate_costs(PlannerInfo *root, RelOptInfo *baserel, FileFdwPlanState *fdw_private, Cost *startup_cost, Cost *total_cost)
Definition: file_fdw.c:1030
Definition: pg_list.h:45
Definition: relation.h:911
double Cost
Definition: nodes.h:636
static ForeignScan * fileGetForeignPlan ( PlannerInfo root,
RelOptInfo baserel,
Oid  foreigntableid,
ForeignPath best_path,
List tlist,
List scan_clauses,
Plan outer_plan 
)
static

Definition at line 568 of file file_fdw.c.

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

Referenced by file_fdw_handler().

575 {
576  Index scan_relid = baserel->relid;
577 
578  /*
579  * We have no native ability to evaluate restriction clauses, so we just
580  * put all the scan_clauses into the plan node's qual list for the
581  * executor to check. So all we have to do here is strip RestrictInfo
582  * nodes from the clauses and ignore pseudoconstants (which will be
583  * handled elsewhere).
584  */
585  scan_clauses = extract_actual_clauses(scan_clauses, false);
586 
587  /* Create the ForeignScan node */
588  return make_foreignscan(tlist,
589  scan_clauses,
590  scan_relid,
591  NIL, /* no expressions to evaluate */
592  best_path->fdw_private,
593  NIL, /* no custom tlist */
594  NIL, /* no remote quals */
595  outer_plan);
596 }
#define NIL
Definition: pg_list.h:69
Index relid
Definition: relation.h:522
unsigned int Index
Definition: c.h:365
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:354
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:5143
List * fdw_private
Definition: relation.h:1096
static void fileGetForeignRelSize ( PlannerInfo root,
RelOptInfo baserel,
Oid  foreigntableid 
)
static

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

491 {
492  FileFdwPlanState *fdw_private;
493 
494  /*
495  * Fetch options. We only need filename (or program) at this point, but
496  * we might as well get everything and not need to re-fetch it later in
497  * planning.
498  */
499  fdw_private = (FileFdwPlanState *) palloc(sizeof(FileFdwPlanState));
500  fileGetOptions(foreigntableid,
501  &fdw_private->filename,
502  &fdw_private->is_program,
503  &fdw_private->options);
504  baserel->fdw_private = (void *) fdw_private;
505 
506  /* Estimate relation size */
507  estimate_size(root, baserel, fdw_private);
508 }
List * options
Definition: file_fdw.c:91
static void estimate_size(PlannerInfo *root, RelOptInfo *baserel, FileFdwPlanState *fdw_private)
Definition: file_fdw.c:949
char * filename
Definition: file_fdw.c:89
static void fileGetOptions(Oid foreigntableid, char **filename, bool *is_program, List **other_options)
Definition: file_fdw.c:341
void * fdw_private
Definition: relation.h:546
void * palloc(Size size)
Definition: mcxt.c:849
static void fileGetOptions ( Oid  foreigntableid,
char **  filename,
bool is_program,
List **  other_options 
)
static

Definition at line 341 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, NULL, ForeignDataWrapper::options, options, ForeignServer::options, ForeignTable::options, and ForeignTable::serverid.

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

343 {
344  ForeignTable *table;
345  ForeignServer *server;
346  ForeignDataWrapper *wrapper;
347  List *options;
348  ListCell *lc,
349  *prev;
350 
351  /*
352  * Extract options from FDW objects. We ignore user mappings because
353  * file_fdw doesn't have any options that can be specified there.
354  *
355  * (XXX Actually, given the current contents of valid_options[], there's
356  * no point in examining anything except the foreign table's own options.
357  * Simplify?)
358  */
359  table = GetForeignTable(foreigntableid);
360  server = GetForeignServer(table->serverid);
361  wrapper = GetForeignDataWrapper(server->fdwid);
362 
363  options = NIL;
364  options = list_concat(options, wrapper->options);
365  options = list_concat(options, server->options);
366  options = list_concat(options, table->options);
367  options = list_concat(options, get_file_fdw_attribute_options(foreigntableid));
368 
369  /*
370  * Separate out the filename or program option (we assume there is only
371  * one).
372  */
373  *filename = NULL;
374  *is_program = false;
375  prev = NULL;
376  foreach(lc, options)
377  {
378  DefElem *def = (DefElem *) lfirst(lc);
379 
380  if (strcmp(def->defname, "filename") == 0)
381  {
382  *filename = defGetString(def);
383  options = list_delete_cell(options, lc, prev);
384  break;
385  }
386  else if (strcmp(def->defname, "program") == 0)
387  {
388  *filename = defGetString(def);
389  *is_program = true;
390  options = list_delete_cell(options, lc, prev);
391  break;
392  }
393  prev = lc;
394  }
395 
396  /*
397  * The validator should have checked that filename or program was included
398  * in the options, but check again, just in case.
399  */
400  if (*filename == NULL)
401  elog(ERROR, "either filename or program is required for file_fdw foreign tables");
402 
403  *other_options = options;
404 }
#define NIL
Definition: pg_list.h:69
static List * get_file_fdw_attribute_options(Oid relid)
Definition: file_fdw.c:415
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 NULL
Definition: c.h:229
#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:708
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
List * options
Definition: foreign.h:53
static bool fileIsForeignScanParallelSafe ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 816 of file file_fdw.c.

Referenced by file_fdw_handler().

818 {
819  return true;
820 }
static TupleTableSlot * fileIterateForeignScan ( ForeignScanState node)
static

Definition at line 688 of file file_fdw.c.

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

Referenced by file_fdw_handler().

689 {
691  TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
692  bool found;
693  ErrorContextCallback errcallback;
694 
695  /* Set up callback to identify error line number. */
696  errcallback.callback = CopyFromErrorCallback;
697  errcallback.arg = (void *) festate->cstate;
698  errcallback.previous = error_context_stack;
699  error_context_stack = &errcallback;
700 
701  /*
702  * The protocol for loading a virtual tuple into a slot is first
703  * ExecClearTuple, then fill the values/isnull arrays, then
704  * ExecStoreVirtualTuple. If we don't find another row in the file, we
705  * just skip the last step, leaving the slot empty as required.
706  *
707  * We can pass ExprContext = NULL because we read all columns from the
708  * file, so no need to evaluate default expressions.
709  *
710  * We can also pass tupleOid = NULL because we don't allow oids for
711  * foreign tables.
712  */
713  ExecClearTuple(slot);
714  found = NextCopyFrom(festate->cstate, NULL,
715  slot->tts_values, slot->tts_isnull,
716  NULL);
717  if (found)
718  ExecStoreVirtualTuple(slot);
719 
720  /* Remove error callback. */
721  error_context_stack = errcallback.previous;
722 
723  return slot;
724 }
ScanState ss
Definition: execnodes.h:1470
void CopyFromErrorCallback(void *arg)
Definition: copy.c:2192
TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: execTuples.c:439
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1047
struct ErrorContextCallback * previous
Definition: elog.h:238
ErrorContextCallback * error_context_stack
Definition: elog.c:88
#define NULL
Definition: c.h:229
void(* callback)(void *arg)
Definition: elog.h:239
bool NextCopyFrom(CopyState cstate, ExprContext *econtext, Datum *values, bool *nulls, Oid *tupleOid)
Definition: copy.c:3191
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:488
static void fileReScanForeignScan ( ForeignScanState node)
static

Definition at line 731 of file file_fdw.c.

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

Referenced by file_fdw_handler().

732 {
734 
735  EndCopyFrom(festate->cstate);
736 
737  festate->cstate = BeginCopyFrom(NULL,
738  node->ss.ss_currentRelation,
739  festate->filename,
740  festate->is_program,
741  NULL,
742  NIL,
743  festate->options);
744 }
#define NIL
Definition: pg_list.h:69
ScanState ss
Definition: execnodes.h:1470
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:2884
Relation ss_currentRelation
Definition: execnodes.h:1045
void EndCopyFrom(CopyState cstate)
Definition: copy.c:3432
#define NULL
Definition: c.h:229
static List * get_file_fdw_attribute_options ( Oid  relid)
static

Definition at line 415 of file file_fdw.c.

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

Referenced by fileGetOptions().

416 {
417  Relation rel;
419  AttrNumber natts;
420  AttrNumber attnum;
421  List *fnncolumns = NIL;
422  List *fncolumns = NIL;
423 
424  List *options = NIL;
425 
426  rel = heap_open(relid, AccessShareLock);
427  tupleDesc = RelationGetDescr(rel);
428  natts = tupleDesc->natts;
429 
430  /* Retrieve FDW options for all user-defined attributes. */
431  for (attnum = 1; attnum <= natts; attnum++)
432  {
433  Form_pg_attribute attr = tupleDesc->attrs[attnum - 1];
434  List *options;
435  ListCell *lc;
436 
437  /* Skip dropped attributes. */
438  if (attr->attisdropped)
439  continue;
440 
441  options = GetForeignColumnOptions(relid, attnum);
442  foreach(lc, options)
443  {
444  DefElem *def = (DefElem *) lfirst(lc);
445 
446  if (strcmp(def->defname, "force_not_null") == 0)
447  {
448  if (defGetBoolean(def))
449  {
450  char *attname = pstrdup(NameStr(attr->attname));
451 
452  fnncolumns = lappend(fnncolumns, makeString(attname));
453  }
454  }
455  else if (strcmp(def->defname, "force_null") == 0)
456  {
457  if (defGetBoolean(def))
458  {
459  char *attname = pstrdup(NameStr(attr->attname));
460 
461  fncolumns = lappend(fncolumns, makeString(attname));
462  }
463  }
464  /* maybe in future handle other options here */
465  }
466  }
467 
469 
470  /*
471  * Return DefElem only when some column(s) have force_not_null /
472  * force_null options set
473  */
474  if (fnncolumns != NIL)
475  options = lappend(options, makeDefElem("force_not_null", (Node *) fnncolumns, -1));
476 
477  if (fncolumns != NIL)
478  options = lappend(options, makeDefElem("force_null", (Node *) fncolumns, -1));
479 
480  return options;
481 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
#define RelationGetDescr(relation)
Definition: rel.h:429
char * pstrdup(const char *in)
Definition: mcxt.c:1077
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:506
#define heap_close(r, l)
Definition: heapam.h:97
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:543
int natts
Definition: tupdesc.h:73
bool defGetBoolean(DefElem *def)
Definition: define.c:111
List * GetForeignColumnOptions(Oid relid, AttrNumber attnum)
Definition: foreign.c:254
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
List * lappend(List *list, void *datum)
Definition: list.c:128
static char ** options
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define lfirst(lc)
Definition: pg_list.h:106
#define NameStr(name)
Definition: c.h:499
char * defname
Definition: parsenodes.h:708
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
static bool is_valid_option ( const char *  option,
Oid  context 
)
static

Definition at line 322 of file file_fdw.c.

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

Referenced by file_fdw_validator().

323 {
324  const struct FileFdwOption *opt;
325 
326  for (opt = valid_options; opt->optname; opt++)
327  {
328  if (context == opt->optcontext && strcmp(opt->optname, option) == 0)
329  return true;
330  }
331  return false;
332 }
Oid optcontext
Definition: file_fdw.c:47
static const struct FileFdwOption valid_options[]
Definition: file_fdw.c:59
const char * optname
Definition: file_fdw.c:46
PG_FUNCTION_INFO_V1 ( file_fdw_handler  )
PG_FUNCTION_INFO_V1 ( file_fdw_validator  )

Variable Documentation

PG_MODULE_MAGIC

Definition at line 39 of file file_fdw.c.

const struct FileFdwOption valid_options[]
static
Initial value:
= {
{"filename", ForeignTableRelationId},
{"program", ForeignTableRelationId},
{"delimiter", ForeignTableRelationId},
{"encoding", ForeignTableRelationId},
{"force_not_null", AttributeRelationId},
{"force_null", AttributeRelationId},
}
#define AttributeRelationId
Definition: pg_attribute.h:33
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
#define ForeignTableRelationId

Definition at line 59 of file file_fdw.c.