Writing A Foreign Data Wrapper
foreign data wrapper
handler for
All operations on a foreign table are handled through its foreign data
wrapper, which consists of a set of functions that the core server
calls. The foreign data wrapper is responsible for fetching
data from the remote data source and returning it to the
PostgreSQL executor. This chapter outlines how
to write a new foreign data wrapper.
The foreign data wrappers included in the standard distribution are good
references when trying to write your own. Look into the
contrib/file_fdw> subdirectory of the source tree.
The reference page also has
some useful details.
The SQL standard specifies an interface for writing foreign data wrappers.
However, PostgreSQL does not implement that API, because the effort to
accommodate it into PostgreSQL would be large, and the standard API hasn't
gained wide adoption anyway.
Foreign Data Wrapper Functions
The FDW author needs to implement a handler function, and optionally
a validator function. Both functions must be written in a compiled
language such as C, using the version-1 interface.
For details on C language calling conventions and dynamic loading,
see .
The handler function simply returns a struct of function pointers to
callback functions that will be called by the planner, executor, and
various maintenance commands.
Most of the effort in writing an FDW is in implementing these callback
functions.
The handler function must be registered with
PostgreSQL as taking no arguments and
returning the special pseudo-type fdw_handler. The
callback functions are plain C functions and are not visible or
callable at the SQL level. The callback functions are described in
.
The validator function is responsible for validating options given in
CREATE and ALTER commands for its
foreign data wrapper, as well as foreign servers, user mappings, and
foreign tables using the wrapper.
The validator function must be registered as taking two arguments, a
text array containing the options to be validated, and an OID
representing the type of object the options are associated with (in
the form of the OID of the system catalog the object would be stored
in, either
ForeignDataWrapperRelationId>,
ForeignServerRelationId>,
UserMappingRelationId>,
or ForeignTableRelationId>).
If no validator function is supplied, options are not checked at object
creation time or object alteration time.
Foreign Data Wrapper Callback Routines
The FDW handler function returns a palloc'd FdwRoutine>
struct containing pointers to the following callback functions:
void
GetForeignRelSize (PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
Obtain relation size estimates for a foreign table. This is called
at the beginning of planning for a query involving a foreign table.
root> is the planner's global information about the query;
baserel> is the planner's information about this table; and
foreigntableid> is the pg_class> OID of the
foreign table. (foreigntableid> could be obtained from the
planner data structures, but it's passed explicitly to save effort.)
This function should update baserel->rows> to be the
expected number of rows returned by the table scan, after accounting for
the filtering done by the restriction quals. The initial value of
baserel->rows> is just a constant default estimate, which
should be replaced if at all possible. The function may also choose to
update baserel->width> if it can compute a better estimate
of the average result row width.
See for additional information.
void
GetForeignPaths (PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
Create possible access paths for a scan on a foreign table.
This is called during query planning.
The parameters are the same as for GetForeignRelSize>,
which has already been called.
This function must generate at least one access path
(ForeignPath> node) for a scan on the foreign table and
must call add_path> to add each such path to
baserel->pathlist>. It's recommended to use
create_foreignscan_path> to build the
ForeignPath> nodes. The function can generate multiple
access paths, e.g., a path which has valid pathkeys> to
represent a pre-sorted result. Each access path must contain cost
estimates, and can contain any FDW-private information that is needed to
identify the specific scan method intended.
See for additional information.
ForeignScan *
GetForeignPlan (PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses);
Create a ForeignScan> plan node from the selected foreign
access path. This is called at the end of query planning.
The parameters are as for GetForeignRelSize>, plus
the selected ForeignPath> (previously produced by
GetForeignPaths>), the target list to be emitted by the
plan node, and the restriction clauses to be enforced by the plan node.
This function must create and return a ForeignScan> plan
node; it's recommended to use make_foreignscan> to build the
ForeignScan> node.
See for additional information.
void
ExplainForeignScan (ForeignScanState *node,
ExplainState *es);
Print additional EXPLAIN> output for a foreign table scan.
This can just return if there is no need to print anything.
Otherwise, it should call ExplainPropertyText> and
related functions to add fields to the EXPLAIN> output.
The flag fields in es> can be used to determine what to
print, and the state of the ForeignScanState> node
can be inspected to provide run-time statistics in the EXPLAIN
ANALYZE> case.
void
BeginForeignScan (ForeignScanState *node,
int eflags);
Begin executing a foreign scan. This is called during executor startup.
It should perform any initialization needed before the scan can start,
but not start executing the actual scan (that should be done upon the
first call to IterateForeignScan>).
The ForeignScanState> node has already been created, but
its fdw_state> field is still NULL. Information about
the table to scan is accessible through the
ForeignScanState> node (in particular, from the underlying
ForeignScan> plan node, which contains any FDW-private
information provided by GetForeignPlan>).
Note that when (eflags & EXEC_FLAG_EXPLAIN_ONLY)> is
true, this function should not perform any externally-visible actions;
it should only do the minimum required to make the node state valid
for ExplainForeignScan> and EndForeignScan>.
TupleTableSlot *
IterateForeignScan (ForeignScanState *node);
Fetch one row from the foreign source, returning it in a tuple table slot
(the node's ScanTupleSlot> should be used for this
purpose). Return NULL if no more rows are available. The tuple table
slot infrastructure allows either a physical or virtual tuple to be
returned; in most cases the latter choice is preferable from a
performance standpoint. Note that this is called in a short-lived memory
context that will be reset between invocations. Create a memory context
in BeginForeignScan> if you need longer-lived storage, or use
the es_query_cxt> of the node's EState>.
The rows returned must match the column signature of the foreign table
being scanned. If you choose to optimize away fetching columns that
are not needed, you should insert nulls in those column positions.
Note that PostgreSQL's executor doesn't care
whether the rows returned violate the NOT NULL
constraints which were defined on the foreign table columns - but the
planner does care, and may optimize queries incorrectly if
NULL> values are present in a column declared not to contain
them. If a NULL> value is encountered when the user has
declared that none should be present, it may be appropriate to raise an
error (just as you would need to do in the case of a data type mismatch).
void
ReScanForeignScan (ForeignScanState *node);
Restart the scan from the beginning. Note that any parameters the
scan depends on may have changed value, so the new scan does not
necessarily return exactly the same rows.
void
EndForeignScan (ForeignScanState *node);
End the scan and release resources. It is normally not important
to release palloc'd memory, but for example open files and connections
to remote servers should be cleaned up.
bool
AnalyzeForeignTable (Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
This function is called when is executed on
a foreign table. If the FDW can collect statistics for this
foreign table, it should return true>, and provide a pointer
to a function that will collect sample rows from the table in
func>, plus the estimated size of the table in pages in
totalpages>. Otherwise, return false>.
If the FDW does not support collecting statistics for any tables, the
AnalyzeForeignTable> pointer can be set to NULL>.
If provided, the sample collection function must have the signature
int
AcquireSampleRowsFunc (Relation relation, int elevel,
HeapTuple *rows, int targrows,
double *totalrows,
double *totaldeadrows);
A random sample of up to targrows> rows should be collected
from the table and stored into the caller-provided rows>
array. The actual number of rows collected must be returned. In
addition, store estimates of the total numbers of live and dead rows in
the table into the output parameters totalrows> and
totaldeadrows>. (Set totaldeadrows> to zero
if the FDW does not have any concept of dead rows.)
The FdwRoutine> struct type is declared in
src/include/foreign/fdwapi.h>, which see for additional
details.
Foreign Data Wrapper Helper Functions
Several helper functions are exported from the core server so that
authors of foreign data wrappers can get easy access to attributes of
FDW-related objects, such as FDW options.
To use any of these functions, you need to include the header file
foreign/foreign.h in your source file.
That header also defines the struct types that are returned by
these functions.
ForeignDataWrapper *
GetForeignDataWrapper(Oid fdwid);
This function returns a ForeignDataWrapper
object for the foreign-data wrapper with the given OID. A
ForeignDataWrapper object contains properties
of the FDW (see foreign/foreign.h for details).
ForeignServer *
GetForeignServer(Oid serverid);
This function returns a ForeignServer object
for the foreign server with the given OID. A
ForeignServer object contains properties
of the server (see foreign/foreign.h for details).
UserMapping *
GetUserMapping(Oid userid, Oid serverid);
This function returns a UserMapping object for
the user mapping of the given role on the given server. (If there is no
mapping for the specific user, it will return the mapping for
PUBLIC>, or throw error if there is none.) A
UserMapping object contains properties of the
user mapping (see foreign/foreign.h for details).
ForeignTable *
GetForeignTable(Oid relid);
This function returns a ForeignTable object for
the foreign table with the given OID. A
ForeignTable object contains properties of the
foreign table (see foreign/foreign.h for details).
List *
GetForeignTableColumnOptions(Oid relid, AttrNumber attnum);
This function returns the per-column FDW options for the column with the
given foreign table OID and attribute number, in the form of a list of
DefElem. NIL is returned if the column has no
options.
Some object types have name-based lookup functions in addition to the
OID-based ones:
ForeignDataWrapper *
GetForeignDataWrapperByName(const char *name, bool missing_ok);
This function returns a ForeignDataWrapper
object for the foreign-data wrapper with the given name. If the wrapper
is not found, return NULL if missing_ok is true, otherwise raise an
error.
ForeignServer *
GetForeignServerByName(const char *name, bool missing_ok);
This function returns a ForeignServer object
for the foreign server with the given name. If the server is not found,
return NULL if missing_ok is true, otherwise raise an error.
Foreign Data Wrapper Query Planning
The FDW callback functions GetForeignRelSize>,
GetForeignPaths>, and GetForeignPlan> must fit
into the workings of the PostgreSQL> planner. Here are
some notes about what they must do.
The information in root> and baserel> can be used
to reduce the amount of information that has to be fetched from the
foreign table (and therefore reduce the cost).
baserel->baserestrictinfo> is particularly interesting, as
it contains restriction quals (WHERE> clauses) that should be
used to filter the rows to be fetched. (The FDW itself is not required
to enforce these quals, as the core executor can check them instead.)
baserel->reltargetlist> can be used to determine which
columns need to be fetched; but note that it only lists columns that
have to be emitted by the ForeignScan> plan node, not
columns that are used in qual evaluation but not output by the query.
Various private fields are available for the FDW planning functions to
keep information in. Generally, whatever you store in FDW private fields
should be palloc'd, so that it will be reclaimed at the end of planning.
baserel->fdw_private> is a void> pointer that is
available for FDW planning functions to store information relevant to
the particular foreign table. The core planner does not touch it except
to initialize it to NULL when the baserel> node is created.
It is useful for passing information forward from
GetForeignRelSize> to GetForeignPaths> and/or
GetForeignPaths> to GetForeignPlan>, thereby
avoiding recalculation.
GetForeignPaths> can identify the meaning of different
access paths by storing private information in the
fdw_private> field of ForeignPath> nodes.
fdw_private> is declared as a List> pointer, but
could actually contain anything since the core planner does not touch
it. However, best practice is to use a representation that's dumpable
by nodeToString>, for use with debugging support available
in the backend.
GetForeignPlan> can examine the fdw_private>
field of the selected ForeignPath> node, and can generate
fdw_exprs> and fdw_private> lists to be
placed in the ForeignScan> plan node, where they will be
available at execution time. Both of these lists must be
represented in a form that copyObject> knows how to copy.
The fdw_private> list has no other restrictions and is
not interpreted by the core backend in any way. The
fdw_exprs> list, if not NIL, is expected to contain
expression trees that are intended to be executed at run time. These
trees will undergo post-processing by the planner to make them fully
executable.
In GetForeignPlan>, generally the passed-in target list can
be copied into the plan node as-is. The passed scan_clauses list
contains the same clauses as baserel->baserestrictinfo>,
but may be re-ordered for better execution efficiency. In simple cases
the FDW can just strip RestrictInfo> nodes from the
scan_clauses list (using extract_actual_clauses>) and put
all the clauses into the plan node's qual list, which means that all the
clauses will be checked by the executor at run time. More complex FDWs
may be able to check some of the clauses internally, in which case those
clauses can be removed from the plan node's qual list so that the
executor doesn't waste time rechecking them.
As an example, the FDW might identify some restriction clauses of the
form foreign_variable> =>
sub_expression>, which it determines can be executed on
the remote server given the locally-evaluated value of the
sub_expression>. The actual identification of such a
clause should happen during GetForeignPaths>, since it would
affect the cost estimate for the path. The path's
fdw_private> field would probably include a pointer to
the identified clause's RestrictInfo> node. Then
GetForeignPlan> would remove that clause from scan_clauses,
but add the sub_expression> to fdw_exprs>
to ensure that it gets massaged into executable form. It would probably
also put control information into the plan node's
fdw_private> field to tell the execution functions what
to do at run time. The query transmitted to the remote server would
involve something like WHERE foreign_variable> =
$1, with the parameter value obtained at run time from
evaluation of the fdw_exprs> expression tree.
The FDW should always construct at least one path that depends only on
the table's restriction clauses. In join queries, it might also choose
to construct path(s) that depend on join clauses, for example
foreign_variable> =>
local_variable>. Such clauses will not be found in
baserel->baserestrictinfo> but must be sought in the
relation's join lists. A path using such a clause is called a
parameterized path>. It must show the other relation(s) as
required_outer> and list the specific join clause(s) in
param_clauses>. In GetForeignPlan>, the
local_variable> portion of the join clause would be added
to fdw_exprs>, and then at run time the case works the
same as for an ordinary restriction clause.