OSDN Git Service

8a9801858569762ce451d612a74125156fd1a9bf
[pg-rex/syncrep.git] / doc / src / sgml / xoper.sgml
1 <!-- $PostgreSQL: pgsql/doc/src/sgml/xoper.sgml,v 1.36 2006/09/16 00:30:16 momjian Exp $ -->
2
3  <sect1 id="xoper">
4   <title>User-Defined Operators</title>
5
6   <indexterm zone="xoper">
7    <primary>operator</primary>
8    <secondary>user-defined</secondary>
9   </indexterm>
10
11   <para>
12    Every operator is <quote>syntactic sugar</quote> for a call to an
13    underlying function that does the real work; so you must
14    first create the underlying function before you can create
15    the operator.  However, an operator is <emphasis>not merely</emphasis>
16    syntactic sugar, because it carries additional information
17    that helps the query planner optimize queries that use the
18    operator.  The next section will be devoted to explaining
19    that additional information.
20   </para>
21
22   <para>
23    <productname>PostgreSQL</productname> supports left unary, right
24    unary, and binary operators.  Operators can be
25    overloaded;<indexterm><primary>overloading</primary><secondary>operators</secondary></indexterm>
26    that is, the same operator name can be used for different operators
27    that have different numbers and types of operands.  When a query is
28    executed, the system determines the operator to call from the
29    number and types of the provided operands.
30   </para>
31
32   <para>
33    Here is an example of creating an operator for adding two complex
34    numbers.  We assume we've already created the definition of type
35    <type>complex</type> (see <xref linkend="xtypes">).  First we need a
36    function that does the work, then we can define the operator:
37
38 <programlisting>
39 CREATE FUNCTION complex_add(complex, complex)
40     RETURNS complex
41     AS '<replaceable>filename</replaceable>', 'complex_add'
42     LANGUAGE C IMMUTABLE STRICT;
43
44 CREATE OPERATOR + (
45     leftarg = complex,
46     rightarg = complex,
47     procedure = complex_add,
48     commutator = +
49 );
50 </programlisting>
51   </para>
52
53   <para>
54    Now we could execute a query like this:
55      
56 <screen>
57 SELECT (a + b) AS c FROM test_complex;
58
59         c
60 -----------------
61  (5.2,6.05)
62  (133.42,144.95)
63 </screen>
64   </para>
65
66   <para>
67    We've shown how to create a binary operator here.  To create unary
68    operators, just omit one of <literal>leftarg</> (for left unary) or
69    <literal>rightarg</> (for right unary).  The <literal>procedure</>
70    clause and the argument clauses are the only required items in
71    <command>CREATE OPERATOR</command>.  The <literal>commutator</>
72    clause shown in the example is an optional hint to the query
73    optimizer.  Further details about <literal>commutator</> and other
74    optimizer hints appear in the next section.
75   </para>
76  </sect1>
77
78   <sect1 id="xoper-optimization">
79    <title>Operator Optimization Information</title>
80
81    <para>
82     A <productname>PostgreSQL</productname> operator definition can include
83     several optional clauses that tell the system useful things about how
84     the operator behaves.  These clauses should be provided whenever
85     appropriate, because they can make for considerable speedups in execution
86     of queries that use the operator.  But if you provide them, you must be
87     sure that they are right!  Incorrect use of an optimization clause can
88     result in server process crashes, subtly wrong output, or other Bad Things.
89     You can always leave out an optimization clause if you are not sure
90     about it; the only consequence is that queries might run slower than
91     they need to.
92    </para>
93
94    <para>
95     Additional optimization clauses might be added in future versions of
96     <productname>PostgreSQL</productname>.  The ones described here are all
97     the ones that release &version; understands.
98    </para>
99
100    <sect2>
101     <title><literal>COMMUTATOR</></title>
102
103     <para>
104      The <literal>COMMUTATOR</> clause, if provided, names an operator that is the
105      commutator of the operator being defined.  We say that operator A is the
106      commutator of operator B if (x A y) equals (y B x) for all possible input
107      values x, y.  Notice that B is also the commutator of A.  For example,
108      operators <literal>&lt;</> and <literal>&gt;</> for a particular data type are usually each others'
109      commutators, and operator <literal>+</> is usually commutative with itself.
110      But operator <literal>-</> is usually not commutative with anything.
111     </para>
112
113     <para>
114      The left operand type of a commutable operator is the same as the
115      right operand type of its commutator, and vice versa.  So the name of
116      the commutator operator is all that <productname>PostgreSQL</productname>
117      needs to be given to look up the commutator, and that's all that needs to
118      be provided in the <literal>COMMUTATOR</> clause.
119     </para>
120
121     <para>
122      It's critical to provide commutator information for operators that
123      will be used in indexes and join clauses, because this allows the
124      query optimizer to <quote>flip around</> such a clause to the forms
125      needed for different plan types.  For example, consider a query with
126      a WHERE clause like <literal>tab1.x = tab2.y</>, where <literal>tab1.x</>
127      and <literal>tab2.y</> are of a user-defined type, and suppose that
128      <literal>tab2.y</> is indexed.  The optimizer cannot generate an
129      index scan unless it can determine how to flip the clause around to
130      <literal>tab2.y = tab1.x</>, because the index-scan machinery expects
131      to see the indexed column on the left of the operator it is given.
132      <productname>PostgreSQL</productname> will <emphasis>not</> simply
133      assume that this is a valid transformation &mdash; the creator of the
134      <literal>=</> operator must specify that it is valid, by marking the
135      operator with commutator information.
136     </para>
137
138     <para>
139      When you are defining a self-commutative operator, you just do it.
140      When you are defining a pair of commutative operators, things are
141      a little trickier: how can the first one to be defined refer to the
142      other one, which you haven't defined yet?  There are two solutions
143      to this problem:
144
145      <itemizedlist>
146       <listitem>
147        <para>
148         One way is to omit the <literal>COMMUTATOR</> clause in the first operator that
149         you define, and then provide one in the second operator's definition.
150         Since <productname>PostgreSQL</productname> knows that commutative
151         operators come in pairs, when it sees the second definition it will
152         automatically go back and fill in the missing <literal>COMMUTATOR</> clause in
153         the first definition.
154        </para>
155       </listitem>
156
157       <listitem>
158        <para>
159         The other, more straightforward way is just to include <literal>COMMUTATOR</> clauses
160         in both definitions.  When <productname>PostgreSQL</productname> processes
161         the first definition and realizes that <literal>COMMUTATOR</> refers to a nonexistent
162         operator, the system will make a dummy entry for that operator in the
163         system catalog.  This dummy entry will have valid data only
164         for the operator name, left and right operand types, and result type,
165         since that's all that <productname>PostgreSQL</productname> can deduce
166         at this point.  The first operator's catalog entry will link to this
167         dummy entry.  Later, when you define the second operator, the system
168         updates the dummy entry with the additional information from the second
169         definition.  If you try to use the dummy operator before it's been filled
170         in, you'll just get an error message.
171        </para>
172       </listitem>
173      </itemizedlist>
174     </para>
175    </sect2>
176
177    <sect2>
178     <title><literal>NEGATOR</></title>
179
180     <para>
181      The <literal>NEGATOR</> clause, if provided, names an operator that is the
182      negator of the operator being defined.  We say that operator A
183      is the negator of operator B if both return Boolean results and
184      (x A y) equals NOT (x B y) for all possible inputs x, y.
185      Notice that B is also the negator of A.
186      For example, <literal>&lt;</> and <literal>&gt;=</> are a negator pair for most data types.
187      An operator can never validly be its own negator.
188     </para>
189
190    <para>
191     Unlike commutators, a pair of unary operators could validly be marked
192     as each others' negators; that would mean (A x) equals NOT (B x)
193     for all x, or the equivalent for right unary operators.
194    </para>
195
196    <para>
197     An operator's negator must have the same left and/or right operand types
198     as the operator to be defined, so just as with <literal>COMMUTATOR</>, only the operator
199     name need be given in the <literal>NEGATOR</> clause.
200    </para>
201
202    <para>
203     Providing a negator is very helpful to the query optimizer since
204     it allows expressions like <literal>NOT (x = y)</> to be simplified into
205     <literal>x &lt;&gt; y</>.  This comes up more often than you might think, because
206     <literal>NOT</> operations can be inserted as a consequence of other rearrangements.
207    </para>
208
209    <para>
210     Pairs of negator operators can be defined using the same methods
211     explained above for commutator pairs.
212    </para>
213
214   </sect2>
215
216   <sect2>
217    <title><literal>RESTRICT</></title>
218
219    <para>
220     The <literal>RESTRICT</> clause, if provided, names a restriction selectivity
221     estimation function for the operator.  (Note that this is a function
222     name, not an operator name.)  <literal>RESTRICT</> clauses only make sense for
223     binary operators that return <type>boolean</>.  The idea behind a restriction
224     selectivity estimator is to guess what fraction of the rows in a
225     table will satisfy a <literal>WHERE</literal>-clause condition of the form
226 <programlisting>
227 column OP constant
228 </programlisting>
229     for the current operator and a particular constant value.
230     This assists the optimizer by
231     giving it some idea of how many rows will be eliminated by <literal>WHERE</>
232     clauses that have this form.  (What happens if the constant is on
233     the left, you may be wondering?  Well, that's one of the things that
234     <literal>COMMUTATOR</> is for...)
235    </para>
236
237    <para>
238     Writing new restriction selectivity estimation functions is far beyond
239     the scope of this chapter, but fortunately you can usually just use
240     one of the system's standard estimators for many of your own operators.
241     These are the standard restriction estimators:
242     <simplelist>
243      <member><function>eqsel</> for <literal>=</></member>
244      <member><function>neqsel</> for <literal>&lt;&gt;</></member>
245      <member><function>scalarltsel</> for <literal>&lt;</> or <literal>&lt;=</></member>
246      <member><function>scalargtsel</> for <literal>&gt;</> or <literal>&gt;=</></member>
247    </simplelist>
248     It might seem a little odd that these are the categories, but they
249     make sense if you think about it.  <literal>=</> will typically accept only
250     a small fraction of the rows in a table; <literal>&lt;&gt;</> will typically reject
251     only a small fraction.  <literal>&lt;</> will accept a fraction that depends on
252     where the given constant falls in the range of values for that table
253     column (which, it just so happens, is information collected by
254     <command>ANALYZE</command> and made available to the selectivity estimator).
255     <literal>&lt;=</> will accept a slightly larger fraction than <literal>&lt;</> for the same
256     comparison constant, but they're close enough to not be worth
257     distinguishing, especially since we're not likely to do better than a
258     rough guess anyhow.  Similar remarks apply to <literal>&gt;</> and <literal>&gt;=</>.
259    </para>
260
261    <para>
262     You can frequently get away with using either <function>eqsel</function> or <function>neqsel</function> for
263     operators that have very high or very low selectivity, even if they
264     aren't really equality or inequality.  For example, the
265     approximate-equality geometric operators use <function>eqsel</function> on the assumption that
266     they'll usually only match a small fraction of the entries in a table.
267    </para>
268
269    <para>
270     You can use <function>scalarltsel</> and <function>scalargtsel</> for comparisons on data types that
271     have some sensible means of being converted into numeric scalars for
272     range comparisons.  If possible, add the data type to those understood
273     by the function <function>convert_to_scalar()</function> in <filename>src/backend/utils/adt/selfuncs.c</filename>.
274     (Eventually, this function should be replaced by per-data-type functions
275     identified through a column of the <classname>pg_type</> system catalog; but that hasn't happened
276     yet.)  If you do not do this, things will still work, but the optimizer's
277     estimates won't be as good as they could be.
278    </para>
279
280    <para>
281     There are additional selectivity estimation functions designed for geometric
282     operators in <filename>src/backend/utils/adt/geo_selfuncs.c</filename>: <function>areasel</function>, <function>positionsel</function>,
283     and <function>contsel</function>.  At this writing these are just stubs, but you may want
284     to use them (or even better, improve them) anyway.
285    </para>
286    </sect2>
287
288    <sect2>
289     <title><literal>JOIN</></title>
290
291     <para>
292      The <literal>JOIN</> clause, if provided, names a join selectivity
293      estimation function for the operator.  (Note that this is a function
294      name, not an operator name.)  <literal>JOIN</> clauses only make sense for
295      binary operators that return <type>boolean</type>.  The idea behind a join
296      selectivity estimator is to guess what fraction of the rows in a
297      pair of tables will satisfy a <literal>WHERE</>-clause condition of the form
298 <programlisting>
299 table1.column1 OP table2.column2
300 </programlisting>
301      for the current operator.  As with the <literal>RESTRICT</literal> clause, this helps
302      the optimizer very substantially by letting it figure out which
303      of several possible join sequences is likely to take the least work.
304     </para>
305
306     <para>
307      As before, this chapter will make no attempt to explain how to write
308      a join selectivity estimator function, but will just suggest that
309      you use one of the standard estimators if one is applicable:
310      <simplelist>
311       <member><function>eqjoinsel</> for <literal>=</></member>
312       <member><function>neqjoinsel</> for <literal>&lt;&gt;</></member>
313       <member><function>scalarltjoinsel</> for <literal>&lt;</> or <literal>&lt;=</></member>
314       <member><function>scalargtjoinsel</> for <literal>&gt;</> or <literal>&gt;=</></member>
315       <member><function>areajoinsel</> for 2D area-based comparisons</member>
316       <member><function>positionjoinsel</> for 2D position-based comparisons</member>
317       <member><function>contjoinsel</> for 2D containment-based comparisons</member>
318      </simplelist>
319     </para>
320    </sect2>
321
322    <sect2>
323     <title><literal>HASHES</></title>
324
325     <para>
326      The <literal>HASHES</literal> clause, if present, tells the system that
327      it is permissible to use the hash join method for a join based on this
328      operator.  <literal>HASHES</> only makes sense for a binary operator that
329      returns <literal>boolean</>, and in practice the operator had better be
330      equality for some data type.
331     </para>
332
333     <para>
334      The assumption underlying hash join is that the join operator can
335      only return true for pairs of left and right values that hash to the
336      same hash code.  If two values get put in different hash buckets, the
337      join will never compare them at all, implicitly assuming that the
338      result of the join operator must be false.  So it never makes sense
339      to specify <literal>HASHES</literal> for operators that do not represent
340      equality.
341     </para>
342
343     <para>
344      To be marked <literal>HASHES</literal>, the join operator must appear
345      in a hash index operator class.  This is not enforced when you create
346      the operator, since of course the referencing operator class couldn't
347      exist yet.  But attempts to use the operator in hash joins will fail
348      at run time if no such operator class exists.  The system needs the
349      operator class to find the data-type-specific hash function for the
350      operator's input data type.  Of course, you must also supply a suitable
351      hash function before you can create the operator class.
352     </para>
353
354     <para>
355      Care should be exercised when preparing a hash function, because there
356      are machine-dependent ways in which it might fail to do the right thing.
357      For example, if your data type is a structure in which there may be
358      uninteresting pad bits, you can't simply pass the whole structure to
359      <function>hash_any</>.  (Unless you write your other operators and
360      functions to ensure that the unused bits are always zero, which is the
361      recommended strategy.)
362      Another example is that on machines that meet the <acronym>IEEE</>
363      floating-point standard, negative zero and positive zero are different
364      values (different bit patterns) but they are defined to compare equal.
365      If a float value might contain negative zero then extra steps are needed
366      to ensure it generates the same hash value as positive zero.
367     </para>
368
369     <note>
370     <para>
371      The function underlying a hash-joinable operator must be marked
372      immutable or stable.  If it is volatile, the system will never
373      attempt to use the operator for a hash join.
374     </para>
375     </note>
376
377     <note>
378     <para>
379      If a hash-joinable operator has an underlying function that is marked
380      strict, the
381      function must also be complete: that is, it should return true or
382      false, never null, for any two nonnull inputs.  If this rule is
383      not followed, hash-optimization of <literal>IN</> operations may
384      generate wrong results.  (Specifically, <literal>IN</> might return
385      false where the correct answer according to the standard would be null; or it might
386      yield an error complaining that it wasn't prepared for a null result.)
387     </para>
388     </note>
389
390    </sect2>
391
392    <sect2>
393     <title><literal>MERGES</> (<literal>SORT1</>, <literal>SORT2</>, <literal>LTCMP</>, <literal>GTCMP</>)</title>
394
395     <para>
396      The <literal>MERGES</literal> clause, if present, tells the system that
397      it is permissible to use the merge-join method for a join based on this
398      operator.  <literal>MERGES</> only makes sense for a binary operator that
399      returns <literal>boolean</>, and in practice the operator must represent
400      equality for some data type or pair of data types.
401     </para>
402
403     <para>
404      Merge join is based on the idea of sorting the left- and right-hand tables
405      into order and then scanning them in parallel.  So, both data types must
406      be capable of being fully ordered, and the join operator must be one
407      that can only succeed for pairs of values that fall at the
408      <quote>same place</>
409      in the sort order.  In practice this means that the join operator must
410      behave like equality.  But unlike hash join, where the left and right
411      data types had better be the same (or at least bitwise equivalent),
412      it is possible to merge-join two
413      distinct data types so long as they are logically compatible.  For
414      example, the <type>smallint</type>-versus-<type>integer</type> equality operator
415      is merge-joinable.
416      We only need sorting operators that will bring both data types into a
417      logically compatible sequence.
418     </para>
419
420     <para>
421      Execution of a merge join requires that the system be able to identify
422      four operators related to the merge-join equality operator: less-than
423      comparison for the left operand data type, less-than comparison for the
424      right operand data type, less-than comparison between the two data types, and
425      greater-than comparison between the two data types.  (These are actually
426      four distinct operators if the merge-joinable operator has two different
427      operand data types; but when the operand types are the same the three
428      less-than operators are all the same operator.)
429      It is possible to
430      specify these operators individually by name, as the <literal>SORT1</>,
431      <literal>SORT2</>, <literal>LTCMP</>, and <literal>GTCMP</> options
432      respectively.  The system will fill in the default names
433      <literal>&lt;</>, <literal>&lt;</>, <literal>&lt;</>, <literal>&gt;</>
434      respectively if any of these are omitted when <literal>MERGES</> is
435      specified.  Also, <literal>MERGES</> will be assumed to be implied if any
436      of these four operator options appear, so it is possible to specify
437      just some of them and let the system fill in the rest.
438     </para>
439
440     <para>
441      The operand data types of the four comparison operators can be deduced
442      from the operand types of the merge-joinable operator, so just as with
443      <literal>COMMUTATOR</>, only the operator names need be given in these
444      clauses.  Unless you are using peculiar choices of operator names,
445      it's sufficient to write <literal>MERGES</> and let the system fill in
446      the details.
447      (As with <literal>COMMUTATOR</> and <literal>NEGATOR</>, the system is
448      able to make dummy
449      operator entries if you happen to define the equality operator before
450      the other ones.)
451     </para>
452
453     <para>
454      There are additional restrictions on operators that you mark
455      merge-joinable.  These restrictions are not currently checked by
456      <command>CREATE OPERATOR</command>, but errors may occur when
457      the operator is used if any are not true:
458
459      <itemizedlist>
460       <listitem>
461        <para>
462         A merge-joinable equality operator must have a merge-joinable
463         commutator (itself if the two operand data types are the same, or a related
464         equality operator if they are different).
465        </para>
466       </listitem>
467
468       <listitem>
469        <para>
470         If there is a merge-joinable operator relating any two data types
471         A and B, and another merge-joinable operator relating B to any
472         third data type C, then A and C must also have a merge-joinable
473         operator; in other words, having a merge-joinable operator must
474         be transitive.
475        </para>
476       </listitem>
477
478       <listitem>
479        <para>
480         Bizarre results will ensue at run time if the four comparison
481         operators you name do not sort the data values compatibly.
482        </para>
483       </listitem>
484      </itemizedlist>
485     </para>
486
487     <note>
488     <para>
489      The function underlying a merge-joinable operator must be marked
490      immutable or stable.  If it is volatile, the system will never
491      attempt to use the operator for a merge join.
492     </para>
493     </note>
494
495     <note>
496     <para>
497      In <productname>PostgreSQL</productname> versions before 7.3,
498      the <literal>MERGES</> shorthand was not available: to make a
499      merge-joinable operator one had to write both <literal>SORT1</> and
500      <literal>SORT2</> explicitly.  Also, the <literal>LTCMP</> and
501      <literal>GTCMP</>
502      options did not exist; the names of those operators were hardwired as
503      <literal>&lt;</> and <literal>&gt;</> respectively.
504     </para>
505     </note>
506    </sect2>
507   </sect1>