<!--
$Header: /cvsroot/pgsql/doc/src/sgml/xoper.sgml,v 1.18 2002/03/22 19:20:34 petere Exp $
-->

 <Chapter Id="xoper">
  <Title>Extending <Acronym>SQL</Acronym>: Operators</Title>

 <sect1 id="xoper-intro">
  <title>Introduction</title>

  <Para>
   <ProductName>PostgreSQL</ProductName> supports left unary,
   right  unary,  and  binary
   operators.   Operators  can  be  overloaded; that is,
   the same operator name can be used for different operators
   that have different numbers and types of operands.   If
   there  is  an ambiguous situation and the system cannot
   determine the correct operator to use, it  will  return
   an  error.  You may have to type-cast the left and/or
   right operands to help it understand which operator you
   meant to use.
  </Para>

  <Para>
   Every operator is <quote>syntactic sugar</quote> for a call to an
   underlying function that does the real work; so you must
   first create the underlying function before you can create
   the operator.  However, an operator is <emphasis>not merely</emphasis>
   syntactic sugar, because it carries additional information
   that helps the query planner optimize queries that use the
   operator.  Much of this chapter will be devoted to explaining
   that additional information.
  </Para>
 </sect1>

 <sect1 id="xoper-example">
  <title>Example</title>

  <Para>
   Here is an example of creating an operator for adding two complex
   numbers.  We assume we've already created the definition of type
   <type>complex</type> (see <xref linkend="xtypes">).  First we need a
   function that does the work, then we can define the operator:

<ProgramListing>
CREATE FUNCTION complex_add(complex, complex)
    RETURNS complex
    AS '<replaceable>PGROOT</replaceable>/tutorial/complex'
    LANGUAGE C;

CREATE OPERATOR + (
    leftarg = complex,
    rightarg = complex,
    procedure = complex_add,
    commutator = +
);
</ProgramListing>
  </Para>

  <Para>
   Now we can do:
     
<screen>
SELECT (a + b) AS c FROM test_complex;

        c
-----------------
 (5.2,6.05)
 (133.42,144.95)
