gooderp18绿色标准版
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

528 linhas
33KB

  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.12. User-Defined Aggregates</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-optimization.html" title="37.11. Function Optimization Information" /><link rel="next" href="xtypes.html" title="37.13. User-Defined Types" /></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.12. User-Defined Aggregates</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="xfunc-optimization.html" title="37.11. Function Optimization Information">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="xtypes.html" title="37.13. User-Defined Types">Next</a></td></tr></table><hr></hr></div><div class="sect1" id="XAGGR"><div class="titlepage"><div><div><h2 class="title" style="clear: both">37.12. User-Defined Aggregates</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="xaggr.html#XAGGR-MOVING-AGGREGATES">37.12.1. Moving-Aggregate Mode</a></span></dt><dt><span class="sect2"><a href="xaggr.html#XAGGR-POLYMORPHIC-AGGREGATES">37.12.2. Polymorphic and Variadic Aggregates</a></span></dt><dt><span class="sect2"><a href="xaggr.html#XAGGR-ORDERED-SET-AGGREGATES">37.12.3. Ordered-Set Aggregates</a></span></dt><dt><span class="sect2"><a href="xaggr.html#XAGGR-PARTIAL-AGGREGATES">37.12.4. Partial Aggregation</a></span></dt><dt><span class="sect2"><a href="xaggr.html#XAGGR-SUPPORT-FUNCTIONS">37.12.5. Support Functions for Aggregates</a></span></dt></dl></div><a id="id-1.8.3.15.2" class="indexterm"></a><p>
  3. Aggregate functions in <span class="productname">PostgreSQL</span>
  4. are defined in terms of <em class="firstterm">state values</em>
  5. and <em class="firstterm">state transition functions</em>.
  6. That is, an aggregate operates using a state value that is updated
  7. as each successive input row is processed.
  8. To define a new aggregate
  9. function, one selects a data type for the state value,
  10. an initial value for the state, and a state transition
  11. function. The state transition function takes the previous state
  12. value and the aggregate's input value(s) for the current row, and
  13. returns a new state value.
  14. A <em class="firstterm">final function</em>
  15. can also be specified, in case the desired result of the aggregate
  16. is different from the data that needs to be kept in the running
  17. state value. The final function takes the ending state value
  18. and returns whatever is wanted as the aggregate result.
  19. In principle, the transition and final functions are just ordinary
  20. functions that could also be used outside the context of the
  21. aggregate. (In practice, it's often helpful for performance reasons
  22. to create specialized transition functions that can only work when
  23. called as part of an aggregate.)
  24. </p><p>
  25. Thus, in addition to the argument and result data types seen by a user
  26. of the aggregate, there is an internal state-value data type that
  27. might be different from both the argument and result types.
  28. </p><p>
  29. If we define an aggregate that does not use a final function,
  30. we have an aggregate that computes a running function of
  31. the column values from each row. <code class="function">sum</code> is an
  32. example of this kind of aggregate. <code class="function">sum</code> starts at
  33. zero and always adds the current row's value to
  34. its running total. For example, if we want to make a <code class="function">sum</code>
  35. aggregate to work on a data type for complex numbers,
  36. we only need the addition function for that data type.
  37. The aggregate definition would be:
  38. </p><pre class="programlisting">
  39. CREATE AGGREGATE sum (complex)
  40. (
  41. sfunc = complex_add,
  42. stype = complex,
  43. initcond = '(0,0)'
  44. );
  45. </pre><p>
  46. which we might use like this:
  47. </p><pre class="programlisting">
  48. SELECT sum(a) FROM test_complex;
  49. sum
  50. -----------
  51. (34,53.9)
  52. </pre><p>
  53. (Notice that we are relying on function overloading: there is more than
  54. one aggregate named <code class="function">sum</code>, but
  55. <span class="productname">PostgreSQL</span> can figure out which kind
  56. of sum applies to a column of type <code class="type">complex</code>.)
  57. </p><p>
  58. The above definition of <code class="function">sum</code> will return zero
  59. (the initial state value) if there are no nonnull input values.
  60. Perhaps we want to return null in that case instead — the SQL standard
  61. expects <code class="function">sum</code> to behave that way. We can do this simply by
  62. omitting the <code class="literal">initcond</code> phrase, so that the initial state
  63. value is null. Ordinarily this would mean that the <code class="literal">sfunc</code>
  64. would need to check for a null state-value input. But for
  65. <code class="function">sum</code> and some other simple aggregates like
  66. <code class="function">max</code> and <code class="function">min</code>,
  67. it is sufficient to insert the first nonnull input value into
  68. the state variable and then start applying the transition function
  69. at the second nonnull input value. <span class="productname">PostgreSQL</span>
  70. will do that automatically if the initial state value is null and
  71. the transition function is marked <span class="quote">“<span class="quote">strict</span>”</span> (i.e., not to be called
  72. for null inputs).
  73. </p><p>
  74. Another bit of default behavior for a <span class="quote">“<span class="quote">strict</span>”</span> transition function
  75. is that the previous state value is retained unchanged whenever a
  76. null input value is encountered. Thus, null values are ignored. If you
  77. need some other behavior for null inputs, do not declare your
  78. transition function as strict; instead code it to test for null inputs and
  79. do whatever is needed.
  80. </p><p>
  81. <code class="function">avg</code> (average) is a more complex example of an aggregate.
  82. It requires
  83. two pieces of running state: the sum of the inputs and the count
  84. of the number of inputs. The final result is obtained by dividing
  85. these quantities. Average is typically implemented by using an
  86. array as the state value. For example,
  87. the built-in implementation of <code class="function">avg(float8)</code>
  88. looks like:
  89. </p><pre class="programlisting">
  90. CREATE AGGREGATE avg (float8)
  91. (
  92. sfunc = float8_accum,
  93. stype = float8[],
  94. finalfunc = float8_avg,
  95. initcond = '{0,0,0}'
  96. );
  97. </pre><p>
  98. </p><div class="note"><h3 class="title">Note</h3><p>
  99. <code class="function">float8_accum</code> requires a three-element array, not just
  100. two elements, because it accumulates the sum of squares as well as
  101. the sum and count of the inputs. This is so that it can be used for
  102. some other aggregates as well as <code class="function">avg</code>.
  103. </p></div><p>
  104. Aggregate function calls in SQL allow <code class="literal">DISTINCT</code>
  105. and <code class="literal">ORDER BY</code> options that control which rows are fed
  106. to the aggregate's transition function and in what order. These
  107. options are implemented behind the scenes and are not the concern
  108. of the aggregate's support functions.
  109. </p><p>
  110. For further details see the
  111. <a class="xref" href="sql-createaggregate.html" title="CREATE AGGREGATE"><span class="refentrytitle">CREATE AGGREGATE</span></a>
  112. command.
  113. </p><div class="sect2" id="XAGGR-MOVING-AGGREGATES"><div class="titlepage"><div><div><h3 class="title">37.12.1. Moving-Aggregate Mode</h3></div></div></div><a id="id-1.8.3.15.12.2" class="indexterm"></a><a id="id-1.8.3.15.12.3" class="indexterm"></a><p>
  114. Aggregate functions can optionally support <em class="firstterm">moving-aggregate
  115. mode</em>, which allows substantially faster execution of aggregate
  116. functions within windows with moving frame starting points.
  117. (See <a class="xref" href="tutorial-window.html" title="3.5. Window Functions">Section 3.5</a>
  118. and <a class="xref" href="sql-expressions.html#SYNTAX-WINDOW-FUNCTIONS" title="4.2.8. Window Function Calls">Section 4.2.8</a> for information about use of
  119. aggregate functions as window functions.)
  120. The basic idea is that in addition to a normal <span class="quote">“<span class="quote">forward</span>”</span>
  121. transition function, the aggregate provides an <em class="firstterm">inverse
  122. transition function</em>, which allows rows to be removed from the
  123. aggregate's running state value when they exit the window frame.
  124. For example a <code class="function">sum</code> aggregate, which uses addition as the
  125. forward transition function, would use subtraction as the inverse
  126. transition function. Without an inverse transition function, the window
  127. function mechanism must recalculate the aggregate from scratch each time
  128. the frame starting point moves, resulting in run time proportional to the
  129. number of input rows times the average frame length. With an inverse
  130. transition function, the run time is only proportional to the number of
  131. input rows.
  132. </p><p>
  133. The inverse transition function is passed the current state value and the
  134. aggregate input value(s) for the earliest row included in the current
  135. state. It must reconstruct what the state value would have been if the
  136. given input row had never been aggregated, but only the rows following
  137. it. This sometimes requires that the forward transition function keep
  138. more state than is needed for plain aggregation mode. Therefore, the
  139. moving-aggregate mode uses a completely separate implementation from the
  140. plain mode: it has its own state data type, its own forward transition
  141. function, and its own final function if needed. These can be the same as
  142. the plain mode's data type and functions, if there is no need for extra
  143. state.
  144. </p><p>
  145. As an example, we could extend the <code class="function">sum</code> aggregate given above
  146. to support moving-aggregate mode like this:
  147. </p><pre class="programlisting">
  148. CREATE AGGREGATE sum (complex)
  149. (
  150. sfunc = complex_add,
  151. stype = complex,
  152. initcond = '(0,0)',
  153. msfunc = complex_add,
  154. minvfunc = complex_sub,
  155. mstype = complex,
  156. minitcond = '(0,0)'
  157. );
  158. </pre><p>
  159. The parameters whose names begin with <code class="literal">m</code> define the
  160. moving-aggregate implementation. Except for the inverse transition
  161. function <code class="literal">minvfunc</code>, they correspond to the plain-aggregate
  162. parameters without <code class="literal">m</code>.
  163. </p><p>
  164. The forward transition function for moving-aggregate mode is not allowed
  165. to return null as the new state value. If the inverse transition
  166. function returns null, this is taken as an indication that the inverse
  167. function cannot reverse the state calculation for this particular input,
  168. and so the aggregate calculation will be redone from scratch for the
  169. current frame starting position. This convention allows moving-aggregate
  170. mode to be used in situations where there are some infrequent cases that
  171. are impractical to reverse out of the running state value. The inverse
  172. transition function can <span class="quote">“<span class="quote">punt</span>”</span> on these cases, and yet still come
  173. out ahead so long as it can work for most cases. As an example, an
  174. aggregate working with floating-point numbers might choose to punt when
  175. a <code class="literal">NaN</code> (not a number) input has to be removed from the running
  176. state value.
  177. </p><p>
  178. When writing moving-aggregate support functions, it is important to be
  179. sure that the inverse transition function can reconstruct the correct
  180. state value exactly. Otherwise there might be user-visible differences
  181. in results depending on whether the moving-aggregate mode is used.
  182. An example of an aggregate for which adding an inverse transition
  183. function seems easy at first, yet where this requirement cannot be met
  184. is <code class="function">sum</code> over <code class="type">float4</code> or <code class="type">float8</code> inputs. A
  185. naive declaration of <code class="function">sum(<code class="type">float8</code>)</code> could be
  186. </p><pre class="programlisting">
  187. CREATE AGGREGATE unsafe_sum (float8)
  188. (
  189. stype = float8,
  190. sfunc = float8pl,
  191. mstype = float8,
  192. msfunc = float8pl,
  193. minvfunc = float8mi
  194. );
  195. </pre><p>
  196. This aggregate, however, can give wildly different results than it would
  197. have without the inverse transition function. For example, consider
  198. </p><pre class="programlisting">
  199. SELECT
  200. unsafe_sum(x) OVER (ORDER BY n ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING)
  201. FROM (VALUES (1, 1.0e20::float8),
  202. (2, 1.0::float8)) AS v (n,x);
  203. </pre><p>
  204. This query returns <code class="literal">0</code> as its second result, rather than the
  205. expected answer of <code class="literal">1</code>. The cause is the limited precision of
  206. floating-point values: adding <code class="literal">1</code> to <code class="literal">1e20</code> results
  207. in <code class="literal">1e20</code> again, and so subtracting <code class="literal">1e20</code> from that
  208. yields <code class="literal">0</code>, not <code class="literal">1</code>. Note that this is a limitation
  209. of floating-point arithmetic in general, not a limitation
  210. of <span class="productname">PostgreSQL</span>.
  211. </p></div><div class="sect2" id="XAGGR-POLYMORPHIC-AGGREGATES"><div class="titlepage"><div><div><h3 class="title">37.12.2. Polymorphic and Variadic Aggregates</h3></div></div></div><a id="id-1.8.3.15.13.2" class="indexterm"></a><a id="id-1.8.3.15.13.3" class="indexterm"></a><p>
  212. Aggregate functions can use polymorphic
  213. state transition functions or final functions, so that the same functions
  214. can be used to implement multiple aggregates.
  215. See <a class="xref" href="extend-type-system.html#EXTEND-TYPES-POLYMORPHIC" title="37.2.5. Polymorphic Types">Section 37.2.5</a>
  216. for an explanation of polymorphic functions.
  217. Going a step further, the aggregate function itself can be specified
  218. with polymorphic input type(s) and state type, allowing a single
  219. aggregate definition to serve for multiple input data types.
  220. Here is an example of a polymorphic aggregate:
  221. </p><pre class="programlisting">
  222. CREATE AGGREGATE array_accum (anyelement)
  223. (
  224. sfunc = array_append,
  225. stype = anyarray,
  226. initcond = '{}'
  227. );
  228. </pre><p>
  229. Here, the actual state type for any given aggregate call is the array type
  230. having the actual input type as elements. The behavior of the aggregate
  231. is to concatenate all the inputs into an array of that type.
  232. (Note: the built-in aggregate <code class="function">array_agg</code> provides similar
  233. functionality, with better performance than this definition would have.)
  234. </p><p>
  235. Here's the output using two different actual data types as arguments:
  236. </p><pre class="programlisting">
  237. SELECT attrelid::regclass, array_accum(attname)
  238. FROM pg_attribute
  239. WHERE attnum &gt; 0 AND attrelid = 'pg_tablespace'::regclass
  240. GROUP BY attrelid;
  241. attrelid | array_accum
  242. ---------------+---------------------------------------
  243. pg_tablespace | {spcname,spcowner,spcacl,spcoptions}
  244. (1 row)
  245. SELECT attrelid::regclass, array_accum(atttypid::regtype)
  246. FROM pg_attribute
  247. WHERE attnum &gt; 0 AND attrelid = 'pg_tablespace'::regclass
  248. GROUP BY attrelid;
  249. attrelid | array_accum
  250. ---------------+---------------------------
  251. pg_tablespace | {name,oid,aclitem[],text[]}
  252. (1 row)
  253. </pre><p>
  254. </p><p>
  255. Ordinarily, an aggregate function with a polymorphic result type has a
  256. polymorphic state type, as in the above example. This is necessary
  257. because otherwise the final function cannot be declared sensibly: it
  258. would need to have a polymorphic result type but no polymorphic argument
  259. type, which <code class="command">CREATE FUNCTION</code> will reject on the grounds that
  260. the result type cannot be deduced from a call. But sometimes it is
  261. inconvenient to use a polymorphic state type. The most common case is
  262. where the aggregate support functions are to be written in C and the
  263. state type should be declared as <code class="type">internal</code> because there is
  264. no SQL-level equivalent for it. To address this case, it is possible to
  265. declare the final function as taking extra <span class="quote">“<span class="quote">dummy</span>”</span> arguments
  266. that match the input arguments of the aggregate. Such dummy arguments
  267. are always passed as null values since no specific value is available when the
  268. final function is called. Their only use is to allow a polymorphic
  269. final function's result type to be connected to the aggregate's input
  270. type(s). For example, the definition of the built-in
  271. aggregate <code class="function">array_agg</code> is equivalent to
  272. </p><pre class="programlisting">
  273. CREATE FUNCTION array_agg_transfn(internal, anynonarray)
  274. RETURNS internal ...;
  275. CREATE FUNCTION array_agg_finalfn(internal, anynonarray)
  276. RETURNS anyarray ...;
  277. CREATE AGGREGATE array_agg (anynonarray)
  278. (
  279. sfunc = array_agg_transfn,
  280. stype = internal,
  281. finalfunc = array_agg_finalfn,
  282. finalfunc_extra
  283. );
  284. </pre><p>
  285. Here, the <code class="literal">finalfunc_extra</code> option specifies that the final
  286. function receives, in addition to the state value, extra dummy
  287. argument(s) corresponding to the aggregate's input argument(s).
  288. The extra <code class="type">anynonarray</code> argument allows the declaration
  289. of <code class="function">array_agg_finalfn</code> to be valid.
  290. </p><p>
  291. An aggregate function can be made to accept a varying number of arguments
  292. by declaring its last argument as a <code class="literal">VARIADIC</code> array, in much
  293. the same fashion as for regular functions; see
  294. <a class="xref" href="xfunc-sql.html#XFUNC-SQL-VARIADIC-FUNCTIONS" title="37.5.5. SQL Functions with Variable Numbers of Arguments">Section 37.5.5</a>. The aggregate's transition
  295. function(s) must have the same array type as their last argument. The
  296. transition function(s) typically would also be marked <code class="literal">VARIADIC</code>,
  297. but this is not strictly required.
  298. </p><div class="note"><h3 class="title">Note</h3><p>
  299. Variadic aggregates are easily misused in connection with
  300. the <code class="literal">ORDER BY</code> option (see <a class="xref" href="sql-expressions.html#SYNTAX-AGGREGATES" title="4.2.7. Aggregate Expressions">Section 4.2.7</a>),
  301. since the parser cannot tell whether the wrong number of actual arguments
  302. have been given in such a combination. Keep in mind that everything to
  303. the right of <code class="literal">ORDER BY</code> is a sort key, not an argument to the
  304. aggregate. For example, in
  305. </p><pre class="programlisting">
  306. SELECT myaggregate(a ORDER BY a, b, c) FROM ...
  307. </pre><p>
  308. the parser will see this as a single aggregate function argument and
  309. three sort keys. However, the user might have intended
  310. </p><pre class="programlisting">
  311. SELECT myaggregate(a, b, c ORDER BY a) FROM ...
  312. </pre><p>
  313. If <code class="literal">myaggregate</code> is variadic, both these calls could be
  314. perfectly valid.
  315. </p><p>
  316. For the same reason, it's wise to think twice before creating aggregate
  317. functions with the same names and different numbers of regular arguments.
  318. </p></div></div><div class="sect2" id="XAGGR-ORDERED-SET-AGGREGATES"><div class="titlepage"><div><div><h3 class="title">37.12.3. Ordered-Set Aggregates</h3></div></div></div><a id="id-1.8.3.15.14.2" class="indexterm"></a><p>
  319. The aggregates we have been describing so far are <span class="quote">“<span class="quote">normal</span>”</span>
  320. aggregates. <span class="productname">PostgreSQL</span> also
  321. supports <em class="firstterm">ordered-set aggregates</em>, which differ from
  322. normal aggregates in two key ways. First, in addition to ordinary
  323. aggregated arguments that are evaluated once per input row, an
  324. ordered-set aggregate can have <span class="quote">“<span class="quote">direct</span>”</span> arguments that are
  325. evaluated only once per aggregation operation. Second, the syntax
  326. for the ordinary aggregated arguments specifies a sort ordering
  327. for them explicitly. An ordered-set aggregate is usually
  328. used to implement a computation that depends on a specific row
  329. ordering, for instance rank or percentile, so that the sort ordering
  330. is a required aspect of any call. For example, the built-in
  331. definition of <code class="function">percentile_disc</code> is equivalent to:
  332. </p><pre class="programlisting">
  333. CREATE FUNCTION ordered_set_transition(internal, anyelement)
  334. RETURNS internal ...;
  335. CREATE FUNCTION percentile_disc_final(internal, float8, anyelement)
  336. RETURNS anyelement ...;
  337. CREATE AGGREGATE percentile_disc (float8 ORDER BY anyelement)
  338. (
  339. sfunc = ordered_set_transition,
  340. stype = internal,
  341. finalfunc = percentile_disc_final,
  342. finalfunc_extra
  343. );
  344. </pre><p>
  345. This aggregate takes a <code class="type">float8</code> direct argument (the percentile
  346. fraction) and an aggregated input that can be of any sortable data type.
  347. It could be used to obtain a median household income like this:
  348. </p><pre class="programlisting">
  349. SELECT percentile_disc(0.5) WITHIN GROUP (ORDER BY income) FROM households;
  350. percentile_disc
  351. -----------------
  352. 50489
  353. </pre><p>
  354. Here, <code class="literal">0.5</code> is a direct argument; it would make no sense
  355. for the percentile fraction to be a value varying across rows.
  356. </p><p>
  357. Unlike the case for normal aggregates, the sorting of input rows for
  358. an ordered-set aggregate is <span class="emphasis"><em>not</em></span> done behind the scenes,
  359. but is the responsibility of the aggregate's support functions.
  360. The typical implementation approach is to keep a reference to
  361. a <span class="quote">“<span class="quote">tuplesort</span>”</span> object in the aggregate's state value, feed the
  362. incoming rows into that object, and then complete the sorting and
  363. read out the data in the final function. This design allows the
  364. final function to perform special operations such as injecting
  365. additional <span class="quote">“<span class="quote">hypothetical</span>”</span> rows into the data to be sorted.
  366. While normal aggregates can often be implemented with support
  367. functions written in <span class="application">PL/pgSQL</span> or another
  368. PL language, ordered-set aggregates generally have to be written in
  369. C, since their state values aren't definable as any SQL data type.
  370. (In the above example, notice that the state value is declared as
  371. type <code class="type">internal</code> — this is typical.)
  372. Also, because the final function performs the sort, it is not possible
  373. to continue adding input rows by executing the transition function again
  374. later. This means the final function is not <code class="literal">READ_ONLY</code>;
  375. it must be declared in <a class="xref" href="sql-createaggregate.html" title="CREATE AGGREGATE"><span class="refentrytitle">CREATE AGGREGATE</span></a>
  376. as <code class="literal">READ_WRITE</code>, or as <code class="literal">SHAREABLE</code> if
  377. it's possible for additional final-function calls to make use of the
  378. already-sorted state.
  379. </p><p>
  380. The state transition function for an ordered-set aggregate receives
  381. the current state value plus the aggregated input values for
  382. each row, and returns the updated state value. This is the
  383. same definition as for normal aggregates, but note that the direct
  384. arguments (if any) are not provided. The final function receives
  385. the last state value, the values of the direct arguments if any,
  386. and (if <code class="literal">finalfunc_extra</code> is specified) null values
  387. corresponding to the aggregated input(s). As with normal
  388. aggregates, <code class="literal">finalfunc_extra</code> is only really useful if the
  389. aggregate is polymorphic; then the extra dummy argument(s) are needed
  390. to connect the final function's result type to the aggregate's input
  391. type(s).
  392. </p><p>
  393. Currently, ordered-set aggregates cannot be used as window functions,
  394. and therefore there is no need for them to support moving-aggregate mode.
  395. </p></div><div class="sect2" id="XAGGR-PARTIAL-AGGREGATES"><div class="titlepage"><div><div><h3 class="title">37.12.4. Partial Aggregation</h3></div></div></div><a id="id-1.8.3.15.15.2" class="indexterm"></a><p>
  396. Optionally, an aggregate function can support <em class="firstterm">partial
  397. aggregation</em>. The idea of partial aggregation is to run the aggregate's
  398. state transition function over different subsets of the input data
  399. independently, and then to combine the state values resulting from those
  400. subsets to produce the same state value that would have resulted from
  401. scanning all the input in a single operation. This mode can be used for
  402. parallel aggregation by having different worker processes scan different
  403. portions of a table. Each worker produces a partial state value, and at
  404. the end those state values are combined to produce a final state value.
  405. (In the future this mode might also be used for purposes such as combining
  406. aggregations over local and remote tables; but that is not implemented
  407. yet.)
  408. </p><p>
  409. To support partial aggregation, the aggregate definition must provide
  410. a <em class="firstterm">combine function</em>, which takes two values of the
  411. aggregate's state type (representing the results of aggregating over two
  412. subsets of the input rows) and produces a new value of the state type,
  413. representing what the state would have been after aggregating over the
  414. combination of those sets of rows. It is unspecified what the relative
  415. order of the input rows from the two sets would have been. This means
  416. that it's usually impossible to define a useful combine function for
  417. aggregates that are sensitive to input row order.
  418. </p><p>
  419. As simple examples, <code class="literal">MAX</code> and <code class="literal">MIN</code> aggregates can be
  420. made to support partial aggregation by specifying the combine function as
  421. the same greater-of-two or lesser-of-two comparison function that is used
  422. as their transition function. <code class="literal">SUM</code> aggregates just need an
  423. addition function as combine function. (Again, this is the same as their
  424. transition function, unless the state value is wider than the input data
  425. type.)
  426. </p><p>
  427. The combine function is treated much like a transition function that
  428. happens to take a value of the state type, not of the underlying input
  429. type, as its second argument. In particular, the rules for dealing
  430. with null values and strict functions are similar. Also, if the aggregate
  431. definition specifies a non-null <code class="literal">initcond</code>, keep in mind that
  432. that will be used not only as the initial state for each partial
  433. aggregation run, but also as the initial state for the combine function,
  434. which will be called to combine each partial result into that state.
  435. </p><p>
  436. If the aggregate's state type is declared as <code class="type">internal</code>, it is
  437. the combine function's responsibility that its result is allocated in
  438. the correct memory context for aggregate state values. This means in
  439. particular that when the first input is <code class="literal">NULL</code> it's invalid
  440. to simply return the second input, as that value will be in the wrong
  441. context and will not have sufficient lifespan.
  442. </p><p>
  443. When the aggregate's state type is declared as <code class="type">internal</code>, it is
  444. usually also appropriate for the aggregate definition to provide a
  445. <em class="firstterm">serialization function</em> and a <em class="firstterm">deserialization
  446. function</em>, which allow such a state value to be copied from one process
  447. to another. Without these functions, parallel aggregation cannot be
  448. performed, and future applications such as local/remote aggregation will
  449. probably not work either.
  450. </p><p>
  451. A serialization function must take a single argument of
  452. type <code class="type">internal</code> and return a result of type <code class="type">bytea</code>, which
  453. represents the state value packaged up into a flat blob of bytes.
  454. Conversely, a deserialization function reverses that conversion. It must
  455. take two arguments of types <code class="type">bytea</code> and <code class="type">internal</code>, and
  456. return a result of type <code class="type">internal</code>. (The second argument is unused
  457. and is always zero, but it is required for type-safety reasons.) The
  458. result of the deserialization function should simply be allocated in the
  459. current memory context, as unlike the combine function's result, it is not
  460. long-lived.
  461. </p><p>
  462. Worth noting also is that for an aggregate to be executed in parallel,
  463. the aggregate itself must be marked <code class="literal">PARALLEL SAFE</code>. The
  464. parallel-safety markings on its support functions are not consulted.
  465. </p></div><div class="sect2" id="XAGGR-SUPPORT-FUNCTIONS"><div class="titlepage"><div><div><h3 class="title">37.12.5. Support Functions for Aggregates</h3></div></div></div><a id="id-1.8.3.15.16.2" class="indexterm"></a><p>
  466. A function written in C can detect that it is being called as an
  467. aggregate support function by calling
  468. <code class="function">AggCheckCallContext</code>, for example:
  469. </p><pre class="programlisting">
  470. if (AggCheckCallContext(fcinfo, NULL))
  471. </pre><p>
  472. One reason for checking this is that when it is true, the first input
  473. must be a temporary state value and can therefore safely be modified
  474. in-place rather than allocating a new copy.
  475. See <code class="function">int8inc()</code> for an example.
  476. (While aggregate transition functions are always allowed to modify
  477. the transition value in-place, aggregate final functions are generally
  478. discouraged from doing so; if they do so, the behavior must be declared
  479. when creating the aggregate. See <a class="xref" href="sql-createaggregate.html" title="CREATE AGGREGATE"><span class="refentrytitle">CREATE AGGREGATE</span></a>
  480. for more detail.)
  481. </p><p>
  482. The second argument of <code class="function">AggCheckCallContext</code> can be used to
  483. retrieve the memory context in which aggregate state values are being kept.
  484. This is useful for transition functions that wish to use <span class="quote">“<span class="quote">expanded</span>”</span>
  485. objects (see <a class="xref" href="xtypes.html#XTYPES-TOAST" title="37.13.1. TOAST Considerations">Section 37.13.1</a>) as their state values.
  486. On first call, the transition function should return an expanded object
  487. whose memory context is a child of the aggregate state context, and then
  488. keep returning the same expanded object on subsequent calls. See
  489. <code class="function">array_append()</code> for an example. (<code class="function">array_append()</code>
  490. is not the transition function of any built-in aggregate, but it is written
  491. to behave efficiently when used as transition function of a custom
  492. aggregate.)
  493. </p><p>
  494. Another support routine available to aggregate functions written in C
  495. is <code class="function">AggGetAggref</code>, which returns the <code class="literal">Aggref</code>
  496. parse node that defines the aggregate call. This is mainly useful
  497. for ordered-set aggregates, which can inspect the substructure of
  498. the <code class="literal">Aggref</code> node to find out what sort ordering they are
  499. supposed to implement. Examples can be found
  500. in <code class="filename">orderedsetaggs.c</code> in the <span class="productname">PostgreSQL</span>
  501. source code.
  502. </p></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="xfunc-optimization.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="xtypes.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">37.11. Function Optimization Information </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> 37.13. User-Defined Types</td></tr></table></div></body></html>
上海开阖软件有限公司 沪ICP备12045867号-1