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>36.10. C-Language Functions</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="xfunc-internal.html" title="36.9. Internal Functions" /><link rel="next" href="xfunc-optimization.html" title="36.11. Function Optimization Information" /></head><body id="docContent" class="container-fluid col-10"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">36.10. C-Language Functions</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="xfunc-internal.html" title="36.9. Internal Functions">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="extend.html" title="Chapter 36. Extending SQL">Up</a></td><th width="60%" align="center">Chapter 36. Extending <acronym class="acronym">SQL</acronym></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="xfunc-optimization.html" title="36.11. Function Optimization Information">Next</a></td></tr></table><hr /></div><div class="sect1" id="XFUNC-C"><div class="titlepage"><div><div><h2 class="title" style="clear: both">36.10. C-Language Functions <a href="#XFUNC-C" class="id_link">#</a></h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-C-DYNLOAD">36.10.1. Dynamic Loading</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-C-BASETYPE">36.10.2. Base Types in C-Language Functions</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-C-V1-CALL-CONV">36.10.3. Version 1 Calling Conventions</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-C-CODE">36.10.4. Writing Code</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#DFUNC">36.10.5. Compiling and Linking Dynamically-Loaded Functions</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-API-ABI-STABILITY-GUIDANCE">36.10.6. Server API and ABI Stability Guidance</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-C-COMPOSITE-TYPE-ARGS">36.10.7. Composite-Type Arguments</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-C-RETURNING-ROWS">36.10.8. Returning Rows (Composite Types)</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-C-RETURN-SET">36.10.9. Returning Sets</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-C-POLYMORPHIC">36.10.10. Polymorphic Arguments and Return Types</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-SHARED-ADDIN">36.10.11. Shared Memory</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-ADDIN-LWLOCKS">36.10.12. LWLocks</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-ADDIN-WAIT-EVENTS">36.10.13. Custom Wait Events</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-ADDIN-INJECTION-POINTS">36.10.14. Injection Points</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-ADDIN-CUSTOM-CUMULATIVE-STATISTICS">36.10.15. Custom Cumulative Statistics</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#EXTEND-CPP">36.10.16. Using C++ for Extensibility</a></span></dt></dl></div><a id="id-1.8.3.13.2" class="indexterm"></a><p>
3 User-defined functions can be written in C (or a language that can
4 be made compatible with C, such as C++). Such functions are
5 compiled into dynamically loadable objects (also called shared
6 libraries) and are loaded by the server on demand. The dynamic
7 loading feature is what distinguishes <span class="quote">“<span class="quote">C language</span>”</span> functions
8 from <span class="quote">“<span class="quote">internal</span>”</span> functions — the actual coding conventions
9 are essentially the same for both. (Hence, the standard internal
10 function library is a rich source of coding examples for user-defined
13 Currently only one calling convention is used for C functions
14 (<span class="quote">“<span class="quote">version 1</span>”</span>). Support for that calling convention is
15 indicated by writing a <code class="literal">PG_FUNCTION_INFO_V1()</code> macro
16 call for the function, as illustrated below.
17 </p><div class="sect2" id="XFUNC-C-DYNLOAD"><div class="titlepage"><div><div><h3 class="title">36.10.1. Dynamic Loading <a href="#XFUNC-C-DYNLOAD" class="id_link">#</a></h3></div></div></div><a id="id-1.8.3.13.5.2" class="indexterm"></a><p>
18 The first time a user-defined function in a particular
19 loadable object file is called in a session,
20 the dynamic loader loads that object file into memory so that the
21 function can be called. The <code class="command">CREATE FUNCTION</code>
22 for a user-defined C function must therefore specify two pieces of
23 information for the function: the name of the loadable
24 object file, and the C name (link symbol) of the specific function to call
25 within that object file. If the C name is not explicitly specified then
26 it is assumed to be the same as the SQL function name.
28 The following algorithm is used to locate the shared object file
29 based on the name given in the <code class="command">CREATE FUNCTION</code>
32 </p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
33 If the name is an absolute path, the given file is loaded.
34 </p></li><li class="listitem"><p>
35 If the name starts with the string <code class="literal">$libdir</code>,
36 that part is replaced by the <span class="productname">PostgreSQL</span> package
38 name, which is determined at build time.<a id="id-1.8.3.13.5.4.2.2.1.3" class="indexterm"></a>
39 </p></li><li class="listitem"><p>
40 If the name does not contain a directory part, the file is
41 searched for in the path specified by the configuration variable
42 <a class="xref" href="runtime-config-client.html#GUC-DYNAMIC-LIBRARY-PATH">dynamic_library_path</a>.<a id="id-1.8.3.13.5.4.2.3.1.2" class="indexterm"></a>
43 </p></li><li class="listitem"><p>
44 Otherwise (the file was not found in the path, or it contains a
45 non-absolute directory part), the dynamic loader will try to
46 take the name as given, which will most likely fail. (It is
47 unreliable to depend on the current working directory.)
48 </p></li></ol></div><p>
50 If this sequence does not work, the platform-specific shared
51 library file name extension (often <code class="filename">.so</code>) is
52 appended to the given name and this sequence is tried again. If
53 that fails as well, the load will fail.
55 It is recommended to locate shared libraries either relative to
56 <code class="literal">$libdir</code> or through the dynamic library path.
57 This simplifies version upgrades if the new installation is at a
58 different location. The actual directory that
59 <code class="literal">$libdir</code> stands for can be found out with the
60 command <code class="literal">pg_config --pkglibdir</code>.
62 The user ID the <span class="productname">PostgreSQL</span> server runs
63 as must be able to traverse the path to the file you intend to
64 load. Making the file or a higher-level directory not readable
65 and/or not executable by the <span class="systemitem">postgres</span>
66 user is a common mistake.
68 In any case, the file name that is given in the
69 <code class="command">CREATE FUNCTION</code> command is recorded literally
70 in the system catalogs, so if the file needs to be loaded again
71 the same procedure is applied.
72 </p><div class="note"><h3 class="title">Note</h3><p>
73 <span class="productname">PostgreSQL</span> will not compile a C function
74 automatically. The object file must be compiled before it is referenced
75 in a <code class="command">CREATE
76 FUNCTION</code> command. See <a class="xref" href="xfunc-c.html#DFUNC" title="36.10.5. Compiling and Linking Dynamically-Loaded Functions">Section 36.10.5</a> for additional
78 </p></div><a id="id-1.8.3.13.5.9" class="indexterm"></a><a id="id-1.8.3.13.5.10" class="indexterm"></a><p>
79 To ensure that a dynamically loaded object file is not loaded into an
80 incompatible server, <span class="productname">PostgreSQL</span> checks that the
81 file contains a <span class="quote">“<span class="quote">magic block</span>”</span> with the appropriate contents.
82 This allows the server to detect obvious incompatibilities, such as code
83 compiled for a different major version of
84 <span class="productname">PostgreSQL</span>. To include a magic block,
85 write this in one (and only one) of the module source files, after having
86 included the header <code class="filename">fmgr.h</code>:
88 </p><pre class="programlisting">
92 </p><pre class="programlisting">
93 PG_MODULE_MAGIC_EXT(<em class="replaceable"><code>parameters</code></em>);
96 The <code class="literal">PG_MODULE_MAGIC_EXT</code> variant allows the specification
97 of additional information about the module; currently, a name and/or a
98 version string can be added. (More fields might be allowed in future.)
99 Write something like this:
101 </p><pre class="programlisting">
103 .name = "my_module_name",
108 Subsequently the name and version can be examined via
109 the <code class="function">pg_get_loaded_modules()</code> function.
110 The meaning of the version string is not restricted
111 by <span class="productname">PostgreSQL</span>, but use of semantic versioning
112 rules is recommended.
114 After it is used for the first time, a dynamically loaded object
115 file is retained in memory. Future calls in the same session to
116 the function(s) in that file will only incur the small overhead of
117 a symbol table lookup. If you need to force a reload of an object
118 file, for example after recompiling it, begin a fresh session.
119 </p><a id="id-1.8.3.13.5.14" class="indexterm"></a><a id="id-1.8.3.13.5.15" class="indexterm"></a><p>
120 Optionally, a dynamically loaded file can contain an initialization
121 function. If the file includes a function named
122 <code class="function">_PG_init</code>, that function will be called immediately after
123 loading the file. The function receives no parameters and should
124 return void. There is presently no way to unload a dynamically loaded file.
125 </p></div><div class="sect2" id="XFUNC-C-BASETYPE"><div class="titlepage"><div><div><h3 class="title">36.10.2. Base Types in C-Language Functions <a href="#XFUNC-C-BASETYPE" class="id_link">#</a></h3></div></div></div><a id="id-1.8.3.13.6.2" class="indexterm"></a><p>
126 To know how to write C-language functions, you need to know how
127 <span class="productname">PostgreSQL</span> internally represents base
128 data types and how they can be passed to and from functions.
129 Internally, <span class="productname">PostgreSQL</span> regards a base
130 type as a <span class="quote">“<span class="quote">blob of memory</span>”</span>. The user-defined
131 functions that you define over a type in turn define the way that
132 <span class="productname">PostgreSQL</span> can operate on it. That
133 is, <span class="productname">PostgreSQL</span> will only store and
134 retrieve the data from disk and use your user-defined functions
135 to input, process, and output the data.
137 Base types can have one of three internal formats:
139 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
140 pass by value, fixed-length
141 </p></li><li class="listitem"><p>
142 pass by reference, fixed-length
143 </p></li><li class="listitem"><p>
144 pass by reference, variable-length
145 </p></li></ul></div><p>
147 By-value types can only be 1, 2, or 4 bytes in length
148 (also 8 bytes, if <code class="literal">sizeof(Datum)</code> is 8 on your machine).
149 You should be careful to define your types such that they will be the
150 same size (in bytes) on all architectures. For example, the
151 <code class="literal">long</code> type is dangerous because it is 4 bytes on some
152 machines and 8 bytes on others, whereas <code class="type">int</code> type is 4 bytes
153 on most Unix machines. A reasonable implementation of the
154 <code class="type">int4</code> type on Unix machines might be:
156 </p><pre class="programlisting">
157 /* 4-byte integer, passed by value */
161 (The actual PostgreSQL C code calls this type <code class="type">int32</code>, because
162 it is a convention in C that <code class="type">int<em class="replaceable"><code>XX</code></em></code>
163 means <em class="replaceable"><code>XX</code></em> <span class="emphasis"><em>bits</em></span>. Note
164 therefore also that the C type <code class="type">int8</code> is 1 byte in size. The
165 SQL type <code class="type">int8</code> is called <code class="type">int64</code> in C. See also
166 <a class="xref" href="xfunc-c.html#XFUNC-C-TYPE-TABLE" title="Table 36.2. Equivalent C Types for Built-in SQL Types">Table 36.2</a>.)
168 On the other hand, fixed-length types of any size can
169 be passed by-reference. For example, here is a sample
170 implementation of a <span class="productname">PostgreSQL</span> type:
172 </p><pre class="programlisting">
173 /* 16-byte structure, passed by reference */
180 Only pointers to such types can be used when passing
181 them in and out of <span class="productname">PostgreSQL</span> functions.
182 To return a value of such a type, allocate the right amount of
183 memory with <code class="literal">palloc</code>, fill in the allocated memory,
184 and return a pointer to it. (Also, if you just want to return the
185 same value as one of your input arguments that's of the same data type,
186 you can skip the extra <code class="literal">palloc</code> and just return the
187 pointer to the input value.)
189 Finally, all variable-length types must also be passed
190 by reference. All variable-length types must begin
191 with an opaque length field of exactly 4 bytes, which will be set
192 by <code class="symbol">SET_VARSIZE</code>; never set this field directly! All data to
193 be stored within that type must be located in the memory
194 immediately following that length field. The
195 length field contains the total length of the structure,
196 that is, it includes the size of the length field
199 Another important point is to avoid leaving any uninitialized bits
200 within data type values; for example, take care to zero out any
201 alignment padding bytes that might be present in structs. Without
202 this, logically-equivalent constants of your data type might be
203 seen as unequal by the planner, leading to inefficient (though not
205 </p><div class="warning"><h3 class="title">Warning</h3><p>
206 <span class="emphasis"><em>Never</em></span> modify the contents of a pass-by-reference input
207 value. If you do so you are likely to corrupt on-disk data, since
208 the pointer you are given might point directly into a disk buffer.
209 The sole exception to this rule is explained in
210 <a class="xref" href="xaggr.html" title="36.12. User-Defined Aggregates">Section 36.12</a>.
212 As an example, we can define the type <code class="type">text</code> as
215 </p><pre class="programlisting">
218 char data[FLEXIBLE_ARRAY_MEMBER];
222 The <code class="literal">[FLEXIBLE_ARRAY_MEMBER]</code> notation means that the actual
223 length of the data part is not specified by this declaration.
226 variable-length types, we must be careful to allocate
227 the correct amount of memory and set the length field correctly.
228 For example, if we wanted to store 40 bytes in a <code class="structname">text</code>
229 structure, we might use a code fragment like this:
231 </p><pre class="programlisting">
232 #include "postgres.h"
234 char buffer[40]; /* our source data */
236 text *destination = (text *) palloc(VARHDRSZ + 40);
237 SET_VARSIZE(destination, VARHDRSZ + 40);
238 memcpy(destination->data, buffer, 40);
243 <code class="literal">VARHDRSZ</code> is the same as <code class="literal">sizeof(int32)</code>, but
244 it's considered good style to use the macro <code class="literal">VARHDRSZ</code>
245 to refer to the size of the overhead for a variable-length type.
246 Also, the length field <span class="emphasis"><em>must</em></span> be set using the
247 <code class="literal">SET_VARSIZE</code> macro, not by simple assignment.
249 <a class="xref" href="xfunc-c.html#XFUNC-C-TYPE-TABLE" title="Table 36.2. Equivalent C Types for Built-in SQL Types">Table 36.2</a> shows the C types
250 corresponding to many of the built-in SQL data types
251 of <span class="productname">PostgreSQL</span>.
252 The <span class="quote">“<span class="quote">Defined In</span>”</span> column gives the header file that
253 needs to be included to get the type definition. (The actual
254 definition might be in a different file that is included by the
255 listed file. It is recommended that users stick to the defined
256 interface.) Note that you should always include
257 <code class="filename">postgres.h</code> first in any source file of server
258 code, because it declares a number of things that you will need
259 anyway, and because including other headers first can cause
261 </p><div class="table" id="XFUNC-C-TYPE-TABLE"><p class="title"><strong>Table 36.2. Equivalent C Types for Built-in SQL Types</strong></p><div class="table-contents"><table class="table" summary="Equivalent C Types for Built-in SQL Types" border="1"><colgroup><col class="col1" /><col class="col2" /><col class="col3" /></colgroup><thead><tr><th>
267 </th></tr></thead><tbody><tr><td><code class="type">boolean</code></td><td><code class="type">bool</code></td><td><code class="filename">postgres.h</code> (maybe compiler built-in)</td></tr><tr><td><code class="type">box</code></td><td><code class="type">BOX*</code></td><td><code class="filename">utils/geo_decls.h</code></td></tr><tr><td><code class="type">bytea</code></td><td><code class="type">bytea*</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">"char"</code></td><td><code class="type">char</code></td><td>(compiler built-in)</td></tr><tr><td><code class="type">character</code></td><td><code class="type">BpChar*</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">cid</code></td><td><code class="type">CommandId</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">date</code></td><td><code class="type">DateADT</code></td><td><code class="filename">utils/date.h</code></td></tr><tr><td><code class="type">float4</code> (<code class="type">real</code>)</td><td><code class="type">float4</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">float8</code> (<code class="type">double precision</code>)</td><td><code class="type">float8</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">int2</code> (<code class="type">smallint</code>)</td><td><code class="type">int16</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">int4</code> (<code class="type">integer</code>)</td><td><code class="type">int32</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">int8</code> (<code class="type">bigint</code>)</td><td><code class="type">int64</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">interval</code></td><td><code class="type">Interval*</code></td><td><code class="filename">datatype/timestamp.h</code></td></tr><tr><td><code class="type">lseg</code></td><td><code class="type">LSEG*</code></td><td><code class="filename">utils/geo_decls.h</code></td></tr><tr><td><code class="type">name</code></td><td><code class="type">Name</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">numeric</code></td><td><code class="type">Numeric</code></td><td><code class="filename">utils/numeric.h</code></td></tr><tr><td><code class="type">oid</code></td><td><code class="type">Oid</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">oidvector</code></td><td><code class="type">oidvector*</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">path</code></td><td><code class="type">PATH*</code></td><td><code class="filename">utils/geo_decls.h</code></td></tr><tr><td><code class="type">point</code></td><td><code class="type">POINT*</code></td><td><code class="filename">utils/geo_decls.h</code></td></tr><tr><td><code class="type">regproc</code></td><td><code class="type">RegProcedure</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">text</code></td><td><code class="type">text*</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">tid</code></td><td><code class="type">ItemPointer</code></td><td><code class="filename">storage/itemptr.h</code></td></tr><tr><td><code class="type">time</code></td><td><code class="type">TimeADT</code></td><td><code class="filename">utils/date.h</code></td></tr><tr><td><code class="type">time with time zone</code></td><td><code class="type">TimeTzADT</code></td><td><code class="filename">utils/date.h</code></td></tr><tr><td><code class="type">timestamp</code></td><td><code class="type">Timestamp</code></td><td><code class="filename">datatype/timestamp.h</code></td></tr><tr><td><code class="type">timestamp with time zone</code></td><td><code class="type">TimestampTz</code></td><td><code class="filename">datatype/timestamp.h</code></td></tr><tr><td><code class="type">varchar</code></td><td><code class="type">VarChar*</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">xid</code></td><td><code class="type">TransactionId</code></td><td><code class="filename">postgres.h</code></td></tr></tbody></table></div></div><br class="table-break" /><p>
268 Now that we've gone over all of the possible structures
269 for base types, we can show some examples of real functions.
270 </p></div><div class="sect2" id="XFUNC-C-V1-CALL-CONV"><div class="titlepage"><div><div><h3 class="title">36.10.3. Version 1 Calling Conventions <a href="#XFUNC-C-V1-CALL-CONV" class="id_link">#</a></h3></div></div></div><p>
271 The version-1 calling convention relies on macros to suppress most
272 of the complexity of passing arguments and results. The C declaration
273 of a version-1 function is always:
274 </p><pre class="programlisting">
275 Datum funcname(PG_FUNCTION_ARGS)
277 In addition, the macro call:
278 </p><pre class="programlisting">
279 PG_FUNCTION_INFO_V1(funcname);
281 must appear in the same source file. (Conventionally, it's
282 written just before the function itself.) This macro call is not
283 needed for <code class="literal">internal</code>-language functions, since
284 <span class="productname">PostgreSQL</span> assumes that all internal functions
285 use the version-1 convention. It is, however, required for
286 dynamically-loaded functions.
288 In a version-1 function, each actual argument is fetched using a
289 <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>()</code>
290 macro that corresponds to the argument's data type. (In non-strict
291 functions there needs to be a previous check about argument null-ness
292 using <code class="function">PG_ARGISNULL()</code>; see below.)
293 The result is returned using a
294 <code class="function">PG_RETURN_<em class="replaceable"><code>xxx</code></em>()</code>
295 macro for the return type.
296 <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>()</code>
297 takes as its argument the number of the function argument to
298 fetch, where the count starts at 0.
299 <code class="function">PG_RETURN_<em class="replaceable"><code>xxx</code></em>()</code>
300 takes as its argument the actual value to return.
302 To call another version-1 function, you can use
303 <code class="function">DirectFunctionCall<em class="replaceable"><code>n</code></em>(func,
304 arg1, ..., argn)</code>. This is particularly useful when you want
305 to call functions defined in the standard internal library, by using an
306 interface similar to their SQL signature.
308 These convenience functions and similar ones can be found
309 in <code class="filename">fmgr.h</code>.
310 The <code class="function">DirectFunctionCall<em class="replaceable"><code>n</code></em></code>
311 family expect a C function name as their first argument. There are also
312 <code class="function">OidFunctionCall<em class="replaceable"><code>n</code></em></code> which
313 take the OID of the target function, and some other variants. All of
314 these expect the function's arguments to be supplied
315 as <code class="type">Datum</code>s, and likewise they return <code class="type">Datum</code>.
316 Note that neither arguments nor result are allowed to be NULL when
317 using these convenience functions.
319 For example, to call the <code class="function">starts_with(text, text)</code>
320 function from C, you can search through the catalog and find out that
321 its C implementation is the
322 <code class="function">Datum text_starts_with(PG_FUNCTION_ARGS)</code>
323 function. Typically you would
324 use <code class="literal">DirectFunctionCall2(text_starts_with, ...)</code> to
325 call such a function. However, <code class="function">starts_with(text,
326 text)</code> requires collation information, so it will fail
327 with <span class="quote">“<span class="quote">could not determine which collation to use for string
328 comparison</span>”</span> if called that way. Instead you must
329 use <code class="literal">DirectFunctionCall2Coll(text_starts_with, ...)</code>
330 and provide the desired collation, which typically is just passed
331 through from <code class="function">PG_GET_COLLATION()</code>, as shown in the
334 <code class="filename">fmgr.h</code> also supplies macros that facilitate
335 conversions between C types and <code class="type">Datum</code>. For example to
336 turn <code class="type">Datum</code> into <code class="type">text*</code>, you can
337 use <code class="function">DatumGetTextPP(X)</code>. While some types have macros
338 named like <code class="function">TypeGetDatum(X)</code> for the reverse
339 conversion, <code class="type">text*</code> does not; it's sufficient to use the
340 generic macro <code class="function">PointerGetDatum(X)</code> for that.
341 If your extension defines additional types, it is usually convenient to
342 define similar macros for your types too.
344 Here are some examples using the version-1 calling convention:
345 </p><pre class="programlisting">
346 #include "postgres.h"
347 #include <string.h>
349 #include "utils/geo_decls.h"
356 PG_FUNCTION_INFO_V1(add_one);
359 add_one(PG_FUNCTION_ARGS)
361 int32 arg = PG_GETARG_INT32(0);
363 PG_RETURN_INT32(arg + 1);
366 /* by reference, fixed length */
368 PG_FUNCTION_INFO_V1(add_one_float8);
371 add_one_float8(PG_FUNCTION_ARGS)
373 /* The macros for FLOAT8 hide its pass-by-reference nature. */
374 float8 arg = PG_GETARG_FLOAT8(0);
376 PG_RETURN_FLOAT8(arg + 1.0);
379 PG_FUNCTION_INFO_V1(makepoint);
382 makepoint(PG_FUNCTION_ARGS)
384 /* Here, the pass-by-reference nature of Point is not hidden. */
385 Point *pointx = PG_GETARG_POINT_P(0);
386 Point *pointy = PG_GETARG_POINT_P(1);
387 Point *new_point = (Point *) palloc(sizeof(Point));
389 new_point->x = pointx->x;
390 new_point->y = pointy->y;
392 PG_RETURN_POINT_P(new_point);
395 /* by reference, variable length */
397 PG_FUNCTION_INFO_V1(copytext);
400 copytext(PG_FUNCTION_ARGS)
402 text *t = PG_GETARG_TEXT_PP(0);
405 * VARSIZE_ANY_EXHDR is the size of the struct in bytes, minus the
406 * VARHDRSZ or VARHDRSZ_SHORT of its header. Construct the copy with a
407 * full-length header.
409 text *new_t = (text *) palloc(VARSIZE_ANY_EXHDR(t) + VARHDRSZ);
410 SET_VARSIZE(new_t, VARSIZE_ANY_EXHDR(t) + VARHDRSZ);
413 * VARDATA is a pointer to the data region of the new struct. The source
414 * could be a short datum, so retrieve its data through VARDATA_ANY.
416 memcpy(VARDATA(new_t), /* destination */
417 VARDATA_ANY(t), /* source */
418 VARSIZE_ANY_EXHDR(t)); /* how many bytes */
419 PG_RETURN_TEXT_P(new_t);
422 PG_FUNCTION_INFO_V1(concat_text);
425 concat_text(PG_FUNCTION_ARGS)
427 text *arg1 = PG_GETARG_TEXT_PP(0);
428 text *arg2 = PG_GETARG_TEXT_PP(1);
429 int32 arg1_size = VARSIZE_ANY_EXHDR(arg1);
430 int32 arg2_size = VARSIZE_ANY_EXHDR(arg2);
431 int32 new_text_size = arg1_size + arg2_size + VARHDRSZ;
432 text *new_text = (text *) palloc(new_text_size);
434 SET_VARSIZE(new_text, new_text_size);
435 memcpy(VARDATA(new_text), VARDATA_ANY(arg1), arg1_size);
436 memcpy(VARDATA(new_text) + arg1_size, VARDATA_ANY(arg2), arg2_size);
437 PG_RETURN_TEXT_P(new_text);
440 /* A wrapper around starts_with(text, text) */
442 PG_FUNCTION_INFO_V1(t_starts_with);
445 t_starts_with(PG_FUNCTION_ARGS)
447 text *t1 = PG_GETARG_TEXT_PP(0);
448 text *t2 = PG_GETARG_TEXT_PP(1);
449 Oid collid = PG_GET_COLLATION();
452 result = DatumGetBool(DirectFunctionCall2Coll(text_starts_with,
455 PointerGetDatum(t2)));
456 PG_RETURN_BOOL(result);
460 Supposing that the above code has been prepared in file
461 <code class="filename">funcs.c</code> and compiled into a shared object,
462 we could define the functions to <span class="productname">PostgreSQL</span>
463 with commands like this:
464 </p><pre class="programlisting">
465 CREATE FUNCTION add_one(integer) RETURNS integer
466 AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'add_one'
469 -- note overloading of SQL function name "add_one"
470 CREATE FUNCTION add_one(double precision) RETURNS double precision
471 AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'add_one_float8'
474 CREATE FUNCTION makepoint(point, point) RETURNS point
475 AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'makepoint'
478 CREATE FUNCTION copytext(text) RETURNS text
479 AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'copytext'
482 CREATE FUNCTION concat_text(text, text) RETURNS text
483 AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'concat_text'
486 CREATE FUNCTION t_starts_with(text, text) RETURNS boolean
487 AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 't_starts_with'
490 Here, <em class="replaceable"><code>DIRECTORY</code></em> stands for the
491 directory of the shared library file (for instance the
492 <span class="productname">PostgreSQL</span> tutorial directory, which
493 contains the code for the examples used in this section).
494 (Better style would be to use just <code class="literal">'funcs'</code> in the
495 <code class="literal">AS</code> clause, after having added
496 <em class="replaceable"><code>DIRECTORY</code></em> to the search path. In any
497 case, we can omit the system-specific extension for a shared
498 library, commonly <code class="literal">.so</code>.)
500 Notice that we have specified the functions as <span class="quote">“<span class="quote">strict</span>”</span>,
502 the system should automatically assume a null result if any input
503 value is null. By doing this, we avoid having to check for null inputs
504 in the function code. Without this, we'd have to check for null values
505 explicitly, using <code class="function">PG_ARGISNULL()</code>.
507 The macro <code class="function">PG_ARGISNULL(<em class="replaceable"><code>n</code></em>)</code>
508 allows a function to test whether each input is null. (Of course, doing
509 this is only necessary in functions not declared <span class="quote">“<span class="quote">strict</span>”</span>.)
511 <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>()</code> macros,
512 the input arguments are counted beginning at zero. Note that one
513 should refrain from executing
514 <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>()</code> until
515 one has verified that the argument isn't null.
516 To return a null result, execute <code class="function">PG_RETURN_NULL()</code>;
517 this works in both strict and nonstrict functions.
519 At first glance, the version-1 coding conventions might appear
520 to be just pointless obscurantism, compared to using
521 plain <code class="literal">C</code> calling conventions. They do however allow
522 us to deal with <code class="literal">NULL</code>able arguments/return values,
523 and <span class="quote">“<span class="quote">toasted</span>”</span> (compressed or out-of-line) values.
525 Other options provided by the version-1 interface are two
527 <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>()</code>
528 macros. The first of these,
529 <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>_COPY()</code>,
530 guarantees to return a copy of the specified argument that is
531 safe for writing into. (The normal macros will sometimes return a
532 pointer to a value that is physically stored in a table, which
533 must not be written to. Using the
534 <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>_COPY()</code>
535 macros guarantees a writable result.)
536 The second variant consists of the
537 <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>_SLICE()</code>
538 macros which take three arguments. The first is the number of the
539 function argument (as above). The second and third are the offset and
540 length of the segment to be returned. Offsets are counted from
541 zero, and a negative length requests that the remainder of the
542 value be returned. These macros provide more efficient access to
543 parts of large values in the case where they have storage type
544 <span class="quote">“<span class="quote">external</span>”</span>. (The storage type of a column can be specified using
545 <code class="literal">ALTER TABLE <em class="replaceable"><code>tablename</code></em> ALTER
546 COLUMN <em class="replaceable"><code>colname</code></em> SET STORAGE
547 <em class="replaceable"><code>storagetype</code></em></code>. <em class="replaceable"><code>storagetype</code></em> is one of
548 <code class="literal">plain</code>, <code class="literal">external</code>, <code class="literal">extended</code>,
549 or <code class="literal">main</code>.)
551 Finally, the version-1 function call conventions make it possible
552 to return set results (<a class="xref" href="xfunc-c.html#XFUNC-C-RETURN-SET" title="36.10.9. Returning Sets">Section 36.10.9</a>) and
553 implement trigger functions (<a class="xref" href="triggers.html" title="Chapter 37. Triggers">Chapter 37</a>) and
554 procedural-language call handlers (<a class="xref" href="plhandler.html" title="Chapter 57. Writing a Procedural Language Handler">Chapter 57</a>). For more details
555 see <code class="filename">src/backend/utils/fmgr/README</code> in the
557 </p></div><div class="sect2" id="XFUNC-C-CODE"><div class="titlepage"><div><div><h3 class="title">36.10.4. Writing Code <a href="#XFUNC-C-CODE" class="id_link">#</a></h3></div></div></div><p>
558 Before we turn to the more advanced topics, we should discuss
559 some coding rules for <span class="productname">PostgreSQL</span>
560 C-language functions. While it might be possible to load functions
561 written in languages other than C into
562 <span class="productname">PostgreSQL</span>, this is usually difficult
563 (when it is possible at all) because other languages, such as
564 C++, FORTRAN, or Pascal often do not follow the same calling
565 convention as C. That is, other languages do not pass argument
566 and return values between functions in the same way. For this
567 reason, we will assume that your C-language functions are
568 actually written in C.
570 The basic rules for writing and building C functions are as follows:
572 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
573 Use <code class="literal">pg_config
574 --includedir-server</code><a id="id-1.8.3.13.8.3.1.1.1.2" class="indexterm"></a>
575 to find out where the <span class="productname">PostgreSQL</span> server header
576 files are installed on your system (or the system that your
577 users will be running on).
578 </p></li><li class="listitem"><p>
579 Compiling and linking your code so that it can be dynamically
580 loaded into <span class="productname">PostgreSQL</span> always
581 requires special flags. See <a class="xref" href="xfunc-c.html#DFUNC" title="36.10.5. Compiling and Linking Dynamically-Loaded Functions">Section 36.10.5</a> for a
582 detailed explanation of how to do it for your particular
584 </p></li><li class="listitem"><p>
585 Remember to define a <span class="quote">“<span class="quote">magic block</span>”</span> for your shared library,
586 as described in <a class="xref" href="xfunc-c.html#XFUNC-C-DYNLOAD" title="36.10.1. Dynamic Loading">Section 36.10.1</a>.
587 </p></li><li class="listitem"><p>
588 When allocating memory, use the
589 <span class="productname">PostgreSQL</span> functions
590 <code class="function">palloc</code><a id="id-1.8.3.13.8.3.1.4.1.3" class="indexterm"></a> and <code class="function">pfree</code><a id="id-1.8.3.13.8.3.1.4.1.5" class="indexterm"></a>
591 instead of the corresponding C library functions
592 <code class="function">malloc</code> and <code class="function">free</code>.
593 The memory allocated by <code class="function">palloc</code> will be
594 freed automatically at the end of each transaction, preventing
596 </p></li><li class="listitem"><p>
597 Always zero the bytes of your structures using <code class="function">memset</code>
598 (or allocate them with <code class="function">palloc0</code> in the first place).
599 Even if you assign to each field of your structure, there might be
600 alignment padding (holes in the structure) that contain
601 garbage values. Without this, it's difficult to
602 support hash indexes or hash joins, as you must pick out only
603 the significant bits of your data structure to compute a hash.
604 The planner also sometimes relies on comparing constants via
605 bitwise equality, so you can get undesirable planning results if
606 logically-equivalent values aren't bitwise equal.
607 </p></li><li class="listitem"><p>
608 Most of the internal <span class="productname">PostgreSQL</span>
609 types are declared in <code class="filename">postgres.h</code>, while
610 the function manager interfaces
611 (<code class="symbol">PG_FUNCTION_ARGS</code>, etc.) are in
612 <code class="filename">fmgr.h</code>, so you will need to include at
613 least these two files. For portability reasons it's best to
614 include <code class="filename">postgres.h</code> <span class="emphasis"><em>first</em></span>,
615 before any other system or user header files. Including
616 <code class="filename">postgres.h</code> will also include
617 <code class="filename">elog.h</code> and <code class="filename">palloc.h</code>
619 </p></li><li class="listitem"><p>
620 Symbol names defined within object files must not conflict
621 with each other or with symbols defined in the
622 <span class="productname">PostgreSQL</span> server executable. You
623 will have to rename your functions or variables if you get
624 error messages to this effect.
625 </p></li></ul></div><p>
626 </p></div><div class="sect2" id="DFUNC"><div class="titlepage"><div><div><h3 class="title">36.10.5. Compiling and Linking Dynamically-Loaded Functions <a href="#DFUNC" class="id_link">#</a></h3></div></div></div><p>
627 Before you are able to use your
628 <span class="productname">PostgreSQL</span> extension functions written in
629 C, they must be compiled and linked in a special way to produce a
630 file that can be dynamically loaded by the server. To be precise, a
631 <em class="firstterm">shared library</em> needs to be
632 created.<a id="id-1.8.3.13.9.2.3" class="indexterm"></a>
635 For information beyond what is contained in this section
636 you should read the documentation of your
637 operating system, in particular the manual pages for the C compiler,
638 <code class="command">cc</code>, and the link editor, <code class="command">ld</code>.
639 In addition, the <span class="productname">PostgreSQL</span> source code
640 contains several working examples in the
641 <code class="filename">contrib</code> directory. If you rely on these
642 examples you will make your modules dependent on the availability
643 of the <span class="productname">PostgreSQL</span> source code, however.
645 Creating shared libraries is generally analogous to linking
646 executables: first the source files are compiled into object files,
647 then the object files are linked together. The object files need to
648 be created as <em class="firstterm">position-independent code</em>
649 (<acronym class="acronym">PIC</acronym>),<a id="id-1.8.3.13.9.4.3" class="indexterm"></a> which
650 conceptually means that they can be placed at an arbitrary location
651 in memory when they are loaded by the executable. (Object files
652 intended for executables are usually not compiled that way.) The
653 command to link a shared library contains special flags to
654 distinguish it from linking an executable (at least in theory
655 — on some systems the practice is much uglier).
657 In the following examples we assume that your source code is in a
658 file <code class="filename">foo.c</code> and we will create a shared library
659 <code class="filename">foo.so</code>. The intermediate object file will be
660 called <code class="filename">foo.o</code> unless otherwise noted. A shared
661 library can contain more than one object file, but we only use one
663 </p><div class="variablelist"><dl class="variablelist"><dt><span class="term">
664 <span class="systemitem">FreeBSD</span>
665 <a id="id-1.8.3.13.9.6.1.1.2" class="indexterm"></a>
667 The compiler flag to create <acronym class="acronym">PIC</acronym> is
668 <code class="option">-fPIC</code>. To create shared libraries the compiler
669 flag is <code class="option">-shared</code>.
670 </p><pre class="programlisting">
672 cc -shared -o foo.so foo.o
674 This is applicable as of version 13.0 of
675 <span class="systemitem">FreeBSD</span>, older versions used
676 the <code class="filename">gcc</code> compiler.
677 </p></dd><dt><span class="term">
678 <span class="systemitem">Linux</span>
679 <a id="id-1.8.3.13.9.6.2.1.2" class="indexterm"></a>
681 The compiler flag to create <acronym class="acronym">PIC</acronym> is
682 <code class="option">-fPIC</code>.
683 The compiler flag to create a shared library is
684 <code class="option">-shared</code>. A complete example looks like this:
685 </p><pre class="programlisting">
687 cc -shared -o foo.so foo.o
689 </p></dd><dt><span class="term">
690 <span class="systemitem">macOS</span>
691 <a id="id-1.8.3.13.9.6.3.1.2" class="indexterm"></a>
693 Here is an example. It assumes the developer tools are installed.
694 </p><pre class="programlisting">
696 cc -bundle -flat_namespace -undefined suppress -o foo.so foo.o
698 </p></dd><dt><span class="term">
699 <span class="systemitem">NetBSD</span>
700 <a id="id-1.8.3.13.9.6.4.1.2" class="indexterm"></a>
702 The compiler flag to create <acronym class="acronym">PIC</acronym> is
703 <code class="option">-fPIC</code>. For <acronym class="acronym">ELF</acronym> systems, the
704 compiler with the flag <code class="option">-shared</code> is used to link
705 shared libraries. On the older non-ELF systems, <code class="literal">ld
706 -Bshareable</code> is used.
707 </p><pre class="programlisting">
709 gcc -shared -o foo.so foo.o
711 </p></dd><dt><span class="term">
712 <span class="systemitem">OpenBSD</span>
713 <a id="id-1.8.3.13.9.6.5.1.2" class="indexterm"></a>
715 The compiler flag to create <acronym class="acronym">PIC</acronym> is
716 <code class="option">-fPIC</code>. <code class="literal">ld -Bshareable</code> is
717 used to link shared libraries.
718 </p><pre class="programlisting">
720 ld -Bshareable -o foo.so foo.o
722 </p></dd><dt><span class="term">
723 <span class="systemitem">Solaris</span>
724 <a id="id-1.8.3.13.9.6.6.1.2" class="indexterm"></a>
726 The compiler flag to create <acronym class="acronym">PIC</acronym> is
727 <code class="option">-KPIC</code> with the Sun compiler and
728 <code class="option">-fPIC</code> with <span class="application">GCC</span>. To
729 link shared libraries, the compiler option is
730 <code class="option">-G</code> with either compiler or alternatively
731 <code class="option">-shared</code> with <span class="application">GCC</span>.
732 </p><pre class="programlisting">
734 cc -G -o foo.so foo.o
737 </p><pre class="programlisting">
739 gcc -G -o foo.so foo.o
741 </p></dd></dl></div><div class="tip"><h3 class="title">Tip</h3><p>
742 If this is too complicated for you, you should consider using
743 <a class="ulink" href="https://www.gnu.org/software/libtool/" target="_top">
744 <span class="productname">GNU Libtool</span></a>,
745 which hides the platform differences behind a uniform interface.
747 The resulting shared library file can then be loaded into
748 <span class="productname">PostgreSQL</span>. When specifying the file name
749 to the <code class="command">CREATE FUNCTION</code> command, one must give it
750 the name of the shared library file, not the intermediate object file.
751 Note that the system's standard shared-library extension (usually
752 <code class="literal">.so</code> or <code class="literal">.sl</code>) can be omitted from
753 the <code class="command">CREATE FUNCTION</code> command, and normally should
754 be omitted for best portability.
756 Refer back to <a class="xref" href="xfunc-c.html#XFUNC-C-DYNLOAD" title="36.10.1. Dynamic Loading">Section 36.10.1</a> about where the
757 server expects to find the shared library files.
758 </p></div><div class="sect2" id="XFUNC-API-ABI-STABILITY-GUIDANCE"><div class="titlepage"><div><div><h3 class="title">36.10.6. Server API and ABI Stability Guidance <a href="#XFUNC-API-ABI-STABILITY-GUIDANCE" class="id_link">#</a></h3></div></div></div><p>
759 This section contains guidance to authors of extensions and other server
760 plugins about API and ABI stability in the
761 <span class="productname">PostgreSQL</span> server.
762 </p><div class="sect3" id="XFUNC-GUIDANCE-GENERAL"><div class="titlepage"><div><div><h4 class="title">36.10.6.1. General <a href="#XFUNC-GUIDANCE-GENERAL" class="id_link">#</a></h4></div></div></div><p>
763 The <span class="productname">PostgreSQL</span> server contains several
764 well-demarcated APIs for server plugins, such as the function manager
765 (<acronym class="acronym">fmgr</acronym>, described in this chapter),
766 <acronym class="acronym">SPI</acronym> (<a class="xref" href="spi.html" title="Chapter 45. Server Programming Interface">Chapter 45</a>), and various hooks
767 specifically designed for extensions. These interfaces are carefully
768 managed for long-term stability and compatibility. However, the entire
769 set of global functions and variables in the server effectively
770 constitutes the publicly usable API, and most of it was not designed
771 with extensibility and long-term stability in mind.
773 Therefore, while taking advantage of these interfaces is valid, the
774 further one strays from the well-trodden path, the likelier it will be
775 that one might encounter API or ABI compatibility issues at some point.
776 Extension authors are encouraged to provide feedback about their
777 requirements, so that over time, as new use patterns arise, certain
778 interfaces can be considered more stabilized or new, better-designed
779 interfaces can be added.
780 </p></div><div class="sect3" id="XFUNC-GUIDANCE-API-COMPATIBILITY"><div class="titlepage"><div><div><h4 class="title">36.10.6.2. API Compatibility <a href="#XFUNC-GUIDANCE-API-COMPATIBILITY" class="id_link">#</a></h4></div></div></div><p>
781 The <acronym class="acronym">API</acronym>, or application programming interface, is the
782 interface used at compile time.
783 </p><div class="sect4" id="XFUNC-GUIDANCE-API-MAJOR-VERSIONS"><div class="titlepage"><div><div><h5 class="title">36.10.6.2.1. Major Versions <a href="#XFUNC-GUIDANCE-API-MAJOR-VERSIONS" class="id_link">#</a></h5></div></div></div><p>
784 There is <span class="emphasis"><em>no</em></span> promise of API compatibility between
785 <span class="productname">PostgreSQL</span> major versions. Extension code
786 therefore might require source code changes to work with multiple major
787 versions. These can usually be managed with preprocessor conditions
788 such as <code class="literal">#if PG_VERSION_NUM >= 160000</code>.
789 Sophisticated extensions that use interfaces beyond the well-demarcated
790 ones usually require a few such changes for each major server version.
791 </p></div><div class="sect4" id="XFUNC-GUIDANCE-API-MNINOR-VERSIONS"><div class="titlepage"><div><div><h5 class="title">36.10.6.2.2. Minor Versions <a href="#XFUNC-GUIDANCE-API-MNINOR-VERSIONS" class="id_link">#</a></h5></div></div></div><p>
792 <span class="productname">PostgreSQL</span> makes an effort to avoid server
793 API breaks in minor releases. In general, extension code that compiles
794 and works with a minor release should also compile and work with any
795 other minor release of the same major version, past or future.
797 When a change <span class="emphasis"><em>is</em></span> required, it will be carefully
798 managed, taking the requirements of extensions into account. Such
799 changes will be communicated in the release notes (<a class="xref" href="release.html" title="Appendix E. Release Notes">Appendix E</a>).
800 </p></div></div><div class="sect3" id="XFUNC-GUIDANCE-ABI-COMPATIBILITY"><div class="titlepage"><div><div><h4 class="title">36.10.6.3. ABI Compatibility <a href="#XFUNC-GUIDANCE-ABI-COMPATIBILITY" class="id_link">#</a></h4></div></div></div><p>
801 The <acronym class="acronym">ABI</acronym>, or application binary interface, is the
802 interface used at run time.
803 </p><div class="sect4" id="XFUNC-GUIDANCE-ABI-MAJOR-VERSIONS"><div class="titlepage"><div><div><h5 class="title">36.10.6.3.1. Major Versions <a href="#XFUNC-GUIDANCE-ABI-MAJOR-VERSIONS" class="id_link">#</a></h5></div></div></div><p>
804 Servers of different major versions have intentionally incompatible
805 ABIs. Extensions that use server APIs must therefore be re-compiled for
806 each major release. The inclusion of <code class="literal">PG_MODULE_MAGIC</code>
807 (see <a class="xref" href="xfunc-c.html#XFUNC-C-DYNLOAD" title="36.10.1. Dynamic Loading">Section 36.10.1</a>) ensures that code compiled for
808 one major version will be rejected by other major versions.
809 </p></div><div class="sect4" id="XFUNC-GUIDANCE-ABI-MNINOR-VERSIONS"><div class="titlepage"><div><div><h5 class="title">36.10.6.3.2. Minor Versions <a href="#XFUNC-GUIDANCE-ABI-MNINOR-VERSIONS" class="id_link">#</a></h5></div></div></div><p>
810 <span class="productname">PostgreSQL</span> makes an effort to avoid server
811 ABI breaks in minor releases. In general, an extension compiled against
812 any minor release should work with any other minor release of the same
813 major version, past or future.
815 When a change <span class="emphasis"><em>is</em></span> required,
816 <span class="productname">PostgreSQL</span> will choose the least invasive
817 change possible, for example by squeezing a new field into padding
818 space or appending it to the end of a struct. These sorts of changes
819 should not impact extensions unless they use very unusual code
822 In rare cases, however, even such non-invasive changes may be
823 impractical or impossible. In such an event, the change will be
824 carefully managed, taking the requirements of extensions into account.
825 Such changes will also be documented in the release notes (<a class="xref" href="release.html" title="Appendix E. Release Notes">Appendix E</a>).
827 Note, however, that many parts of the server are not designed or
828 maintained as publicly-consumable APIs (and that, in most cases, the
829 actual boundary is also not well-defined). If urgent needs arise,
830 changes in those parts will naturally be made with less consideration
831 for extension code than changes in well-defined and widely used
834 Also, in the absence of automated detection of such changes, this is
835 not a guarantee, but historically such breaking changes have been
837 </p></div></div></div><div class="sect2" id="XFUNC-C-COMPOSITE-TYPE-ARGS"><div class="titlepage"><div><div><h3 class="title">36.10.7. Composite-Type Arguments <a href="#XFUNC-C-COMPOSITE-TYPE-ARGS" class="id_link">#</a></h3></div></div></div><p>
838 Composite types do not have a fixed layout like C structures.
839 Instances of a composite type can contain null fields. In
840 addition, composite types that are part of an inheritance
841 hierarchy can have different fields than other members of the
842 same inheritance hierarchy. Therefore,
843 <span class="productname">PostgreSQL</span> provides a function
844 interface for accessing fields of composite types from C.
846 Suppose we want to write a function to answer the query:
848 </p><pre class="programlisting">
849 SELECT name, c_overpaid(emp, 1500) AS overpaid
851 WHERE name = 'Bill' OR name = 'Sam';
854 Using the version-1 calling conventions, we can define
855 <code class="function">c_overpaid</code> as:
857 </p><pre class="programlisting">
858 #include "postgres.h"
859 #include "executor/executor.h" /* for GetAttributeByName() */
863 PG_FUNCTION_INFO_V1(c_overpaid);
866 c_overpaid(PG_FUNCTION_ARGS)
868 HeapTupleHeader t = PG_GETARG_HEAPTUPLEHEADER(0);
869 int32 limit = PG_GETARG_INT32(1);
873 salary = GetAttributeByName(t, "salary", &isnull);
875 PG_RETURN_BOOL(false);
876 /* Alternatively, we might prefer to do PG_RETURN_NULL() for null salary. */
878 PG_RETURN_BOOL(DatumGetInt32(salary) > limit);
883 <code class="function">GetAttributeByName</code> is the
884 <span class="productname">PostgreSQL</span> system function that
885 returns attributes out of the specified row. It has
886 three arguments: the argument of type <code class="type">HeapTupleHeader</code> passed
888 the function, the name of the desired attribute, and a
889 return parameter that tells whether the attribute
890 is null. <code class="function">GetAttributeByName</code> returns a <code class="type">Datum</code>
891 value that you can convert to the proper data type by using the
892 appropriate <code class="function">DatumGet<em class="replaceable"><code>XXX</code></em>()</code>
893 function. Note that the return value is meaningless if the null flag is
894 set; always check the null flag before trying to do anything with the
897 There is also <code class="function">GetAttributeByNum</code>, which selects
898 the target attribute by column number instead of name.
900 The following command declares the function
901 <code class="function">c_overpaid</code> in SQL:
903 </p><pre class="programlisting">
904 CREATE FUNCTION c_overpaid(emp, integer) RETURNS boolean
905 AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'c_overpaid'
909 Notice we have used <code class="literal">STRICT</code> so that we did not have to
910 check whether the input arguments were NULL.
911 </p></div><div class="sect2" id="XFUNC-C-RETURNING-ROWS"><div class="titlepage"><div><div><h3 class="title">36.10.8. Returning Rows (Composite Types) <a href="#XFUNC-C-RETURNING-ROWS" class="id_link">#</a></h3></div></div></div><p>
912 To return a row or composite-type value from a C-language
913 function, you can use a special API that provides macros and
914 functions to hide most of the complexity of building composite
915 data types. To use this API, the source file must include:
916 </p><pre class="programlisting">
920 There are two ways you can build a composite data value (henceforth
921 a <span class="quote">“<span class="quote">tuple</span>”</span>): you can build it from an array of Datum values,
922 or from an array of C strings that can be passed to the input
923 conversion functions of the tuple's column data types. In either
924 case, you first need to obtain or construct a <code class="structname">TupleDesc</code>
925 descriptor for the tuple structure. When working with Datums, you
926 pass the <code class="structname">TupleDesc</code> to <code class="function">BlessTupleDesc</code>,
927 and then call <code class="function">heap_form_tuple</code> for each row. When working
928 with C strings, you pass the <code class="structname">TupleDesc</code> to
929 <code class="function">TupleDescGetAttInMetadata</code>, and then call
930 <code class="function">BuildTupleFromCStrings</code> for each row. In the case of a
931 function returning a set of tuples, the setup steps can all be done
932 once during the first call of the function.
934 Several helper functions are available for setting up the needed
935 <code class="structname">TupleDesc</code>. The recommended way to do this in most
936 functions returning composite values is to call:
937 </p><pre class="programlisting">
938 TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo,
940 TupleDesc *resultTupleDesc)
942 passing the same <code class="literal">fcinfo</code> struct passed to the calling function
943 itself. (This of course requires that you use the version-1
944 calling conventions.) <code class="varname">resultTypeId</code> can be specified
945 as <code class="literal">NULL</code> or as the address of a local variable to receive the
946 function's result type OID. <code class="varname">resultTupleDesc</code> should be the
947 address of a local <code class="structname">TupleDesc</code> variable. Check that the
948 result is <code class="literal">TYPEFUNC_COMPOSITE</code>; if so,
949 <code class="varname">resultTupleDesc</code> has been filled with the needed
950 <code class="structname">TupleDesc</code>. (If it is not, you can report an error along
951 the lines of <span class="quote">“<span class="quote">function returning record called in context that
952 cannot accept type record</span>”</span>.)
953 </p><div class="tip"><h3 class="title">Tip</h3><p>
954 <code class="function">get_call_result_type</code> can resolve the actual type of a
955 polymorphic function result; so it is useful in functions that return
956 scalar polymorphic results, not only functions that return composites.
957 The <code class="varname">resultTypeId</code> output is primarily useful for functions
958 returning polymorphic scalars.
959 </p></div><div class="note"><h3 class="title">Note</h3><p>
960 <code class="function">get_call_result_type</code> has a sibling
961 <code class="function">get_expr_result_type</code>, which can be used to resolve the
962 expected output type for a function call represented by an expression
963 tree. This can be used when trying to determine the result type from
964 outside the function itself. There is also
965 <code class="function">get_func_result_type</code>, which can be used when only the
966 function's OID is available. However these functions are not able
967 to deal with functions declared to return <code class="structname">record</code>, and
968 <code class="function">get_func_result_type</code> cannot resolve polymorphic types,
969 so you should preferentially use <code class="function">get_call_result_type</code>.
971 Older, now-deprecated functions for obtaining
972 <code class="structname">TupleDesc</code>s are:
973 </p><pre class="programlisting">
974 TupleDesc RelationNameGetTupleDesc(const char *relname)
976 to get a <code class="structname">TupleDesc</code> for the row type of a named relation,
978 </p><pre class="programlisting">
979 TupleDesc TypeGetTupleDesc(Oid typeoid, List *colaliases)
981 to get a <code class="structname">TupleDesc</code> based on a type OID. This can
982 be used to get a <code class="structname">TupleDesc</code> for a base or
983 composite type. It will not work for a function that returns
984 <code class="structname">record</code>, however, and it cannot resolve polymorphic
987 Once you have a <code class="structname">TupleDesc</code>, call:
988 </p><pre class="programlisting">
989 TupleDesc BlessTupleDesc(TupleDesc tupdesc)
991 if you plan to work with Datums, or:
992 </p><pre class="programlisting">
993 AttInMetadata *TupleDescGetAttInMetadata(TupleDesc tupdesc)
995 if you plan to work with C strings. If you are writing a function
996 returning set, you can save the results of these functions in the
997 <code class="structname">FuncCallContext</code> structure — use the
998 <code class="structfield">tuple_desc</code> or <code class="structfield">attinmeta</code> field
1001 When working with Datums, use:
1002 </p><pre class="programlisting">
1003 HeapTuple heap_form_tuple(TupleDesc tupdesc, Datum *values, bool *isnull)
1005 to build a <code class="structname">HeapTuple</code> given user data in Datum form.
1007 When working with C strings, use:
1008 </p><pre class="programlisting">
1009 HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
1011 to build a <code class="structname">HeapTuple</code> given user data
1012 in C string form. <em class="parameter"><code>values</code></em> is an array of C strings,
1013 one for each attribute of the return row. Each C string should be in
1014 the form expected by the input function of the attribute data
1015 type. In order to return a null value for one of the attributes,
1016 the corresponding pointer in the <em class="parameter"><code>values</code></em> array
1017 should be set to <code class="symbol">NULL</code>. This function will need to
1018 be called again for each row you return.
1020 Once you have built a tuple to return from your function, it
1021 must be converted into a <code class="type">Datum</code>. Use:
1022 </p><pre class="programlisting">
1023 HeapTupleGetDatum(HeapTuple tuple)
1025 to convert a <code class="structname">HeapTuple</code> into a valid Datum. This
1026 <code class="type">Datum</code> can be returned directly if you intend to return
1027 just a single row, or it can be used as the current return value
1028 in a set-returning function.
1030 An example appears in the next section.
1031 </p></div><div class="sect2" id="XFUNC-C-RETURN-SET"><div class="titlepage"><div><div><h3 class="title">36.10.9. Returning Sets <a href="#XFUNC-C-RETURN-SET" class="id_link">#</a></h3></div></div></div><p>
1032 C-language functions have two options for returning sets (multiple
1033 rows). In one method, called <em class="firstterm">ValuePerCall</em>
1034 mode, a set-returning function is called repeatedly (passing the same
1035 arguments each time) and it returns one new row on each call, until
1036 it has no more rows to return and signals that by returning NULL.
1037 The set-returning function (<acronym class="acronym">SRF</acronym>) must therefore
1038 save enough state across calls to remember what it was doing and
1039 return the correct next item on each call.
1040 In the other method, called <em class="firstterm">Materialize</em> mode,
1041 an SRF fills and returns a tuplestore object containing its
1042 entire result; then only one call occurs for the whole result, and
1043 no inter-call state is needed.
1045 When using ValuePerCall mode, it is important to remember that the
1046 query is not guaranteed to be run to completion; that is, due to
1047 options such as <code class="literal">LIMIT</code>, the executor might stop
1048 making calls to the set-returning function before all rows have been
1049 fetched. This means it is not safe to perform cleanup activities in
1050 the last call, because that might not ever happen. It's recommended
1051 to use Materialize mode for functions that need access to external
1052 resources, such as file descriptors.
1054 The remainder of this section documents a set of helper macros that
1055 are commonly used (though not required to be used) for SRFs using
1056 ValuePerCall mode. Additional details about Materialize mode can be
1057 found in <code class="filename">src/backend/utils/fmgr/README</code>. Also,
1058 the <code class="filename">contrib</code> modules in
1059 the <span class="productname">PostgreSQL</span> source distribution contain
1060 many examples of SRFs using both ValuePerCall and Materialize mode.
1062 To use the ValuePerCall support macros described here,
1063 include <code class="filename">funcapi.h</code>. These macros work with a
1064 structure <code class="structname">FuncCallContext</code> that contains the
1065 state that needs to be saved across calls. Within the calling
1066 SRF, <code class="literal">fcinfo->flinfo->fn_extra</code> is used to
1067 hold a pointer to <code class="structname">FuncCallContext</code> across
1068 calls. The macros automatically fill that field on first use,
1069 and expect to find the same pointer there on subsequent uses.
1070 </p><pre class="programlisting">
1071 typedef struct FuncCallContext
1074 * Number of times we've been called before
1076 * call_cntr is initialized to 0 for you by SRF_FIRSTCALL_INIT(), and
1077 * incremented for you every time SRF_RETURN_NEXT() is called.
1082 * OPTIONAL maximum number of calls
1084 * max_calls is here for convenience only and setting it is optional.
1085 * If not set, you must provide alternative means to know when the
1091 * OPTIONAL pointer to miscellaneous user-provided context information
1093 * user_fctx is for use as a pointer to your own data to retain
1094 * arbitrary context information between calls of your function.
1099 * OPTIONAL pointer to struct containing attribute type input metadata
1101 * attinmeta is for use when returning tuples (i.e., composite data types)
1102 * and is not used when returning base data types. It is only needed
1103 * if you intend to use BuildTupleFromCStrings() to create the return
1106 AttInMetadata *attinmeta;
1109 * memory context used for structures that must live for multiple calls
1111 * multi_call_memory_ctx is set by SRF_FIRSTCALL_INIT() for you, and used
1112 * by SRF_RETURN_DONE() for cleanup. It is the most appropriate memory
1113 * context for any memory that is to be reused across multiple calls
1116 MemoryContext multi_call_memory_ctx;
1119 * OPTIONAL pointer to struct containing tuple description
1121 * tuple_desc is for use when returning tuples (i.e., composite data types)
1122 * and is only needed if you are going to build the tuples with
1123 * heap_form_tuple() rather than with BuildTupleFromCStrings(). Note that
1124 * the TupleDesc pointer stored here should usually have been run through
1125 * BlessTupleDesc() first.
1127 TupleDesc tuple_desc;
1132 The macros to be used by an <acronym class="acronym">SRF</acronym> using this
1134 </p><pre class="programlisting">
1137 Use this to determine if your function is being called for the first or a
1138 subsequent time. On the first call (only), call:
1139 </p><pre class="programlisting">
1140 SRF_FIRSTCALL_INIT()
1142 to initialize the <code class="structname">FuncCallContext</code>. On every function call,
1143 including the first, call:
1144 </p><pre class="programlisting">
1147 to set up for using the <code class="structname">FuncCallContext</code>.
1149 If your function has data to return in the current call, use:
1150 </p><pre class="programlisting">
1151 SRF_RETURN_NEXT(funcctx, result)
1153 to return it to the caller. (<code class="literal">result</code> must be of type
1154 <code class="type">Datum</code>, either a single value or a tuple prepared as
1155 described above.) Finally, when your function is finished
1156 returning data, use:
1157 </p><pre class="programlisting">
1158 SRF_RETURN_DONE(funcctx)
1160 to clean up and end the <acronym class="acronym">SRF</acronym>.
1162 The memory context that is current when the <acronym class="acronym">SRF</acronym> is called is
1163 a transient context that will be cleared between calls. This means
1164 that you do not need to call <code class="function">pfree</code> on everything
1165 you allocated using <code class="function">palloc</code>; it will go away anyway. However, if you want to allocate
1166 any data structures to live across calls, you need to put them somewhere
1167 else. The memory context referenced by
1168 <code class="structfield">multi_call_memory_ctx</code> is a suitable location for any
1169 data that needs to survive until the <acronym class="acronym">SRF</acronym> is finished running. In most
1170 cases, this means that you should switch into
1171 <code class="structfield">multi_call_memory_ctx</code> while doing the
1173 Use <code class="literal">funcctx->user_fctx</code> to hold a pointer to
1174 any such cross-call data structures.
1176 in <code class="structfield">multi_call_memory_ctx</code> will go away
1177 automatically when the query ends, so it is not necessary to free
1178 that data manually, either.)
1179 </p><div class="warning"><h3 class="title">Warning</h3><p>
1180 While the actual arguments to the function remain unchanged between
1181 calls, if you detoast the argument values (which is normally done
1182 transparently by the
1183 <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em></code> macro)
1184 in the transient context then the detoasted copies will be freed on
1185 each cycle. Accordingly, if you keep references to such values in
1186 your <code class="structfield">user_fctx</code>, you must either copy them into the
1187 <code class="structfield">multi_call_memory_ctx</code> after detoasting, or ensure
1188 that you detoast the values only in that context.
1190 A complete pseudo-code example looks like the following:
1191 </p><pre class="programlisting">
1193 my_set_returning_function(PG_FUNCTION_ARGS)
1195 FuncCallContext *funcctx;
1197 <em class="replaceable"><code>further declarations as needed</code></em>
1199 if (SRF_IS_FIRSTCALL())
1201 MemoryContext oldcontext;
1203 funcctx = SRF_FIRSTCALL_INIT();
1204 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1205 /* One-time setup code appears here: */
1206 <em class="replaceable"><code>user code</code></em>
1207 <em class="replaceable"><code>if returning composite</code></em>
1208 <em class="replaceable"><code>build TupleDesc, and perhaps AttInMetadata</code></em>
1209 <em class="replaceable"><code>endif returning composite</code></em>
1210 <em class="replaceable"><code>user code</code></em>
1211 MemoryContextSwitchTo(oldcontext);
1214 /* Each-time setup code appears here: */
1215 <em class="replaceable"><code>user code</code></em>
1216 funcctx = SRF_PERCALL_SETUP();
1217 <em class="replaceable"><code>user code</code></em>
1219 /* this is just one way we might test whether we are done: */
1220 if (funcctx->call_cntr < funcctx->max_calls)
1222 /* Here we want to return another item: */
1223 <em class="replaceable"><code>user code</code></em>
1224 <em class="replaceable"><code>obtain result Datum</code></em>
1225 SRF_RETURN_NEXT(funcctx, result);
1229 /* Here we are done returning items, so just report that fact. */
1230 /* (Resist the temptation to put cleanup code here.) */
1231 SRF_RETURN_DONE(funcctx);
1236 A complete example of a simple <acronym class="acronym">SRF</acronym> returning a composite type
1238 </p><pre class="programlisting">
1239 PG_FUNCTION_INFO_V1(retcomposite);
1242 retcomposite(PG_FUNCTION_ARGS)
1244 FuncCallContext *funcctx;
1248 AttInMetadata *attinmeta;
1250 /* stuff done only on the first call of the function */
1251 if (SRF_IS_FIRSTCALL())
1253 MemoryContext oldcontext;
1255 /* create a function context for cross-call persistence */
1256 funcctx = SRF_FIRSTCALL_INIT();
1258 /* switch to memory context appropriate for multiple function calls */
1259 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1261 /* total number of tuples to be returned */
1262 funcctx->max_calls = PG_GETARG_INT32(0);
1264 /* Build a tuple descriptor for our result type */
1265 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1267 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1268 errmsg("function returning record called in context "
1269 "that cannot accept type record")));
1272 * generate attribute metadata needed later to produce tuples from raw
1275 attinmeta = TupleDescGetAttInMetadata(tupdesc);
1276 funcctx->attinmeta = attinmeta;
1278 MemoryContextSwitchTo(oldcontext);
1281 /* stuff done on every call of the function */
1282 funcctx = SRF_PERCALL_SETUP();
1284 call_cntr = funcctx->call_cntr;
1285 max_calls = funcctx->max_calls;
1286 attinmeta = funcctx->attinmeta;
1288 if (call_cntr < max_calls) /* do when there is more left to send */
1295 * Prepare a values array for building the returned tuple.
1296 * This should be an array of C strings which will
1297 * be processed later by the type input functions.
1299 values = (char **) palloc(3 * sizeof(char *));
1300 values[0] = (char *) palloc(16 * sizeof(char));
1301 values[1] = (char *) palloc(16 * sizeof(char));
1302 values[2] = (char *) palloc(16 * sizeof(char));
1304 snprintf(values[0], 16, "%d", 1 * PG_GETARG_INT32(1));
1305 snprintf(values[1], 16, "%d", 2 * PG_GETARG_INT32(1));
1306 snprintf(values[2], 16, "%d", 3 * PG_GETARG_INT32(1));
1309 tuple = BuildTupleFromCStrings(attinmeta, values);
1311 /* make the tuple into a datum */
1312 result = HeapTupleGetDatum(tuple);
1314 /* clean up (this is not really necessary) */
1320 SRF_RETURN_NEXT(funcctx, result);
1322 else /* do when there is no more left */
1324 SRF_RETURN_DONE(funcctx);
1330 One way to declare this function in SQL is:
1331 </p><pre class="programlisting">
1332 CREATE TYPE __retcomposite AS (f1 integer, f2 integer, f3 integer);
1334 CREATE OR REPLACE FUNCTION retcomposite(integer, integer)
1335 RETURNS SETOF __retcomposite
1336 AS '<em class="replaceable"><code>filename</code></em>', 'retcomposite'
1337 LANGUAGE C IMMUTABLE STRICT;
1339 A different way is to use OUT parameters:
1340 </p><pre class="programlisting">
1341 CREATE OR REPLACE FUNCTION retcomposite(IN integer, IN integer,
1342 OUT f1 integer, OUT f2 integer, OUT f3 integer)
1343 RETURNS SETOF record
1344 AS '<em class="replaceable"><code>filename</code></em>', 'retcomposite'
1345 LANGUAGE C IMMUTABLE STRICT;
1347 Notice that in this method the output type of the function is formally
1348 an anonymous <code class="structname">record</code> type.
1349 </p></div><div class="sect2" id="XFUNC-C-POLYMORPHIC"><div class="titlepage"><div><div><h3 class="title">36.10.10. Polymorphic Arguments and Return Types <a href="#XFUNC-C-POLYMORPHIC" class="id_link">#</a></h3></div></div></div><p>
1350 C-language functions can be declared to accept and
1351 return the polymorphic types described in <a class="xref" href="extend-type-system.html#EXTEND-TYPES-POLYMORPHIC" title="36.2.5. Polymorphic Types">Section 36.2.5</a>.
1352 When a function's arguments or return types
1353 are defined as polymorphic types, the function author cannot know
1354 in advance what data type it will be called with, or
1355 need to return. There are two routines provided in <code class="filename">fmgr.h</code>
1356 to allow a version-1 C function to discover the actual data types
1357 of its arguments and the type it is expected to return. The routines are
1358 called <code class="literal">get_fn_expr_rettype(FmgrInfo *flinfo)</code> and
1359 <code class="literal">get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)</code>.
1360 They return the result or argument type OID, or <code class="symbol">InvalidOid</code> if the
1361 information is not available.
1362 The structure <code class="literal">flinfo</code> is normally accessed as
1363 <code class="literal">fcinfo->flinfo</code>. The parameter <code class="literal">argnum</code>
1364 is zero based. <code class="function">get_call_result_type</code> can also be used
1365 as an alternative to <code class="function">get_fn_expr_rettype</code>.
1366 There is also <code class="function">get_fn_expr_variadic</code>, which can be used to
1367 find out whether variadic arguments have been merged into an array.
1368 This is primarily useful for <code class="literal">VARIADIC "any"</code> functions,
1369 since such merging will always have occurred for variadic functions
1370 taking ordinary array types.
1372 For example, suppose we want to write a function to accept a single
1373 element of any type, and return a one-dimensional array of that type:
1375 </p><pre class="programlisting">
1376 PG_FUNCTION_INFO_V1(make_array);
1378 make_array(PG_FUNCTION_ARGS)
1381 Oid element_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
1391 if (!OidIsValid(element_type))
1392 elog(ERROR, "could not determine data type of input");
1394 /* get the provided element, being careful in case it's NULL */
1395 isnull = PG_ARGISNULL(0);
1397 element = (Datum) 0;
1399 element = PG_GETARG_DATUM(0);
1401 /* we have one dimension */
1403 /* and one element */
1405 /* and lower bound is 1 */
1408 /* get required info about the element type */
1409 get_typlenbyvalalign(element_type, &typlen, &typbyval, &typalign);
1411 /* now build the array */
1412 result = construct_md_array(&element, &isnull, ndims, dims, lbs,
1413 element_type, typlen, typbyval, typalign);
1415 PG_RETURN_ARRAYTYPE_P(result);
1419 The following command declares the function
1420 <code class="function">make_array</code> in SQL:
1422 </p><pre class="programlisting">
1423 CREATE FUNCTION make_array(anyelement) RETURNS anyarray
1424 AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'make_array'
1425 LANGUAGE C IMMUTABLE;
1428 There is a variant of polymorphism that is only available to C-language
1429 functions: they can be declared to take parameters of type
1430 <code class="literal">"any"</code>. (Note that this type name must be double-quoted,
1431 since it's also an SQL reserved word.) This works like
1432 <code class="type">anyelement</code> except that it does not constrain different
1433 <code class="literal">"any"</code> arguments to be the same type, nor do they help
1434 determine the function's result type. A C-language function can also
1435 declare its final parameter to be <code class="literal">VARIADIC "any"</code>. This will
1436 match one or more actual arguments of any type (not necessarily the same
1437 type). These arguments will <span class="emphasis"><em>not</em></span> be gathered into an array
1438 as happens with normal variadic functions; they will just be passed to
1439 the function separately. The <code class="function">PG_NARGS()</code> macro and the
1440 methods described above must be used to determine the number of actual
1441 arguments and their types when using this feature. Also, users of such
1442 a function might wish to use the <code class="literal">VARIADIC</code> keyword in their
1443 function call, with the expectation that the function would treat the
1444 array elements as separate arguments. The function itself must implement
1445 that behavior if wanted, after using <code class="function">get_fn_expr_variadic</code> to
1446 detect that the actual argument was marked with <code class="literal">VARIADIC</code>.
1447 </p></div><div class="sect2" id="XFUNC-SHARED-ADDIN"><div class="titlepage"><div><div><h3 class="title">36.10.11. Shared Memory <a href="#XFUNC-SHARED-ADDIN" class="id_link">#</a></h3></div></div></div><div class="sect3" id="XFUNC-SHARED-ADDIN-AT-STARTUP"><div class="titlepage"><div><div><h4 class="title">36.10.11.1. Requesting Shared Memory at Startup <a href="#XFUNC-SHARED-ADDIN-AT-STARTUP" class="id_link">#</a></h4></div></div></div><p>
1448 Add-ins can reserve shared memory on server startup. To do so, the
1449 add-in's shared library must be preloaded by specifying it in
1450 <a class="xref" href="runtime-config-client.html#GUC-SHARED-PRELOAD-LIBRARIES">shared_preload_libraries</a><a id="id-1.8.3.13.15.2.2.2" class="indexterm"></a>.
1451 The shared library should also register a
1452 <code class="literal">shmem_request_hook</code> in its
1453 <code class="function">_PG_init</code> function. This
1454 <code class="literal">shmem_request_hook</code> can reserve shared memory by
1456 </p><pre class="programlisting">
1457 void RequestAddinShmemSpace(Size size)
1459 Each backend should obtain a pointer to the reserved shared memory by
1461 </p><pre class="programlisting">
1462 void *ShmemInitStruct(const char *name, Size size, bool *foundPtr)
1464 If this function sets <code class="literal">foundPtr</code> to
1465 <code class="literal">false</code>, the caller should proceed to initialize the
1466 contents of the reserved shared memory. If <code class="literal">foundPtr</code>
1467 is set to <code class="literal">true</code>, the shared memory was already
1468 initialized by another backend, and the caller need not initialize
1471 To avoid race conditions, each backend should use the LWLock
1472 <code class="function">AddinShmemInitLock</code> when initializing its allocation
1473 of shared memory, as shown here:
1474 </p><pre class="programlisting">
1475 static mystruct *ptr = NULL;
1478 LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
1479 ptr = ShmemInitStruct("my struct name", size, &found);
1482 ... initialize contents of shared memory ...
1483 ptr->locks = GetNamedLWLockTranche("my tranche name");
1485 LWLockRelease(AddinShmemInitLock);
1487 <code class="literal">shmem_startup_hook</code> provides a convenient place for the
1488 initialization code, but it is not strictly required that all such code
1489 be placed in this hook. On Windows (and anywhere else where
1490 <code class="literal">EXEC_BACKEND</code> is defined), each backend executes the
1491 registered <code class="literal">shmem_startup_hook</code> shortly after it
1492 attaches to shared memory, so add-ins should still acquire
1493 <code class="function">AddinShmemInitLock</code> within this hook, as shown in the
1494 example above. On other platforms, only the postmaster process executes
1495 the <code class="literal">shmem_startup_hook</code>, and each backend automatically
1496 inherits the pointers to shared memory.
1498 An example of a <code class="literal">shmem_request_hook</code> and
1499 <code class="literal">shmem_startup_hook</code> can be found in
1500 <code class="filename">contrib/pg_stat_statements/pg_stat_statements.c</code> in
1501 the <span class="productname">PostgreSQL</span> source tree.
1502 </p></div><div class="sect3" id="XFUNC-SHARED-ADDIN-AFTER-STARTUP"><div class="titlepage"><div><div><h4 class="title">36.10.11.2. Requesting Shared Memory After Startup <a href="#XFUNC-SHARED-ADDIN-AFTER-STARTUP" class="id_link">#</a></h4></div></div></div><p>
1503 There is another, more flexible method of reserving shared memory that
1504 can be done after server startup and outside a
1505 <code class="literal">shmem_request_hook</code>. To do so, each backend that will
1506 use the shared memory should obtain a pointer to it by calling:
1507 </p><pre class="programlisting">
1508 void *GetNamedDSMSegment(const char *name, size_t size,
1509 void (*init_callback) (void *ptr),
1512 If a dynamic shared memory segment with the given name does not yet
1513 exist, this function will allocate it and initialize it with the provided
1514 <code class="function">init_callback</code> callback function. If the segment has
1515 already been allocated and initialized by another backend, this function
1516 simply attaches the existing dynamic shared memory segment to the current
1519 Unlike shared memory reserved at server startup, there is no need to
1520 acquire <code class="function">AddinShmemInitLock</code> or otherwise take action
1521 to avoid race conditions when reserving shared memory with
1522 <code class="function">GetNamedDSMSegment</code>. This function ensures that only
1523 one backend allocates and initializes the segment and that all other
1524 backends receive a pointer to the fully allocated and initialized
1527 A complete usage example of <code class="function">GetNamedDSMSegment</code> can
1529 <code class="filename">src/test/modules/test_dsm_registry/test_dsm_registry.c</code>
1530 in the <span class="productname">PostgreSQL</span> source tree.
1531 </p></div></div><div class="sect2" id="XFUNC-ADDIN-LWLOCKS"><div class="titlepage"><div><div><h3 class="title">36.10.12. LWLocks <a href="#XFUNC-ADDIN-LWLOCKS" class="id_link">#</a></h3></div></div></div><div class="sect3" id="XFUNC-ADDIN-LWLOCKS-AT-STARTUP"><div class="titlepage"><div><div><h4 class="title">36.10.12.1. Requesting LWLocks at Startup <a href="#XFUNC-ADDIN-LWLOCKS-AT-STARTUP" class="id_link">#</a></h4></div></div></div><p>
1532 Add-ins can reserve LWLocks on server startup. As with shared memory
1533 reserved at server startup, the add-in's shared library must be preloaded
1535 <a class="xref" href="runtime-config-client.html#GUC-SHARED-PRELOAD-LIBRARIES">shared_preload_libraries</a><a id="id-1.8.3.13.16.2.2.2" class="indexterm"></a>,
1536 and the shared library should register a
1537 <code class="literal">shmem_request_hook</code> in its
1538 <code class="function">_PG_init</code> function. This
1539 <code class="literal">shmem_request_hook</code> can reserve LWLocks by calling:
1540 </p><pre class="programlisting">
1541 void RequestNamedLWLockTranche(const char *tranche_name, int num_lwlocks)
1543 This ensures that an array of <code class="literal">num_lwlocks</code> LWLocks is
1544 available under the name <code class="literal">tranche_name</code>. A pointer to
1545 this array can be obtained by calling:
1546 </p><pre class="programlisting">
1547 LWLockPadded *GetNamedLWLockTranche(const char *tranche_name)
1549 </p></div><div class="sect3" id="XFUNC-ADDIN-LWLOCKS-AFTER-STARTUP"><div class="titlepage"><div><div><h4 class="title">36.10.12.2. Requesting LWLocks After Startup <a href="#XFUNC-ADDIN-LWLOCKS-AFTER-STARTUP" class="id_link">#</a></h4></div></div></div><p>
1550 There is another, more flexible method of obtaining LWLocks that can be
1551 done after server startup and outside a
1552 <code class="literal">shmem_request_hook</code>. To do so, first allocate a
1553 <code class="literal">tranche_id</code> by calling:
1554 </p><pre class="programlisting">
1555 int LWLockNewTrancheId(void)
1557 Next, initialize each LWLock, passing the new
1558 <code class="literal">tranche_id</code> as an argument:
1559 </p><pre class="programlisting">
1560 void LWLockInitialize(LWLock *lock, int tranche_id)
1562 Similar to shared memory, each backend should ensure that only one
1563 process allocates a new <code class="literal">tranche_id</code> and initializes
1564 each new LWLock. One way to do this is to only call these functions in
1565 your shared memory initialization code with the
1566 <code class="function">AddinShmemInitLock</code> held exclusively. If using
1567 <code class="function">GetNamedDSMSegment</code>, calling these functions in the
1568 <code class="function">init_callback</code> callback function is sufficient to
1569 avoid race conditions.
1571 Finally, each backend using the <code class="literal">tranche_id</code> should
1572 associate it with a <code class="literal">tranche_name</code> by calling:
1573 </p><pre class="programlisting">
1574 void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
1577 A complete usage example of <code class="function">LWLockNewTrancheId</code>,
1578 <code class="function">LWLockInitialize</code>, and
1579 <code class="function">LWLockRegisterTranche</code> can be found in
1580 <code class="filename">contrib/pg_prewarm/autoprewarm.c</code> in the
1581 <span class="productname">PostgreSQL</span> source tree.
1582 </p></div></div><div class="sect2" id="XFUNC-ADDIN-WAIT-EVENTS"><div class="titlepage"><div><div><h3 class="title">36.10.13. Custom Wait Events <a href="#XFUNC-ADDIN-WAIT-EVENTS" class="id_link">#</a></h3></div></div></div><p>
1583 Add-ins can define custom wait events under the wait event type
1584 <code class="literal">Extension</code> by calling:
1585 </p><pre class="programlisting">
1586 uint32 WaitEventExtensionNew(const char *wait_event_name)
1588 The wait event is associated to a user-facing custom string.
1589 An example can be found in <code class="filename">src/test/modules/worker_spi</code>
1590 in the PostgreSQL source tree.
1592 Custom wait events can be viewed in
1593 <a class="link" href="monitoring-stats.html#MONITORING-PG-STAT-ACTIVITY-VIEW" title="27.2.3. pg_stat_activity"><code class="structname">pg_stat_activity</code></a>:
1594 </p><pre class="screen">
1595 =# SELECT wait_event_type, wait_event FROM pg_stat_activity
1596 WHERE backend_type ~ 'worker_spi';
1597 wait_event_type | wait_event
1598 -----------------+---------------
1599 Extension | WorkerSpiMain
1602 </p></div><div class="sect2" id="XFUNC-ADDIN-INJECTION-POINTS"><div class="titlepage"><div><div><h3 class="title">36.10.14. Injection Points <a href="#XFUNC-ADDIN-INJECTION-POINTS" class="id_link">#</a></h3></div></div></div><p>
1603 An injection point with a given <code class="literal">name</code> is declared using
1605 </p><pre class="programlisting">
1606 INJECTION_POINT(name, arg);
1609 There are a few injection points already declared at strategic points
1610 within the server code. After adding a new injection point the code needs
1611 to be compiled in order for that injection point to be available in the
1612 binary. Add-ins written in C-language can declare injection points in
1613 their own code using the same macro. The injection point names should use
1614 lower-case characters, with terms separated by
1615 dashes. <code class="literal">arg</code> is an optional argument value given to the
1616 callback at run-time.
1618 Executing an injection point can require allocating a small amount of
1619 memory, which can fail. If you need to have an injection point in a
1620 critical section where dynamic allocations are not allowed, you can use
1621 a two-step approach with the following macros:
1622 </p><pre class="programlisting">
1623 INJECTION_POINT_LOAD(name);
1624 INJECTION_POINT_CACHED(name, arg);
1627 Before entering the critical section,
1628 call <code class="function">INJECTION_POINT_LOAD</code>. It checks the shared
1629 memory state, and loads the callback into backend-private memory if it is
1630 active. Inside the critical section, use
1631 <code class="function">INJECTION_POINT_CACHED</code> to execute the callback.
1633 Add-ins can attach callbacks to an already-declared injection point by
1635 </p><pre class="programlisting">
1636 extern void InjectionPointAttach(const char *name,
1637 const char *library,
1638 const char *function,
1639 const void *private_data,
1640 int private_data_size);
1643 <code class="literal">name</code> is the name of the injection point, which when
1644 reached during execution will execute the <code class="literal">function</code>
1645 loaded from <code class="literal">library</code>. <code class="literal">private_data</code>
1646 is a private area of data of size <code class="literal">private_data_size</code>
1647 given as argument to the callback when executed.
1649 Here is an example of callback for
1650 <code class="literal">InjectionPointCallback</code>:
1651 </p><pre class="programlisting">
1653 custom_injection_callback(const char *name,
1654 const void *private_data,
1657 uint32 wait_event_info = WaitEventInjectionPointNew(name);
1659 pgstat_report_wait_start(wait_event_info);
1660 elog(NOTICE, "%s: executed custom callback", name);
1661 pgstat_report_wait_end();
1664 This callback prints a message to server error log with severity
1665 <code class="literal">NOTICE</code>, but callbacks may implement more complex
1668 An alternative way to define the action to take when an injection point
1669 is reached is to add the testing code alongside the normal source
1670 code. This can be useful if the action e.g. depends on local variables
1671 that are not accessible to loaded modules. The
1672 <code class="function">IS_INJECTION_POINT_ATTACHED</code> macro can then be used
1673 to check if an injection point is attached, for example:
1674 </p><pre class="programlisting">
1675 #ifdef USE_INJECTION_POINTS
1676 if (IS_INJECTION_POINT_ATTACHED("before-foobar"))
1678 /* change a local variable if injection point is attached */
1681 /* also execute the callback */
1682 INJECTION_POINT_CACHED("before-foobar", NULL);
1686 Note that the callback attached to the injection point will not be
1687 executed by the <code class="function">IS_INJECTION_POINT_ATTACHED</code>
1688 macro. If you want to execute the callback, you must also call
1689 <code class="function">INJECTION_POINT_CACHED</code> like in the above example.
1691 Optionally, it is possible to detach an injection point by calling:
1692 </p><pre class="programlisting">
1693 extern bool InjectionPointDetach(const char *name);
1695 On success, <code class="literal">true</code> is returned, <code class="literal">false</code>
1698 A callback attached to an injection point is available across all the
1699 backends including the backends started after
1700 <code class="literal">InjectionPointAttach</code> is called. It remains attached
1701 while the server is running or until the injection point is detached
1702 using <code class="literal">InjectionPointDetach</code>.
1704 An example can be found in
1705 <code class="filename">src/test/modules/injection_points</code> in the PostgreSQL
1708 Enabling injections points requires
1709 <code class="option">--enable-injection-points</code> with
1710 <code class="command">configure</code> or <code class="option">-Dinjection_points=true</code>
1711 with <span class="application">Meson</span>.
1712 </p></div><div class="sect2" id="XFUNC-ADDIN-CUSTOM-CUMULATIVE-STATISTICS"><div class="titlepage"><div><div><h3 class="title">36.10.15. Custom Cumulative Statistics <a href="#XFUNC-ADDIN-CUSTOM-CUMULATIVE-STATISTICS" class="id_link">#</a></h3></div></div></div><p>
1713 It is possible for add-ins written in C-language to use custom types
1714 of cumulative statistics registered in the
1715 <a class="link" href="monitoring-stats.html#MONITORING-STATS-SETUP" title="27.2.1. Statistics Collection Configuration">Cumulative Statistics System</a>.
1717 First, define a <code class="literal">PgStat_KindInfo</code> that includes all
1718 the information related to the custom type registered. For example:
1719 </p><pre class="programlisting">
1720 static const PgStat_KindInfo custom_stats = {
1721 .name = "custom_stats",
1722 .fixed_amount = false,
1723 .shared_size = sizeof(PgStatShared_Custom),
1724 .shared_data_off = offsetof(PgStatShared_Custom, stats),
1725 .shared_data_len = sizeof(((PgStatShared_Custom *) 0)->stats),
1726 .pending_size = sizeof(PgStat_StatCustomEntry),
1730 Then, each backend that needs to use this custom type needs to register
1731 it with <code class="literal">pgstat_register_kind</code> and a unique ID used to
1732 store the entries related to this type of statistics:
1733 </p><pre class="programlisting">
1734 extern PgStat_Kind pgstat_register_kind(PgStat_Kind kind,
1735 const PgStat_KindInfo *kind_info);
1737 While developing a new extension, use
1738 <code class="literal">PGSTAT_KIND_EXPERIMENTAL</code> for
1739 <em class="parameter"><code>kind</code></em>. When you are ready to release the extension
1740 to users, reserve a kind ID at the
1741 <a class="ulink" href="https://wiki.postgresql.org/wiki/CustomCumulativeStats" target="_top">
1742 Custom Cumulative Statistics</a> page.
1744 The details of the API for <code class="literal">PgStat_KindInfo</code> can
1745 be found in <code class="filename">src/include/utils/pgstat_internal.h</code>.
1747 The type of statistics registered is associated with a name and a unique
1748 ID shared across the server in shared memory. Each backend using a
1749 custom type of statistics maintains a local cache storing the information
1750 of each custom <code class="literal">PgStat_KindInfo</code>.
1752 Place the extension module implementing the custom cumulative statistics
1753 type in <a class="xref" href="runtime-config-client.html#GUC-SHARED-PRELOAD-LIBRARIES">shared_preload_libraries</a> so that it will
1754 be loaded early during <span class="productname">PostgreSQL</span> startup.
1756 An example describing how to register and use custom statistics can be
1757 found in <code class="filename">src/test/modules/injection_points</code>.
1758 </p></div><div class="sect2" id="EXTEND-CPP"><div class="titlepage"><div><div><h3 class="title">36.10.16. Using C++ for Extensibility <a href="#EXTEND-CPP" class="id_link">#</a></h3></div></div></div><a id="id-1.8.3.13.20.2" class="indexterm"></a><p>
1759 Although the <span class="productname">PostgreSQL</span> backend is written in
1760 C, it is possible to write extensions in C++ if these guidelines are
1763 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
1764 All functions accessed by the backend must present a C interface
1765 to the backend; these C functions can then call C++ functions.
1766 For example, <code class="literal">extern C</code> linkage is required for
1767 backend-accessed functions. This is also necessary for any
1768 functions that are passed as pointers between the backend and
1770 </p></li><li class="listitem"><p>
1771 Free memory using the appropriate deallocation method. For example,
1772 most backend memory is allocated using <code class="function">palloc()</code>, so use
1773 <code class="function">pfree()</code> to free it. Using C++
1774 <code class="function">delete</code> in such cases will fail.
1775 </p></li><li class="listitem"><p>
1776 Prevent exceptions from propagating into the C code (use a catch-all
1777 block at the top level of all <code class="literal">extern C</code> functions). This
1778 is necessary even if the C++ code does not explicitly throw any
1779 exceptions, because events like out-of-memory can still throw
1780 exceptions. Any exceptions must be caught and appropriate errors
1781 passed back to the C interface. If possible, compile C++ with
1782 <code class="option">-fno-exceptions</code> to eliminate exceptions entirely; in such
1783 cases, you must check for failures in your C++ code, e.g., check for
1784 NULL returned by <code class="function">new()</code>.
1785 </p></li><li class="listitem"><p>
1786 If calling backend functions from C++ code, be sure that the
1787 C++ call stack contains only plain old data structures
1788 (<acronym class="acronym">POD</acronym>). This is necessary because backend errors
1789 generate a distant <code class="function">longjmp()</code> that does not properly
1790 unroll a C++ call stack with non-POD objects.
1791 </p></li></ul></div><p>
1793 In summary, it is best to place C++ code behind a wall of
1794 <code class="literal">extern C</code> functions that interface to the backend,
1795 and avoid exception, memory, and call stack leakage.
1796 </p></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="xfunc-internal.html" title="36.9. Internal Functions">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="extend.html" title="Chapter 36. Extending SQL">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="xfunc-optimization.html" title="36.11. Function Optimization Information">Next</a></td></tr><tr><td width="40%" align="left" valign="top">36.9. Internal 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"> 36.11. Function Optimization Information</td></tr></table></div></body></html>