</screen>
  </Para>

  <Para>
   We've shown how to create a binary operator here.  To create unary
   operators, just omit one of <literal>leftarg</> (for left unary) or
   <literal>rightarg</> (for right unary).  The <literal>procedure</>
   clause and the argument clauses are the only required items in
   <command>CREATE OPERATOR</command>.  The <literal>commutator</>
   clause shown in the example is an optional hint to the query
   optimizer.  Further details about <literal>commutator</> and other
   optimizer hints appear below.
  </Para>
 </sect1>

  <sect1 id="xoper-optimization">
   <title>Operator Optimization Information</title>

   <note>
    <title>Author</title>
    <para>
     Written by Tom Lane.
    </para>
   </note>

   <para>
    A <ProductName>PostgreSQL</ProductName> operator definition can include
    several optional clauses that tell the system useful things about how
    the operator behaves.  These clauses should be provided whenever
    appropriate, because they can make for considerable speedups in execution
    of queries that use the operator.  But if you provide them, you must be
    sure that they are right!  Incorrect use of an optimization clause can
    result in backend crashes, subtly wrong output, or other Bad Things.
    You can always leave out an optimization clause if you are not sure
    about it; the only consequence is that queries might run slower than
    they need to.
   </para>

   <para>
    Additional optimization clauses might be added in future versions of
    <ProductName>PostgreSQL</ProductName>.  The ones described here are all
    the ones that release &version; understands.
   </para>

   <sect2>
    <title>COMMUTATOR</title>

    <para>
     The <literal>COMMUTATOR</> clause, if provided, names an operator that is the
     commutator of the operator being defined.  We say that operator A is the
     commutator of operator B if (x A y) equals (y B x) for all possible input
     values x, y.  Notice that B is also the commutator of A.  For example,
     operators <literal>&lt;</> and <literal>&gt;</> for a particular data type are usually each others'
     commutators, and operator <literal>+</> is usually commutative with itself.
     But operator <literal>-</> is usually not commutative with anything.
    </para>

    <para>
     The left operand type of a commuted operator is the same as the
     right operand type of its commutator, and vice versa.  So the name of
     the commutator operator is all that <ProductName>PostgreSQL</ProductName>
     needs to be given to look up the commutator, and that's all that needs to
     be provided in the <literal>COMMUTATOR</> clause.
    </para>

    <para>
     When you are defining a self-commutative operator, you just do it.
     When you are defining a pair of commutative operators, things are
     a little trickier: how can the first one to be defined refer to the
     other one, which you haven't defined yet?  There are two solutions
     to this problem:

     <itemizedlist>
      <listitem>
       <para>
	One way is to omit the <literal>COMMUTATOR</> clause in the first operator that
	you define, and then provide one in the second operator's definition.
	Since <ProductName>PostgreSQL</ProductName> knows that commutative
	operators come in pairs, when it sees the second definition it will
	automatically go back and fill in the missing <literal>COMMUTATOR</> clause in
	the first definition.
       </para>
      </listitem>

      <listitem>
       <para>
	The other, more straightforward way is just to include <literal>COMMUTATOR</> clauses
	in both definitions.  When <ProductName>PostgreSQL</ProductName> processes
	the first definition and realizes that <literal>COMMUTATOR</> refers to a non-existent
	operator, the system will make a dummy entry for that operator in the
	system catalog.  This dummy entry will have valid data only
	for the operator name, left and right operand types, and result type,
	since that's all that <ProductName>PostgreSQL</ProductName> can deduce
	at this point.  The first operator's catalog entry will link to this
	dummy entry.  Later, when you define the second operator, the system
	updates the dummy entry with the additional information from the second
	definition.  If you try to use the dummy operator before it's been filled
	in, you'll just get an error message.  (Note: This procedure did not work
	reliably in <ProductName>PostgreSQL</ProductName> versions before 6.5,
	but it is now the recommended way to do things.)
       </para>
      </listitem>
     </itemizedlist>
    </para>
   </sect2>

   <sect2>
    <title>NEGATOR</title>

    <para>
     The <literal>NEGATOR</> clause, if provided, names an operator that is the
     negator of the operator being defined.  We say that operator A
     is the negator of operator B if both return Boolean results and
     (x A y) equals NOT (x B y) for all possible inputs x, y.
     Notice that B is also the negator of A.
     For example, <literal>&lt;</> and <literal>&gt;=</> are a negator pair for most data types.
     An operator can never validly be its own negator.
    </para>

   <para>
    Unlike commutators, a pair of unary operators could validly be marked
    as each others' negators; that would mean (A x) equals NOT (B x)
    for all x, or the equivalent for right unary operators.
   </para>

   <para>
    An operator's negator must have the same left and/or right operand types
    as the operator itself, so just as with <literal>COMMUTATOR</>, only the operator
    name need be given in the <literal>NEGATOR</> clause.
   </para>

   <para>
    Providing a negator is very helpful to the query optimizer since
    it allows expressions like NOT (x = y) to be simplified into
    x &lt;&gt; y.  This comes up more often than you might think, because
    NOTs can be inserted as a consequence of other rearrangements.
   </para>

   <para>
    Pairs of negator operators can be defined using the same methods
    explained above for commutator pairs.
   </para>

  </sect2>

  <sect2>
   <title>RESTRICT</title>

   <para>
    The <literal>RESTRICT</> clause, if provided, names a restriction selectivity
    estimation function for the operator (note that this is a function
    name, not an operator name).  <literal>RESTRICT</> clauses only make sense for
    binary operators that return <type>boolean</>.  The idea behind a restriction
    selectivity estimator is to guess what fraction of the rows in a
    table will satisfy a <literal>WHERE</literal>-clause condition of the form
