gooderp18绿色标准版
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1387 行
77KB

  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>37.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 V1.79.1" /><link rel="prev" href="xfunc-internal.html" title="37.9. Internal Functions" /><link rel="next" href="xfunc-optimization.html" title="37.11. Function Optimization Information" /></head><body><div xmlns="http://www.w3.org/TR/xhtml1/transitional" class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">37.10. C-Language Functions</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="xfunc-internal.html" title="37.9. Internal Functions">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="extend.html" title="Chapter 37. Extending SQL">Up</a></td><th width="60%" align="center">Chapter 37. Extending <acronym xmlns="http://www.w3.org/1999/xhtml" class="acronym">SQL</acronym></th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 12.4 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="xfunc-optimization.html" title="37.11. Function Optimization Information">Next</a></td></tr></table><hr></hr></div><div class="sect1" id="XFUNC-C"><div class="titlepage"><div><div><h2 class="title" style="clear: both">37.10. C-Language Functions</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-C-DYNLOAD">37.10.1. Dynamic Loading</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-C-BASETYPE">37.10.2. Base Types in C-Language Functions</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#id-1.8.3.13.7">37.10.3. Version 1 Calling Conventions</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#id-1.8.3.13.8">37.10.4. Writing Code</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#DFUNC">37.10.5. Compiling and Linking Dynamically-Loaded Functions</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#id-1.8.3.13.10">37.10.6. Composite-Type Arguments</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#id-1.8.3.13.11">37.10.7. Returning Rows (Composite Types)</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#XFUNC-C-RETURN-SET">37.10.8. Returning Sets</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#id-1.8.3.13.13">37.10.9. Polymorphic Arguments and Return Types</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#id-1.8.3.13.14">37.10.10. Shared Memory and LWLocks</a></span></dt><dt><span class="sect2"><a href="xfunc-c.html#EXTEND-CPP">37.10.11. 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
  11. C functions.)
  12. </p><p>
  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">37.10.1. Dynamic Loading</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.
  27. </p><p>
  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>
  30. command:
  31. </p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
  32. If the name is an absolute path, the given file is loaded.
  33. </p></li><li class="listitem"><p>
  34. If the name starts with the string <code class="literal">$libdir</code>,
  35. that part is replaced by the <span class="productname">PostgreSQL</span> package
  36. library directory
  37. name, which is determined at build time.<a id="id-1.8.3.13.5.4.2.2.1.3" class="indexterm"></a>
  38. </p></li><li class="listitem"><p>
  39. If the name does not contain a directory part, the file is
  40. searched for in the path specified by the configuration variable
  41. <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>
  42. </p></li><li class="listitem"><p>
  43. Otherwise (the file was not found in the path, or it contains a
  44. non-absolute directory part), the dynamic loader will try to
  45. take the name as given, which will most likely fail. (It is
  46. unreliable to depend on the current working directory.)
  47. </p></li></ol></div><p>
  48. If this sequence does not work, the platform-specific shared
  49. library file name extension (often <code class="filename">.so</code>) is
  50. appended to the given name and this sequence is tried again. If
  51. that fails as well, the load will fail.
  52. </p><p>
  53. It is recommended to locate shared libraries either relative to
  54. <code class="literal">$libdir</code> or through the dynamic library path.
  55. This simplifies version upgrades if the new installation is at a
  56. different location. The actual directory that
  57. <code class="literal">$libdir</code> stands for can be found out with the
  58. command <code class="literal">pg_config --pkglibdir</code>.
  59. </p><p>
  60. The user ID the <span class="productname">PostgreSQL</span> server runs
  61. as must be able to traverse the path to the file you intend to
  62. load. Making the file or a higher-level directory not readable
  63. and/or not executable by the <span class="systemitem">postgres</span>
  64. user is a common mistake.
  65. </p><p>
  66. In any case, the file name that is given in the
  67. <code class="command">CREATE FUNCTION</code> command is recorded literally
  68. in the system catalogs, so if the file needs to be loaded again
  69. the same procedure is applied.
  70. </p><div class="note"><h3 class="title">Note</h3><p>
  71. <span class="productname">PostgreSQL</span> will not compile a C function
  72. automatically. The object file must be compiled before it is referenced
  73. in a <code class="command">CREATE
  74. FUNCTION</code> command. See <a class="xref" href="xfunc-c.html#DFUNC" title="37.10.5. Compiling and Linking Dynamically-Loaded Functions">Section 37.10.5</a> for additional
  75. information.
  76. </p></div><a id="id-1.8.3.13.5.9" class="indexterm"></a><p>
  77. To ensure that a dynamically loaded object file is not loaded into an
  78. incompatible server, <span class="productname">PostgreSQL</span> checks that the
  79. file contains a <span class="quote">“<span class="quote">magic block</span>”</span> with the appropriate contents.
  80. This allows the server to detect obvious incompatibilities, such as code
  81. compiled for a different major version of
  82. <span class="productname">PostgreSQL</span>. To include a magic block,
  83. write this in one (and only one) of the module source files, after having
  84. included the header <code class="filename">fmgr.h</code>:
  85. </p><pre class="programlisting">
  86. PG_MODULE_MAGIC;
  87. </pre><p>
  88. </p><p>
  89. After it is used for the first time, a dynamically loaded object
  90. file is retained in memory. Future calls in the same session to
  91. the function(s) in that file will only incur the small overhead of
  92. a symbol table lookup. If you need to force a reload of an object
  93. file, for example after recompiling it, begin a fresh session.
  94. </p><a id="id-1.8.3.13.5.12" class="indexterm"></a><a id="id-1.8.3.13.5.13" class="indexterm"></a><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>
  95. Optionally, a dynamically loaded file can contain initialization and
  96. finalization functions. If the file includes a function named
  97. <code class="function">_PG_init</code>, that function will be called immediately after
  98. loading the file. The function receives no parameters and should
  99. return void. If the file includes a function named
  100. <code class="function">_PG_fini</code>, that function will be called immediately before
  101. unloading the file. Likewise, the function receives no parameters and
  102. should return void. Note that <code class="function">_PG_fini</code> will only be called
  103. during an unload of the file, not during process termination.
  104. (Presently, unloads are disabled and will never occur, but this may
  105. change in the future.)
  106. </p></div><div class="sect2" id="XFUNC-C-BASETYPE"><div class="titlepage"><div><div><h3 class="title">37.10.2. Base Types in C-Language Functions</h3></div></div></div><a id="id-1.8.3.13.6.2" class="indexterm"></a><p>
  107. To know how to write C-language functions, you need to know how
  108. <span class="productname">PostgreSQL</span> internally represents base
  109. data types and how they can be passed to and from functions.
  110. Internally, <span class="productname">PostgreSQL</span> regards a base
  111. type as a <span class="quote">“<span class="quote">blob of memory</span>”</span>. The user-defined
  112. functions that you define over a type in turn define the way that
  113. <span class="productname">PostgreSQL</span> can operate on it. That
  114. is, <span class="productname">PostgreSQL</span> will only store and
  115. retrieve the data from disk and use your user-defined functions
  116. to input, process, and output the data.
  117. </p><p>
  118. Base types can have one of three internal formats:
  119. </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
  120. pass by value, fixed-length
  121. </p></li><li class="listitem"><p>
  122. pass by reference, fixed-length
  123. </p></li><li class="listitem"><p>
  124. pass by reference, variable-length
  125. </p></li></ul></div><p>
  126. </p><p>
  127. By-value types can only be 1, 2, or 4 bytes in length
  128. (also 8 bytes, if <code class="literal">sizeof(Datum)</code> is 8 on your machine).
  129. You should be careful to define your types such that they will be the
  130. same size (in bytes) on all architectures. For example, the
  131. <code class="literal">long</code> type is dangerous because it is 4 bytes on some
  132. machines and 8 bytes on others, whereas <code class="type">int</code> type is 4 bytes
  133. on most Unix machines. A reasonable implementation of the
  134. <code class="type">int4</code> type on Unix machines might be:
  135. </p><pre class="programlisting">
  136. /* 4-byte integer, passed by value */
  137. typedef int int4;
  138. </pre><p>
  139. (The actual PostgreSQL C code calls this type <code class="type">int32</code>, because
  140. it is a convention in C that <code class="type">int<em class="replaceable"><code>XX</code></em></code>
  141. means <em class="replaceable"><code>XX</code></em> <span class="emphasis"><em>bits</em></span>. Note
  142. therefore also that the C type <code class="type">int8</code> is 1 byte in size. The
  143. SQL type <code class="type">int8</code> is called <code class="type">int64</code> in C. See also
  144. <a class="xref" href="xfunc-c.html#XFUNC-C-TYPE-TABLE" title="Table 37.1. Equivalent C Types for Built-in SQL Types">Table 37.1</a>.)
  145. </p><p>
  146. On the other hand, fixed-length types of any size can
  147. be passed by-reference. For example, here is a sample
  148. implementation of a <span class="productname">PostgreSQL</span> type:
  149. </p><pre class="programlisting">
  150. /* 16-byte structure, passed by reference */
  151. typedef struct
  152. {
  153. double x, y;
  154. } Point;
  155. </pre><p>
  156. Only pointers to such types can be used when passing
  157. them in and out of <span class="productname">PostgreSQL</span> functions.
  158. To return a value of such a type, allocate the right amount of
  159. memory with <code class="literal">palloc</code>, fill in the allocated memory,
  160. and return a pointer to it. (Also, if you just want to return the
  161. same value as one of your input arguments that's of the same data type,
  162. you can skip the extra <code class="literal">palloc</code> and just return the
  163. pointer to the input value.)
  164. </p><p>
  165. Finally, all variable-length types must also be passed
  166. by reference. All variable-length types must begin
  167. with an opaque length field of exactly 4 bytes, which will be set
  168. by <code class="symbol">SET_VARSIZE</code>; never set this field directly! All data to
  169. be stored within that type must be located in the memory
  170. immediately following that length field. The
  171. length field contains the total length of the structure,
  172. that is, it includes the size of the length field
  173. itself.
  174. </p><p>
  175. Another important point is to avoid leaving any uninitialized bits
  176. within data type values; for example, take care to zero out any
  177. alignment padding bytes that might be present in structs. Without
  178. this, logically-equivalent constants of your data type might be
  179. seen as unequal by the planner, leading to inefficient (though not
  180. incorrect) plans.
  181. </p><div class="warning"><h3 class="title">Warning</h3><p>
  182. <span class="emphasis"><em>Never</em></span> modify the contents of a pass-by-reference input
  183. value. If you do so you are likely to corrupt on-disk data, since
  184. the pointer you are given might point directly into a disk buffer.
  185. The sole exception to this rule is explained in
  186. <a class="xref" href="xaggr.html" title="37.12. User-Defined Aggregates">Section 37.12</a>.
  187. </p></div><p>
  188. As an example, we can define the type <code class="type">text</code> as
  189. follows:
  190. </p><pre class="programlisting">
  191. typedef struct {
  192. int32 length;
  193. char data[FLEXIBLE_ARRAY_MEMBER];
  194. } text;
  195. </pre><p>
  196. The <code class="literal">[FLEXIBLE_ARRAY_MEMBER]</code> notation means that the actual
  197. length of the data part is not specified by this declaration.
  198. </p><p>
  199. When manipulating
  200. variable-length types, we must be careful to allocate
  201. the correct amount of memory and set the length field correctly.
  202. For example, if we wanted to store 40 bytes in a <code class="structname">text</code>
  203. structure, we might use a code fragment like this:
  204. </p><pre class="programlisting">
  205. #include "postgres.h"
  206. ...
  207. char buffer[40]; /* our source data */
  208. ...
  209. text *destination = (text *) palloc(VARHDRSZ + 40);
  210. SET_VARSIZE(destination, VARHDRSZ + 40);
  211. memcpy(destination-&gt;data, buffer, 40);
  212. ...
  213. </pre><p>
  214. <code class="literal">VARHDRSZ</code> is the same as <code class="literal">sizeof(int32)</code>, but
  215. it's considered good style to use the macro <code class="literal">VARHDRSZ</code>
  216. to refer to the size of the overhead for a variable-length type.
  217. Also, the length field <span class="emphasis"><em>must</em></span> be set using the
  218. <code class="literal">SET_VARSIZE</code> macro, not by simple assignment.
  219. </p><p>
  220. <a class="xref" href="xfunc-c.html#XFUNC-C-TYPE-TABLE" title="Table 37.1. Equivalent C Types for Built-in SQL Types">Table 37.1</a> specifies which C type
  221. corresponds to which SQL type when writing a C-language function
  222. that uses a built-in type of <span class="productname">PostgreSQL</span>.
  223. The <span class="quote">“<span class="quote">Defined In</span>”</span> column gives the header file that
  224. needs to be included to get the type definition. (The actual
  225. definition might be in a different file that is included by the
  226. listed file. It is recommended that users stick to the defined
  227. interface.) Note that you should always include
  228. <code class="filename">postgres.h</code> first in any source file, because
  229. it declares a number of things that you will need anyway.
  230. </p><div class="table" id="XFUNC-C-TYPE-TABLE"><p class="title"><strong>Table 37.1. 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 /><col /><col /></colgroup><thead><tr><th>
  231. SQL Type
  232. </th><th>
  233. C Type
  234. </th><th>
  235. Defined In
  236. </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">smallint</code> (<code class="type">int2</code>)</td><td><code class="type">int16</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">int2vector</code></td><td><code class="type">int2vector*</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">integer</code> (<code class="type">int4</code>)</td><td><code class="type">int32</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">real</code> (<code class="type">float4</code>)</td><td><code class="type">float4*</code></td><td><code class="filename">postgres.h</code></td></tr><tr><td><code class="type">double precision</code> (<code class="type">float8</code>)</td><td><code class="type">float8*</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">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">regproc</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">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>
  237. Now that we've gone over all of the possible structures
  238. for base types, we can show some examples of real functions.
  239. </p></div><div class="sect2" id="id-1.8.3.13.7"><div class="titlepage"><div><div><h3 class="title">37.10.3. Version 1 Calling Conventions</h3></div></div></div><p>
  240. The version-1 calling convention relies on macros to suppress most
  241. of the complexity of passing arguments and results. The C declaration
  242. of a version-1 function is always:
  243. </p><pre class="programlisting">
  244. Datum funcname(PG_FUNCTION_ARGS)
  245. </pre><p>
  246. In addition, the macro call:
  247. </p><pre class="programlisting">
  248. PG_FUNCTION_INFO_V1(funcname);
  249. </pre><p>
  250. must appear in the same source file. (Conventionally, it's
  251. written just before the function itself.) This macro call is not
  252. needed for <code class="literal">internal</code>-language functions, since
  253. <span class="productname">PostgreSQL</span> assumes that all internal functions
  254. use the version-1 convention. It is, however, required for
  255. dynamically-loaded functions.
  256. </p><p>
  257. In a version-1 function, each actual argument is fetched using a
  258. <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>()</code>
  259. macro that corresponds to the argument's data type. (In non-strict
  260. functions there needs to be a previous check about argument null-ness
  261. using <code class="function">PG_ARGISNULL()</code>; see below.)
  262. The result is returned using a
  263. <code class="function">PG_RETURN_<em class="replaceable"><code>xxx</code></em>()</code>
  264. macro for the return type.
  265. <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>()</code>
  266. takes as its argument the number of the function argument to
  267. fetch, where the count starts at 0.
  268. <code class="function">PG_RETURN_<em class="replaceable"><code>xxx</code></em>()</code>
  269. takes as its argument the actual value to return.
  270. </p><p>
  271. Here are some examples using the version-1 calling convention:
  272. </p><pre class="programlisting">
  273. #include "postgres.h"
  274. #include &lt;string.h&gt;
  275. #include "fmgr.h"
  276. #include "utils/geo_decls.h"
  277. PG_MODULE_MAGIC;
  278. /* by value */
  279. PG_FUNCTION_INFO_V1(add_one);
  280. Datum
  281. add_one(PG_FUNCTION_ARGS)
  282. {
  283. int32 arg = PG_GETARG_INT32(0);
  284. PG_RETURN_INT32(arg + 1);
  285. }
  286. /* by reference, fixed length */
  287. PG_FUNCTION_INFO_V1(add_one_float8);
  288. Datum
  289. add_one_float8(PG_FUNCTION_ARGS)
  290. {
  291. /* The macros for FLOAT8 hide its pass-by-reference nature. */
  292. float8 arg = PG_GETARG_FLOAT8(0);
  293. PG_RETURN_FLOAT8(arg + 1.0);
  294. }
  295. PG_FUNCTION_INFO_V1(makepoint);
  296. Datum
  297. makepoint(PG_FUNCTION_ARGS)
  298. {
  299. /* Here, the pass-by-reference nature of Point is not hidden. */
  300. Point *pointx = PG_GETARG_POINT_P(0);
  301. Point *pointy = PG_GETARG_POINT_P(1);
  302. Point *new_point = (Point *) palloc(sizeof(Point));
  303. new_point-&gt;x = pointx-&gt;x;
  304. new_point-&gt;y = pointy-&gt;y;
  305. PG_RETURN_POINT_P(new_point);
  306. }
  307. /* by reference, variable length */
  308. PG_FUNCTION_INFO_V1(copytext);
  309. Datum
  310. copytext(PG_FUNCTION_ARGS)
  311. {
  312. text *t = PG_GETARG_TEXT_PP(0);
  313. /*
  314. * VARSIZE_ANY_EXHDR is the size of the struct in bytes, minus the
  315. * VARHDRSZ or VARHDRSZ_SHORT of its header. Construct the copy with a
  316. * full-length header.
  317. */
  318. text *new_t = (text *) palloc(VARSIZE_ANY_EXHDR(t) + VARHDRSZ);
  319. SET_VARSIZE(new_t, VARSIZE_ANY_EXHDR(t) + VARHDRSZ);
  320. /*
  321. * VARDATA is a pointer to the data region of the new struct. The source
  322. * could be a short datum, so retrieve its data through VARDATA_ANY.
  323. */
  324. memcpy((void *) VARDATA(new_t), /* destination */
  325. (void *) VARDATA_ANY(t), /* source */
  326. VARSIZE_ANY_EXHDR(t)); /* how many bytes */
  327. PG_RETURN_TEXT_P(new_t);
  328. }
  329. PG_FUNCTION_INFO_V1(concat_text);
  330. Datum
  331. concat_text(PG_FUNCTION_ARGS)
  332. {
  333. text *arg1 = PG_GETARG_TEXT_PP(0);
  334. text *arg2 = PG_GETARG_TEXT_PP(1);
  335. int32 arg1_size = VARSIZE_ANY_EXHDR(arg1);
  336. int32 arg2_size = VARSIZE_ANY_EXHDR(arg2);
  337. int32 new_text_size = arg1_size + arg2_size + VARHDRSZ;
  338. text *new_text = (text *) palloc(new_text_size);
  339. SET_VARSIZE(new_text, new_text_size);
  340. memcpy(VARDATA(new_text), VARDATA_ANY(arg1), arg1_size);
  341. memcpy(VARDATA(new_text) + arg1_size, VARDATA_ANY(arg2), arg2_size);
  342. PG_RETURN_TEXT_P(new_text);
  343. }
  344. </pre><p>
  345. Supposing that the above code has been prepared in file
  346. <code class="filename">funcs.c</code> and compiled into a shared object,
  347. we could define the functions to <span class="productname">PostgreSQL</span>
  348. with commands like this:
  349. </p><pre class="programlisting">
  350. CREATE FUNCTION add_one(integer) RETURNS integer
  351. AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'add_one'
  352. LANGUAGE C STRICT;
  353. -- note overloading of SQL function name "add_one"
  354. CREATE FUNCTION add_one(double precision) RETURNS double precision
  355. AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'add_one_float8'
  356. LANGUAGE C STRICT;
  357. CREATE FUNCTION makepoint(point, point) RETURNS point
  358. AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'makepoint'
  359. LANGUAGE C STRICT;
  360. CREATE FUNCTION copytext(text) RETURNS text
  361. AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'copytext'
  362. LANGUAGE C STRICT;
  363. CREATE FUNCTION concat_text(text, text) RETURNS text
  364. AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'concat_text'
  365. LANGUAGE C STRICT;
  366. </pre><p>
  367. Here, <em class="replaceable"><code>DIRECTORY</code></em> stands for the
  368. directory of the shared library file (for instance the
  369. <span class="productname">PostgreSQL</span> tutorial directory, which
  370. contains the code for the examples used in this section).
  371. (Better style would be to use just <code class="literal">'funcs'</code> in the
  372. <code class="literal">AS</code> clause, after having added
  373. <em class="replaceable"><code>DIRECTORY</code></em> to the search path. In any
  374. case, we can omit the system-specific extension for a shared
  375. library, commonly <code class="literal">.so</code>.)
  376. </p><p>
  377. Notice that we have specified the functions as <span class="quote">“<span class="quote">strict</span>”</span>,
  378. meaning that
  379. the system should automatically assume a null result if any input
  380. value is null. By doing this, we avoid having to check for null inputs
  381. in the function code. Without this, we'd have to check for null values
  382. explicitly, using <code class="function">PG_ARGISNULL()</code>.
  383. </p><p>
  384. The macro <code class="function">PG_ARGISNULL(<em class="replaceable"><code>n</code></em>)</code>
  385. allows a function to test whether each input is null. (Of course, doing
  386. this is only necessary in functions not declared <span class="quote">“<span class="quote">strict</span>”</span>.)
  387. As with the
  388. <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>()</code> macros,
  389. the input arguments are counted beginning at zero. Note that one
  390. should refrain from executing
  391. <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>()</code> until
  392. one has verified that the argument isn't null.
  393. To return a null result, execute <code class="function">PG_RETURN_NULL()</code>;
  394. this works in both strict and nonstrict functions.
  395. </p><p>
  396. At first glance, the version-1 coding conventions might appear
  397. to be just pointless obscurantism, compared to using
  398. plain <code class="literal">C</code> calling conventions. They do however allow
  399. us to deal with <code class="literal">NULL</code>able arguments/return values,
  400. and <span class="quote">“<span class="quote">toasted</span>”</span> (compressed or out-of-line) values.
  401. </p><p>
  402. Other options provided by the version-1 interface are two
  403. variants of the
  404. <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>()</code>
  405. macros. The first of these,
  406. <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>_COPY()</code>,
  407. guarantees to return a copy of the specified argument that is
  408. safe for writing into. (The normal macros will sometimes return a
  409. pointer to a value that is physically stored in a table, which
  410. must not be written to. Using the
  411. <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>_COPY()</code>
  412. macros guarantees a writable result.)
  413. The second variant consists of the
  414. <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>_SLICE()</code>
  415. macros which take three arguments. The first is the number of the
  416. function argument (as above). The second and third are the offset and
  417. length of the segment to be returned. Offsets are counted from
  418. zero, and a negative length requests that the remainder of the
  419. value be returned. These macros provide more efficient access to
  420. parts of large values in the case where they have storage type
  421. <span class="quote">“<span class="quote">external</span>”</span>. (The storage type of a column can be specified using
  422. <code class="literal">ALTER TABLE <em class="replaceable"><code>tablename</code></em> ALTER
  423. COLUMN <em class="replaceable"><code>colname</code></em> SET STORAGE
  424. <em class="replaceable"><code>storagetype</code></em></code>. <em class="replaceable"><code>storagetype</code></em> is one of
  425. <code class="literal">plain</code>, <code class="literal">external</code>, <code class="literal">extended</code>,
  426. or <code class="literal">main</code>.)
  427. </p><p>
  428. Finally, the version-1 function call conventions make it possible
  429. to return set results (<a class="xref" href="xfunc-c.html#XFUNC-C-RETURN-SET" title="37.10.8. Returning Sets">Section 37.10.8</a>) and
  430. implement trigger functions (<a class="xref" href="triggers.html" title="Chapter 38. Triggers">Chapter 38</a>) and
  431. procedural-language call handlers (<a class="xref" href="plhandler.html" title="Chapter 55. Writing a Procedural Language Handler">Chapter 55</a>). For more details
  432. see <code class="filename">src/backend/utils/fmgr/README</code> in the
  433. source distribution.
  434. </p></div><div class="sect2" id="id-1.8.3.13.8"><div class="titlepage"><div><div><h3 class="title">37.10.4. Writing Code</h3></div></div></div><p>
  435. Before we turn to the more advanced topics, we should discuss
  436. some coding rules for <span class="productname">PostgreSQL</span>
  437. C-language functions. While it might be possible to load functions
  438. written in languages other than C into
  439. <span class="productname">PostgreSQL</span>, this is usually difficult
  440. (when it is possible at all) because other languages, such as
  441. C++, FORTRAN, or Pascal often do not follow the same calling
  442. convention as C. That is, other languages do not pass argument
  443. and return values between functions in the same way. For this
  444. reason, we will assume that your C-language functions are
  445. actually written in C.
  446. </p><p>
  447. The basic rules for writing and building C functions are as follows:
  448. </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
  449. Use <code class="literal">pg_config
  450. --includedir-server</code><a id="id-1.8.3.13.8.3.1.1.1.2" class="indexterm"></a>
  451. to find out where the <span class="productname">PostgreSQL</span> server header
  452. files are installed on your system (or the system that your
  453. users will be running on).
  454. </p></li><li class="listitem"><p>
  455. Compiling and linking your code so that it can be dynamically
  456. loaded into <span class="productname">PostgreSQL</span> always
  457. requires special flags. See <a class="xref" href="xfunc-c.html#DFUNC" title="37.10.5. Compiling and Linking Dynamically-Loaded Functions">Section 37.10.5</a> for a
  458. detailed explanation of how to do it for your particular
  459. operating system.
  460. </p></li><li class="listitem"><p>
  461. Remember to define a <span class="quote">“<span class="quote">magic block</span>”</span> for your shared library,
  462. as described in <a class="xref" href="xfunc-c.html#XFUNC-C-DYNLOAD" title="37.10.1. Dynamic Loading">Section 37.10.1</a>.
  463. </p></li><li class="listitem"><p>
  464. When allocating memory, use the
  465. <span class="productname">PostgreSQL</span> functions
  466. <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>
  467. instead of the corresponding C library functions
  468. <code class="function">malloc</code> and <code class="function">free</code>.
  469. The memory allocated by <code class="function">palloc</code> will be
  470. freed automatically at the end of each transaction, preventing
  471. memory leaks.
  472. </p></li><li class="listitem"><p>
  473. Always zero the bytes of your structures using <code class="function">memset</code>
  474. (or allocate them with <code class="function">palloc0</code> in the first place).
  475. Even if you assign to each field of your structure, there might be
  476. alignment padding (holes in the structure) that contain
  477. garbage values. Without this, it's difficult to
  478. support hash indexes or hash joins, as you must pick out only
  479. the significant bits of your data structure to compute a hash.
  480. The planner also sometimes relies on comparing constants via
  481. bitwise equality, so you can get undesirable planning results if
  482. logically-equivalent values aren't bitwise equal.
  483. </p></li><li class="listitem"><p>
  484. Most of the internal <span class="productname">PostgreSQL</span>
  485. types are declared in <code class="filename">postgres.h</code>, while
  486. the function manager interfaces
  487. (<code class="symbol">PG_FUNCTION_ARGS</code>, etc.) are in
  488. <code class="filename">fmgr.h</code>, so you will need to include at
  489. least these two files. For portability reasons it's best to
  490. include <code class="filename">postgres.h</code> <span class="emphasis"><em>first</em></span>,
  491. before any other system or user header files. Including
  492. <code class="filename">postgres.h</code> will also include
  493. <code class="filename">elog.h</code> and <code class="filename">palloc.h</code>
  494. for you.
  495. </p></li><li class="listitem"><p>
  496. Symbol names defined within object files must not conflict
  497. with each other or with symbols defined in the
  498. <span class="productname">PostgreSQL</span> server executable. You
  499. will have to rename your functions or variables if you get
  500. error messages to this effect.
  501. </p></li></ul></div><p>
  502. </p></div><div class="sect2" id="DFUNC"><div class="titlepage"><div><div><h3 class="title">37.10.5. Compiling and Linking Dynamically-Loaded Functions</h3></div></div></div><p>
  503. Before you are able to use your
  504. <span class="productname">PostgreSQL</span> extension functions written in
  505. C, they must be compiled and linked in a special way to produce a
  506. file that can be dynamically loaded by the server. To be precise, a
  507. <em class="firstterm">shared library</em> needs to be
  508. created.<a id="id-1.8.3.13.9.2.3" class="indexterm"></a>
  509. </p><p>
  510. For information beyond what is contained in this section
  511. you should read the documentation of your
  512. operating system, in particular the manual pages for the C compiler,
  513. <code class="command">cc</code>, and the link editor, <code class="command">ld</code>.
  514. In addition, the <span class="productname">PostgreSQL</span> source code
  515. contains several working examples in the
  516. <code class="filename">contrib</code> directory. If you rely on these
  517. examples you will make your modules dependent on the availability
  518. of the <span class="productname">PostgreSQL</span> source code, however.
  519. </p><p>
  520. Creating shared libraries is generally analogous to linking
  521. executables: first the source files are compiled into object files,
  522. then the object files are linked together. The object files need to
  523. be created as <em class="firstterm">position-independent code</em>
  524. (<acronym class="acronym">PIC</acronym>),<a id="id-1.8.3.13.9.4.3" class="indexterm"></a> which
  525. conceptually means that they can be placed at an arbitrary location
  526. in memory when they are loaded by the executable. (Object files
  527. intended for executables are usually not compiled that way.) The
  528. command to link a shared library contains special flags to
  529. distinguish it from linking an executable (at least in theory
  530. — on some systems the practice is much uglier).
  531. </p><p>
  532. In the following examples we assume that your source code is in a
  533. file <code class="filename">foo.c</code> and we will create a shared library
  534. <code class="filename">foo.so</code>. The intermediate object file will be
  535. called <code class="filename">foo.o</code> unless otherwise noted. A shared
  536. library can contain more than one object file, but we only use one
  537. here.
  538. </p><div class="variablelist"><dl class="variablelist"><dt><span class="term">
  539. <span class="systemitem">FreeBSD</span>
  540. <a id="id-1.8.3.13.9.6.1.1.2" class="indexterm"></a>
  541. </span></dt><dd><p>
  542. The compiler flag to create <acronym class="acronym">PIC</acronym> is
  543. <code class="option">-fPIC</code>. To create shared libraries the compiler
  544. flag is <code class="option">-shared</code>.
  545. </p><pre class="programlisting">
  546. gcc -fPIC -c foo.c
  547. gcc -shared -o foo.so foo.o
  548. </pre><p>
  549. This is applicable as of version 3.0 of
  550. <span class="systemitem">FreeBSD</span>.
  551. </p></dd><dt><span class="term">
  552. <span class="systemitem">HP-UX</span>
  553. <a id="id-1.8.3.13.9.6.2.1.2" class="indexterm"></a>
  554. </span></dt><dd><p>
  555. The compiler flag of the system compiler to create
  556. <acronym class="acronym">PIC</acronym> is <code class="option">+z</code>. When using
  557. <span class="application">GCC</span> it's <code class="option">-fPIC</code>. The
  558. linker flag for shared libraries is <code class="option">-b</code>. So:
  559. </p><pre class="programlisting">
  560. cc +z -c foo.c
  561. </pre><p>
  562. or:
  563. </p><pre class="programlisting">
  564. gcc -fPIC -c foo.c
  565. </pre><p>
  566. and then:
  567. </p><pre class="programlisting">
  568. ld -b -o foo.sl foo.o
  569. </pre><p>
  570. <span class="systemitem">HP-UX</span> uses the extension
  571. <code class="filename">.sl</code> for shared libraries, unlike most other
  572. systems.
  573. </p></dd><dt><span class="term">
  574. <span class="systemitem">Linux</span>
  575. <a id="id-1.8.3.13.9.6.3.1.2" class="indexterm"></a>
  576. </span></dt><dd><p>
  577. The compiler flag to create <acronym class="acronym">PIC</acronym> is
  578. <code class="option">-fPIC</code>.
  579. The compiler flag to create a shared library is
  580. <code class="option">-shared</code>. A complete example looks like this:
  581. </p><pre class="programlisting">
  582. cc -fPIC -c foo.c
  583. cc -shared -o foo.so foo.o
  584. </pre><p>
  585. </p></dd><dt><span class="term">
  586. <span class="systemitem">macOS</span>
  587. <a id="id-1.8.3.13.9.6.4.1.2" class="indexterm"></a>
  588. </span></dt><dd><p>
  589. Here is an example. It assumes the developer tools are installed.
  590. </p><pre class="programlisting">
  591. cc -c foo.c
  592. cc -bundle -flat_namespace -undefined suppress -o foo.so foo.o
  593. </pre><p>
  594. </p></dd><dt><span class="term">
  595. <span class="systemitem">NetBSD</span>
  596. <a id="id-1.8.3.13.9.6.5.1.2" class="indexterm"></a>
  597. </span></dt><dd><p>
  598. The compiler flag to create <acronym class="acronym">PIC</acronym> is
  599. <code class="option">-fPIC</code>. For <acronym class="acronym">ELF</acronym> systems, the
  600. compiler with the flag <code class="option">-shared</code> is used to link
  601. shared libraries. On the older non-ELF systems, <code class="literal">ld
  602. -Bshareable</code> is used.
  603. </p><pre class="programlisting">
  604. gcc -fPIC -c foo.c
  605. gcc -shared -o foo.so foo.o
  606. </pre><p>
  607. </p></dd><dt><span class="term">
  608. <span class="systemitem">OpenBSD</span>
  609. <a id="id-1.8.3.13.9.6.6.1.2" class="indexterm"></a>
  610. </span></dt><dd><p>
  611. The compiler flag to create <acronym class="acronym">PIC</acronym> is
  612. <code class="option">-fPIC</code>. <code class="literal">ld -Bshareable</code> is
  613. used to link shared libraries.
  614. </p><pre class="programlisting">
  615. gcc -fPIC -c foo.c
  616. ld -Bshareable -o foo.so foo.o
  617. </pre><p>
  618. </p></dd><dt><span class="term">
  619. <span class="systemitem">Solaris</span>
  620. <a id="id-1.8.3.13.9.6.7.1.2" class="indexterm"></a>
  621. </span></dt><dd><p>
  622. The compiler flag to create <acronym class="acronym">PIC</acronym> is
  623. <code class="option">-KPIC</code> with the Sun compiler and
  624. <code class="option">-fPIC</code> with <span class="application">GCC</span>. To
  625. link shared libraries, the compiler option is
  626. <code class="option">-G</code> with either compiler or alternatively
  627. <code class="option">-shared</code> with <span class="application">GCC</span>.
  628. </p><pre class="programlisting">
  629. cc -KPIC -c foo.c
  630. cc -G -o foo.so foo.o
  631. </pre><p>
  632. or
  633. </p><pre class="programlisting">
  634. gcc -fPIC -c foo.c
  635. gcc -G -o foo.so foo.o
  636. </pre><p>
  637. </p></dd></dl></div><div class="tip"><h3 class="title">Tip</h3><p>
  638. If this is too complicated for you, you should consider using
  639. <a class="ulink" href="https://www.gnu.org/software/libtool/" target="_top">
  640. <span class="productname">GNU Libtool</span></a>,
  641. which hides the platform differences behind a uniform interface.
  642. </p></div><p>
  643. The resulting shared library file can then be loaded into
  644. <span class="productname">PostgreSQL</span>. When specifying the file name
  645. to the <code class="command">CREATE FUNCTION</code> command, one must give it
  646. the name of the shared library file, not the intermediate object file.
  647. Note that the system's standard shared-library extension (usually
  648. <code class="literal">.so</code> or <code class="literal">.sl</code>) can be omitted from
  649. the <code class="command">CREATE FUNCTION</code> command, and normally should
  650. be omitted for best portability.
  651. </p><p>
  652. Refer back to <a class="xref" href="xfunc-c.html#XFUNC-C-DYNLOAD" title="37.10.1. Dynamic Loading">Section 37.10.1</a> about where the
  653. server expects to find the shared library files.
  654. </p></div><div class="sect2" id="id-1.8.3.13.10"><div class="titlepage"><div><div><h3 class="title">37.10.6. Composite-Type Arguments</h3></div></div></div><p>
  655. Composite types do not have a fixed layout like C structures.
  656. Instances of a composite type can contain null fields. In
  657. addition, composite types that are part of an inheritance
  658. hierarchy can have different fields than other members of the
  659. same inheritance hierarchy. Therefore,
  660. <span class="productname">PostgreSQL</span> provides a function
  661. interface for accessing fields of composite types from C.
  662. </p><p>
  663. Suppose we want to write a function to answer the query:
  664. </p><pre class="programlisting">
  665. SELECT name, c_overpaid(emp, 1500) AS overpaid
  666. FROM emp
  667. WHERE name = 'Bill' OR name = 'Sam';
  668. </pre><p>
  669. Using the version-1 calling conventions, we can define
  670. <code class="function">c_overpaid</code> as:
  671. </p><pre class="programlisting">
  672. #include "postgres.h"
  673. #include "executor/executor.h" /* for GetAttributeByName() */
  674. PG_MODULE_MAGIC;
  675. PG_FUNCTION_INFO_V1(c_overpaid);
  676. Datum
  677. c_overpaid(PG_FUNCTION_ARGS)
  678. {
  679. HeapTupleHeader t = PG_GETARG_HEAPTUPLEHEADER(0);
  680. int32 limit = PG_GETARG_INT32(1);
  681. bool isnull;
  682. Datum salary;
  683. salary = GetAttributeByName(t, "salary", &amp;isnull);
  684. if (isnull)
  685. PG_RETURN_BOOL(false);
  686. /* Alternatively, we might prefer to do PG_RETURN_NULL() for null salary. */
  687. PG_RETURN_BOOL(DatumGetInt32(salary) &gt; limit);
  688. }
  689. </pre><p>
  690. </p><p>
  691. <code class="function">GetAttributeByName</code> is the
  692. <span class="productname">PostgreSQL</span> system function that
  693. returns attributes out of the specified row. It has
  694. three arguments: the argument of type <code class="type">HeapTupleHeader</code> passed
  695. into
  696. the function, the name of the desired attribute, and a
  697. return parameter that tells whether the attribute
  698. is null. <code class="function">GetAttributeByName</code> returns a <code class="type">Datum</code>
  699. value that you can convert to the proper data type by using the
  700. appropriate <code class="function">DatumGet<em class="replaceable"><code>XXX</code></em>()</code>
  701. macro. Note that the return value is meaningless if the null flag is
  702. set; always check the null flag before trying to do anything with the
  703. result.
  704. </p><p>
  705. There is also <code class="function">GetAttributeByNum</code>, which selects
  706. the target attribute by column number instead of name.
  707. </p><p>
  708. The following command declares the function
  709. <code class="function">c_overpaid</code> in SQL:
  710. </p><pre class="programlisting">
  711. CREATE FUNCTION c_overpaid(emp, integer) RETURNS boolean
  712. AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'c_overpaid'
  713. LANGUAGE C STRICT;
  714. </pre><p>
  715. Notice we have used <code class="literal">STRICT</code> so that we did not have to
  716. check whether the input arguments were NULL.
  717. </p></div><div class="sect2" id="id-1.8.3.13.11"><div class="titlepage"><div><div><h3 class="title">37.10.7. Returning Rows (Composite Types)</h3></div></div></div><p>
  718. To return a row or composite-type value from a C-language
  719. function, you can use a special API that provides macros and
  720. functions to hide most of the complexity of building composite
  721. data types. To use this API, the source file must include:
  722. </p><pre class="programlisting">
  723. #include "funcapi.h"
  724. </pre><p>
  725. </p><p>
  726. There are two ways you can build a composite data value (henceforth
  727. a <span class="quote">“<span class="quote">tuple</span>”</span>): you can build it from an array of Datum values,
  728. or from an array of C strings that can be passed to the input
  729. conversion functions of the tuple's column data types. In either
  730. case, you first need to obtain or construct a <code class="structname">TupleDesc</code>
  731. descriptor for the tuple structure. When working with Datums, you
  732. pass the <code class="structname">TupleDesc</code> to <code class="function">BlessTupleDesc</code>,
  733. and then call <code class="function">heap_form_tuple</code> for each row. When working
  734. with C strings, you pass the <code class="structname">TupleDesc</code> to
  735. <code class="function">TupleDescGetAttInMetadata</code>, and then call
  736. <code class="function">BuildTupleFromCStrings</code> for each row. In the case of a
  737. function returning a set of tuples, the setup steps can all be done
  738. once during the first call of the function.
  739. </p><p>
  740. Several helper functions are available for setting up the needed
  741. <code class="structname">TupleDesc</code>. The recommended way to do this in most
  742. functions returning composite values is to call:
  743. </p><pre class="programlisting">
  744. TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo,
  745. Oid *resultTypeId,
  746. TupleDesc *resultTupleDesc)
  747. </pre><p>
  748. passing the same <code class="literal">fcinfo</code> struct passed to the calling function
  749. itself. (This of course requires that you use the version-1
  750. calling conventions.) <code class="varname">resultTypeId</code> can be specified
  751. as <code class="literal">NULL</code> or as the address of a local variable to receive the
  752. function's result type OID. <code class="varname">resultTupleDesc</code> should be the
  753. address of a local <code class="structname">TupleDesc</code> variable. Check that the
  754. result is <code class="literal">TYPEFUNC_COMPOSITE</code>; if so,
  755. <code class="varname">resultTupleDesc</code> has been filled with the needed
  756. <code class="structname">TupleDesc</code>. (If it is not, you can report an error along
  757. the lines of <span class="quote">“<span class="quote">function returning record called in context that
  758. cannot accept type record</span>”</span>.)
  759. </p><div class="tip"><h3 class="title">Tip</h3><p>
  760. <code class="function">get_call_result_type</code> can resolve the actual type of a
  761. polymorphic function result; so it is useful in functions that return
  762. scalar polymorphic results, not only functions that return composites.
  763. The <code class="varname">resultTypeId</code> output is primarily useful for functions
  764. returning polymorphic scalars.
  765. </p></div><div class="note"><h3 class="title">Note</h3><p>
  766. <code class="function">get_call_result_type</code> has a sibling
  767. <code class="function">get_expr_result_type</code>, which can be used to resolve the
  768. expected output type for a function call represented by an expression
  769. tree. This can be used when trying to determine the result type from
  770. outside the function itself. There is also
  771. <code class="function">get_func_result_type</code>, which can be used when only the
  772. function's OID is available. However these functions are not able
  773. to deal with functions declared to return <code class="structname">record</code>, and
  774. <code class="function">get_func_result_type</code> cannot resolve polymorphic types,
  775. so you should preferentially use <code class="function">get_call_result_type</code>.
  776. </p></div><p>
  777. Older, now-deprecated functions for obtaining
  778. <code class="structname">TupleDesc</code>s are:
  779. </p><pre class="programlisting">
  780. TupleDesc RelationNameGetTupleDesc(const char *relname)
  781. </pre><p>
  782. to get a <code class="structname">TupleDesc</code> for the row type of a named relation,
  783. and:
  784. </p><pre class="programlisting">
  785. TupleDesc TypeGetTupleDesc(Oid typeoid, List *colaliases)
  786. </pre><p>
  787. to get a <code class="structname">TupleDesc</code> based on a type OID. This can
  788. be used to get a <code class="structname">TupleDesc</code> for a base or
  789. composite type. It will not work for a function that returns
  790. <code class="structname">record</code>, however, and it cannot resolve polymorphic
  791. types.
  792. </p><p>
  793. Once you have a <code class="structname">TupleDesc</code>, call:
  794. </p><pre class="programlisting">
  795. TupleDesc BlessTupleDesc(TupleDesc tupdesc)
  796. </pre><p>
  797. if you plan to work with Datums, or:
  798. </p><pre class="programlisting">
  799. AttInMetadata *TupleDescGetAttInMetadata(TupleDesc tupdesc)
  800. </pre><p>
  801. if you plan to work with C strings. If you are writing a function
  802. returning set, you can save the results of these functions in the
  803. <code class="structname">FuncCallContext</code> structure — use the
  804. <code class="structfield">tuple_desc</code> or <code class="structfield">attinmeta</code> field
  805. respectively.
  806. </p><p>
  807. When working with Datums, use:
  808. </p><pre class="programlisting">
  809. HeapTuple heap_form_tuple(TupleDesc tupdesc, Datum *values, bool *isnull)
  810. </pre><p>
  811. to build a <code class="structname">HeapTuple</code> given user data in Datum form.
  812. </p><p>
  813. When working with C strings, use:
  814. </p><pre class="programlisting">
  815. HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
  816. </pre><p>
  817. to build a <code class="structname">HeapTuple</code> given user data
  818. in C string form. <em class="parameter"><code>values</code></em> is an array of C strings,
  819. one for each attribute of the return row. Each C string should be in
  820. the form expected by the input function of the attribute data
  821. type. In order to return a null value for one of the attributes,
  822. the corresponding pointer in the <em class="parameter"><code>values</code></em> array
  823. should be set to <code class="symbol">NULL</code>. This function will need to
  824. be called again for each row you return.
  825. </p><p>
  826. Once you have built a tuple to return from your function, it
  827. must be converted into a <code class="type">Datum</code>. Use:
  828. </p><pre class="programlisting">
  829. HeapTupleGetDatum(HeapTuple tuple)
  830. </pre><p>
  831. to convert a <code class="structname">HeapTuple</code> into a valid Datum. This
  832. <code class="type">Datum</code> can be returned directly if you intend to return
  833. just a single row, or it can be used as the current return value
  834. in a set-returning function.
  835. </p><p>
  836. An example appears in the next section.
  837. </p></div><div class="sect2" id="XFUNC-C-RETURN-SET"><div class="titlepage"><div><div><h3 class="title">37.10.8. Returning Sets</h3></div></div></div><p>
  838. C-language functions have two options for returning sets (multiple
  839. rows). In one method, called <em class="firstterm">ValuePerCall</em>
  840. mode, a set-returning function is called repeatedly (passing the same
  841. arguments each time) and it returns one new row on each call, until
  842. it has no more rows to return and signals that by returning NULL.
  843. The set-returning function (<acronym class="acronym">SRF</acronym>) must therefore
  844. save enough state across calls to remember what it was doing and
  845. return the correct next item on each call.
  846. In the other method, called <em class="firstterm">Materialize</em> mode,
  847. a SRF fills and returns a tuplestore object containing its
  848. entire result; then only one call occurs for the whole result, and
  849. no inter-call state is needed.
  850. </p><p>
  851. When using ValuePerCall mode, it is important to remember that the
  852. query is not guaranteed to be run to completion; that is, due to
  853. options such as <code class="literal">LIMIT</code>, the executor might stop
  854. making calls to the set-returning function before all rows have been
  855. fetched. This means it is not safe to perform cleanup activities in
  856. the last call, because that might not ever happen. It's recommended
  857. to use Materialize mode for functions that need access to external
  858. resources, such as file descriptors.
  859. </p><p>
  860. The remainder of this section documents a set of helper macros that
  861. are commonly used (though not required to be used) for SRFs using
  862. ValuePerCall mode. Additional details about Materialize mode can be
  863. found in <code class="filename">src/backend/utils/fmgr/README</code>. Also,
  864. the <code class="filename">contrib</code> modules in
  865. the <span class="productname">PostgreSQL</span> source distribution contain
  866. many examples of SRFs using both ValuePerCall and Materialize mode.
  867. </p><p>
  868. To use the ValuePerCall support macros described here,
  869. include <code class="filename">funcapi.h</code>. These macros work with a
  870. structure <code class="structname">FuncCallContext</code> that contains the
  871. state that needs to be saved across calls. Within the calling
  872. SRF, <code class="literal">fcinfo-&gt;flinfo-&gt;fn_extra</code> is used to
  873. hold a pointer to <code class="structname">FuncCallContext</code> across
  874. calls. The macros automatically fill that field on first use,
  875. and expect to find the same pointer there on subsequent uses.
  876. </p><pre class="programlisting">
  877. typedef struct FuncCallContext
  878. {
  879. /*
  880. * Number of times we've been called before
  881. *
  882. * call_cntr is initialized to 0 for you by SRF_FIRSTCALL_INIT(), and
  883. * incremented for you every time SRF_RETURN_NEXT() is called.
  884. */
  885. uint64 call_cntr;
  886. /*
  887. * OPTIONAL maximum number of calls
  888. *
  889. * max_calls is here for convenience only and setting it is optional.
  890. * If not set, you must provide alternative means to know when the
  891. * function is done.
  892. */
  893. uint64 max_calls;
  894. /*
  895. * OPTIONAL pointer to miscellaneous user-provided context information
  896. *
  897. * user_fctx is for use as a pointer to your own data to retain
  898. * arbitrary context information between calls of your function.
  899. */
  900. void *user_fctx;
  901. /*
  902. * OPTIONAL pointer to struct containing attribute type input metadata
  903. *
  904. * attinmeta is for use when returning tuples (i.e., composite data types)
  905. * and is not used when returning base data types. It is only needed
  906. * if you intend to use BuildTupleFromCStrings() to create the return
  907. * tuple.
  908. */
  909. AttInMetadata *attinmeta;
  910. /*
  911. * memory context used for structures that must live for multiple calls
  912. *
  913. * multi_call_memory_ctx is set by SRF_FIRSTCALL_INIT() for you, and used
  914. * by SRF_RETURN_DONE() for cleanup. It is the most appropriate memory
  915. * context for any memory that is to be reused across multiple calls
  916. * of the SRF.
  917. */
  918. MemoryContext multi_call_memory_ctx;
  919. /*
  920. * OPTIONAL pointer to struct containing tuple description
  921. *
  922. * tuple_desc is for use when returning tuples (i.e., composite data types)
  923. * and is only needed if you are going to build the tuples with
  924. * heap_form_tuple() rather than with BuildTupleFromCStrings(). Note that
  925. * the TupleDesc pointer stored here should usually have been run through
  926. * BlessTupleDesc() first.
  927. */
  928. TupleDesc tuple_desc;
  929. } FuncCallContext;
  930. </pre><p>
  931. </p><p>
  932. The macros to be used by an <acronym class="acronym">SRF</acronym> using this
  933. infrastructure are:
  934. </p><pre class="programlisting">
  935. SRF_IS_FIRSTCALL()
  936. </pre><p>
  937. Use this to determine if your function is being called for the first or a
  938. subsequent time. On the first call (only), call:
  939. </p><pre class="programlisting">
  940. SRF_FIRSTCALL_INIT()
  941. </pre><p>
  942. to initialize the <code class="structname">FuncCallContext</code>. On every function call,
  943. including the first, call:
  944. </p><pre class="programlisting">
  945. SRF_PERCALL_SETUP()
  946. </pre><p>
  947. to set up for using the <code class="structname">FuncCallContext</code>.
  948. </p><p>
  949. If your function has data to return in the current call, use:
  950. </p><pre class="programlisting">
  951. SRF_RETURN_NEXT(funcctx, result)
  952. </pre><p>
  953. to return it to the caller. (<code class="literal">result</code> must be of type
  954. <code class="type">Datum</code>, either a single value or a tuple prepared as
  955. described above.) Finally, when your function is finished
  956. returning data, use:
  957. </p><pre class="programlisting">
  958. SRF_RETURN_DONE(funcctx)
  959. </pre><p>
  960. to clean up and end the <acronym class="acronym">SRF</acronym>.
  961. </p><p>
  962. The memory context that is current when the <acronym class="acronym">SRF</acronym> is called is
  963. a transient context that will be cleared between calls. This means
  964. that you do not need to call <code class="function">pfree</code> on everything
  965. you allocated using <code class="function">palloc</code>; it will go away anyway. However, if you want to allocate
  966. any data structures to live across calls, you need to put them somewhere
  967. else. The memory context referenced by
  968. <code class="structfield">multi_call_memory_ctx</code> is a suitable location for any
  969. data that needs to survive until the <acronym class="acronym">SRF</acronym> is finished running. In most
  970. cases, this means that you should switch into
  971. <code class="structfield">multi_call_memory_ctx</code> while doing the
  972. first-call setup.
  973. Use <code class="literal">funcctx-&gt;user_fctx</code> to hold a pointer to
  974. any such cross-call data structures.
  975. (Data you allocate
  976. in <code class="structfield">multi_call_memory_ctx</code> will go away
  977. automatically when the query ends, so it is not necessary to free
  978. that data manually, either.)
  979. </p><div class="warning"><h3 class="title">Warning</h3><p>
  980. While the actual arguments to the function remain unchanged between
  981. calls, if you detoast the argument values (which is normally done
  982. transparently by the
  983. <code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em></code> macro)
  984. in the transient context then the detoasted copies will be freed on
  985. each cycle. Accordingly, if you keep references to such values in
  986. your <code class="structfield">user_fctx</code>, you must either copy them into the
  987. <code class="structfield">multi_call_memory_ctx</code> after detoasting, or ensure
  988. that you detoast the values only in that context.
  989. </p></div><p>
  990. A complete pseudo-code example looks like the following:
  991. </p><pre class="programlisting">
  992. Datum
  993. my_set_returning_function(PG_FUNCTION_ARGS)
  994. {
  995. FuncCallContext *funcctx;
  996. Datum result;
  997. <em class="replaceable"><code>further declarations as needed</code></em>
  998. if (SRF_IS_FIRSTCALL())
  999. {
  1000. MemoryContext oldcontext;
  1001. funcctx = SRF_FIRSTCALL_INIT();
  1002. oldcontext = MemoryContextSwitchTo(funcctx-&gt;multi_call_memory_ctx);
  1003. /* One-time setup code appears here: */
  1004. <em class="replaceable"><code>user code</code></em>
  1005. <em class="replaceable"><code>if returning composite</code></em>
  1006. <em class="replaceable"><code>build TupleDesc, and perhaps AttInMetadata</code></em>
  1007. <em class="replaceable"><code>endif returning composite</code></em>
  1008. <em class="replaceable"><code>user code</code></em>
  1009. MemoryContextSwitchTo(oldcontext);
  1010. }
  1011. /* Each-time setup code appears here: */
  1012. <em class="replaceable"><code>user code</code></em>
  1013. funcctx = SRF_PERCALL_SETUP();
  1014. <em class="replaceable"><code>user code</code></em>
  1015. /* this is just one way we might test whether we are done: */
  1016. if (funcctx-&gt;call_cntr &lt; funcctx-&gt;max_calls)
  1017. {
  1018. /* Here we want to return another item: */
  1019. <em class="replaceable"><code>user code</code></em>
  1020. <em class="replaceable"><code>obtain result Datum</code></em>
  1021. SRF_RETURN_NEXT(funcctx, result);
  1022. }
  1023. else
  1024. {
  1025. /* Here we are done returning items, so just report that fact. */
  1026. /* (Resist the temptation to put cleanup code here.) */
  1027. SRF_RETURN_DONE(funcctx);
  1028. }
  1029. }
  1030. </pre><p>
  1031. </p><p>
  1032. A complete example of a simple <acronym class="acronym">SRF</acronym> returning a composite type
  1033. looks like:
  1034. </p><pre class="programlisting">
  1035. PG_FUNCTION_INFO_V1(retcomposite);
  1036. Datum
  1037. retcomposite(PG_FUNCTION_ARGS)
  1038. {
  1039. FuncCallContext *funcctx;
  1040. int call_cntr;
  1041. int max_calls;
  1042. TupleDesc tupdesc;
  1043. AttInMetadata *attinmeta;
  1044. /* stuff done only on the first call of the function */
  1045. if (SRF_IS_FIRSTCALL())
  1046. {
  1047. MemoryContext oldcontext;
  1048. /* create a function context for cross-call persistence */
  1049. funcctx = SRF_FIRSTCALL_INIT();
  1050. /* switch to memory context appropriate for multiple function calls */
  1051. oldcontext = MemoryContextSwitchTo(funcctx-&gt;multi_call_memory_ctx);
  1052. /* total number of tuples to be returned */
  1053. funcctx-&gt;max_calls = PG_GETARG_UINT32(0);
  1054. /* Build a tuple descriptor for our result type */
  1055. if (get_call_result_type(fcinfo, NULL, &amp;tupdesc) != TYPEFUNC_COMPOSITE)
  1056. ereport(ERROR,
  1057. (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
  1058. errmsg("function returning record called in context "
  1059. "that cannot accept type record")));
  1060. /*
  1061. * generate attribute metadata needed later to produce tuples from raw
  1062. * C strings
  1063. */
  1064. attinmeta = TupleDescGetAttInMetadata(tupdesc);
  1065. funcctx-&gt;attinmeta = attinmeta;
  1066. MemoryContextSwitchTo(oldcontext);
  1067. }
  1068. /* stuff done on every call of the function */
  1069. funcctx = SRF_PERCALL_SETUP();
  1070. call_cntr = funcctx-&gt;call_cntr;
  1071. max_calls = funcctx-&gt;max_calls;
  1072. attinmeta = funcctx-&gt;attinmeta;
  1073. if (call_cntr &lt; max_calls) /* do when there is more left to send */
  1074. {
  1075. char **values;
  1076. HeapTuple tuple;
  1077. Datum result;
  1078. /*
  1079. * Prepare a values array for building the returned tuple.
  1080. * This should be an array of C strings which will
  1081. * be processed later by the type input functions.
  1082. */
  1083. values = (char **) palloc(3 * sizeof(char *));
  1084. values[0] = (char *) palloc(16 * sizeof(char));
  1085. values[1] = (char *) palloc(16 * sizeof(char));
  1086. values[2] = (char *) palloc(16 * sizeof(char));
  1087. snprintf(values[0], 16, "%d", 1 * PG_GETARG_INT32(1));
  1088. snprintf(values[1], 16, "%d", 2 * PG_GETARG_INT32(1));
  1089. snprintf(values[2], 16, "%d", 3 * PG_GETARG_INT32(1));
  1090. /* build a tuple */
  1091. tuple = BuildTupleFromCStrings(attinmeta, values);
  1092. /* make the tuple into a datum */
  1093. result = HeapTupleGetDatum(tuple);
  1094. /* clean up (this is not really necessary) */
  1095. pfree(values[0]);
  1096. pfree(values[1]);
  1097. pfree(values[2]);
  1098. pfree(values);
  1099. SRF_RETURN_NEXT(funcctx, result);
  1100. }
  1101. else /* do when there is no more left */
  1102. {
  1103. SRF_RETURN_DONE(funcctx);
  1104. }
  1105. }
  1106. </pre><p>
  1107. One way to declare this function in SQL is:
  1108. </p><pre class="programlisting">
  1109. CREATE TYPE __retcomposite AS (f1 integer, f2 integer, f3 integer);
  1110. CREATE OR REPLACE FUNCTION retcomposite(integer, integer)
  1111. RETURNS SETOF __retcomposite
  1112. AS '<em class="replaceable"><code>filename</code></em>', 'retcomposite'
  1113. LANGUAGE C IMMUTABLE STRICT;
  1114. </pre><p>
  1115. A different way is to use OUT parameters:
  1116. </p><pre class="programlisting">
  1117. CREATE OR REPLACE FUNCTION retcomposite(IN integer, IN integer,
  1118. OUT f1 integer, OUT f2 integer, OUT f3 integer)
  1119. RETURNS SETOF record
  1120. AS '<em class="replaceable"><code>filename</code></em>', 'retcomposite'
  1121. LANGUAGE C IMMUTABLE STRICT;
  1122. </pre><p>
  1123. Notice that in this method the output type of the function is formally
  1124. an anonymous <code class="structname">record</code> type.
  1125. </p></div><div class="sect2" id="id-1.8.3.13.13"><div class="titlepage"><div><div><h3 class="title">37.10.9. Polymorphic Arguments and Return Types</h3></div></div></div><p>
  1126. C-language functions can be declared to accept and
  1127. return the polymorphic types
  1128. <code class="type">anyelement</code>, <code class="type">anyarray</code>, <code class="type">anynonarray</code>,
  1129. <code class="type">anyenum</code>, and <code class="type">anyrange</code>.
  1130. See <a class="xref" href="extend-type-system.html#EXTEND-TYPES-POLYMORPHIC" title="37.2.5. Polymorphic Types">Section 37.2.5</a> for a more detailed explanation
  1131. of polymorphic functions. When function arguments or return types
  1132. are defined as polymorphic types, the function author cannot know
  1133. in advance what data type it will be called with, or
  1134. need to return. There are two routines provided in <code class="filename">fmgr.h</code>
  1135. to allow a version-1 C function to discover the actual data types
  1136. of its arguments and the type it is expected to return. The routines are
  1137. called <code class="literal">get_fn_expr_rettype(FmgrInfo *flinfo)</code> and
  1138. <code class="literal">get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)</code>.
  1139. They return the result or argument type OID, or <code class="symbol">InvalidOid</code> if the
  1140. information is not available.
  1141. The structure <code class="literal">flinfo</code> is normally accessed as
  1142. <code class="literal">fcinfo-&gt;flinfo</code>. The parameter <code class="literal">argnum</code>
  1143. is zero based. <code class="function">get_call_result_type</code> can also be used
  1144. as an alternative to <code class="function">get_fn_expr_rettype</code>.
  1145. There is also <code class="function">get_fn_expr_variadic</code>, which can be used to
  1146. find out whether variadic arguments have been merged into an array.
  1147. This is primarily useful for <code class="literal">VARIADIC "any"</code> functions,
  1148. since such merging will always have occurred for variadic functions
  1149. taking ordinary array types.
  1150. </p><p>
  1151. For example, suppose we want to write a function to accept a single
  1152. element of any type, and return a one-dimensional array of that type:
  1153. </p><pre class="programlisting">
  1154. PG_FUNCTION_INFO_V1(make_array);
  1155. Datum
  1156. make_array(PG_FUNCTION_ARGS)
  1157. {
  1158. ArrayType *result;
  1159. Oid element_type = get_fn_expr_argtype(fcinfo-&gt;flinfo, 0);
  1160. Datum element;
  1161. bool isnull;
  1162. int16 typlen;
  1163. bool typbyval;
  1164. char typalign;
  1165. int ndims;
  1166. int dims[MAXDIM];
  1167. int lbs[MAXDIM];
  1168. if (!OidIsValid(element_type))
  1169. elog(ERROR, "could not determine data type of input");
  1170. /* get the provided element, being careful in case it's NULL */
  1171. isnull = PG_ARGISNULL(0);
  1172. if (isnull)
  1173. element = (Datum) 0;
  1174. else
  1175. element = PG_GETARG_DATUM(0);
  1176. /* we have one dimension */
  1177. ndims = 1;
  1178. /* and one element */
  1179. dims[0] = 1;
  1180. /* and lower bound is 1 */
  1181. lbs[0] = 1;
  1182. /* get required info about the element type */
  1183. get_typlenbyvalalign(element_type, &amp;typlen, &amp;typbyval, &amp;typalign);
  1184. /* now build the array */
  1185. result = construct_md_array(&amp;element, &amp;isnull, ndims, dims, lbs,
  1186. element_type, typlen, typbyval, typalign);
  1187. PG_RETURN_ARRAYTYPE_P(result);
  1188. }
  1189. </pre><p>
  1190. </p><p>
  1191. The following command declares the function
  1192. <code class="function">make_array</code> in SQL:
  1193. </p><pre class="programlisting">
  1194. CREATE FUNCTION make_array(anyelement) RETURNS anyarray
  1195. AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'make_array'
  1196. LANGUAGE C IMMUTABLE;
  1197. </pre><p>
  1198. </p><p>
  1199. There is a variant of polymorphism that is only available to C-language
  1200. functions: they can be declared to take parameters of type
  1201. <code class="literal">"any"</code>. (Note that this type name must be double-quoted,
  1202. since it's also a SQL reserved word.) This works like
  1203. <code class="type">anyelement</code> except that it does not constrain different
  1204. <code class="literal">"any"</code> arguments to be the same type, nor do they help
  1205. determine the function's result type. A C-language function can also
  1206. declare its final parameter to be <code class="literal">VARIADIC "any"</code>. This will
  1207. match one or more actual arguments of any type (not necessarily the same
  1208. type). These arguments will <span class="emphasis"><em>not</em></span> be gathered into an array
  1209. as happens with normal variadic functions; they will just be passed to
  1210. the function separately. The <code class="function">PG_NARGS()</code> macro and the
  1211. methods described above must be used to determine the number of actual
  1212. arguments and their types when using this feature. Also, users of such
  1213. a function might wish to use the <code class="literal">VARIADIC</code> keyword in their
  1214. function call, with the expectation that the function would treat the
  1215. array elements as separate arguments. The function itself must implement
  1216. that behavior if wanted, after using <code class="function">get_fn_expr_variadic</code> to
  1217. detect that the actual argument was marked with <code class="literal">VARIADIC</code>.
  1218. </p></div><div class="sect2" id="id-1.8.3.13.14"><div class="titlepage"><div><div><h3 class="title">37.10.10. Shared Memory and LWLocks</h3></div></div></div><p>
  1219. Add-ins can reserve LWLocks and an allocation of shared memory on server
  1220. startup. The add-in's shared library must be preloaded by specifying
  1221. it in
  1222. <a class="xref" href="runtime-config-client.html#GUC-SHARED-PRELOAD-LIBRARIES">shared_preload_libraries</a><a id="id-1.8.3.13.14.2.2" class="indexterm"></a>.
  1223. Shared memory is reserved by calling:
  1224. </p><pre class="programlisting">
  1225. void RequestAddinShmemSpace(int size)
  1226. </pre><p>
  1227. from your <code class="function">_PG_init</code> function.
  1228. </p><p>
  1229. LWLocks are reserved by calling:
  1230. </p><pre class="programlisting">
  1231. void RequestNamedLWLockTranche(const char *tranche_name, int num_lwlocks)
  1232. </pre><p>
  1233. from <code class="function">_PG_init</code>. This will ensure that an array of
  1234. <code class="literal">num_lwlocks</code> LWLocks is available under the name
  1235. <code class="literal">tranche_name</code>. Use <code class="function">GetNamedLWLockTranche</code>
  1236. to get a pointer to this array.
  1237. </p><p>
  1238. To avoid possible race-conditions, each backend should use the LWLock
  1239. <code class="function">AddinShmemInitLock</code> when connecting to and initializing
  1240. its allocation of shared memory, as shown here:
  1241. </p><pre class="programlisting">
  1242. static mystruct *ptr = NULL;
  1243. if (!ptr)
  1244. {
  1245. bool found;
  1246. LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
  1247. ptr = ShmemInitStruct("my struct name", size, &amp;found);
  1248. if (!found)
  1249. {
  1250. initialize contents of shmem area;
  1251. acquire any requested LWLocks using:
  1252. ptr-&gt;locks = GetNamedLWLockTranche("my tranche name");
  1253. }
  1254. LWLockRelease(AddinShmemInitLock);
  1255. }
  1256. </pre><p>
  1257. </p></div><div class="sect2" id="EXTEND-CPP"><div class="titlepage"><div><div><h3 class="title">37.10.11. Using C++ for Extensibility</h3></div></div></div><a id="id-1.8.3.13.15.2" class="indexterm"></a><p>
  1258. Although the <span class="productname">PostgreSQL</span> backend is written in
  1259. C, it is possible to write extensions in C++ if these guidelines are
  1260. followed:
  1261. </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
  1262. All functions accessed by the backend must present a C interface
  1263. to the backend; these C functions can then call C++ functions.
  1264. For example, <code class="literal">extern C</code> linkage is required for
  1265. backend-accessed functions. This is also necessary for any
  1266. functions that are passed as pointers between the backend and
  1267. C++ code.
  1268. </p></li><li class="listitem"><p>
  1269. Free memory using the appropriate deallocation method. For example,
  1270. most backend memory is allocated using <code class="function">palloc()</code>, so use
  1271. <code class="function">pfree()</code> to free it. Using C++
  1272. <code class="function">delete</code> in such cases will fail.
  1273. </p></li><li class="listitem"><p>
  1274. Prevent exceptions from propagating into the C code (use a catch-all
  1275. block at the top level of all <code class="literal">extern C</code> functions). This
  1276. is necessary even if the C++ code does not explicitly throw any
  1277. exceptions, because events like out-of-memory can still throw
  1278. exceptions. Any exceptions must be caught and appropriate errors
  1279. passed back to the C interface. If possible, compile C++ with
  1280. <code class="option">-fno-exceptions</code> to eliminate exceptions entirely; in such
  1281. cases, you must check for failures in your C++ code, e.g. check for
  1282. NULL returned by <code class="function">new()</code>.
  1283. </p></li><li class="listitem"><p>
  1284. If calling backend functions from C++ code, be sure that the
  1285. C++ call stack contains only plain old data structures
  1286. (<acronym class="acronym">POD</acronym>). This is necessary because backend errors
  1287. generate a distant <code class="function">longjmp()</code> that does not properly
  1288. unroll a C++ call stack with non-POD objects.
  1289. </p></li></ul></div><p>
  1290. </p><p>
  1291. In summary, it is best to place C++ code behind a wall of
  1292. <code class="literal">extern C</code> functions that interface to the backend,
  1293. and avoid exception, memory, and call stack leakage.
  1294. </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">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="extend.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="xfunc-optimization.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">37.9. Internal Functions </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> 37.11. Function Optimization Information</td></tr></table></div></body></html>
上海开阖软件有限公司 沪ICP备12045867号-1