1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>58.2. Foreign Data Wrapper Callback Routines</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><link rel="prev" href="fdw-functions.html" title="58.1. Foreign Data Wrapper Functions" /><link rel="next" href="fdw-helpers.html" title="58.3. Foreign Data Wrapper Helper Functions" /></head><body id="docContent" class="container-fluid col-10"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">58.2. Foreign Data Wrapper Callback Routines</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="fdw-functions.html" title="58.1. Foreign Data Wrapper Functions">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="fdwhandler.html" title="Chapter 58. Writing a Foreign Data Wrapper">Up</a></td><th width="60%" align="center">Chapter 58. Writing a Foreign Data Wrapper</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="fdw-helpers.html" title="58.3. Foreign Data Wrapper Helper Functions">Next</a></td></tr></table><hr /></div><div class="sect1" id="FDW-CALLBACKS"><div class="titlepage"><div><div><h2 class="title" style="clear: both">58.2. Foreign Data Wrapper Callback Routines <a href="#FDW-CALLBACKS" class="id_link">#</a></h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="fdw-callbacks.html#FDW-CALLBACKS-SCAN">58.2.1. FDW Routines for Scanning Foreign Tables</a></span></dt><dt><span class="sect2"><a href="fdw-callbacks.html#FDW-CALLBACKS-JOIN-SCAN">58.2.2. FDW Routines for Scanning Foreign Joins</a></span></dt><dt><span class="sect2"><a href="fdw-callbacks.html#FDW-CALLBACKS-UPPER-PLANNING">58.2.3. FDW Routines for Planning Post-Scan/Join Processing</a></span></dt><dt><span class="sect2"><a href="fdw-callbacks.html#FDW-CALLBACKS-UPDATE">58.2.4. FDW Routines for Updating Foreign Tables</a></span></dt><dt><span class="sect2"><a href="fdw-callbacks.html#FDW-CALLBACKS-TRUNCATE">58.2.5. FDW Routines for <code class="command">TRUNCATE</code></a></span></dt><dt><span class="sect2"><a href="fdw-callbacks.html#FDW-CALLBACKS-ROW-LOCKING">58.2.6. FDW Routines for Row Locking</a></span></dt><dt><span class="sect2"><a href="fdw-callbacks.html#FDW-CALLBACKS-EXPLAIN">58.2.7. FDW Routines for <code class="command">EXPLAIN</code></a></span></dt><dt><span class="sect2"><a href="fdw-callbacks.html#FDW-CALLBACKS-ANALYZE">58.2.8. FDW Routines for <code class="command">ANALYZE</code></a></span></dt><dt><span class="sect2"><a href="fdw-callbacks.html#FDW-CALLBACKS-IMPORT">58.2.9. FDW Routines for <code class="command">IMPORT FOREIGN SCHEMA</code></a></span></dt><dt><span class="sect2"><a href="fdw-callbacks.html#FDW-CALLBACKS-PARALLEL">58.2.10. FDW Routines for Parallel Execution</a></span></dt><dt><span class="sect2"><a href="fdw-callbacks.html#FDW-CALLBACKS-ASYNC">58.2.11. FDW Routines for Asynchronous Execution</a></span></dt><dt><span class="sect2"><a href="fdw-callbacks.html#FDW-CALLBACKS-REPARAMETERIZE-PATHS">58.2.12. FDW Routines for Reparameterization of Paths</a></span></dt></dl></div><p>
3 The FDW handler function returns a palloc'd <code class="structname">FdwRoutine</code>
4 struct containing pointers to the callback functions described below.
5 The scan-related functions are required, the rest are optional.
7 The <code class="structname">FdwRoutine</code> struct type is declared in
8 <code class="filename">src/include/foreign/fdwapi.h</code>, which see for additional
10 </p><div class="sect2" id="FDW-CALLBACKS-SCAN"><div class="titlepage"><div><div><h3 class="title">58.2.1. FDW Routines for Scanning Foreign Tables <a href="#FDW-CALLBACKS-SCAN" class="id_link">#</a></h3></div></div></div><p>
11 </p><pre class="programlisting">
13 GetForeignRelSize(PlannerInfo *root,
18 Obtain relation size estimates for a foreign table. This is called
19 at the beginning of planning for a query that scans a foreign table.
20 <code class="literal">root</code> is the planner's global information about the query;
21 <code class="literal">baserel</code> is the planner's information about this table; and
22 <code class="literal">foreigntableid</code> is the <code class="structname">pg_class</code> OID of the
23 foreign table. (<code class="literal">foreigntableid</code> could be obtained from the
24 planner data structures, but it's passed explicitly to save effort.)
26 This function should update <code class="literal">baserel->rows</code> to be the
27 expected number of rows returned by the table scan, after accounting for
28 the filtering done by the restriction quals. The initial value of
29 <code class="literal">baserel->rows</code> is just a constant default estimate, which
30 should be replaced if at all possible. The function may also choose to
31 update <code class="literal">baserel->width</code> if it can compute a better estimate
32 of the average result row width.
33 (The initial value is based on column data types and on column
34 average-width values measured by the last <code class="command">ANALYZE</code>.)
35 Also, this function may update <code class="literal">baserel->tuples</code> if
36 it can compute a better estimate of the foreign table's total row count.
38 from <code class="structname">pg_class</code>.<code class="structfield">reltuples</code>
39 which represents the total row count seen by the
40 last <code class="command">ANALYZE</code>; it will be <code class="literal">-1</code> if
41 no <code class="command">ANALYZE</code> has been done on this foreign table.)
43 See <a class="xref" href="fdw-planning.html" title="58.4. Foreign Data Wrapper Query Planning">Section 58.4</a> for additional information.
45 </p><pre class="programlisting">
47 GetForeignPaths(PlannerInfo *root,
52 Create possible access paths for a scan on a foreign table.
53 This is called during query planning.
54 The parameters are the same as for <code class="function">GetForeignRelSize</code>,
55 which has already been called.
57 This function must generate at least one access path
58 (<code class="structname">ForeignPath</code> node) for a scan on the foreign table and
59 must call <code class="function">add_path</code> to add each such path to
60 <code class="literal">baserel->pathlist</code>. It's recommended to use
61 <code class="function">create_foreignscan_path</code> to build the
62 <code class="structname">ForeignPath</code> nodes. The function can generate multiple
63 access paths, e.g., a path which has valid <code class="literal">pathkeys</code> to
64 represent a pre-sorted result. Each access path must contain cost
65 estimates, and can contain any FDW-private information that is needed to
66 identify the specific scan method intended.
68 See <a class="xref" href="fdw-planning.html" title="58.4. Foreign Data Wrapper Query Planning">Section 58.4</a> for additional information.
70 </p><pre class="programlisting">
72 GetForeignPlan(PlannerInfo *root,
75 ForeignPath *best_path,
81 Create a <code class="structname">ForeignScan</code> plan node from the selected foreign
82 access path. This is called at the end of query planning.
83 The parameters are as for <code class="function">GetForeignRelSize</code>, plus
84 the selected <code class="structname">ForeignPath</code> (previously produced by
85 <code class="function">GetForeignPaths</code>, <code class="function">GetForeignJoinPaths</code>,
86 or <code class="function">GetForeignUpperPaths</code>),
87 the target list to be emitted by the plan node,
88 the restriction clauses to be enforced by the plan node,
89 and the outer subplan of the <code class="structname">ForeignScan</code>,
90 which is used for rechecks performed by <code class="function">RecheckForeignScan</code>.
91 (If the path is for a join rather than a base
92 relation, <code class="literal">foreigntableid</code> is <code class="literal">InvalidOid</code>.)
94 This function must create and return a <code class="structname">ForeignScan</code> plan
95 node; it's recommended to use <code class="function">make_foreignscan</code> to build the
96 <code class="structname">ForeignScan</code> node.
98 See <a class="xref" href="fdw-planning.html" title="58.4. Foreign Data Wrapper Query Planning">Section 58.4</a> for additional information.
100 </p><pre class="programlisting">
102 BeginForeignScan(ForeignScanState *node,
106 Begin executing a foreign scan. This is called during executor startup.
107 It should perform any initialization needed before the scan can start,
108 but not start executing the actual scan (that should be done upon the
109 first call to <code class="function">IterateForeignScan</code>).
110 The <code class="structname">ForeignScanState</code> node has already been created, but
111 its <code class="structfield">fdw_state</code> field is still NULL. Information about
112 the table to scan is accessible through the
113 <code class="structname">ForeignScanState</code> node (in particular, from the underlying
114 <code class="structname">ForeignScan</code> plan node, which contains any FDW-private
115 information provided by <code class="function">GetForeignPlan</code>).
116 <code class="literal">eflags</code> contains flag bits describing the executor's
117 operating mode for this plan node.
119 Note that when <code class="literal">(eflags & EXEC_FLAG_EXPLAIN_ONLY)</code> is
120 true, this function should not perform any externally-visible actions;
121 it should only do the minimum required to make the node state valid
122 for <code class="function">ExplainForeignScan</code> and <code class="function">EndForeignScan</code>.
124 </p><pre class="programlisting">
126 IterateForeignScan(ForeignScanState *node);
129 Fetch one row from the foreign source, returning it in a tuple table slot
130 (the node's <code class="structfield">ScanTupleSlot</code> should be used for this
131 purpose). Return NULL if no more rows are available. The tuple table
132 slot infrastructure allows either a physical or virtual tuple to be
133 returned; in most cases the latter choice is preferable from a
134 performance standpoint. Note that this is called in a short-lived memory
135 context that will be reset between invocations. Create a memory context
136 in <code class="function">BeginForeignScan</code> if you need longer-lived storage, or use
137 the <code class="structfield">es_query_cxt</code> of the node's <code class="structname">EState</code>.
139 The rows returned must match the <code class="structfield">fdw_scan_tlist</code> target
140 list if one was supplied, otherwise they must match the row type of the
141 foreign table being scanned. If you choose to optimize away fetching
142 columns that are not needed, you should insert nulls in those column
143 positions, or else generate a <code class="structfield">fdw_scan_tlist</code> list with
144 those columns omitted.
146 Note that <span class="productname">PostgreSQL</span>'s executor doesn't care
147 whether the rows returned violate any constraints that were defined on
148 the foreign table — but the planner does care, and may optimize
149 queries incorrectly if there are rows visible in the foreign table that
150 do not satisfy a declared constraint. If a constraint is violated when
151 the user has declared that the constraint should hold true, it may be
152 appropriate to raise an error (just as you would need to do in the case
153 of a data type mismatch).
155 </p><pre class="programlisting">
157 ReScanForeignScan(ForeignScanState *node);
160 Restart the scan from the beginning. Note that any parameters the
161 scan depends on may have changed value, so the new scan does not
162 necessarily return exactly the same rows.
164 </p><pre class="programlisting">
166 EndForeignScan(ForeignScanState *node);
169 End the scan and release resources. It is normally not important
170 to release palloc'd memory, but for example open files and connections
171 to remote servers should be cleaned up.
172 </p></div><div class="sect2" id="FDW-CALLBACKS-JOIN-SCAN"><div class="titlepage"><div><div><h3 class="title">58.2.2. FDW Routines for Scanning Foreign Joins <a href="#FDW-CALLBACKS-JOIN-SCAN" class="id_link">#</a></h3></div></div></div><p>
173 If an FDW supports performing foreign joins remotely (rather than
174 by fetching both tables' data and doing the join locally), it should
175 provide this callback function:
177 </p><pre class="programlisting">
179 GetForeignJoinPaths(PlannerInfo *root,
181 RelOptInfo *outerrel,
182 RelOptInfo *innerrel,
184 JoinPathExtraData *extra);
186 Create possible access paths for a join of two (or more) foreign tables
187 that all belong to the same foreign server. This optional
188 function is called during query planning. As
189 with <code class="function">GetForeignPaths</code>, this function should
190 generate <code class="structname">ForeignPath</code> path(s) for the
191 supplied <code class="literal">joinrel</code>
192 (use <code class="function">create_foreign_join_path</code> to build them),
193 and call <code class="function">add_path</code> to add these
194 paths to the set of paths considered for the join. But unlike
195 <code class="function">GetForeignPaths</code>, it is not necessary that this function
196 succeed in creating at least one path, since paths involving local
197 joining are always possible.
199 Note that this function will be invoked repeatedly for the same join
200 relation, with different combinations of inner and outer relations; it is
201 the responsibility of the FDW to minimize duplicated work.
203 Note also that the set of join clauses to apply to the join,
204 which is passed as <code class="literal">extra->restrictlist</code>, varies
205 depending on the combination of inner and outer relations. A
206 <code class="structname">ForeignPath</code> path generated for the
207 <code class="literal">joinrel</code> must contain the set of join clauses it uses,
208 which will be used by the planner to convert the
209 <code class="structname">ForeignPath</code> path into a plan, if it is selected
210 by the planner as the best path for the <code class="literal">joinrel</code>.
212 If a <code class="structname">ForeignPath</code> path is chosen for the join, it will
213 represent the entire join process; paths generated for the component
214 tables and subsidiary joins will not be used. Subsequent processing of
215 the join path proceeds much as it does for a path scanning a single
216 foreign table. One difference is that the <code class="structfield">scanrelid</code> of
217 the resulting <code class="structname">ForeignScan</code> plan node should be set to zero,
218 since there is no single relation that it represents; instead,
219 the <code class="structfield">fs_relids</code> field of the <code class="structname">ForeignScan</code>
220 node represents the set of relations that were joined. (The latter field
221 is set up automatically by the core planner code, and need not be filled
222 by the FDW.) Another difference is that, because the column list for a
223 remote join cannot be found from the system catalogs, the FDW must
224 fill <code class="structfield">fdw_scan_tlist</code> with an appropriate list
225 of <code class="structfield">TargetEntry</code> nodes, representing the set of columns
226 it will supply at run time in the tuples it returns.
227 </p><div class="note"><h3 class="title">Note</h3><p>
228 Beginning with <span class="productname">PostgreSQL</span> 16,
229 <code class="structfield">fs_relids</code> includes the rangetable indexes
230 of outer joins, if any were involved in this join. The new field
231 <code class="structfield">fs_base_relids</code> includes only base
232 relation indexes, and thus
233 mimics <code class="structfield">fs_relids</code>'s old semantics.
235 See <a class="xref" href="fdw-planning.html" title="58.4. Foreign Data Wrapper Query Planning">Section 58.4</a> for additional information.
236 </p></div><div class="sect2" id="FDW-CALLBACKS-UPPER-PLANNING"><div class="titlepage"><div><div><h3 class="title">58.2.3. FDW Routines for Planning Post-Scan/Join Processing <a href="#FDW-CALLBACKS-UPPER-PLANNING" class="id_link">#</a></h3></div></div></div><p>
237 If an FDW supports performing remote post-scan/join processing, such as
238 remote aggregation, it should provide this callback function:
240 </p><pre class="programlisting">
242 GetForeignUpperPaths(PlannerInfo *root,
243 UpperRelationKind stage,
244 RelOptInfo *input_rel,
245 RelOptInfo *output_rel,
248 Create possible access paths for <em class="firstterm">upper relation</em> processing,
249 which is the planner's term for all post-scan/join query processing, such
250 as aggregation, window functions, sorting, and table updates. This
251 optional function is called during query planning. Currently, it is
252 called only if all base relation(s) involved in the query belong to the
253 same FDW. This function should generate <code class="structname">ForeignPath</code>
254 path(s) for any post-scan/join processing that the FDW knows how to
256 (use <code class="function">create_foreign_upper_path</code> to build them),
257 and call <code class="function">add_path</code> to add these paths to
258 the indicated upper relation. As with <code class="function">GetForeignJoinPaths</code>,
259 it is not necessary that this function succeed in creating any paths,
260 since paths involving local processing are always possible.
262 The <code class="literal">stage</code> parameter identifies which post-scan/join step is
263 currently being considered. <code class="literal">output_rel</code> is the upper relation
264 that should receive paths representing computation of this step,
265 and <code class="literal">input_rel</code> is the relation representing the input to this
266 step. The <code class="literal">extra</code> parameter provides additional details,
267 currently, it is set only for <code class="literal">UPPERREL_PARTIAL_GROUP_AGG</code>
268 or <code class="literal">UPPERREL_GROUP_AGG</code>, in which case it points to a
269 <code class="literal">GroupPathExtraData</code> structure;
270 or for <code class="literal">UPPERREL_FINAL</code>, in which case it points to a
271 <code class="literal">FinalPathExtraData</code> structure.
272 (Note that <code class="structname">ForeignPath</code> paths added
273 to <code class="literal">output_rel</code> would typically not have any direct dependency
274 on paths of the <code class="literal">input_rel</code>, since their processing is expected
275 to be done externally. However, examining paths previously generated for
276 the previous processing step can be useful to avoid redundant planning
279 See <a class="xref" href="fdw-planning.html" title="58.4. Foreign Data Wrapper Query Planning">Section 58.4</a> for additional information.
280 </p></div><div class="sect2" id="FDW-CALLBACKS-UPDATE"><div class="titlepage"><div><div><h3 class="title">58.2.4. FDW Routines for Updating Foreign Tables <a href="#FDW-CALLBACKS-UPDATE" class="id_link">#</a></h3></div></div></div><p>
281 If an FDW supports writable foreign tables, it should provide
282 some or all of the following callback functions depending on
283 the needs and capabilities of the FDW:
285 </p><pre class="programlisting">
287 AddForeignUpdateTargets(PlannerInfo *root,
289 RangeTblEntry *target_rte,
290 Relation target_relation);
293 <code class="command">UPDATE</code> and <code class="command">DELETE</code> operations are performed
294 against rows previously fetched by the table-scanning functions. The
295 FDW may need extra information, such as a row ID or the values of
296 primary-key columns, to ensure that it can identify the exact row to
297 update or delete. To support that, this function can add extra hidden,
298 or <span class="quote">“<span class="quote">junk</span>”</span>, target columns to the list of columns that are to be
299 retrieved from the foreign table during an <code class="command">UPDATE</code> or
300 <code class="command">DELETE</code>.
302 To do that, construct a <code class="structname">Var</code> representing
303 an extra value you need, and pass it
304 to <code class="function">add_row_identity_var</code>, along with a name for
305 the junk column. (You can do this more than once if several columns
306 are needed.) You must choose a distinct junk column name for each
307 different <code class="structname">Var</code> you need, except
308 that <code class="structname">Var</code>s that are identical except for
309 the <code class="structfield">varno</code> field can and should share a
311 The core system uses the junk column names
312 <code class="literal">tableoid</code> for a
313 table's <code class="structfield">tableoid</code> column,
314 <code class="literal">ctid</code>
315 or <code class="literal">ctid<em class="replaceable"><code>N</code></em></code>
316 for <code class="structfield">ctid</code>,
317 <code class="literal">wholerow</code>
318 for a whole-row <code class="structname">Var</code> marked with
319 <code class="structfield">vartype</code> = <code class="type">RECORD</code>,
320 and <code class="literal">wholerow<em class="replaceable"><code>N</code></em></code>
321 for a whole-row <code class="structname">Var</code> with
322 <code class="structfield">vartype</code> equal to the table's declared row type.
323 Re-use these names when you can (the planner will combine duplicate
324 requests for identical junk columns). If you need another kind of
325 junk column besides these, it might be wise to choose a name prefixed
326 with your extension name, to avoid conflicts against other FDWs.
328 If the <code class="function">AddForeignUpdateTargets</code> pointer is set to
329 <code class="literal">NULL</code>, no extra target expressions are added.
330 (This will make it impossible to implement <code class="command">DELETE</code>
331 operations, though <code class="command">UPDATE</code> may still be feasible if the FDW
332 relies on an unchanging primary key to identify rows.)
334 </p><pre class="programlisting">
336 PlanForeignModify(PlannerInfo *root,
338 Index resultRelation,
342 Perform any additional planning actions needed for an insert, update, or
343 delete on a foreign table. This function generates the FDW-private
344 information that will be attached to the <code class="structname">ModifyTable</code> plan
345 node that performs the update action. This private information must
346 have the form of a <code class="literal">List</code>, and will be delivered to
347 <code class="function">BeginForeignModify</code> during the execution stage.
349 <code class="literal">root</code> is the planner's global information about the query.
350 <code class="literal">plan</code> is the <code class="structname">ModifyTable</code> plan node, which is
351 complete except for the <code class="structfield">fdwPrivLists</code> field.
352 <code class="literal">resultRelation</code> identifies the target foreign table by its
353 range table index. <code class="literal">subplan_index</code> identifies which target of
354 the <code class="structname">ModifyTable</code> plan node this is, counting from zero;
355 use this if you want to index into per-target-relation substructures of the
356 <code class="literal">plan</code> node.
358 See <a class="xref" href="fdw-planning.html" title="58.4. Foreign Data Wrapper Query Planning">Section 58.4</a> for additional information.
360 If the <code class="function">PlanForeignModify</code> pointer is set to
361 <code class="literal">NULL</code>, no additional plan-time actions are taken, and the
362 <code class="literal">fdw_private</code> list delivered to
363 <code class="function">BeginForeignModify</code> will be NIL.
365 </p><pre class="programlisting">
367 BeginForeignModify(ModifyTableState *mtstate,
368 ResultRelInfo *rinfo,
374 Begin executing a foreign table modification operation. This routine is
375 called during executor startup. It should perform any initialization
376 needed prior to the actual table modifications. Subsequently,
377 <code class="function">ExecForeignInsert/ExecForeignBatchInsert</code>,
378 <code class="function">ExecForeignUpdate</code> or
379 <code class="function">ExecForeignDelete</code> will be called for tuple(s) to be
380 inserted, updated, or deleted.
382 <code class="literal">mtstate</code> is the overall state of the
383 <code class="structname">ModifyTable</code> plan node being executed; global data about
384 the plan and execution state is available via this structure.
385 <code class="literal">rinfo</code> is the <code class="structname">ResultRelInfo</code> struct describing
386 the target foreign table. (The <code class="structfield">ri_FdwState</code> field of
387 <code class="structname">ResultRelInfo</code> is available for the FDW to store any
388 private state it needs for this operation.)
389 <code class="literal">fdw_private</code> contains the private data generated by
390 <code class="function">PlanForeignModify</code>, if any.
391 <code class="literal">subplan_index</code> identifies which target of
392 the <code class="structname">ModifyTable</code> plan node this is.
393 <code class="literal">eflags</code> contains flag bits describing the executor's
394 operating mode for this plan node.
396 Note that when <code class="literal">(eflags & EXEC_FLAG_EXPLAIN_ONLY)</code> is
397 true, this function should not perform any externally-visible actions;
398 it should only do the minimum required to make the node state valid
399 for <code class="function">ExplainForeignModify</code> and <code class="function">EndForeignModify</code>.
401 If the <code class="function">BeginForeignModify</code> pointer is set to
402 <code class="literal">NULL</code>, no action is taken during executor startup.
404 </p><pre class="programlisting">
406 ExecForeignInsert(EState *estate,
407 ResultRelInfo *rinfo,
408 TupleTableSlot *slot,
409 TupleTableSlot *planSlot);
412 Insert one tuple into the foreign table.
413 <code class="literal">estate</code> is global execution state for the query.
414 <code class="literal">rinfo</code> is the <code class="structname">ResultRelInfo</code> struct describing
415 the target foreign table.
416 <code class="literal">slot</code> contains the tuple to be inserted; it will match the
417 row-type definition of the foreign table.
418 <code class="literal">planSlot</code> contains the tuple that was generated by the
419 <code class="structname">ModifyTable</code> plan node's subplan; it differs from
420 <code class="literal">slot</code> in possibly containing additional <span class="quote">“<span class="quote">junk</span>”</span>
421 columns. (The <code class="literal">planSlot</code> is typically of little interest
422 for <code class="command">INSERT</code> cases, but is provided for completeness.)
424 The return value is either a slot containing the data that was actually
425 inserted (this might differ from the data supplied, for example as a
426 result of trigger actions), or NULL if no row was actually inserted
427 (again, typically as a result of triggers). The passed-in
428 <code class="literal">slot</code> can be re-used for this purpose.
430 The data in the returned slot is used only if the <code class="command">INSERT</code>
431 statement has a <code class="literal">RETURNING</code> clause or involves a view
432 <code class="literal">WITH CHECK OPTION</code>; or if the foreign table has
433 an <code class="literal">AFTER ROW</code> trigger. Triggers require all columns,
434 but the FDW could choose to optimize away returning some or all columns
435 depending on the contents of the <code class="literal">RETURNING</code> clause or
436 <code class="literal">WITH CHECK OPTION</code> constraints. Regardless, some slot
437 must be returned to indicate success, or the query's reported row count
440 If the <code class="function">ExecForeignInsert</code> pointer is set to
441 <code class="literal">NULL</code>, attempts to insert into the foreign table will fail
442 with an error message.
444 Note that this function is also called when inserting routed tuples into
445 a foreign-table partition or executing <code class="command">COPY FROM</code> on
446 a foreign table, in which case it is called in a different way than it
447 is in the <code class="command">INSERT</code> case. See the callback functions
448 described below that allow the FDW to support that.
450 </p><pre class="programlisting">
452 ExecForeignBatchInsert(EState *estate,
453 ResultRelInfo *rinfo,
454 TupleTableSlot **slots,
455 TupleTableSlot **planSlots,
459 Insert multiple tuples in bulk into the foreign table.
460 The parameters are the same for <code class="function">ExecForeignInsert</code>
461 except <code class="literal">slots</code> and <code class="literal">planSlots</code> contain
462 multiple tuples and <code class="literal">*numSlots</code> specifies the number of
463 tuples in those arrays.
465 The return value is an array of slots containing the data that was
466 actually inserted (this might differ from the data supplied, for
467 example as a result of trigger actions.)
468 The passed-in <code class="literal">slots</code> can be re-used for this purpose.
469 The number of successfully inserted tuples is returned in
470 <code class="literal">*numSlots</code>.
472 The data in the returned slot is used only if the <code class="command">INSERT</code>
473 statement involves a view
474 <code class="literal">WITH CHECK OPTION</code>; or if the foreign table has
475 an <code class="literal">AFTER ROW</code> trigger. Triggers require all columns,
476 but the FDW could choose to optimize away returning some or all columns
477 depending on the contents of the
478 <code class="literal">WITH CHECK OPTION</code> constraints.
480 If the <code class="function">ExecForeignBatchInsert</code> or
481 <code class="function">GetForeignModifyBatchSize</code> pointer is set to
482 <code class="literal">NULL</code>, attempts to insert into the foreign table will
483 use <code class="function">ExecForeignInsert</code>.
484 This function is not used if the <code class="command">INSERT</code> has the
485 <code class="literal">RETURNING</code> clause.
487 Note that this function is also called when inserting routed tuples into
488 a foreign-table partition or executing <code class="command">COPY FROM</code> on
489 a foreign table, in which case it is called in a different way than it
490 is in the <code class="command">INSERT</code> case. See the callback functions
491 described below that allow the FDW to support that.
493 </p><pre class="programlisting">
495 GetForeignModifyBatchSize(ResultRelInfo *rinfo);
498 Report the maximum number of tuples that a single
499 <code class="function">ExecForeignBatchInsert</code> call can handle for
500 the specified foreign table. The executor passes at most
501 the given number of tuples to <code class="function">ExecForeignBatchInsert</code>.
502 <code class="literal">rinfo</code> is the <code class="structname">ResultRelInfo</code> struct describing
503 the target foreign table.
504 The FDW is expected to provide a foreign server and/or foreign
505 table option for the user to set this value, or some hard-coded value.
507 If the <code class="function">ExecForeignBatchInsert</code> or
508 <code class="function">GetForeignModifyBatchSize</code> pointer is set to
509 <code class="literal">NULL</code>, attempts to insert into the foreign table will
510 use <code class="function">ExecForeignInsert</code>.
512 </p><pre class="programlisting">
514 ExecForeignUpdate(EState *estate,
515 ResultRelInfo *rinfo,
516 TupleTableSlot *slot,
517 TupleTableSlot *planSlot);
520 Update one tuple in the foreign table.
521 <code class="literal">estate</code> is global execution state for the query.
522 <code class="literal">rinfo</code> is the <code class="structname">ResultRelInfo</code> struct describing
523 the target foreign table.
524 <code class="literal">slot</code> contains the new data for the tuple; it will match the
525 row-type definition of the foreign table.
526 <code class="literal">planSlot</code> contains the tuple that was generated by the
527 <code class="structname">ModifyTable</code> plan node's subplan. Unlike
528 <code class="literal">slot</code>, this tuple contains only the new values for
529 columns changed by the query, so do not rely on attribute numbers of the
530 foreign table to index into <code class="literal">planSlot</code>.
531 Also, <code class="literal">planSlot</code> typically contains
532 additional <span class="quote">“<span class="quote">junk</span>”</span> columns. In particular, any junk columns
533 that were requested by <code class="function">AddForeignUpdateTargets</code> will
534 be available from this slot.
536 The return value is either a slot containing the row as it was actually
537 updated (this might differ from the data supplied, for example as a
538 result of trigger actions), or NULL if no row was actually updated
539 (again, typically as a result of triggers). The passed-in
540 <code class="literal">slot</code> can be re-used for this purpose.
542 The data in the returned slot is used only if the <code class="command">UPDATE</code>
543 statement has a <code class="literal">RETURNING</code> clause or involves a view
544 <code class="literal">WITH CHECK OPTION</code>; or if the foreign table has
545 an <code class="literal">AFTER ROW</code> trigger. Triggers require all columns,
546 but the FDW could choose to optimize away returning some or all columns
547 depending on the contents of the <code class="literal">RETURNING</code> clause or
548 <code class="literal">WITH CHECK OPTION</code> constraints. Regardless, some slot
549 must be returned to indicate success, or the query's reported row count
552 If the <code class="function">ExecForeignUpdate</code> pointer is set to
553 <code class="literal">NULL</code>, attempts to update the foreign table will fail
554 with an error message.
556 </p><pre class="programlisting">
558 ExecForeignDelete(EState *estate,
559 ResultRelInfo *rinfo,
560 TupleTableSlot *slot,
561 TupleTableSlot *planSlot);
564 Delete one tuple from the foreign table.
565 <code class="literal">estate</code> is global execution state for the query.
566 <code class="literal">rinfo</code> is the <code class="structname">ResultRelInfo</code> struct describing
567 the target foreign table.
568 <code class="literal">slot</code> contains nothing useful upon call, but can be used to
569 hold the returned tuple.
570 <code class="literal">planSlot</code> contains the tuple that was generated by the
571 <code class="structname">ModifyTable</code> plan node's subplan; in particular, it will
572 carry any junk columns that were requested by
573 <code class="function">AddForeignUpdateTargets</code>. The junk column(s) must be used
574 to identify the tuple to be deleted.
576 The return value is either a slot containing the row that was deleted,
577 or NULL if no row was deleted (typically as a result of triggers). The
578 passed-in <code class="literal">slot</code> can be used to hold the tuple to be returned.
580 The data in the returned slot is used only if the <code class="command">DELETE</code>
581 query has a <code class="literal">RETURNING</code> clause or the foreign table has
582 an <code class="literal">AFTER ROW</code> trigger. Triggers require all columns, but the
583 FDW could choose to optimize away returning some or all columns depending
584 on the contents of the <code class="literal">RETURNING</code> clause. Regardless, some
585 slot must be returned to indicate success, or the query's reported row
588 If the <code class="function">ExecForeignDelete</code> pointer is set to
589 <code class="literal">NULL</code>, attempts to delete from the foreign table will fail
590 with an error message.
592 </p><pre class="programlisting">
594 EndForeignModify(EState *estate,
595 ResultRelInfo *rinfo);
598 End the table update and release resources. It is normally not important
599 to release palloc'd memory, but for example open files and connections
600 to remote servers should be cleaned up.
602 If the <code class="function">EndForeignModify</code> pointer is set to
603 <code class="literal">NULL</code>, no action is taken during executor shutdown.
605 Tuples inserted into a partitioned table by <code class="command">INSERT</code> or
606 <code class="command">COPY FROM</code> are routed to partitions. If an FDW
607 supports routable foreign-table partitions, it should also provide the
608 following callback functions. These functions are also called when
609 <code class="command">COPY FROM</code> is executed on a foreign table.
611 </p><pre class="programlisting">
613 BeginForeignInsert(ModifyTableState *mtstate,
614 ResultRelInfo *rinfo);
617 Begin executing an insert operation on a foreign table. This routine is
618 called right before the first tuple is inserted into the foreign table
619 in both cases when it is the partition chosen for tuple routing and the
620 target specified in a <code class="command">COPY FROM</code> command. It should
621 perform any initialization needed prior to the actual insertion.
622 Subsequently, <code class="function">ExecForeignInsert</code> or
623 <code class="function">ExecForeignBatchInsert</code> will be called for
624 tuple(s) to be inserted into the foreign table.
626 <code class="literal">mtstate</code> is the overall state of the
627 <code class="structname">ModifyTable</code> plan node being executed; global data about
628 the plan and execution state is available via this structure.
629 <code class="literal">rinfo</code> is the <code class="structname">ResultRelInfo</code> struct describing
630 the target foreign table. (The <code class="structfield">ri_FdwState</code> field of
631 <code class="structname">ResultRelInfo</code> is available for the FDW to store any
632 private state it needs for this operation.)
634 When this is called by a <code class="command">COPY FROM</code> command, the
635 plan-related global data in <code class="literal">mtstate</code> is not provided
636 and the <code class="literal">planSlot</code> parameter of
637 <code class="function">ExecForeignInsert</code> subsequently called for each
638 inserted tuple is <code class="literal">NULL</code>, whether the foreign table is
639 the partition chosen for tuple routing or the target specified in the
642 If the <code class="function">BeginForeignInsert</code> pointer is set to
643 <code class="literal">NULL</code>, no action is taken for the initialization.
645 Note that if the FDW does not support routable foreign-table partitions
646 and/or executing <code class="command">COPY FROM</code> on foreign tables, this
647 function or <code class="function">ExecForeignInsert/ExecForeignBatchInsert</code>
648 subsequently called must throw error as needed.
650 </p><pre class="programlisting">
652 EndForeignInsert(EState *estate,
653 ResultRelInfo *rinfo);
656 End the insert operation and release resources. It is normally not important
657 to release palloc'd memory, but for example open files and connections
658 to remote servers should be cleaned up.
660 If the <code class="function">EndForeignInsert</code> pointer is set to
661 <code class="literal">NULL</code>, no action is taken for the termination.
663 </p><pre class="programlisting">
665 IsForeignRelUpdatable(Relation rel);
668 Report which update operations the specified foreign table supports.
669 The return value should be a bit mask of rule event numbers indicating
670 which operations are supported by the foreign table, using the
671 <code class="literal">CmdType</code> enumeration; that is,
672 <code class="literal">(1 << CMD_UPDATE) = 4</code> for <code class="command">UPDATE</code>,
673 <code class="literal">(1 << CMD_INSERT) = 8</code> for <code class="command">INSERT</code>, and
674 <code class="literal">(1 << CMD_DELETE) = 16</code> for <code class="command">DELETE</code>.
676 If the <code class="function">IsForeignRelUpdatable</code> pointer is set to
677 <code class="literal">NULL</code>, foreign tables are assumed to be insertable, updatable,
678 or deletable if the FDW provides <code class="function">ExecForeignInsert</code>,
679 <code class="function">ExecForeignUpdate</code>, or <code class="function">ExecForeignDelete</code>
680 respectively. This function is only needed if the FDW supports some
681 tables that are updatable and some that are not. (Even then, it's
682 permissible to throw an error in the execution routine instead of
683 checking in this function. However, this function is used to determine
684 updatability for display in the <code class="literal">information_schema</code> views.)
686 Some inserts, updates, and deletes to foreign tables can be optimized
687 by implementing an alternative set of interfaces. The ordinary
688 interfaces for inserts, updates, and deletes fetch rows from the remote
689 server and then modify those rows one at a time. In some cases, this
690 row-by-row approach is necessary, but it can be inefficient. If it is
691 possible for the foreign server to determine which rows should be
692 modified without actually retrieving them, and if there are no local
693 structures which would affect the operation (row-level local triggers,
694 stored generated columns, or <code class="literal">WITH CHECK OPTION</code>
695 constraints from parent views), then it is possible to arrange things
696 so that the entire operation is performed on the remote server. The
697 interfaces described below make this possible.
699 </p><pre class="programlisting">
701 PlanDirectModify(PlannerInfo *root,
703 Index resultRelation,
707 Decide whether it is safe to execute a direct modification
708 on the remote server. If so, return <code class="literal">true</code> after performing
709 planning actions needed for that. Otherwise, return <code class="literal">false</code>.
710 This optional function is called during query planning.
711 If this function succeeds, <code class="function">BeginDirectModify</code>,
712 <code class="function">IterateDirectModify</code> and <code class="function">EndDirectModify</code> will
713 be called at the execution stage, instead. Otherwise, the table
714 modification will be executed using the table-updating functions
716 The parameters are the same as for <code class="function">PlanForeignModify</code>.
718 To execute the direct modification on the remote server, this function
719 must rewrite the target subplan with a <code class="structname">ForeignScan</code> plan
720 node that executes the direct modification on the remote server. The
721 <code class="structfield">operation</code> and <code class="structfield">resultRelation</code> fields
722 of the <code class="structname">ForeignScan</code> must be set appropriately.
723 <code class="structfield">operation</code> must be set to the <code class="literal">CmdType</code>
724 enumeration corresponding to the statement kind (that is,
725 <code class="literal">CMD_UPDATE</code> for <code class="command">UPDATE</code>,
726 <code class="literal">CMD_INSERT</code> for <code class="command">INSERT</code>, and
727 <code class="literal">CMD_DELETE</code> for <code class="command">DELETE</code>), and the
728 <code class="literal">resultRelation</code> argument must be copied to the
729 <code class="structfield">resultRelation</code> field.
731 See <a class="xref" href="fdw-planning.html" title="58.4. Foreign Data Wrapper Query Planning">Section 58.4</a> for additional information.
733 If the <code class="function">PlanDirectModify</code> pointer is set to
734 <code class="literal">NULL</code>, no attempts to execute a direct modification on the
735 remote server are taken.
737 </p><pre class="programlisting">
739 BeginDirectModify(ForeignScanState *node,
743 Prepare to execute a direct modification on the remote server.
744 This is called during executor startup. It should perform any
745 initialization needed prior to the direct modification (that should be
746 done upon the first call to <code class="function">IterateDirectModify</code>).
747 The <code class="structname">ForeignScanState</code> node has already been created, but
748 its <code class="structfield">fdw_state</code> field is still NULL. Information about
749 the table to modify is accessible through the
750 <code class="structname">ForeignScanState</code> node (in particular, from the underlying
751 <code class="structname">ForeignScan</code> plan node, which contains any FDW-private
752 information provided by <code class="function">PlanDirectModify</code>).
753 <code class="literal">eflags</code> contains flag bits describing the executor's
754 operating mode for this plan node.
756 Note that when <code class="literal">(eflags & EXEC_FLAG_EXPLAIN_ONLY)</code> is
757 true, this function should not perform any externally-visible actions;
758 it should only do the minimum required to make the node state valid
759 for <code class="function">ExplainDirectModify</code> and <code class="function">EndDirectModify</code>.
761 If the <code class="function">BeginDirectModify</code> pointer is set to
762 <code class="literal">NULL</code>, no attempts to execute a direct modification on the
763 remote server are taken.
765 </p><pre class="programlisting">
767 IterateDirectModify(ForeignScanState *node);
770 When the <code class="command">INSERT</code>, <code class="command">UPDATE</code> or <code class="command">DELETE</code>
771 query doesn't have a <code class="literal">RETURNING</code> clause, just return NULL
772 after a direct modification on the remote server.
773 When the query has the clause, fetch one result containing the data
774 needed for the <code class="literal">RETURNING</code> calculation, returning it in a
775 tuple table slot (the node's <code class="structfield">ScanTupleSlot</code> should be
776 used for this purpose). The data that was actually inserted, updated
777 or deleted must be stored in
778 <code class="literal">node->resultRelInfo->ri_projectReturning->pi_exprContext->ecxt_scantuple</code>.
779 Return NULL if no more rows are available.
780 Note that this is called in a short-lived memory context that will be
781 reset between invocations. Create a memory context in
782 <code class="function">BeginDirectModify</code> if you need longer-lived storage, or use
783 the <code class="structfield">es_query_cxt</code> of the node's <code class="structname">EState</code>.
785 The rows returned must match the <code class="structfield">fdw_scan_tlist</code> target
786 list if one was supplied, otherwise they must match the row type of the
787 foreign table being updated. If you choose to optimize away fetching
788 columns that are not needed for the <code class="literal">RETURNING</code> calculation,
789 you should insert nulls in those column positions, or else generate a
790 <code class="structfield">fdw_scan_tlist</code> list with those columns omitted.
792 Whether the query has the clause or not, the query's reported row count
793 must be incremented by the FDW itself. When the query doesn't have the
794 clause, the FDW must also increment the row count for the
795 <code class="structname">ForeignScanState</code> node in the <code class="command">EXPLAIN ANALYZE</code>
798 If the <code class="function">IterateDirectModify</code> pointer is set to
799 <code class="literal">NULL</code>, no attempts to execute a direct modification on the
800 remote server are taken.
802 </p><pre class="programlisting">
804 EndDirectModify(ForeignScanState *node);
807 Clean up following a direct modification on the remote server. It is
808 normally not important to release palloc'd memory, but for example open
809 files and connections to the remote server should be cleaned up.
811 If the <code class="function">EndDirectModify</code> pointer is set to
812 <code class="literal">NULL</code>, no attempts to execute a direct modification on the
813 remote server are taken.
814 </p></div><div class="sect2" id="FDW-CALLBACKS-TRUNCATE"><div class="titlepage"><div><div><h3 class="title">58.2.5. FDW Routines for <code class="command">TRUNCATE</code> <a href="#FDW-CALLBACKS-TRUNCATE" class="id_link">#</a></h3></div></div></div><p>
815 </p><pre class="programlisting">
817 ExecForeignTruncate(List *rels,
818 DropBehavior behavior,
822 Truncate foreign tables. This function is called when
823 <a class="xref" href="sql-truncate.html" title="TRUNCATE"><span class="refentrytitle">TRUNCATE</span></a> is executed on a foreign table.
824 <code class="literal">rels</code> is a list of <code class="structname">Relation</code>
825 data structures of foreign tables to truncate.
827 <code class="literal">behavior</code> is either <code class="literal">DROP_RESTRICT</code>
828 or <code class="literal">DROP_CASCADE</code> indicating that the
829 <code class="literal">RESTRICT</code> or <code class="literal">CASCADE</code> option was
830 requested in the original <code class="command">TRUNCATE</code> command,
833 If <code class="literal">restart_seqs</code> is <code class="literal">true</code>,
834 the original <code class="command">TRUNCATE</code> command requested the
835 <code class="literal">RESTART IDENTITY</code> behavior, otherwise the
836 <code class="literal">CONTINUE IDENTITY</code> behavior was requested.
838 Note that the <code class="literal">ONLY</code> options specified
839 in the original <code class="command">TRUNCATE</code> command are not passed to
840 <code class="function">ExecForeignTruncate</code>. This behavior is similar to
841 the callback functions of <code class="command">SELECT</code>,
842 <code class="command">UPDATE</code> and <code class="command">DELETE</code> on
845 <code class="function">ExecForeignTruncate</code> is invoked once per
846 foreign server for which foreign tables are to be truncated.
847 This means that all foreign tables included in <code class="literal">rels</code>
848 must belong to the same server.
850 If the <code class="function">ExecForeignTruncate</code> pointer is set to
851 <code class="literal">NULL</code>, attempts to truncate foreign tables will
852 fail with an error message.
853 </p></div><div class="sect2" id="FDW-CALLBACKS-ROW-LOCKING"><div class="titlepage"><div><div><h3 class="title">58.2.6. FDW Routines for Row Locking <a href="#FDW-CALLBACKS-ROW-LOCKING" class="id_link">#</a></h3></div></div></div><p>
854 If an FDW wishes to support <em class="firstterm">late row locking</em> (as described
855 in <a class="xref" href="fdw-row-locking.html" title="58.5. Row Locking in Foreign Data Wrappers">Section 58.5</a>), it must provide the following
858 </p><pre class="programlisting">
860 GetForeignRowMarkType(RangeTblEntry *rte,
861 LockClauseStrength strength);
864 Report which row-marking option to use for a foreign table.
865 <code class="literal">rte</code> is the <code class="structname">RangeTblEntry</code> node for the table
866 and <code class="literal">strength</code> describes the lock strength requested by the
867 relevant <code class="literal">FOR UPDATE/SHARE</code> clause, if any. The result must be
868 a member of the <code class="literal">RowMarkType</code> enum type.
870 This function is called during query planning for each foreign table that
871 appears in an <code class="command">UPDATE</code>, <code class="command">DELETE</code>, or <code class="command">SELECT
872 FOR UPDATE/SHARE</code> query and is not the target of <code class="command">UPDATE</code>
873 or <code class="command">DELETE</code>.
875 If the <code class="function">GetForeignRowMarkType</code> pointer is set to
876 <code class="literal">NULL</code>, the <code class="literal">ROW_MARK_COPY</code> option is always used.
877 (This implies that <code class="function">RefetchForeignRow</code> will never be called,
878 so it need not be provided either.)
880 See <a class="xref" href="fdw-row-locking.html" title="58.5. Row Locking in Foreign Data Wrappers">Section 58.5</a> for more information.
882 </p><pre class="programlisting">
884 RefetchForeignRow(EState *estate,
887 TupleTableSlot *slot,
891 Re-fetch one tuple slot from the foreign table, after locking it if required.
892 <code class="literal">estate</code> is global execution state for the query.
893 <code class="literal">erm</code> is the <code class="structname">ExecRowMark</code> struct describing
894 the target foreign table and the row lock type (if any) to acquire.
895 <code class="literal">rowid</code> identifies the tuple to be fetched.
896 <code class="literal">slot</code> contains nothing useful upon call, but can be used to
897 hold the returned tuple. <code class="literal">updated</code> is an output parameter.
899 This function should store the tuple into the provided slot, or clear it if
900 the row lock couldn't be obtained. The row lock type to acquire is
901 defined by <code class="literal">erm->markType</code>, which is the value
902 previously returned by <code class="function">GetForeignRowMarkType</code>.
903 (<code class="literal">ROW_MARK_REFERENCE</code> means to just re-fetch the tuple
904 without acquiring any lock, and <code class="literal">ROW_MARK_COPY</code> will
905 never be seen by this routine.)
907 In addition, <code class="literal">*updated</code> should be set to <code class="literal">true</code>
908 if what was fetched was an updated version of the tuple rather than
909 the same version previously obtained. (If the FDW cannot be sure about
910 this, always returning <code class="literal">true</code> is recommended.)
912 Note that by default, failure to acquire a row lock should result in
913 raising an error; returning with an empty slot is only appropriate if
914 the <code class="literal">SKIP LOCKED</code> option is specified
915 by <code class="literal">erm->waitPolicy</code>.
917 The <code class="literal">rowid</code> is the <code class="structfield">ctid</code> value previously read
918 for the row to be re-fetched. Although the <code class="literal">rowid</code> value is
919 passed as a <code class="type">Datum</code>, it can currently only be a <code class="type">tid</code>. The
920 function API is chosen in hopes that it may be possible to allow other
921 data types for row IDs in future.
923 If the <code class="function">RefetchForeignRow</code> pointer is set to
924 <code class="literal">NULL</code>, attempts to re-fetch rows will fail
925 with an error message.
927 See <a class="xref" href="fdw-row-locking.html" title="58.5. Row Locking in Foreign Data Wrappers">Section 58.5</a> for more information.
929 </p><pre class="programlisting">
931 RecheckForeignScan(ForeignScanState *node,
932 TupleTableSlot *slot);
934 Recheck that a previously-returned tuple still matches the relevant
935 scan and join qualifiers, and possibly provide a modified version of
936 the tuple. For foreign data wrappers which do not perform join pushdown,
937 it will typically be more convenient to set this to <code class="literal">NULL</code> and
938 instead set <code class="structfield">fdw_recheck_quals</code> appropriately.
939 When outer joins are pushed down, however, it isn't sufficient to
940 reapply the checks relevant to all the base tables to the result tuple,
941 even if all needed attributes are present, because failure to match some
942 qualifier might result in some attributes going to NULL, rather than in
943 no tuple being returned. <code class="literal">RecheckForeignScan</code> can recheck
944 qualifiers and return true if they are still satisfied and false
945 otherwise, but it can also store a replacement tuple into the supplied
948 To implement join pushdown, a foreign data wrapper will typically
949 construct an alternative local join plan which is used only for
950 rechecks; this will become the outer subplan of the
951 <code class="literal">ForeignScan</code>. When a recheck is required, this subplan
952 can be executed and the resulting tuple can be stored in the slot.
953 This plan need not be efficient since no base table will return more
954 than one row; for example, it may implement all joins as nested loops.
955 The function <code class="literal">GetExistingLocalJoinPath</code> may be used to search
956 existing paths for a suitable local join path, which can be used as the
957 alternative local join plan. <code class="literal">GetExistingLocalJoinPath</code>
958 searches for an unparameterized path in the path list of the specified
959 join relation. (If it does not find such a path, it returns NULL, in
960 which case a foreign data wrapper may build the local path by itself or
961 may choose not to create access paths for that join.)
962 </p></div><div class="sect2" id="FDW-CALLBACKS-EXPLAIN"><div class="titlepage"><div><div><h3 class="title">58.2.7. FDW Routines for <code class="command">EXPLAIN</code> <a href="#FDW-CALLBACKS-EXPLAIN" class="id_link">#</a></h3></div></div></div><p>
963 </p><pre class="programlisting">
965 ExplainForeignScan(ForeignScanState *node,
969 Print additional <code class="command">EXPLAIN</code> output for a foreign table scan.
970 This function can call <code class="function">ExplainPropertyText</code> and
971 related functions to add fields to the <code class="command">EXPLAIN</code> output.
972 The flag fields in <code class="literal">es</code> can be used to determine what to
973 print, and the state of the <code class="structname">ForeignScanState</code> node
974 can be inspected to provide run-time statistics in the <code class="command">EXPLAIN
977 If the <code class="function">ExplainForeignScan</code> pointer is set to
978 <code class="literal">NULL</code>, no additional information is printed during
979 <code class="command">EXPLAIN</code>.
981 </p><pre class="programlisting">
983 ExplainForeignModify(ModifyTableState *mtstate,
984 ResultRelInfo *rinfo,
987 struct ExplainState *es);
990 Print additional <code class="command">EXPLAIN</code> output for a foreign table update.
991 This function can call <code class="function">ExplainPropertyText</code> and
992 related functions to add fields to the <code class="command">EXPLAIN</code> output.
993 The flag fields in <code class="literal">es</code> can be used to determine what to
994 print, and the state of the <code class="structname">ModifyTableState</code> node
995 can be inspected to provide run-time statistics in the <code class="command">EXPLAIN
996 ANALYZE</code> case. The first four arguments are the same as for
997 <code class="function">BeginForeignModify</code>.
999 If the <code class="function">ExplainForeignModify</code> pointer is set to
1000 <code class="literal">NULL</code>, no additional information is printed during
1001 <code class="command">EXPLAIN</code>.
1003 </p><pre class="programlisting">
1005 ExplainDirectModify(ForeignScanState *node,
1009 Print additional <code class="command">EXPLAIN</code> output for a direct modification
1010 on the remote server.
1011 This function can call <code class="function">ExplainPropertyText</code> and
1012 related functions to add fields to the <code class="command">EXPLAIN</code> output.
1013 The flag fields in <code class="literal">es</code> can be used to determine what to
1014 print, and the state of the <code class="structname">ForeignScanState</code> node
1015 can be inspected to provide run-time statistics in the <code class="command">EXPLAIN
1016 ANALYZE</code> case.
1018 If the <code class="function">ExplainDirectModify</code> pointer is set to
1019 <code class="literal">NULL</code>, no additional information is printed during
1020 <code class="command">EXPLAIN</code>.
1021 </p></div><div class="sect2" id="FDW-CALLBACKS-ANALYZE"><div class="titlepage"><div><div><h3 class="title">58.2.8. FDW Routines for <code class="command">ANALYZE</code> <a href="#FDW-CALLBACKS-ANALYZE" class="id_link">#</a></h3></div></div></div><p>
1022 </p><pre class="programlisting">
1024 AnalyzeForeignTable(Relation relation,
1025 AcquireSampleRowsFunc *func,
1026 BlockNumber *totalpages);
1029 This function is called when <a class="xref" href="sql-analyze.html" title="ANALYZE"><span class="refentrytitle">ANALYZE</span></a> is executed on
1030 a foreign table. If the FDW can collect statistics for this
1031 foreign table, it should return <code class="literal">true</code>, and provide a pointer
1032 to a function that will collect sample rows from the table in
1033 <em class="parameter"><code>func</code></em>, plus the estimated size of the table in pages in
1034 <em class="parameter"><code>totalpages</code></em>. Otherwise, return <code class="literal">false</code>.
1036 If the FDW does not support collecting statistics for any tables, the
1037 <code class="function">AnalyzeForeignTable</code> pointer can be set to <code class="literal">NULL</code>.
1039 If provided, the sample collection function must have the signature
1040 </p><pre class="programlisting">
1042 AcquireSampleRowsFunc(Relation relation,
1047 double *totaldeadrows);
1050 A random sample of up to <em class="parameter"><code>targrows</code></em> rows should be collected
1051 from the table and stored into the caller-provided <em class="parameter"><code>rows</code></em>
1052 array. The actual number of rows collected must be returned. In
1053 addition, store estimates of the total numbers of live and dead rows in
1054 the table into the output parameters <em class="parameter"><code>totalrows</code></em> and
1055 <em class="parameter"><code>totaldeadrows</code></em>. (Set <em class="parameter"><code>totaldeadrows</code></em> to zero
1056 if the FDW does not have any concept of dead rows.)
1057 </p></div><div class="sect2" id="FDW-CALLBACKS-IMPORT"><div class="titlepage"><div><div><h3 class="title">58.2.9. FDW Routines for <code class="command">IMPORT FOREIGN SCHEMA</code> <a href="#FDW-CALLBACKS-IMPORT" class="id_link">#</a></h3></div></div></div><p>
1058 </p><pre class="programlisting">
1060 ImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid);
1063 Obtain a list of foreign table creation commands. This function is
1064 called when executing <a class="xref" href="sql-importforeignschema.html" title="IMPORT FOREIGN SCHEMA"><span class="refentrytitle">IMPORT FOREIGN SCHEMA</span></a>, and is
1065 passed the parse tree for that statement, as well as the OID of the
1066 foreign server to use. It should return a list of C strings, each of
1067 which must contain a <a class="xref" href="sql-createforeigntable.html" title="CREATE FOREIGN TABLE"><span class="refentrytitle">CREATE FOREIGN TABLE</span></a> command.
1068 These strings will be parsed and executed by the core server.
1070 Within the <code class="structname">ImportForeignSchemaStmt</code> struct,
1071 <code class="structfield">remote_schema</code> is the name of the remote schema from
1072 which tables are to be imported.
1073 <code class="structfield">list_type</code> identifies how to filter table names:
1074 <code class="literal">FDW_IMPORT_SCHEMA_ALL</code> means that all tables in the remote
1075 schema should be imported (in this case <code class="structfield">table_list</code> is
1076 empty), <code class="literal">FDW_IMPORT_SCHEMA_LIMIT_TO</code> means to include only
1077 tables listed in <code class="structfield">table_list</code>,
1078 and <code class="literal">FDW_IMPORT_SCHEMA_EXCEPT</code> means to exclude the tables
1079 listed in <code class="structfield">table_list</code>.
1080 <code class="structfield">options</code> is a list of options used for the import process.
1081 The meanings of the options are up to the FDW.
1082 For example, an FDW could use an option to define whether the
1083 <code class="literal">NOT NULL</code> attributes of columns should be imported.
1084 These options need not have anything to do with those supported by the
1085 FDW as database object options.
1087 The FDW may ignore the <code class="structfield">local_schema</code> field of
1088 the <code class="structname">ImportForeignSchemaStmt</code>, because the core server
1089 will automatically insert that name into the parsed <code class="command">CREATE
1090 FOREIGN TABLE</code> commands.
1092 The FDW does not have to concern itself with implementing the filtering
1093 specified by <code class="structfield">list_type</code> and <code class="structfield">table_list</code>,
1094 either, as the core server will automatically skip any returned commands
1095 for tables excluded according to those options. However, it's often
1096 useful to avoid the work of creating commands for excluded tables in the
1097 first place. The function <code class="function">IsImportableForeignTable()</code> may be
1098 useful to test whether a given foreign-table name will pass the filter.
1100 If the FDW does not support importing table definitions, the
1101 <code class="function">ImportForeignSchema</code> pointer can be set to <code class="literal">NULL</code>.
1102 </p></div><div class="sect2" id="FDW-CALLBACKS-PARALLEL"><div class="titlepage"><div><div><h3 class="title">58.2.10. FDW Routines for Parallel Execution <a href="#FDW-CALLBACKS-PARALLEL" class="id_link">#</a></h3></div></div></div><p>
1103 A <code class="structname">ForeignScan</code> node can, optionally, support parallel
1104 execution. A parallel <code class="structname">ForeignScan</code> will be executed
1105 in multiple processes and must return each row exactly once across
1106 all cooperating processes. To do this, processes can coordinate through
1107 fixed-size chunks of dynamic shared memory. This shared memory is not
1108 guaranteed to be mapped at the same address in every process, so it
1109 must not contain pointers. The following functions are all optional,
1110 but most are required if parallel execution is to be supported.
1112 </p><pre class="programlisting">
1114 IsForeignScanParallelSafe(PlannerInfo *root, RelOptInfo *rel,
1115 RangeTblEntry *rte);
1117 Test whether a scan can be performed within a parallel worker. This
1118 function will only be called when the planner believes that a parallel
1119 plan might be possible, and should return true if it is safe for that scan
1120 to run within a parallel worker. This will generally not be the case if
1121 the remote data source has transaction semantics, unless the worker's
1122 connection to the data can somehow be made to share the same transaction
1123 context as the leader.
1125 If this function is not defined, it is assumed that the scan must take
1126 place within the parallel leader. Note that returning true does not mean
1127 that the scan itself can be done in parallel, only that the scan can be
1128 performed within a parallel worker. Therefore, it can be useful to define
1129 this method even when parallel execution is not supported.
1131 </p><pre class="programlisting">
1133 EstimateDSMForeignScan(ForeignScanState *node, ParallelContext *pcxt);
1135 Estimate the amount of dynamic shared memory that will be required
1136 for parallel operation. This may be higher than the amount that will
1137 actually be used, but it must not be lower. The return value is in bytes.
1138 This function is optional, and can be omitted if not needed; but if it
1139 is omitted, the next three functions must be omitted as well, because
1140 no shared memory will be allocated for the FDW's use.
1142 </p><pre class="programlisting">
1144 InitializeDSMForeignScan(ForeignScanState *node, ParallelContext *pcxt,
1147 Initialize the dynamic shared memory that will be required for parallel
1148 operation. <code class="literal">coordinate</code> points to a shared memory area of
1149 size equal to the return value of <code class="function">EstimateDSMForeignScan</code>.
1150 This function is optional, and can be omitted if not needed.
1152 </p><pre class="programlisting">
1154 ReInitializeDSMForeignScan(ForeignScanState *node, ParallelContext *pcxt,
1157 Re-initialize the dynamic shared memory required for parallel operation
1158 when the foreign-scan plan node is about to be re-scanned.
1159 This function is optional, and can be omitted if not needed.
1160 Recommended practice is that this function reset only shared state,
1161 while the <code class="function">ReScanForeignScan</code> function resets only local
1162 state. Currently, this function will be called
1163 before <code class="function">ReScanForeignScan</code>, but it's best not to rely on
1166 </p><pre class="programlisting">
1168 InitializeWorkerForeignScan(ForeignScanState *node, shm_toc *toc,
1171 Initialize a parallel worker's local state based on the shared state
1172 set up by the leader during <code class="function">InitializeDSMForeignScan</code>.
1173 This function is optional, and can be omitted if not needed.
1175 </p><pre class="programlisting">
1177 ShutdownForeignScan(ForeignScanState *node);
1179 Release resources when it is anticipated the node will not be executed
1180 to completion. This is not called in all cases; sometimes,
1181 <code class="literal">EndForeignScan</code> may be called without this function having
1182 been called first. Since the DSM segment used by parallel query is
1183 destroyed just after this callback is invoked, foreign data wrappers that
1184 wish to take some action before the DSM segment goes away should implement
1186 </p></div><div class="sect2" id="FDW-CALLBACKS-ASYNC"><div class="titlepage"><div><div><h3 class="title">58.2.11. FDW Routines for Asynchronous Execution <a href="#FDW-CALLBACKS-ASYNC" class="id_link">#</a></h3></div></div></div><p>
1187 A <code class="structname">ForeignScan</code> node can, optionally, support
1188 asynchronous execution as described in
1189 <code class="filename">src/backend/executor/README</code>. The following
1190 functions are all optional, but are all required if asynchronous
1191 execution is to be supported.
1193 </p><pre class="programlisting">
1195 IsForeignPathAsyncCapable(ForeignPath *path);
1197 Test whether a given <code class="structname">ForeignPath</code> path can scan
1198 the underlying foreign relation asynchronously.
1199 This function will only be called at the end of query planning when the
1200 given path is a direct child of an <code class="structname">AppendPath</code>
1201 path and when the planner believes that asynchronous execution improves
1202 performance, and should return true if the given path is able to scan the
1203 foreign relation asynchronously.
1205 If this function is not defined, it is assumed that the given path scans
1206 the foreign relation using <code class="function">IterateForeignScan</code>.
1207 (This implies that the callback functions described below will never be
1208 called, so they need not be provided either.)
1210 </p><pre class="programlisting">
1212 ForeignAsyncRequest(AsyncRequest *areq);
1214 Produce one tuple asynchronously from the
1215 <code class="structname">ForeignScan</code> node. <code class="literal">areq</code> is
1216 the <code class="structname">AsyncRequest</code> struct describing the
1217 <code class="structname">ForeignScan</code> node and the parent
1218 <code class="structname">Append</code> node that requested the tuple from it.
1219 This function should store the tuple into the slot specified by
1220 <code class="literal">areq->result</code>, and set
1221 <code class="literal">areq->request_complete</code> to <code class="literal">true</code>;
1222 or if it needs to wait on an event external to the core server such as
1223 network I/O, and cannot produce any tuple immediately, set the flag to
1224 <code class="literal">false</code>, and set
1225 <code class="literal">areq->callback_pending</code> to <code class="literal">true</code>
1226 for the <code class="structname">ForeignScan</code> node to get a callback from
1227 the callback functions described below. If no more tuples are available,
1228 set the slot to NULL or an empty slot, and the
1229 <code class="literal">areq->request_complete</code> flag to
1230 <code class="literal">true</code>. It's recommended to use
1231 <code class="function">ExecAsyncRequestDone</code> or
1232 <code class="function">ExecAsyncRequestPending</code> to set the output parameters
1233 in the <code class="literal">areq</code>.
1235 </p><pre class="programlisting">
1237 ForeignAsyncConfigureWait(AsyncRequest *areq);
1239 Configure a file descriptor event for which the
1240 <code class="structname">ForeignScan</code> node wishes to wait.
1241 This function will only be called when the
1242 <code class="structname">ForeignScan</code> node has the
1243 <code class="literal">areq->callback_pending</code> flag set, and should add
1244 the event to the <code class="structfield">as_eventset</code> of the parent
1245 <code class="structname">Append</code> node described by the
1246 <code class="literal">areq</code>. See the comments for
1247 <code class="function">ExecAsyncConfigureWait</code> in
1248 <code class="filename">src/backend/executor/execAsync.c</code> for additional
1249 information. When the file descriptor event occurs,
1250 <code class="function">ForeignAsyncNotify</code> will be called.
1252 </p><pre class="programlisting">
1254 ForeignAsyncNotify(AsyncRequest *areq);
1256 Process a relevant event that has occurred, then produce one tuple
1257 asynchronously from the <code class="structname">ForeignScan</code> node.
1258 This function should set the output parameters in the
1259 <code class="literal">areq</code> in the same way as
1260 <code class="function">ForeignAsyncRequest</code>.
1261 </p></div><div class="sect2" id="FDW-CALLBACKS-REPARAMETERIZE-PATHS"><div class="titlepage"><div><div><h3 class="title">58.2.12. FDW Routines for Reparameterization of Paths <a href="#FDW-CALLBACKS-REPARAMETERIZE-PATHS" class="id_link">#</a></h3></div></div></div><p>
1262 </p><pre class="programlisting">
1264 ReparameterizeForeignPathByChild(PlannerInfo *root, List *fdw_private,
1265 RelOptInfo *child_rel);
1267 This function is called while converting a path parameterized by the
1268 top-most parent of the given child relation <code class="literal">child_rel</code> to be
1269 parameterized by the child relation. The function is used to reparameterize
1270 any paths or translate any expression nodes saved in the given
1271 <code class="literal">fdw_private</code> member of a <code class="structname">ForeignPath</code>. The
1272 callback may use <code class="literal">reparameterize_path_by_child</code>,
1273 <code class="literal">adjust_appendrel_attrs</code> or
1274 <code class="literal">adjust_appendrel_attrs_multilevel</code> as required.
1275 </p></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="fdw-functions.html" title="58.1. Foreign Data Wrapper Functions">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="fdwhandler.html" title="Chapter 58. Writing a Foreign Data Wrapper">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="fdw-helpers.html" title="58.3. Foreign Data Wrapper Helper Functions">Next</a></td></tr><tr><td width="40%" align="left" valign="top">58.1. Foreign Data Wrapper Functions </td><td width="20%" align="center"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="40%" align="right" valign="top"> 58.3. Foreign Data Wrapper Helper Functions</td></tr></table></div></body></html>