<ProgramListing>
column OP constant
</ProgramListing>
    for the current operator and a particular constant value.
    This assists the optimizer by
    giving it some idea of how many rows will be eliminated by <literal>WHERE</>
    clauses that have this form.  (What happens if the constant is on
    the left, you may be wondering?  Well, that's one of the things that
    <literal>COMMUTATOR</> is for...)
   </para>

   <para>
    Writing new restriction selectivity estimation functions is far beyond
    the scope of this chapter, but fortunately you can usually just use
    one of the system's standard estimators for many of your own operators.
    These are the standard restriction estimators:
    <simplelist>
     <member><function>eqsel</>	for <literal>=</></member>
     <member><function>neqsel</> for <literal>&lt;&gt;</></member>
     <member><function>scalarltsel</> for <literal>&lt;</> or <literal>&lt;=</></member>
     <member><function>scalargtsel</> for <literal>&gt;</> or <literal>&gt;=</></member>
   </simplelist>
    It might seem a little odd that these are the categories, but they
    make sense if you think about it.  <literal>=</> will typically accept only
    a small fraction of the rows in a table; <literal>&lt;&gt;</> will typically reject
    only a small fraction.  <literal>&lt;</> will accept a fraction that depends on
    where the given constant falls in the range of values for that table
    column (which, it just so happens, is information collected by
    <command>ANALYZE</command> and made available to the selectivity estimator).
    <literal>&lt;=</> will accept a slightly larger fraction than <literal>&lt;</> for the same
    comparison constant, but they're close enough to not be worth
    distinguishing, especially since we're not likely to do better than a
    rough guess anyhow.  Similar remarks apply to <literal>&gt;</> and <literal>&gt;=</>.
   </para>

   <para>
    You can frequently get away with using either <function>eqsel</function> or <function>neqsel</function> for
    operators that have very high or very low selectivity, even if they
    aren't really equality or inequality.  For example, the
    approximate-equality geometric operators use <function>eqsel</function> on the assumption that
    they'll usually only match a small fraction of the entries in a table.
   </para>

   <para>
    You can use <function>scalarltsel</> and <function>scalargtsel</> for comparisons on data types that
    have some sensible means of being converted into numeric scalars for
    range comparisons.  If possible, add the data type to those understood
    by the routine <function>convert_to_scalar()</function> in <filename>src/backend/utils/adt/selfuncs.c</filename>.
    (Eventually, this routine should be replaced by per-data-type functions
    identified through a column of the <classname>pg_type</> system catalog; but that hasn't happened
    yet.)  If you do not do this, things will still work, but the optimizer's
    estimates won't be as good as they could be.
   </para>

   <para>
    There are additional selectivity functions designed for geometric
    operators in <filename>src/backend/utils/adt/geo_selfuncs.c</filename>: <function>areasel</function>, <function>positionsel</function>,
    and <function>contsel</function>.  At this writing these are just stubs, but you may want
    to use them (or even better, improve them) anyway.
   </para>
   </sect2>

   <sect2>
    <title>JOIN</title>

    <para>
     The <literal>JOIN</> clause, if provided, names a join selectivity
     estimation function for the operator (note that this is a function
     name, not an operator name).  <literal>JOIN</> clauses only make sense for
     binary operators that return <type>boolean</type>.  The idea behind a join
     selectivity estimator is to guess what fraction of the rows in a
     pair of tables will satisfy a <literal>WHERE</>-clause condition of the form
<ProgramListing>
table1.column1 OP table2.column2
</ProgramListing>
     for the current operator.  As with the <literal>RESTRICT</literal> clause, this helps
     the optimizer very substantially by letting it figure out which
     of several possible join sequences is likely to take the least work.
    </para>

    <para>
     As before, this chapter will make no attempt to explain how to write
     a join selectivity estimator function, but will just suggest that
     you use one of the standard estimators if one is applicable:
     <simplelist>
      <member><function>eqjoinsel</> for <literal>=</></member>
      <member><function>neqjoinsel</> for <literal>&lt;&gt;</></member>
      <member><function>scalarltjoinsel</> for <literal>&lt;</> or <literal>&lt;=</></member>
      <member><function>scalargtjoinsel</> for <literal>&gt;</> or <literal>&gt;=</></member>
      <member><function>areajoinsel</> for 2D area-based comparisons</member>
      <member><function>positionjoinsel</> for 2D position-based comparisons</member>
      <member><function>contjoinsel</> for 2D containment-based comparisons</member>
     </simplelist>
    </para>
   </sect2>

   <sect2>
    <title>HASHES</title>

    <para>
     The <literal>HASHES</literal> clause, if present, tells the system that it is OK to
     use the hash join method for a join based on this operator.  <literal>HASHES</>
     only makes sense for binary operators that return <literal>boolean</>, and
     in practice the operator had better be equality for some data type.
    </para>

    <para>
     The assumption underlying hash join is that the join operator can
     only return true for pairs of left and right values that hash to the
     same hash code.  If two values get put in different hash buckets, the
     join will never compare them at all, implicitly assuming that the
     result of the join operator must be false.  So it never makes sense
     to specify <literal>HASHES</literal> for operators that do not represent equality.
    </para>

    <para>
     In fact, logical equality is not good enough either; the operator
     had better represent pure bitwise equality, because the hash function
     will be computed on the memory representation of the values regardless
     of what the bits mean.  For example, equality of
     time intervals is not bitwise equality; the interval equality operator
     considers two time intervals equal if they have the same
     duration, whether or not their endpoints are identical.  What this means
     is that a join using <literal>=</literal> between interval fields would yield different
     results if implemented as a hash join than if implemented another way,
     because a large fraction of the pairs that should match will hash to
     different values and will never be compared by the hash join.  But
     if the optimizer chose to use a different kind of join, all the pairs
     that the equality operator says are equal will be found.
     We don't want that kind of inconsistency, so we don't mark interval
     equality as hashable.
    </para>

    <para>
     There are also machine-dependent ways in which a hash join might fail
     to do the right thing.  For example, if your data type
     is a structure in which there may be uninteresting pad bits, it's unsafe
     to mark the equality operator <literal>HASHES</>.  (Unless, perhaps, you write
     your other operators to ensure that the unused bits are always zero.)
     Another example is that the floating-point data types are unsafe for hash
     joins.  On machines that meet the <acronym>IEEE</> floating-point standard, minus
     zero and plus zero are different values (different bit patterns) but
     they are defined to compare equal.  So, if the equality operator on floating-point data types were marked
     <literal>HASHES</>, a minus zero and a plus zero would probably not be matched up
     by a hash join, but they would be matched up by any other join process.
    </para>

    <para>
     The bottom line is that you should probably only use <literal>HASHES</literal> for
     equality operators that are (or could be) implemented by <function>memcmp()</function>.
    </para>

   </sect2>

   <sect2>
    <title>SORT1 and SORT2</title>

    <para>
     The <literal>SORT</literal> clauses, if present, tell the system that it is permissible to use
     the merge join method for a join based on the current operator.
     Both must be specified if either is.  The current operator must be
     equality for some pair of data types, and the <literal>SORT1</> and <literal>SORT2</> clauses
     name the ordering operator (<quote>&lt;</quote> operator) for the left and right-side
     data types respectively.
    </para>

    <para>
     Merge join is based on the idea of sorting the left- and right-hand tables
     into order and then scanning them in parallel.  So, both data types must
     be capable of being fully ordered, and the join operator must be one
     that can only succeed for pairs of values that fall at the <quote>same place</>
     in the sort order.  In practice this means that the join operator must
     behave like equality.  But unlike hash join, where the left and right
     data types had better be the same (or at least bitwise equivalent),
     it is possible to merge-join two
     distinct data types so long as they are logically compatible.  For
     example, the <type>int2</type>-versus-<type>int4</type> equality operator is merge-joinable.
     We only need sorting operators that will bring both data types into a
     logically compatible sequence.
    </para>

    <para>
     When specifying merge-sort operators, the current operator and both
     referenced operators must return <type>boolean</type>; the <literal>SORT1</> operator must have
     both input data types equal to the current operator's left operand type,
     and the <literal>SORT2</> operator must have
     both input data types equal to the current operator's right operand type.
     (As with <literal>COMMUTATOR</> and <literal>NEGATOR</>, this means that the operator name is
     sufficient to specify the operator, and the system is able to make dummy
     operator entries if you happen to define the equality operator before
     the other ones.)
    </para>

    <para>
     In practice you should only write <literal>SORT</> clauses for an <literal>=</> operator,
     and the two referenced operators should always be named <literal>&lt;</>.  Trying
     to use merge join with operators named anything else will result in
     hopeless confusion, for reasons we'll see in a moment.
    </para>

    <para>
     There are additional restrictions on operators that you mark
     merge-joinable.  These restrictions are not currently checked by
     <command>CREATE OPERATOR</command>, but a merge join may fail at run time if any are
     not true:

     <itemizedlist>
      <listitem>
       <para>
	The merge-joinable equality operator must have a commutator
	(itself if the two data types are the same, or a related equality operator
	if they are different).
       </para>
      </listitem>

      <listitem>
       <para>
	There must be <literal>&lt;</> and <literal>&gt;</> ordering operators having the same left and
	right operand data types as the merge-joinable operator itself.  These
	operators <emphasis>must</emphasis> be named <literal>&lt;</> and <literal>&gt;</>; you do
	not have any choice in the matter, since there is no provision for
	specifying them explicitly.  Note that if the left and right data types
	are different, neither of these operators is the same as either
	<literal>SORT</literal> operator.  But they had better order the data values compatibly
	with the <literal>SORT</literal> operators, or the merge join will fail to work.
       </para>
      </listitem>
     </itemizedlist>
    </para>
   </sect2>

  </sect1>
 </Chapter>

<!-- Keep this comment at the end of the file
Local variables:
mode:sgml
sgml-omittag:nil
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:"./reference.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:("/usr/lib/sgml/catalog")
sgml-local-ecat-files:nil
End:
-->
