<!--
$Heder: /usr/prj/pg/cvsroot//doc/doc/src/sgml/arch-dev.sgml,v 1.1.1.1 2001/03/21 05:40:51 i-kaori Exp $
-->

 <chapter id="overview">
  <!-- <title>Overview of PostgreSQL Internals</title> -->
  <title>PostgreSQL内部の概略</title>
<indexterm><primary>PostgreSQL</primary><secondary sortas="ないぶのがいりゃく">内部の概略</secondary></indexterm>

  <note>
<!--   <title>Author</title> -->
   <title>著者</title> 
<!--  <para>
    This chapter originally appeared as a part of
    <xref linkend="SIM98" endterm="SIM98">, Stefan Simkovics'
    Master's Thesis prepared at Vienna University of Technology under the 
    direction
    of O.Univ.Prof.Dr. Georg Gottlob and Univ.Ass. Mag. Katrin Seyr.
   </para> -->
   <para>
    この章は、もともとは<xref linkend="SIM98" endterm="SIM98">, Vienna 
    University of TechnologyにおいてO.Univ.Prof.Dr. Georg GottlobとUniv.Ass. 
    Mag. Katrin Seyr.の指導によるStefan Simkovicsの修士論文との一部として書かれました。
  </para>
  </note>

<!--  <para>
   This chapter gives an overview of the internal structure of the
   backend of <productname>Postgres</productname>.
   After having read the following sections you
   should have an idea of how a query is processed. Don't expect a
   detailed description here (I think such a description dealing with
   all data structures and functions used within <productname>Postgres
  </productname>
   would exceed 1000
   pages!). This chapter is intended to help understanding the general
   control and data flow within the backend from receiving a query to
   sending the results.
  </para> -->

  <para>
   この章では<productname>Postgres</productname>のバックエンドの内部構造の概略
   を解説しています。これらのセクションを読めば問い合わせがどのように処理されるかがわかると思います。詳しい記述は期待しないでください（<productname>Postgres</productname>で使われるすべてのデータ構造や関数についての詳細に解説すると1,000ページを越えてしまうでしょう）。この章の目的は、バックエンドで問い合わせを受け取り結果を返すまでの大まかな制御とデータの流れを理解する手助けをすることです。
   </para>

  <sect1 id="query-path">
   <!-- <title>The Path of a Query</title> -->
   <title>問い合わせのパス</title>
<indexterm><primary sortas="といあわせのぱす">問い合わせのパス</primary></indexterm>
<indexterm><primary>PostgreSQL</primary><secondary sortas="といあわせのぱす">問い合わせのぱす</secondary></indexterm>

<!--   <para>
    Here we give a short overview of the stages a query has to pass in
    order to obtain a result.
   </para> -->

   <para>
    ここでは、問い合わせが結果を得るための過程を簡単に説明します。
   </para>

   <procedure>
    <step>
     <!-- <para>
      A connection from an application program to the <productname>Postgres
      </productname>
      server has to be established. The application program transmits a
      query to the server and receives the results sent back by the server.
     </para> -->
     <para>
      アプリケーションプログラムから<productname>Postgres</productname>サーバーに接続する必要があります。アプリケーションプログラムがサーバーに問い合わせを伝え、サーバーからの結果を受け取ります。
     </para>
    </step>

    <step>
<!--     <para>
      The <firstterm>parser stage</firstterm> checks the query
      transmitted by the application
      program (client) for correct syntax and creates
      a <firstterm>query tree</firstterm>.
     </para>  -->
     <para>
      <firstterm>構文解析過程</firstterm>が、アプリケーションプログラム（クライアント）から伝えられた問い合わせの構文をチェックし、<firstterm>問い合わせツリー</firstterm>を作ります。
     </para>
    </step>

    <step>
<!--     <para>
      The <firstterm>rewrite system</firstterm> takes
      the query tree created by the parser stage and looks for
      any <firstterm>rules</firstterm> (stored in the
      <firstterm>system catalogs</firstterm>) to apply to 
      the <firstterm>querytree</firstterm> and performs the
      transformations given in the <firstterm>rule bodies</firstterm>.
      One application of the rewrite system is given in the realization of
      <firstterm>views</firstterm>.
     </para> -->

     <para>
      <firstterm>リライトシステム</firstterm>が構文解析過程で作られた問い合わせツリーを受け取り、<firstterm>問い合わせツリー</firstterm>に適用するためのルール（<firstterm>システムカタログ</firstterm>に格納されている）を探します。そして<firstterm>ルール本体</firstterm>で与えられた変換を実行します。リライトシステムの適用例としては<firstterm>ビュー</firstterm>の実体化が挙げられます。 
     </para>

<!--     <para>
      Whenever a query against a view
      (i.e. a <firstterm>virtual table</firstterm>) is made,
      the rewrite system rewrites the user's query to
      a query that accesses the <firstterm>base tables</firstterm> given in
      the <firstterm>view definition</firstterm> instead.
     </para> -->

     <para>
      ビュー（すなわち<firstterm>仮想テーブル</firstterm>）に対して問い合わせがあると、リライトシステムがユーザーの問い合わせを、<firstterm>ビュー定義</firstterm>で与えられた<firstterm>実テーブル</firstterm>にアクセスする問い合わせに書き換えます。 
     </para>

    </step>

    <step>
<!--     <para>
      The <firstterm>planner/optimizer</firstterm> takes
      the (rewritten) querytree and creates a 
      <firstterm>queryplan</firstterm> that will be the input to the
      <firstterm>executor</firstterm>.
     </para> -->

     <para>
      <firstterm>プランナ/オプティマイザ</firstterm>は、（書き換えられた）問い合わせツリーをみて、<firstterm>エクゼキュータ</firstterm>に渡すための<firstterm>問い合わせ計画</firstterm>を作ります。
     </para>

<!--     <para>
      It does so by first creating all possible <firstterm>paths</firstterm>
      leading to the same result. For example if there is an index on a
      relation to be scanned, there are two paths for the
      scan. One possibility is a simple sequential scan and the other
      possibility is to use the index. Next the cost for the execution of
      each plan is estimated and the
      cheapest plan is chosen and handed back.
     </para> -->

     <para>
      そのためにはまず同じ結果を得られるすべての<firstterm>パス</firstterm>を作ります。たとえば、もしスキャン対象のリレーション上にインデックスがあった場合、2つのパスが考えられます。1つは単なる順スキャンで、もう1つはインデックスを使ったスキャンです。次にそれぞれの計画を実行するためのコストが見積もられ、一番コストの小さいものが選ばれ返されます。
     </para>

    </step>

    <step>
<!--     <para>
      The executor recursively steps through
      the <firstterm>plan tree</firstterm> and
      retrieves tuples in the way represented by the plan.
      The executor makes use of the
      <firstterm>storage system</firstterm> while scanning
      relations, performs <firstterm>sorts</firstterm> and <firstterm>joins
      </firstterm>,
      evaluates <firstterm>qualifications</firstterm> and finally hands 
      back the tuples derived.
     </para> -->

     <para>
      エクゼキュータは再帰的に<firstterm>計画ツリー</firstterm>を走査し、計画で表されている方法でタプルを検索します。エクゼキュータはリレーションをスキャンする間<firstterm>ストレージシステム</firstterm>を利用し、ソートと結合を実行します。そして<firstterm>検索条件</firstterm>を評価します。最後に、得られたタプルを返します。
     </para>

    </step>
   </procedure>

<!--   <para>
    In the following sections we will cover every of the above listed items
    in more detail to give a better understanding on <productname>Postgres
    </productname>'s internal
    control and data structures.
   </para> -->

   <para>
    ここからのセクションでは、<productname>Postgres</productname>の内部制御とデータ構造をよりよく理解するために、上記で示した事柄をさらに詳しく説明します。
   </para>

  </sect1>

  <sect1 id="connect-estab">
<!--   <title>How Connections are Established</title> -->
   <title>接続の方法</title>
<indexterm><primary sortas="せつぞくのほうほう">接続の方法</primary></indexterm>
<indexterm><primary>PostgreSQL</primary><secondary sortas="せつぞくのほうほう">接続の方法</secondary></indexterm>

<!--   <para>
    <productname>Postgres</productname> is implemented using a simple 
    "process per-user"
    client/server model.  In this model there is one <firstterm>client process
   </firstterm>
    connected to exactly one <firstterm>server process</firstterm>.
    As we don't know <foreignphrase>per se</foreignphrase> 
    how many connections will be made, we have to use a <firstterm>
    master process</firstterm>
    that spawns a new server process every time a connection is
    requested. This master process is called <literal>postmaster</literal> 
    and 
    listens at a specified TCP/IP port for incoming connections. Whenever
    a request for a connection is detected the <literal>postmaster</literal>
    process
    spawns a new server process called <literal>postgres</literal>. The 
    server
    tasks (<literal>postgres</literal> processes) communicate with each 
    other using
    <firstterm>semaphores</firstterm> and <firstterm>shared memory</firstterm>
    to ensure data integrity
    throughout concurrent data access. Figure
    &bsol;ref{connection} illustrates the interaction of the master process 
    <literal>postmaster</literal> the server process <literal>postgres
    </literal> and a client
    application. 
   </para> -->

   <para>
    <productname>Postgres</productname>は簡単な「1プロセスに1ユーザー」のクライアント/サーバーモデルを使って実装されています。このモデルでは1つの<firstterm>サーバープロセス</firstterm>に対して正確に1つの<firstterm>クライアントプロセス</firstterm>しかありません。いくつの接続が行われるか事前にはわからないため、接続がリクエストされるたびに新しいプロセスを作る<firstterm>マスタープロセス</firstterm>を使わなければいけません。このマスタープロセスは<literal>postmaster</literal>と呼ばれ、新しい接続には、指定されたTCP/IPポートを使います。接続のリクエストがあると、<literal>postmaster</literal>のプロセスは<literal>postgres</literal>と呼ばれる新しいサーバープロセスを作ります。それぞれのサーバーのタスク（<literal>postgres</literal>プロセス）は<firstterm>セマフォ</firstterm>と<firstterm>共有メモリ</firstterm>を使って、同時にデータにアクセスしても整合性が保たれるようにお互いと連絡をとりあいます。<!-- NO FIGURE AVAILABLE...図&bsol;ref{connection}はマスタープロセスの<literal>postmaster</literal>、サーバープロセスの<literal>postgres</literal>、そしてクライアントアプリケーション、3つの相互連関を表します。-->
   </para>

<!--   <para>
    The client process can either be the <application>psql</application> frontend (for
    interactive SQL queries) or any user application implemented using
    the <filename>libpg</filename> library. Note that applications implemented using
    <application>ecpg</application>
    (the <productname>Postgres</productname> embedded SQL preprocessor for C)
    also use this library.
   </para> -->

   <para>
    クライアントプロセスは、<application>psql</application>フロントエンド（対話式SQL問い合わせ用）、または<filename>libpg</filename>ライブラリを使って実装されたユーザーアプリケーションのどちらかです。<application>ecpg</application>（<productname>Postgres</productname>のC言語用の埋め込みSQLプリプロセッサ）を使って実装されたアプリケーションもこのライブラリを使います。
   </para>

<!--   <para>
    Once a connection is established the client process can send a query
    to the <firstterm>backend</firstterm> (server). The query is transmitted 
    using plain text,
    i.e. there is no parsing done in the <firstterm>frontend</firstterm> 
    (client). The
    server parses the query, creates an <firstterm>execution plan</firstterm>,
    executes the plan and returns the retrieved tuples to the client
    by transmitting them over the established connection.
   </para> -->

   <para>
    接続が確立されると、クライアントプロセスは<firstterm>バックエンド</firstterm>（サーバー）に問い合わせを送ることができます。<firstterm>フロントエンド</firstterm>（クライアント）では解析は行われません。つまり、問い合わせはプレーンテキストを使って伝えられます。サーバーは問い合わせを解析し、<firstterm>実行計画</firstterm>を作ります。そして計画を実行し、検索したタプルを、確立された接続からクライアントに伝えます。
   </para>

<!--
&bsol;begin{figure}[ht]
&bsol;begin{center}
&bsol;epsfig{figure=figures/connection.ps}
&bsol;caption{How a connection is established}
&bsol;label{connection}
&bsol;end{center}
&bsol;end{figure}
-->

  </sect1>

  <sect1 id="parser-stage">
<!--   <title>The Parser Stage</title> -->
   <title>構文解析過程</title>
<indexterm><primary sortas="こうぶんかいせき">構文解析</primary></indexterm>
<indexterm><primary>PostgreSQL</primary><secondary sortas="こうぶんかいせき">構文解析</secondary></indexterm>

   <para>
<!--    The <firstterm>parser stage</firstterm> consists of two parts: -->
    <firstterm>構文解析過程</firstterm>は2つの部分で構成されます。
</para>

    <itemizedlist>
     <listitem>
<!--      <para>
       The <firstterm>parser</firstterm> defined in
       <filename>gram.y</filename> and <filename>scan.l</filename> is
       built using the Unix tools <application>yacc</application>
       and <application>lex</application>.
      </para> -->

      <para>
       <filename>gram.y</filename>と<filename>scan.l</filename>で定義されている<firstterm>パーサー</firstterm>は、Unixのツール<application>yacc</application>と<application>lex</application>を使って作られています。 
      </para>

     </listitem>
     <listitem>
<!--      <para>
       The <firstterm>transformation process</firstterm> does
       modifications and augmentations to the data structures returned by 
       the parser.
      </para> -->

      <para>
       <firstterm>変換プロセス</firstterm>は、パーサーから返されたデータ構造の変更や追加をします。
      </para>

     </listitem>
    </itemizedlist>

   <sect2>
<!--    <title>Parser</title>  -->
   <title>パーサー</title> 

<!--    <para>
     The parser has to check the query string (which arrives as
     plain ASCII text) for valid syntax. If the syntax is correct a
     <firstterm>parse tree</firstterm> is built up and handed back otherwise an error is
     returned. For the implementation the well known Unix
     tools <application>lex</application> and <application>yacc</application>
     are used.
    </para>  -->

    <para>
     パーサーは、問い合わせ文字列（ASCIIテキストとして渡される）が正しい構文になるようにチェックしなければいけません。もし構文が正しい場合は<firstterm>構文解析ツリー</firstterm>が作られ返されます。正しくない場合はエラーが返されます。実装にはUnixのよく知られたツールである<application>lex</application>と<application>yacc</application>が使われています。
    </para>

<!--    <para>
     The <firstterm>lexer</firstterm> is defined in the file
     <filename>scan.l</filename> and is responsible
     for recognizing <firstterm>identifiers</firstterm>,
     the <firstterm>SQL keywords</firstterm> etc. For
     every keyword or identifier that is found, a <firstterm>token
     </firstterm>
     is generated and handed to the parser.
    </para>  -->

    <para>
     <firstterm>字句解析</firstterm>はファイル<filename>scan.l</filename>で定義されていて、<firstterm>識別子</firstterm>や<firstterm>SQLキーワード</firstterm>の認識をします。認識されたすべてのキーワードや識別子に対して<firstterm>トークン</firstterm>が作られパーサーに渡されます。
    </para>

<!--    <para>
     The parser is defined in the file <filename>gram.y</filename> and 
     consists of a
     set of <firstterm>grammar rules</firstterm> and <firstterm>actions
     </firstterm>
     that are executed
     whenever a rule is fired. The code of the actions (which
     is actually C-code) is used to build up the parse tree.
    </para> -->

    <para>
     パーサーはファイル<filename>gram.y</filename>の中で定義されていて、<firstterm>文法ルール</firstterm>とルールが実行されたときに起こる<firstterm>アクション</firstterm>のセットから構成されています。アクションのコード（Cコードで書かれています）は構文解析ツリーを作るのに使われます。
    </para>

<!--    <para>
     The file <filename>scan.l</filename> is transformed to
     the C-source file <filename>scan.c</filename>
     using the program <application>lex</application>
     and <filename>gram.y</filename> is transformed to
     <filename>gram.c</filename> using <application>yacc</application>.
     After these transformations have taken
     place a normal C-compiler can be used to create the
     parser. Never make any changes to the generated C-files as they will
     be overwritten the next time <application>lex</application>
     or <application>yacc</application> is called.</para> -->
     

    <para>
     ファイル<filename>scan.l</filename>はプログラム<application>lex</application>を使ってCのソースファイル<filename>scan.c</filename>に変換されます。そして<filename>gram.y</filename>は<application>yacc</application>を使って<filename>gram.c</filename>に書き換えられます。これらの書き換えが終わると、パーサーを作るために通常のCコンパイラが使えるようになります。作られたCのファイルには変更を加えないでください。次に<application>lex</application>か<application>yacc</application>が呼ばれたときにそれらは上書きされてしまいます。
    </para>
 
     <note>
<!--      <para>
       The mentioned transformations and compilations are normally done
       automatically using the <firstterm>makefiles</firstterm>
       shipped with the 
       source distribution.
      </para> -->

      <para>
       ここで述べられた書き換えやコンパイルは通常<productname>Postgres</productname>のソースと一緒に配布される<firstterm>メイクファイル</firstterm>を使って自動的に行われます。
      </para>

     </note>
<!--    </para> -->

<!--    <para>
     A detailed description of <application>yacc</application> or
     the grammar rules given in <filename>gram.y</filename> would be
     beyond the scope of this paper. There are many books and
     documents dealing with <application>lex</application> and
     <application>yacc</application>. You should be familiar with
     <application>yacc</application> before you start to study the
     grammar given in <filename>gram.y</filename> otherwise you won't
     understand what happens there.
    </para> -->

    <para>
     <application>yacc</application>や<filename>gram.y</filename>で定義される文法ルールの詳しい説明は本稿では説明しきれません。<application>lex</application>や<application>yacc</application>については本や資料がたくさん出ています。<filename>gram.y</filename>の文法の勉強を始める前に<application>yacc</application>の知識を得ておくことをお勧めします。その知識を持たないと、何が起こっているのか理解するのが難しいと思います。
    </para>

<!--    <para>
     For a better understanding of the data structures used in
     <productname>Postgres</productname>
     for the processing of a query we use an example to illustrate the
     changes made to these data structures in every stage.
     This example contains the following simple query that will be used in
     various descriptions and figures throughout the following
     sections. The query assumes that the tables given in
     <citetitle>The Supplier Database</citetitle>

     XXX The above citetitle should really be an xref,
     but that part has not yet been converted from Stefan's original 
     document.
     - thomas 1999-02-11
    <xref linkend="supplier" endterm="supplier">

     have already been defined.

     <example id="simple-select">
      <title>A Simple Select</title>

<programlisting>
select s.sname, se.pno
    from supplier s, sells se
    where s.sno > 2 and s.sno = se.sno;
</programlisting>
     </example>
    </para> -->

    <para>
     問い合わせの処理時に<productname>Postgres</productname>で使われるデータ構造をわかりやすく説明するため、処理の過程でこれらのデータ構造に加えられる様子を表す例を使いたいと思います。この例はこれからのセクションのさまざまな説明でも使われる簡単な問い合わせを含んでいます。この問い合わせでは、<quote>サプライヤーデータベース</quote>（<citetitle>&tutorial-guide;</citetitle>のSQLの章を参照）で使われるテーブルがすでに定義済みであるものとします。
     <!--
     XXX The above citetitle should really be an xref,
     but that part has not yet been converted from Stefan's original 
     document.
     - thomas 1999-02-11
    <xref linkend="supplier" endterm="supplier">
     -->
</para>

     <example id="simple-select">
      <title>単純なセレクト文</title>

<programlisting>
       select s.sname, se.pno
       from supplier s, sells se
       where s.sno > 2 and s.sno = se.sno;
</programlisting>
     </example>

<!--    <para>
     Figure &bsol;ref{parsetree} shows the <firstterm>parse tree</firstterm> 
     built by the
     grammar rules and actions given in <filename>gram.y</filename> for the 
     query
     given in  <xref linkend="simple-select">
     (without the <firstterm>operator tree</firstterm> for
     the <firstterm>where clause</firstterm> which is shown in figure 
     &bsol;ref{where_clause}
     because there was not enough space to show both data structures in one
     figure).
    </para> -->

    <para>
     <!--図がないため文章を変更-->
     <!--図&bsol;ref{parsetree}は--><xref linkend="simple-select">で与えられる問い合わせのために<filename>gram.y</filename>が、ルールとアクションによって作られる<firstterm>構文解析ツリー</firstterm>を作ります。
     <!--（1つの図で両方のデータ構造を見せるスペースがなかったため、&bsol;ref{where_clause}で表される<firstterm>where句</firstterm>のための<firstterm>演算子ツリー</firstterm>は入っていません）-->
    </para>

<!--    <para>
     The top node of the tree is a <literal>SelectStmt</literal> node. For 
     every entry
     appearing in the <firstterm>from clause</firstterm> of the SQL query a 
     <literal>RangeVar</literal>
     node is created holding the name of the <firstterm>alias</firstterm> 
     and a pointer to a
     <literal>RelExpr</literal> node holding the name of the <firstterm>
     relation</firstterm>. All
     <literal>RangeVar</literal> nodes are collected in a list which is 
     attached to the field
     <literal>fromClause</literal> of the <literal>SelectStmt</literal> node.
    </para> -->

    <para>
     ツリーの頂点にあるのは<literal>SelectStmt</literal>というノードです。SQLの問い合わせの<firstterm>from句</firstterm>に現れるすべてのソーステーブルに対し<firstterm>エイリアス</firstterm>の名前と、<firstterm>リレーション</firstterm>の名前を持つ<literal>RelExpr</literal>ノードのポインタを持つ<literal>RangeVar</literal>ノードが作られます。すべての<literal>RangeVar</literal>ノードは<literal>SelectStmt</literal>ノードの<literal>fromClause</literal>フィールドに付けられたリストに集められます。
    </para>

<!--    <para>
     For every entry appearing in the <firstterm>select list</firstterm> of 
     the SQL query a
     <literal>ResTarget</literal> node is created holding a pointer to an 
     <literal>Attr</literal>
     node. The <literal>Attr</literal> node holds the <firstterm>relation 
     name</firstterm> of the entry and
     a pointer to a <literal>Value</literal> node holding the name of the
     <firstterm>attribute</firstterm>.
     All <literal>ResTarget</literal> nodes are collected to a list which is
     connected to the field <literal>targetList</literal> of the <literal>
     SelectStmt</literal> node.
    </para> -->

    <para>
     SQL問い合わせの<firstterm>セレクトリスト</firstterm>に現れるそれぞれの項目に対して、<literal>Attr</literal>ノードへのポインタを持つ<literal>ResTarget</literal>ノードが作られます。<literal>Attr</literal>ノードはその項目の<firstterm>リレーション名</firstterm>と<firstterm>属性</firstterm>の名前を持つ<literal>Value</literal>ノードへのポインタを持ちます。すべての<literal>ResTarget</literal>ノードは<literal>SelectStmt</literal>ノードのフィールド<literal>targetList</literal>と接続されたリストにまとめられます。
    </para>

<!--    <para>
     Figure &bsol;ref{where_clause} shows the operator tree built for the
     where clause of the SQL query given in
     <xref linkend="simple-select">
     which is attached to the field
     <literal>qual</literal> of the <literal>SelectStmt</literal> node. 
     The top node of the
     operator tree is an <literal>A_Expr</literal> node representing an 
     <literal>AND</literal>
     operation. This node has two successors called <literal>lexpr</literal> 
     and
     <literal>rexpr</literal> pointing to two <firstterm>subtrees</firstterm>. 
     The subtree attached to
     <literal>lexpr</literal> represents the qualification <literal>s.sno 
     &gt; 2</literal> and the one
     attached to <literal>rexpr</literal> represents <literal>s.sno = se.sno
     </literal>. For every
     attribute an <literal>Attr</literal> node is created holding the name 
     of the
     relation and a pointer to a <literal>Value</literal> node holding the 
     name of the attribute. For the constant term appearing in the query a
     <literal>Const</literal> node is created holding the value.
    </para> -->

    <para>
     <!--図&bsol;ref{where_clause}は、-->SQL問い合わせ<xref linkend="simple-select">where句のための演算子ツリーは、<literal>SelectStmt</literal>ノードのフィールド<literal>qual</literal>につながっています。演算子ツリーの頂点の節は<literal>AND</literal>操作を表す<literal>A_Expr</literal>ノードです。このノードは2つの<firstterm>サブツリー</firstterm>を指す<literal>lexpr</literal>と<literal>rexpr</literal>という子節を持ちます。<literal>lexpr</literal>に付随されたサブツリーは<literal>s.sno &gt; 2</literal>の条件を表し、<literal>rexpr</literal>に付随されたものは<literal>s.sno = se.sno</literal>を表します。それぞれの属性に対してリレーションの名前と属性名を持つ<literal>Value</literal>ノードへのポインタを持つ<literal>Attr</literal>ノードが作られます。問い合わせにあらわれる定数に対しては、定数の値を保持するために<literal>Const</literal>ノードが作られます。
    </para>

<!--
XXX merge in the figures later... - thomas 1999-01-29

&bsol;begin{figure}[ht]
&bsol;begin{center}
&bsol;epsfig{figure=figures/parsetree.ps}
&bsol;caption{{&bsol;it TargetList} and {&bsol;it FromList} for query of example &bsol;ref{simple_select}}
&bsol;label{parsetree}
&bsol;end{center}
&bsol;end{figure}

&bsol;begin{figure}[ht]
&bsol;begin{center}
&bsol;epsfig{figure=figures/where_clause.ps}
&bsol;caption{{&bsol;it WhereClause} for query of example &bsol;ref{simple_select}}
&bsol;label{where_clause}
&bsol;end{center}
&bsol;end{figure}
-->

   </sect2>

   <sect2>
     <!-- <title>Transformation Process</title> -->
     <title>書き換えプロセス</title>

<!--    <para>
     The <firstterm>transformation process</firstterm> takes the tree
     handed back by
     the parser as input and steps recursively through it.  If
     a <literal>SelectStmt</literal> node is found, it is transformed
     to a <literal>Query</literal>
     node that will be the top most node of the new data structure. Figure
     &bsol;ref{transformed} shows the transformed data structure (the part
     for the transformed <firstterm>where clause</firstterm> is given in 
     figure
     &bsol;ref{transformed_where} because there was not enough space to show all
     parts in one figure).
    </para> -->

    <para>
     <firstterm>書き換えプロセス</firstterm>は、パーサーから引数としてツリーを受け取り、その中を再帰的に移動します。<literal>SelectStmt</literal>ノードが見つかった場合、それは新しいデータ構造の頂点になる<literal>Query</literal>ノードに書き換えられます。<!--図&bsol;ref{transformed}は、書き換えられたデータ構造を表しています（1つの図ですべてを示すスペースがなかったため、書き換えられた<firstterm>where句</firstterm>の部分は図&bsol;ref{transformed_where}で示されています）。-->
    </para>

<!--    <para>
     Now a check is made, if the <firstterm>relation names</firstterm> in the
     <firstterm>FROM clause</firstterm> are known to the system. For every 
     relation name
     that is present in the <firstterm>system catalogs</firstterm> a 
    <abbrev>RTE</abbrev> node is
     created containing the relation name, the <firstterm>alias name
     </firstterm> and
     the <firstterm>relation id</firstterm>. From now on the relation ids 
     are used to
     refer to the <firstterm>relations</firstterm> given in the query. All 
     <abbrev>RTE</abbrev> nodes
     are collected in the <firstterm>range table entry list</firstterm> 
     that is connected
     to the field <literal>rtable</literal> of the <literal>Query</literal> 
     node. If a name of a
     relation that is not known to the system is detected in the query an
     error will be returned and the query processing will be aborted.
    </para> -->

    <para>
     <firstterm>FROM句</firstterm>の<firstterm>リレーション名</firstterm>がシステムに認識された場合、ここで照合が行われます。<firstterm>システムカタログ</firstterm>に存在するすべてのリレーション名に対して、リレーション名、<firstterm>エイリアス名</firstterm>、<firstterm>リレーションID</firstterm>を持つ<abbrev>RTE</abbrev>ノードが作られます。ここからはリレーションIDは問い合わせで作られる<firstterm>リレーション</firstterm>を参照するために使われます。すべての<abbrev>RTE</abbrev>ノードは、<literal>Query</literal>ノードの<literal>rtable</literal>フィールドと結び付けられた<firstterm>レンジテーブルエントリリスト</firstterm>（range table entry list）に納められます。問い合わせの中でシステムが認識できないリレーションが発見された場合は、エラーが返され問い合わせプロセスはアボートされます。
    </para>

<!--    <para>
     Next it is checked if the <firstterm>attribute names</firstterm> used 
     are 
     contained in the relations given in the query. For every
     attribute} that is found a <abbrev>TLE</abbrev> node is created holding 
     a pointer
     to a <literal>Resdom</literal> node (which holds the name of the column)
     and a
     pointer to a <literal>VAR</literal> node. There are two important 
     numbers in the
     <literal>VAR</literal> node. The field <literal>varno</literal> gives 
     the position of the
     relation containing the current attribute} in the range
     table entry list created above. The field <literal>varattno</literal> 
     gives the
     position of the attribute within the relation. If the name
     of an attribute cannot be found an error will be returned and
     the query processing will be aborted.
    </para> -->

    <para>
     次に、<firstterm>属性名</firstterm>が問い合わせで使われるリレーションの中に含まれているかがチェックされます。見つかったすべての属性に対して、<literal>Resdom</literal>ノード（カラム名を持ちます）へのポインタと<literal>VAR</literal>ノードへのポインタを持つ<abbrev>TLE</abbrev>節が作られます。<literal>VAR</literal>ノードには重要な2つの数字があります。フィールド<literal>varno</literal>は上でエントリリストが作った範囲の中で現在の属性を持つリレーションのポジションを示します。フィールド<literal>varattno</literal>はリレーション内の属性のポジションを示します。もし属性の名前が見付けられない場合、エラーが返され問い合わせプロセスはアボートされます。
    </para>

<!--
&bsol;begin{figure}[ht]
&bsol;begin{center}
&bsol;epsfig{figure=figures/transform.ps}
&bsol;caption{Transformed {&bsol;it TargetList} and {&bsol;it FromList} for query of example &bsol;ref{simple_select}}
&bsol;label{transformed}
&bsol;end{center}
&bsol;end{figure}

&bsol;noindent Figure &bsol;ref{transformed_where} shows the transformed {&bsol;it where
clause}. Every {&bsol;tt A&bsol;_Expr} node is transformed to an {&bsol;tt Expr}
node. The {&bsol;tt Attr} nodes representing the attributes are replaced by
{&bsol;tt VAR} nodes as it has been done for the {&bsol;it targetlist}
above. Checks if the appearing {&bsol;it attributes} are valid and known to the
system are made. If there is an {&bsol;it attribute} used which
is not known an error will be returned and the {&bsol;it query
processing} will be aborted. &bsol;&bsol;
&bsol;&bsol;
The whole {&bsol;it transformation process} performs a transformation of
the data structure handed back by the {&bsol;it parser} to a more
comfortable form. The character strings representing the {&bsol;it
relations} and {&bsol;it attributes} in the original tree are replaced by
{&bsol;it relation ids} and {&bsol;tt VAR} nodes whose fields are referring to
the entries of the {&bsol;it range table entry list}. In addition to the
transformation, also various checks if the used {&bsol;it relation}
and {&bsol;it attribute} names (appearing in the query) are valid in the
current context are performed.

&bsol;begin{figure}[ht]
&bsol;begin{center}
&bsol;epsfig{figure=figures/transform_where.ps}
&bsol;caption{Transformed {&bsol;it where clause} for query of example &bsol;ref{simple_select}}
&bsol;label{transformed_where}
&bsol;end{center}
&bsol;end{figure}

&bsol;pagebreak
&bsol;clearpage

&bsol;begin{figure}[ht]
&bsol;begin{center}
&bsol;epsfig{figure=figures/plan.ps}
&bsol;caption{{&bsol;it Plan} for query of example &bsol;ref{simple_select}}
&bsol;label{plan}
&bsol;end{center}
&bsol;end{figure}
-->

   </sect2>
  </sect1>

  <sect1 id="rule-system">
   <!-- <title>The <productname>Postgres</productname> Rule System</title> -->
   <title><productname>Postgres</productname>ルールシステム</title>

<!--   <para>
    <productname>Postgres</productname> supports a powerful
    <firstterm>rule system</firstterm> for the specification
    of <firstterm>views</firstterm> and ambiguous <firstterm>view updates</firstterm>.
    Originally the <productname>Postgres</productname>
    rule system consisted of two implementations: -->

   <para>
    <productname>Postgres</productname>は、<firstterm>ビュー</firstterm>とあいまいな<firstterm>ビューの更新</firstterm>にも対応できる充実した<firstterm>ルールシステム</firstterm>を持っています。もともとは<productname>Postgres</productname>のルールシステムは2つの実装で構成されていました。
</para>

    <itemizedlist>
     <listitem>
<!--      <para>
       The first one worked using <firstterm>tuple level</firstterm> 
       processing and was
       implemented deep in the <firstterm>executor</firstterm>. The rule 
       system was
       called whenever an individual tuple had been accessed. This
       implementation was removed in 1995 when the last official release
       of the <productname>Postgres</productname> project was transformed 
       into 
       <productname>Postgres95</productname>. 
      </para>  -->

      <para>
       1つは<firstterm>タプルレベル</firstterm>の処理を使って行われ、<firstterm>エクゼキュータ</firstterm>の内部に実装されていました。個別のタプルがアクセスされるたびにルールシステムが呼ばれていました。この実装は1995年、最後の<productname>Postgres</productname>プロジェクトのリソースから<productname>Postgres95</productname>へと移行する間に取り除かれました。
      </para>

     </listitem>

     <listitem>
<!--      <para>
       The second implementation of the rule system is a technique
       called <firstterm>query rewriting</firstterm>.
       The <firstterm>rewrite system</firstterm>} is a module
       that exists between the <firstterm>parser stage</firstterm> and the
       <firstterm>planner/optimizer</firstterm>. This technique is still 
       implemented.
      </para> -->

      <para>
       ルールシステムの2つ目の実装は<firstterm>問い合わせ書き換え</firstterm>と呼ばれるテクニックです。<firstterm>リライトシステム</firstterm>は<firstterm>構文解析過程</firstterm>と<firstterm>プランナ/オプティマイザ</firstterm>の間にあるモジュールです。このテクニックは今でも実装されています。 
      </para>

     </listitem>
    </itemizedlist>

<!--   <para>
    For information on the syntax and creation of rules in the
    <productname>Postgres</productname> system refer to
    <citetitle>The PostgreSQL User's Guide</citetitle>.
   </para> -->

   <para>
    <productname>Postgres</productname>システムの構文やルールの作成に関する情報については<citetitle>&user-guide;</citetitle>を参照してください。
   </para>

   <sect2>
<!--    <title>The Rewrite System</title> -->
    <title>リライトシステム</title>

<!--    <para>
     The <firstterm>query rewrite system</firstterm> is a module between
     the parser stage and the planner/optimizer. It processes the tree handed
     back by the parser stage (which represents a user query) and if
     there is a rule present that has to be applied to the query it
     rewrites the tree to an alternate form.
    </para> -->

    <para>
     <firstterm>問い合わせリライトシステム</firstterm>は、構文解析過程とプランナ/オプティマイザの間にあるモジュールです。このシステムは構文解析過程から返されたツリー（ユーザーの問い合わせを表すもの）を処理し、問い合わせに適用されるべきルールがあった場合はツリーをそれに合わせて書き直します。
    </para>

    <sect3 id="view-impl">
<!--     <title>Techniques To Implement Views</title> -->
     <title>ビューを実装するテクニック</title>

<!--     <para>
      Now we will sketch the algorithm of the query rewrite system. For
      better illustration we show how to implement views using rules
      as an example.
     </para> -->

     <para>
      ここでは問い合わせリライトシステムのアルゴリズムを紹介します。よりわかりやすくするために、ルールを使ってビューを実装する方法を例として使います。
     </para>

<!--     <para>
      Let the following rule be given: -->

     <para>
      次のようなルールがあったとします。
</para>

<programlisting>
  create rule view_rule
  as on select 
  to test_view
  do instead
     select s.sname, p.pname
     from supplier s, sells se, part p
     where s.sno = se.sno and
           p.pno = se.pno;   
</programlisting>

<!--     <para>
      The given rule will be <firstterm>fired</firstterm> whenever a select
      against the relation <literal>test_view</literal> is detected. Instead 
      of
      selecting the tuples from <literal>test_view</literal> the select 
      statement
      given in the <firstterm>action part</firstterm> of the rule is executed.
     </para> -->

     <para>
      このようなルールは、リレーション<literal>test_view</literal>に対する選択が認識されると<firstterm>起動</firstterm>されます。<literal>test_view</literal>からタプルを選択する代わりに<firstterm>アクションパート</firstterm>のルールが実行されます。
     </para>

<!--     <para>
      Let the following user-query against <literal>test_view</literal> 
      be given: -->

     <para>
       <literal>test_view</literal>に対する次のようなユーザー問い合わせがあったとします。
</para>

<programlisting>
  select sname 
  from test_view
  where sname &lt;&gt; 'Smith';
</programlisting>

<!--     <para>
      Here is a list of the steps performed by the query rewrite
      system whenever a user-query against <literal>test_view</literal>
      appears. (The
      following listing is a very informal description of the algorithm just
      intended for basic understanding. For a detailed description refer
      to <xref linkend="STON89-full" endterm="STON89">).
     </para> -->

     <para>
      以下に、<literal>test_view</literal>に対するユーザー問い合わせがあるたびに問い合わせリライトシステムが実行する過程を示します。このリストは基礎的な理解をうながすためのアルゴリズムをとても簡単に書いたものです。詳しい説明については<xref linkend="STON89-full"  endterm="STON89">）を参照してください。
     </para>

     <procedure>
<!--      <title><literal>test_view</literal> Rewrite</title> -->
      <title><literal>test_view</literal>リライト</title>
      <step>
<!--       <para>
	Take the query given in the action part of the rule.
       </para> -->

       <para>
	ルールの実行部分で与えられた問い合わせを受け取ります。
       </para>

      </step>

      <step>
<!--       <para>
	Adapt the targetlist to meet the number and order of
	attributes given in the user-query.
       </para> -->

       <para>
	ユーザー問い合わせで与えられた属性の数字と順番が合うようにターゲットリストを調整します。
       </para>

      </step>

      <step>
<!--       <para>
	Add the qualification given in the where clause of the
	user-query to the qualification of the query given in the
	action part of the rule.
       </para> -->

       <para>
        ユーザー問い合わせのwhere句で与えられる制限を、ルールのアクションパートで与えられる問い合わせの制限に追加します。
       </para>

      </step>
     </procedure>

<!--     <para>
      Given the rule definition above, the user-query will be
      rewritten to the following form (Note that the rewriting is done on
      the internal representation of the user-query handed back by the
      parser stage but the derived new data structure will represent the following
      query): -->

     <para>
      実際には上記のようにルールが定義され、ユーザーの問い合わせは次のような形に書き換えられます（書き換えは構文解析過程から返されたユーザー問い合わせの内部表現に適用されますが、新しく作られたデータ構造は次の問い合わせを表現しています）。
</para>

<programlisting>
  select s.sname
  from supplier s, sells se, part p
  where s.sno = se.sno and
        p.pno = se.pno and
        s.sname &lt;&gt; 'Smith';
</programlisting>
</sect3>
   </sect2>
  </sect1>

  <sect1 id="planner-optimizer">
   <!-- <title>Planner/Optimizer</title> -->
   <title>プランナ/オプティマイザ</title>

<!--   <para>
    The task of the <firstterm>planner/optimizer</firstterm> is to create 
    an optimal
    execution plan. It first combines all possible ways of
    <firstterm>scanning</firstterm> and <firstterm>joining</firstterm>
    the relations that appear in a
    query. All the created paths lead to the same result and it's the
    task of the optimizer to estimate the cost of executing each path and
    find out which one is the cheapest.
   </para> -->

   <para>
    <firstterm>プランナ/オプティマイザ</firstterm>の役割は、最適な実行計画を作ることです。まず始めに、問い合わせのなかに登場するリレーションを<firstterm>スキャン</firstterm>し、<firstterm>結合</firstterm>するためのすべての方法をまとめます。作られたすべてのパスは同じ結果を得られますが、それぞれのパスのコストを見積もり、一番安いものを選ぶのはオプティマイザの役割です。
   </para>

   <sect2>
<!--    <title>Generating Possible Plans</title> -->
    <title>可能な計画を生成する</title>

<!--    <para>
     The planner/optimizer decides which plans should be generated
     based upon the types of indices defined on the relations appearing in
     a query. There is always the possibility of performing a
     sequential scan on a relation, so a plan using only
     sequential scans is always created. Assume an index is defined on a
     relation (for example a B-tree index) and a query contains the
     restriction
     <literal>relation.attribute OPR constant</literal>. If
     <literal>relation.attribute</literal> happens to match the key of the B-tree
     index and <literal>OPR</literal> is anything but '&lt;&gt;' another plan is created using
     the B-tree index to scan the relation. If there are further indices
     present and the restrictions in the query happen to match a key of an
     index further plans will be considered.
    </para> -->

    <para>
     プランナ/オプティマイザは、問い合わせの中に現れるリレーションで定義されるインデックスの型に基づいて、どのプランが作られるべきかを決めます。リレーション上で順スキャンを行う可能性は常にあるため、順スキャンのみを使ったプランが作られます。たとえばリレーション上にインデックス（たとえばB-treeインデックス）が定義され、問い合わせは制約<literal>relation.attribute OPR constant</literal>を含むとします。もし<literal>relation.attribute</literal>がB-treeインデックスのキーと同じで<literal>OPR</literal>が「&lt;&gt;」以外だった場合、リレーションをスキャンするための別の計画がB-treeインデックスを使って作られます。もしさらにインデックスがあり、問い合わせの制約がインデックスのキーと同じ場合、さらなる計画が検討されます。
    </para>

<!--    <para>
     After all feasible plans have been found for scanning single
     relations, plans for joining relations are created. The
     planner/optimizer considers only joins between every two relations for
     which there exists a corresponding join clause (i.e. for which a
     restriction like <literal>where rel1.attr1=rel2.attr2</literal> exists) in the
     where qualification. All possible plans are generated for every
     join pair considered by the planner/optimizer. The three possible join
     strategies are: -->

    <para>
     個々のリレーションをスキャンするためのすべての可能な計画が見つけられると、リレーションを結合するための計画が作られます。プランナ/オプティマイザは、where制約のなかで一致する結合句が存在する2つのリレーション（例：<literal>where rel1.attr1=rel2.attr2</literal>のような制約が存在する場合）のみを考慮します。プランナ/オプティマイザに考慮された結合ペアにはすべての可能な計画が作られます。以下は3つの可能な策です。
</para>

     <itemizedlist>
      <listitem>
<!--       <para>
	<firstterm>nested iteration join</firstterm>: The right relation is 
        scanned
	once for every tuple found in the left relation. This strategy
	is easy to implement but can be very time consuming.
       </para> -->

       <para>
	<firstterm>入れ子反復結合</firstterm>――左側のリレーションのなかで見つけられるタプルごとに右側のリレーションがスキャンされます。この方法は実装が簡単ですが、時間をとる場合があります。
       </para>

      </listitem>

      <listitem>
<!--       <para>
	<firstterm>merge sort join</firstterm>: Each relation is sorted on
        the join
	attributes before the join starts. Then the two relations are
	merged together taking into account that both relations are
	ordered on the join attributes. This kind of join is more
	attractive because every relation has to be scanned only once.
       </para> -->
 
       <para>
	<firstterm>マージソート結合</firstterm>――結合が始まる前に、それぞれのリレーションが結合属性でソートされます。そして2つのリレーションは両方とも結合属性で並んでいるという前提でマージされます。それぞれのリレーションが一回しかスキャンされなくて済むのでこの結合は魅力的です。
       </para>

      </listitem>

      <listitem>
<!--       <para>
	<firstterm>hash join</firstterm>: the right relation is first hashed on its
	join attributes. Next the left relation is scanned and the
	appropriate values of every tuple found are used as hash keys to
	locate the tuples in the right relation.
       </para> -->

       <para>
	<firstterm>ハッシュ結合</firstterm>――まず右側のリレーションがその結合属性によってハッシュされます。次に左側のリレーションがスキャンされ、見つかったそれぞれのタプルにふさわしい値が、右側のリレーションのタプルを配置するためのハッシュキーとして使われます。
       </para>

      </listitem>
     </itemizedlist>
   </sect2>

   <sect2>
<!--    <title>Data Structure of the Plan</title> -->
    <title>計画のデータ構造</title>

<!--    <para>
     Here we will give a little description of the nodes appearing in the
     plan. Figure &bsol;ref{plan} shows the plan produced for the query in
     example &bsol;ref{simple_select}.
    </para> -->

    <para>
     ここでは計画で登場するノードについて簡単に説明します。<!--図&bsol;ref{plan}は--><xref linkend="simple-select">の問い合わせのために作られた計画を考えてみましょう。
    </para>

<!--    <para>
     The top node of the plan is a <literal>MergeJoin</literal> node that 
     has two
     successors, one attached to the field <literal>lefttree</literal> and 
     the second
     attached to the field <literal>righttree</literal>. Each of the 
     subnodes represents
     one relation of the join. As mentioned above a merge sort
     join requires each relation to be sorted. That's why we find
     a <literal>Sort</literal> node in each subplan. The additional 
     qualification given
     in the query (<literal>s.sno &gt; 2</literal>) is pushed down as far 
     as possible and is
     attached to the <literal>qpqual</literal> field of the leaf <literal>
     SeqScan</literal> node of
     the corresponding subplan.
    </para> -->

    <para>
     計画の頂点にあるノードは<literal>MergeJoin</literal>ノードで、2つの子ノードを持ちます。1つは<literal>lefttree</literal>フィールドに付随するもので、2つ目は<literal>righttree</literal>フィールドに付随するものです。それぞれのサブノードは結合の1つのリレーションを表します。上でも触れたように、マージソート結合は各々のリレーションがあらかじめソートされていることを必要とします。そのために各々のサブプランに<literal>Sort</literal>ノードがあるのです。問い合わせ（<literal>s.sno &gt; 2</literal>）でさらに与えられる制約は下に押し出され、相当するサブプランの節<literal>SeqScan</literal>の<literal>qpqual</literal>フィールドに付随しています。
    </para>

<!--    <para>
     The list attached to the field <literal>mergeclauses</literal> of the
     <literal>MergeJoin</literal> node contains information about the join
     attributes.
     The values <literal>65000</literal> and <literal>65001</literal>
     for the <literal>varno</literal> fields in the
     <literal>VAR</literal> nodes appearing in the <literal>mergeclauses
     </literal> list (and also in the
     <literal>targetlist</literal>) mean that not the tuples of the current 
     node should be
     considered but the tuples of the next "deeper" nodes (i.e. the top
     nodes of the subplans) should be used instead.
    </para> -->

    <para>
     <literal>MergeJoin</literal>ノードの<literal>mergeclauses</literal>フィールドに付随されたリストは結合属性に関する情報を持っています。<literal>mergeclauses</literal>リスト（<literal>ターゲットリスト</literal>にもあります）に現れる<literal>VAR</literal>ノードにある<literal>verno</literal>フィールドの値、<literal>65000</literal>と<literal>65001</literal>は現在のノードのタプルではなく次の「深さ」のノード（つまりサブプランの頂点にあるノード）が使われるべきだということを意味しています。
    </para>

<!--    <para>
     Note that every <literal>Sort</literal> and <literal>SeqScan</literal> 
     node appearing in figure
     &bsol;ref{plan} has got a <literal>targetlist</literal> but because there 
     was not enough space
     only the one for the <literal>MergeJoin</literal> node could be drawn.
    </para> -->

    <!--
    <para>
     図&bsol;ref{plan}に現れるすべての<literal>Sort</literal>と<literal>SeqScan</literal>ノードは<literal>ターゲットリスト</literal>を持ちますが、スペースが足りないため<literal>MergeJoin</literal>ノードのものだけが書かれています。
    </para>
    -->

<!--    <para>
     Another task performed by the planner/optimizer is fixing the
     <firstterm>operator ids</firstterm> in the <literal>Expr</literal>
     and <literal>Oper</literal> nodes. As
     mentioned earlier, <productname>Postgres</productname> supports a 
     variety of different data
     types and even user defined types can be used. To be able to maintain
     the huge amount of functions and operators it is necessary to store
     them in a system table. Each function and operator gets a unique
     operator id. According to the types of the attributes used
     within the qualifications etc., the appropriate operator ids
     have to be used.
    </para> -->

    <para>
     プランナ/オプティマイザに実行されるもう1つの仕事は、<literal>Expr</literal>と<literal>Oper</literal>ノードの中で<firstterm>演算子ID</firstterm>を調整することです。始めのほうで述べたように、<productname>Postgres</productname>はさまざまなデータ型をサポートし、ユーザー定義のものまで使うことができます。そのような大量の関数や演算子を保持するためにはシステムテーブルにそれらを格納しておくことが必要になります。各々の関数や演算子は一意な演算子IDが与えられます。制約のなかで使われる属性の型などに基づいて、ふさわしい演算子IDが使わなければいけません。
    </para>

   </sect2>
  </sect1>

  <sect1 id="executor">
<!--   <title>Executor</title> -->
   <title>エクゼキュータ</title>

<!--   <para>
    The <firstterm>executor</firstterm> takes the plan handed back by the
    planner/optimizer and starts processing the top node. In the case of
    our example (the query given in example &bsol;ref{simple_select}) the top
    node is a <literal>MergeJoin</literal> node. 
   </para> -->

   <para>
    <firstterm>エクゼキュータ</firstterm>は、プランナ/オプティマイザから返された計画を受け取り、頂点のノードの実行を始めます。ここでの例の場合（<xref linkend="simple-select">の問い合わせ）、頂点のノードは<literal>MergeJoin</literal>ノードです。
   </para>

<!--   <para>
    Before any merge can be done two tuples have to be fetched (one from
    each subplan). So the executor recursively calls itself to
    process the subplans (it starts with the subplan attached to
    <literal>lefttree</literal>). The new top node (the top node of the left 
    subplan) is a
    <literal>SeqScan</literal> node and again a tuple has to be fetched 
    before the node
    itself can be processed. The executor calls itself recursively
    another time for the subplan attached to <literal>lefttree</literal> of 
    the
    <literal>SeqScan</literal> node.
   </para> -->

   <para>
    マージが実行される前に2つのタプル（それぞれのサブプランから1つづつ）を取って来なくてはいけません。ですからエクゼキュータはサブプランを処理するために自分自身を再帰的に呼び出します（<literal>lefttree</literal>に付随するサブプランから始めます）。新しい頂点のノード（左のサブプランの頂点のノード）は<literal>SeqScan</literal>ノードで、ここでもノード自体が実行される前にタプルを取らなくてはいけません。エクゼキュータは<literal>SeqScan</literal>ノードの<literal>lefttree</literal>に付随するサブプランのために自分自身をもう一度再帰的に呼び出します。
   </para>

<!--   <para>
    Now the new top node is a <literal>Sort</literal> node. As a sort has 
    to be done on
    the whole relation, the executor starts fetching tuples
    from the <literal>Sort</literal> node's subplan and sorts them into a 
    temporary
    relation (in memory or a file) when the <literal>Sort</literal> node is 
    visited for
    the first time. (Further examinations of the <literal>Sort</literal> 
    node will
    always return just one tuple from the sorted temporary
    relation.)
   </para> -->

   <para>
    ここで頂点のノードは<literal>Sort</literal>ノードになります。ソートはリレーション全体にかけられなければいけないため、エクゼキュータは<literal>Sort</literal>ノードのサブプランからタプルを取り始め、<literal>Sort</literal>ノードが始めて読み込まれると、一時リレーション（メモリもしくはファイル上）にそれらをソートします（<literal>Sort</literal>ノードのさらなる検査は、常にソートされた一時リレーションからタプルを1つだけ返します）。
   </para>

<!--   <para>
    Every time the processing of the <literal>Sort</literal> node needs a 
    new tuple the
    executor is recursively called for the <literal>SeqScan</literal> node
    attached as subplan. The relation (internally referenced by the
    value given in the <literal>scanrelid</literal> field) is scanned for 
    the next
    tuple. If the tuple satisfies the qualification given by the tree
    attached to <literal>qpqual</literal> it is handed back, otherwise the 
    next tuple
    is fetched until the qualification is satisfied. If the last tuple of
    the relation has been processed a <literal>NULL</literal> pointer is
    returned.
   </para> -->

   <para>
    <literal>Sort</literal>の実行に新しいタプルが必要になると、サブプランとして付随された<literal>SeqScan</literal>ノードのためにエクゼキュータが再帰的に呼び出されます。そのリレーション（<literal>scanrelid</literal>フィールドで与えられた値に内部的に参照される）は次のタプルのためにスキャンされます。もしそのタプルが<literal>qpqual</literal>に付随するツリーで与えられる制約を満たす場合、それは返されます。そうでない場合、制約が満たされるまで次のタプルがとられます。もしリレーション上の最後のタプルがプロセスされた場合は、<literal>NULL</literal>ポインタが返されます。
   </para>

<!--   <para>
    After a tuple has been handed back by the <literal>lefttree</literal> 
    of the
    <literal>MergeJoin</literal> the <literal>righttree</literal> is 
    processed in the same way. If both
    tuples are present the executor processes the <literal>MergeJoin
    </literal>
    node. Whenever a new tuple from one of the subplans is needed a
    recursive call to the executor is performed to obtain it. If a
    joined tuple could be created it is handed back and one complete
    processing of the plan tree has finished. 
   </para> -->

   <para>
    <literal>MergeJoin</literal>の<literal>lefttree</literal>からタプルが返されると、<literal>righttree</literal>が同じように処理されます。両方のタプルが存在する場合、エクゼキュータは<literal>MergeJoin</literal>ノードを処理します。サブプランの1つからタプルが必要とされる場合、それを得るためにエクゼキュータへの再帰呼び出しが行われます。結合されたタプルが作られるとそれは返され、1つの計画ツリーの実行が完了します。 
   </para>

<!--   <para>
    Now the described steps are performed once for every tuple, until a
    <literal>NULL</literal> pointer is returned for the processing of the
    <literal>MergeJoin</literal> node, indicating that we are finished.
   </para> -->

   <para>
    ここで説明された処置は、<literal>MergeJoin</literal>ノード実行の<literal>NULL</literal>ポインタが返され処理が終わったことを知らせるまで、タプルごとに1回ずつ実行されます。
   </para>

  </sect1>

<![IGNORE[
**********************************************************
**********************************************************
**********************************************************
**********************************************************
**********************************************************

&bsol;pagebreak
&bsol;clearpage

&bsol;section{The Realization of the Having Clause}
&bsol;label{having_impl}

The {&bsol;it having clause} has been designed in SQL to be able to use the
results of {&bsol;it aggregate functions} within a query qualification. The
handling of the {&bsol;it having clause} is very similar to the handling of
the {&bsol;it where clause}. Both are formulas in first order logic (FOL)
that have to evaluate to true for a certain object to be handed back:
%
&bsol;begin{itemize}
<step> The formula given in the {&bsol;it where clause} is evaluated for
every tuple. If the evaluation returns {&bsol;tt true} the tuple is
returned, every tuple not satisfying the qualification is ignored.
%
<step> In the case of {&bsol;it groups} the {&bsol;it having clause} is evaluated
for every group. If the evaluation returns {&bsol;tt true} the group is
taken into account otherwise it is ignored.
&bsol;end{itemize}
%
&bsol;subsection{How Aggregate Functions are Implemented}
&bsol;label{aggregates}

Before we can describe how the {&bsol;it having clause} is implemented we
will have a look at the implementation of {&bsol;it aggregate functions} as
long as they just appear in the {&bsol;it targetlist}. Note that {&bsol;it aggregate
functions} are applied to groups so the query must contain a {&bsol;it
group clause}.
%
&bsol;begin{example} 
&bsol;label{having}
Here is an example of the usage of the {&bsol;it aggregate
function} {&bsol;tt count} which counts the number of part numbers ({&bsol;tt
pno}) of every group. (The table {&bsol;tt sells} is defined in example
&bsol;ref{supplier}.)
%
&bsol;begin{verbatim}
  select sno, count(pno)
  from sells
  group by sno;
&bsol;end{verbatim}
%
&bsol;end{example}
%
A query like the one in example &bsol;ref{having} is processed by the usual
stages:
%
&bsol;begin{itemize}
<step> the parser stage
<step> the rewrite system
<step> the planner/optimizer 
<step> the executor
&bsol;end{itemize}
%
and in the following sections we will describe what every stage does
to the query in order to obtain the appropriate result.

&bsol;subsubsection{The Parser Stage}

&bsol;begin{figure}[ht]
&bsol;begin{center}
&bsol;epsfig{figure=figures/parse_having.ps}
&bsol;caption{{&bsol;it Querytree} built up for the query of example &bsol;ref{having}}
&bsol;label{parse_having}
&bsol;end{center}
&bsol;end{figure}

The parser stage builds up a {&bsol;it querytree} containing the {&bsol;it
where} qualification and information about the {&bsol;it grouping} that has
to be done (i.e. a list of all attributes to group for is attached to
the field {&bsol;tt groupClause}). The main difference to {&bsol;it querytrees}
built up for queries without {&bsol;it aggregate functions} is given in the
field {&bsol;tt hasAggs} which is set to {&bsol;tt true} and in the {&bsol;it
targetlist}. The {&bsol;tt expr} field of the second {&bsol;tt TLE} node of the
{&bsol;it targetlist} shown in figure &bsol;ref{parse_having} does not point
directly to a {&bsol;tt VAR} node but to an {&bsol;tt Aggreg} node representing
the {&bsol;it aggregate function} used in the query.

A check is made that every attribute grouped for appears only without
an {&bsol;it aggregate function} in the {&bsol;it targetlist} and that every
attribute that appears without an {&bsol;it aggregate function} in the
{&bsol;it targetlist} is grouped for.
%

&bsol;pagebreak 

&bsol;subsubsection{The Rewrite System}

The rewriting system does not make any changes to the {&bsol;it querytree}
as long as the query involves just {&bsol;it base tables}. If any {&bsol;it
views} are present the query is rewritten to access the tables
specified in the {&bsol;it view definition}.
%
&bsol;subsubsection{Planner/Optimizer}
Whenever an {&bsol;it aggregate function} is involved in a query (which is
indicated by the {&bsol;tt hasAggs} flag set to {&bsol;tt true}) the planner
creates a {&bsol;it plantree} whose top node is an {&bsol;tt AGG} node. The {&bsol;it
targetlist} is searched for {&bsol;it aggregate functions} and for every
function that is found, a pointer to the corresponding {&bsol;tt Aggreg}
node is added to a list which is finally attached to the field {&bsol;tt aggs} of
the {&bsol;tt AGG} node. This list is needed by the {&bsol;it executor} to know which
{&bsol;it aggregate functions} are present and have to be
handled.

The {&bsol;tt AGG} node is followed by a {&bsol;tt GRP} node. The implementation
of the {&bsol;it grouping} logic needs a sorted table for its operation so
the {&bsol;tt GRP} node is followed by a {&bsol;tt SORT} node. The {&bsol;tt SORT}
operation gets its tuples from a kind of {&bsol;tt Scan} node (if no
indices are present this will be a simple {&bsol;tt SeqScan} node). Any
qualifications present are attached to the {&bsol;tt Scan} node. Figure
&bsol;ref{plan_having} shows the {&bsol;it plan} created for the query given in
example &bsol;ref{having}.

&bsol;begin{figure}[ht]
&bsol;begin{center}
&bsol;epsfig{figure=figures/plan_having.ps}
&bsol;caption{{&bsol;it Plantree} for the query of example &bsol;ref{having}}
&bsol;label{plan_having}
&bsol;end{center}
&bsol;end{figure}

Note that every node has its own {&bsol;it targetlist} which may differ from the
one of the node above or below.  The field {&bsol;tt varattno} of every
{&bsol;tt VAR} node included in a {&bsol;it targetlist} contains a number representing
the position of the attribute's value in the tuple of the current node.

&bsol;pagebreak
&bsol;clearpage

&bsol;subsubsection{Executor}

The {&bsol;it executor} uses the function {&bsol;tt execAgg()} to execute {&bsol;tt AGG}
nodes. As described earlier it uses one main function {&bsol;tt
ExecProcNode} which is called recursively to execute subtrees. The
following steps are performed by {&bsol;tt execAgg()}:
%
&bsol;begin{itemize}
%
<step> The list attached to the field {&bsol;tt aggs} of the {&bsol;tt AGG} node is
examined and for every {&bsol;it aggregate function} included the {&bsol;it transition
functions} are fetched from a {&bsol;it function table}. Calculating the
value of an {&bsol;it aggregate function} is done using three functions:
%
&bsol;begin{itemize}
<step> The {&bsol;it first transition function} {&bsol;tt xfn1} is called with the
current value of the attribute the {&bsol;it aggregate function} is applied
to and changes its internal state using the attribute's value given as
an argument.
%
<step> The {&bsol;it second transition function} {&bsol;tt xfn2} is called without any
arguments and changes its internal state only according to internal rules.
%
<step> The {&bsol;it final function} {&bsol;tt finalfn} takes the final states of {&bsol;tt
xfn1} and {&bsol;tt xfn2} as arguments and finishes the {&bsol;it aggregation}.
&bsol;end{itemize}
%
&bsol;begin{example} Recall the functions necessary to implement the
{&bsol;it aggregate function} {&bsol;tt avg} building the average over all
values of an attribute in a group (see section &bsol;ref{ext_agg} {&bsol;it
Extending Aggregates}):
%
&bsol;begin{itemize}
%
<step> The first transition function {&bsol;tt xfn1} has to be a function that
takes the actual value of the attribute {&bsol;tt avg} is applied to as an
argument and adds it to the internally stored sum of previous
calls.
%
<step> The second transition function {&bsol;tt xfn2} only increases an internal
counter every time it is called. 
%
<step> The final function {&bsol;tt finalfn} divides the result of {&bsol;tt xfn1} by
the counter of {&bsol;tt xfn2} to calculate the average.
%
&bsol;end{itemize}
%
&bsol;end{example}
%
Note that {&bsol;tt xfn2} and {&bsol;tt finalfn} may be absent (e.g. for the
{&bsol;it aggregate function} {&bsol;tt sum} which simply sums up all values of
the given attribute within a group. &bsol;&bsol;
&bsol;&bsol;
{&bsol;tt execAgg()} creates an array containing one entry for every {&bsol;it
aggregate function} found in the list attached to the field {&bsol;tt
aggs}. The array will hold information needed for the execution of
every {&bsol;it aggregate function} (including the {&bsol;it transition functions}
described above).
%
<step> The following steps are executed in a loop as long as there are
still tuples returned by the subplan (i.e. as long as there are still
tuples left in the current group). When there are no tuples left
in the group a {&bsol;tt NULL} pointer is returned indicating the end of the
group.
%
&bsol;begin{itemize}
<step> A new tuple from the subplan (i.e. the {&bsol;it plan} attached to the
field {&bsol;tt lefttree}) is fetched by recursively calling {&bsol;tt
ExecProcNode()} with the subplan as argument.
%
<step> For every {&bsol;it aggregate function} (contained in the array created
before) apply the transition functions {&bsol;tt xfn1} and {&bsol;tt xfn2} to
the values of the appropriate attributes of the current tuple.
&bsol;end{itemize}
%
<step> When we get here, all tuples of the current group have been
processed and the {&bsol;it transition functions} of all {&bsol;it aggregate
functions} have been applied to the values of the attributes. We are
now ready to complete the {&bsol;it aggregation} by applying the {&bsol;it final
function} ({&bsol;tt finalfn}) for every {&bsol;it aggregate function}.
%
<step> Store the tuple containing the new values (the results of the
{&bsol;it aggregate functions}) and hand it back.
&bsol;end{itemize}
%
Note that the procedure described above only returns one tuple
(i.e. it processes just one group and when the end of the group is
detected it processes the {&bsol;it aggregate functions} and hands back one
tuple). To retrieve all tuples (i.e. to process all groups) the
function {&bsol;tt execAgg()} has to be called (returning a new tuple every
time) until it returns a {&bsol;tt NULL} pointer indicating that there are
no groups left to process.

&bsol;subsection{How the Having Clause is Implemented}

The basic idea of the implementation is to attach the {&bsol;it operator tree}
built for the {&bsol;it having clause} to the field {&bsol;tt qpqual} of
node {&bsol;tt AGG} (which is the top node of the query tree). Now the executor
has to evaluate the new {&bsol;it operator tree} attached to {&bsol;tt qpqual} for
every group processed. If the evaluation returns {&bsol;tt true} the group
is taken into account otherwise it is ignored and the next group will
be examined. &bsol;&bsol;
&bsol;&bsol;
In order to implement the {&bsol;it having clause} a variety of changes
have been made to the following stages:
%
&bsol;begin{itemize}
<step> The {&bsol;it parser stage} has been modified slightly to build up and
transform an {&bsol;it operator tree} for the {&bsol;it having clause}.
%
<step> The {&bsol;it rewrite system} has been adapted to be able to use {&bsol;it
views} with the {&bsol;it having logic}.
%
<step> The {&bsol;it planner/optimizer}  now takes the {&bsol;it operator tree} of
the {&bsol;it having clause} and attaches it to the {&bsol;tt AGG} node (which
is the top node of the {&bsol;it queryplan}).
%
<step> The {&bsol;it executor} has been modified to evaluate the {&bsol;it operator tree}
(i.e. the internal representation of the {&bsol;it having
qualification}) attached to the {&bsol;tt AGG} node and the results of the
{&bsol;it aggregation} are only considered if the evaluation returns {&bsol;tt true}.
&bsol;end{itemize}
%
In the following sections we will describe the changes made to every
single stage in detail.

&bsol;subsubsection{The Parser Stage}

The grammar rules of the {&bsol;it parser} defined in {&bsol;tt gram.y} did not
require any changes (i.e. the rules had already been prepared for the
{&bsol;it having clause}). The {&bsol;it operator tree} built up for the {&bsol;it having
clause} is attached to the field {&bsol;tt havingClause} of the {&bsol;tt
SelectStmt} node handed back by the {&bsol;it parser}. &bsol;&bsol;
&bsol;&bsol;
The {&bsol;it transformation} procedures applied to the tree handed back by
the {&bsol;it parser} transform the {&bsol;it operator tree} attached to the field
{&bsol;tt havingClause} using exactly the same functions used for the
transformation of the {&bsol;it operator tree} for the {&bsol;it where clause}. This
is possible because both trees are built up by the same grammar rules
of the {&bsol;it parser} and are therefore compatible. Additional checks
that make sure that the {&bsol;it having clause} involves at least one
{&bsol;it aggregate function} etc. are performed at a later point in time
in the {&bsol;it planner/optimizer} stage. &bsol;&bsol;
&bsol;&bsol;
The necessary changes have been applied to the following functions
included in the file {&bsol;tt
$&bsol;ldots$/src/backend/parser/analyze.c}. Note, that only the relevant
parts of the affected code are presented instead of the whole
functions. Every added source line will be marked by a {&bsol;tt '+'} at the
beginning of the line and every changed source line will be marked by
a {&bsol;tt '!'} throughout the following code listings. Whenever a part of
the code that is not relevant at the moment is skipped, three
vertical dots are inserted instead.
%
&bsol;pagebreak
%
&bsol;begin{itemize}
<step> {&bsol;tt transformInsertStmt()} &bsol;&bsol;
This function becomes is invoked every time a SQL {&bsol;tt insert}
statement involving a {&bsol;tt select} is used like the following example
illustrates:
%
&bsol;begin{verbatim}
  insert into t2
  select x, y
  from t1;
&bsol;end{verbatim}
%
Two statements have been added to this function. The first one
performs the transformation of the {&bsol;it operator tree} attached to the
field {&bsol;tt havingClause} using the function {&bsol;tt
transformWhereClause()} as done for the {&bsol;it where clause}. It is
possible to use the same function for both clauses, because they are
both built up by the same {&bsol;it grammar rules} given in {&bsol;tt gram.y}
and are therefore compatible.

The second statement makes sure, that {&bsol;it aggregate functions} are
involved in the query whenever a {&bsol;it having clause} is used,
otherwise the query could have been formulated using only a {&bsol;it where
clause}.
%
&bsol;begin{verbatim}
  static Query *
  transformInsertStmt(ParseState *pstate, 
                      InsertStmt *stmt)
  {
    /* make a new query tree */
    Query *qry = makeNode(Query);
                            .
                            .
                            .
    /* fix where clause */
    qry->qual = transformWhereClause(pstate, 
                                     stmt->whereClause);

+   /* The havingQual has a similar meaning as "qual" in 
+    * the where statement. So we can easily use the  
+    * code from the "where clause" with some additional
+    * traversals done in .../optimizer/plan/planner.c 
+    */
+   qry->havingQual = transformWhereClause(pstate, 
+                                   stmt->havingClause);     
                            .
                            .
                            .
+   /* If there is a havingQual but there are no 
+    * aggregates, then there is something wrong with 
+    * the query because having must contain aggregates 
+    * in its expressions! Otherwise the query could 
+    * have been formulated using the where clause.
+    */
+   if((qry->hasAggs == false) && 
+      (qry->havingQual != NULL))
+   {
+     elog(ERROR,"This is not a valid having query!");
+     return (Query *)NIL;
+   }
    return (Query *) qry;
  }
&bsol;end{verbatim}
%
<step> {&bsol;tt transformSelectStmt()} &bsol;&bsol;
Exactly the same statements added to the function {&bsol;tt
transformInsertStmt()} above have been added here as well.
%
&bsol;begin{verbatim}
  static Query *
  transformSelectStmt(ParseState *pstate, 
                      SelectStmt *stmt)
  {
    Query  *qry = makeNode(Query);

    qry->commandType = CMD_SELECT;
                            .
                            .
                            .
    qry->qual = transformWhereClause(pstate, 
                                     stmt->whereClause);

+   /* The havingQual has a similar meaning as "qual" in 
+    * the where statement. So we can easily use the  
+    * code from the "where clause" with some additional
+    * traversals done in .../optimizer/plan/planner.c 
+    */
+   qry->havingQual = transformWhereClause(pstate, 
+                                   stmt->havingClause);     
                            .
                            .
                            .
+   /* If there is a havingQual but there are no 
+    * aggregates, then there is something wrong with 
+    * the query because having must contain aggregates 
+    * in its expressions! Otherwise the query could 
+    * have been formulated using the where clause.
+    */
+   if((qry->hasAggs == false) && 
+      (qry->havingQual != NULL))
+   {
+     elog(ERROR,"This is not a valid having query!");
+     return (Query *)NIL;
+   }
    return (Query *) qry;
  }
&bsol;end{verbatim}
%
&bsol;end{itemize}


&bsol;subsubsection{The Rewrite System}

This section describes the changes to the {&bsol;it rewrite system} of
<productname>Postgres</productname> that have been necessary to support the use of {&bsol;it views}
within queries using a {&bsol;it having clause} and to support the
definition of {&bsol;it views} by queries using a {&bsol;it having clause}.

As described in section &bsol;ref{view_impl} {&bsol;it Techniques To Implement
Views} a query rewrite technique is used to implement {&bsol;it
views}. There are two cases to be handled within the {&bsol;it rewrite
system} as far as the {&bsol;it having clause} is concerned:
%
&bsol;pagebreak
%
&bsol;begin{itemize}
<step> The {&bsol;it view definition} does not contain a {&bsol;it having clause}
but the queries evaluated against this view may contain {&bsol;it having
clauses}.
<step> The {&bsol;it view definition} contains a {&bsol;it having clause}. In this
case queries evaluated against this view must meet some
restrictions as we will describe later.
&bsol;end{itemize}
%
&bsol;paragraph{No having clause in the view definition:} First we will
look at  the changes necessary to support queries using a
{&bsol;it having clause} against a {&bsol;it view} defined without
a {&bsol;it having clause}. &bsol;&bsol;
&bsol;&bsol;
Let the following view definition be given:
%
&bsol;begin{verbatim}
  create view test_view
  as select sno, pno
     from sells
     where sno > 2;
&bsol;end{verbatim}
%
and the following query made against <literal>test_view</literal>:
%
&bsol;begin{verbatim}
  select * 
  from testview
  where sno <> 5;
&bsol;end{verbatim}
%
The query will be rewritten to:
%
&bsol;begin{verbatim}
  select sno, pno
  from sells
  where sno > 2 and
        sno <> 5;
&bsol;end{verbatim}
%
The query given in the definition of the {&bsol;it view} <literal>test_view</literal>
is the {&bsol;it backbone} of the rewritten query. The {&bsol;it targetlist} is taken
from the user's query and also the {&bsol;it where qualification } of the
user's query is added to the {&bsol;it where qualification} of the new
query by using an {&bsol;tt AND} operation. &bsol;&bsol;
&bsol;&bsol;
Now consider the following query:
%
&bsol;begin{verbatim}
  select sno, count(pno)
  from testview
  where sno <> 5
  group by sno
  having count(pno) > 1;  
&bsol;end{verbatim}
%
From now on it is no longer sufficient to add just the {&bsol;it where
clause} and the {&bsol;it targetlist} of the user's query to the new query. The
{&bsol;it group clause} and the {&bsol;it having qualification} also have to be
added to the rewritten query:
%
&bsol;begin{verbatim}
  select sno, count(pno)
  from sells
  where sno > 2 and
        sno <> 5
  group by sno
  having count(pno) > 1;
&bsol;end{verbatim}
%
&bsol;pagebreak

&bsol;noindent Several changes that have already been applied to the {&bsol;it
targetlist} and the {&bsol;it where clause} also have to be applied to the
{&bsol;it having clause}. Here is a collection of all {&bsol;it additional} steps that
have to be performed in order to rewrite a query using a {&bsol;it having
clause} against a simple {&bsol;it view} (i.e. a {&bsol;it view} whose
definition does not use any {&bsol;it group} and {&bsol;it having clauses}):
%
&bsol;begin{itemize}
%
<step> Rewrite the subselects contained in the {&bsol;it having clause} if any are
present.
%
<step> Adapt the {&bsol;tt varno} and {&bsol;tt varattno} fields of all {&bsol;tt
VAR} nodes contained in the {&bsol;it operator tree} representing the {&bsol;it
having clause} in the same way as it has been done for the tree
representing the {&bsol;it where clause}. The {&bsol;tt varno} fields are changed
to use the {&bsol;it base tables} given in the {&bsol;it view definition} (which
have been inserted into the {&bsol;it range table entry list} in the
meantime) instead of the {&bsol;it virtual tables}. The positions of
the attributes used in the {&bsol;it view} may differ from the positions of
the corresponding attributes in the {&bsol;it base tables}. That's why the
{&bsol;tt varattno} fields also have to be adapted.
%
<step> Adapt the {&bsol;tt varno} and {&bsol;tt varattno} fields of all {&bsol;tt
VAR} nodes contained in the {&bsol;tt groupClause} of the user's query in
the way and for the reasons described above.
%
<step> Attach the tree representing the {&bsol;it having qualification} (which is
currently attached to the field {&bsol;tt havingClause} of the {&bsol;tt Query}
node for the user's query) to the field {&bsol;tt havingClause} of the {&bsol;tt
Query} node for the new (rewritten) query.
%
<step> Attach the list representing the {&bsol;it group clause} (currently
attached to the field {&bsol;tt groupClause} of the {&bsol;tt Query} node for
the user's query) to the field {&bsol;it group clause} of the node for the
new (rewritten) query.
%
&bsol;end{itemize} 

&bsol;paragraph{The view definition contains a having clause:}  Now we will
look at the problems that can arise using {&bsol;it views} that are
defined using a query involving a {&bsol;it having clause}. &bsol;&bsol;
&bsol;&bsol;
Let the following {&bsol;it view definition} be given:
%
&bsol;begin{verbatim}
  create view test_view
  as select sno, count(pno) as number
     from sells
     where sno > 2
     group by sno
     having count(pno) > 1;
&bsol;end{verbatim}
%
Simple queries against this {&bsol;it view} will not cause any troubles:
%
&bsol;begin{verbatim}
  select * 
  from test_view
  where sno <> 5;
&bsol;end{verbatim}
%
This query can easily be rewritten by adding the {&bsol;it where
qualification} of the user's query ({&bsol;tt sno $<>$ 5}) to the {&bsol;it
where qualification} of the {&bsol;it view definition's } query. &bsol;&bsol;
&bsol;&bsol;
The next query is also simple but it will cause troubles when
it is evaluated against the above given {&bsol;it view definition}:
%
&bsol;begin{verbatim}
  select * 
  from test_view
  where number > 1; /* count(pno) in the view def.
                     * is called  number here */
&bsol;end{verbatim}
%
&bsol;pagebreak
The currently implemented techniques for query rewriting will rewrite
the query to:
%
&bsol;begin{verbatim}
  select *
  from sells
  where sno > 2 and
        count(pno) > 1
  group by sno         
  having count(pno) > 1;
&bsol;end{verbatim}
%
which is an invalid query because an {&bsol;it aggregate function} appears
in the {&bsol;it where clause}. &bsol;&bsol;
&bsol;&bsol;
Also the next query will cause troubles:
%
&bsol;begin{verbatim}
  select pno, count(sno)
  from test_view
  group by pno;
&bsol;end{verbatim}
%
As you can see this query does neither involve a {&bsol;it where clause}
nor a {&bsol;it having clause} but it contains a {&bsol;it group clause} which
groups by the attribute {&bsol;tt pno}. The query in the definition of the
{&bsol;it view} also contains a {&bsol;it group clause} that groups by the
attribute {&bsol;tt sno}. The two {&bsol;it group clauses} are in conflict with
each other and therefore the query cannot be rewritten to a form that
would make sense.&bsol;&bsol;
&bsol;&bsol;
{&bsol;bf Note:} There is no solution to the above mentioned problems at the
moment and it does not make sense to put much effort into that because
the implementation of the support for queries like:
%
&bsol;begin{verbatim}
  select pno_count, count(sno) 
  from ( select sno, count(pno) as pno_count
         from sells 
         where sno > 2
         group by sno
         having count(pno) > 1)
  group by pno_count;
&bsol;end{verbatim}
%
(which is part of the SQL92 standard) will automatically also solve
these problems. &bsol;&bsol;
&bsol;&bsol;
In the next part of the current section we will present the changes
applied to the source code in order to realize the above described
items. Note that it is not necessary to understand the meaning of
every single source line here and therefore we will not discuss
detailed questions like "Why has the variable {&bsol;tt varno} to be
increased by 3?". Questions like that belong to a chapter dealing
with the implementation of {&bsol;it views} in <productname>Postgres</productname> and to be able to
answer them it would be necessary to know all the functions and not
only those described here. The fact important for us is to make sure,
that whatever is applied to the {&bsol;it targetlist} and the data
structures representing the {&bsol;it where clause} is also applied to the
data structures for the {&bsol;it having clause}. There are three files
affected: &bsol;&bsol;
&bsol;&bsol;
&bsol;indent {&bsol;tt $&bsol;ldots$/src/backend/rewrite/rewriteHandler.c} &bsol;&bsol;
&bsol;indent {&bsol;tt $&bsol;ldots$/src/backend/rewrite/rewriteManip.c} &bsol;&bsol;
&bsol;indent {&bsol;tt $&bsol;ldots$/src/backend/commands/view.c} &bsol;&bsol;
&bsol;&bsol;
Here is a description of the changes made to the functions contained
in the file {&bsol;tt $&bsol;ldots$/src/backend/rewrite/rewriteHandler.c}:
%
&bsol;pagebreak
%
&bsol;begin{itemize}
<step> {&bsol;tt ApplyRetrieveRule()} &bsol;&bsol;
This function becomes invoked whenever a {&bsol;tt select} statement
against a {&bsol;it view} is recognized and applies the {&bsol;it rewrite rule}
stored in the {&bsol;it system catalogs}. The additional source lines given
in the listing below make sure that the functions {&bsol;tt
OffsetVarNodes()} and {&bsol;tt ChangeVarNodes()} that are invoked for the
{&bsol;it where clause} and the {&bsol;it targetlist} of the query given in the
{&bsol;it view definition} are also called for the {&bsol;it having clause} and
the {&bsol;it group clause} of the query in the {&bsol;it view
definition}. These functions adapt the {&bsol;tt varno} and {&bsol;tt varattno}
fields of the {&bsol;tt VAR} nodes involved.

The additional source lines at the end of {&bsol;tt ApplyRetrieveRule()}
attach the data structures representing the {&bsol;it having clause} and
the {&bsol;it group clause} of the query in the {&bsol;it view definition} to
the rewritten {&bsol;it parsetree}. As mentioned earlier, a {&bsol;it view
definition} involving a {&bsol;it group clause} will cause troubles
whenever a query using a different {&bsol;it group clause} against this
{&bsol;it view} is executed. There is no mechanism preventing these
troubles included at the moment.

Note that the functions {&bsol;tt OffsetVarNodes()} , {&bsol;tt ChangeVarNodes()}
and {&bsol;tt AddHavingQual()} appearing in {&bsol;tt ApplyRetrieveRule()} are
described at a later point in time.
%
&bsol;begin{verbatim}
  static void
  ApplyRetrieveRule(Query *parsetree, RewriteRule *rule,
                    int rt_index, int relation_level,
                    Relation relation, int *modified)
  {
    Query  *rule_action = NULL;
    Node   *rule_qual;
    List   *rtable,
                            .
                            .
                            .
    OffsetVarNodes((Node *) rule_action->targetList, 
                   rt_length);
    OffsetVarNodes(rule_qual, rt_length);
        
+   OffsetVarNodes((Node *) rule_action->groupClause, 
+                  rt_length);
+   OffsetVarNodes((Node *) rule_action->havingQual, 
+                  rt_length);
                            .
                            .
                            .
    ChangeVarNodes(rule_qual, 
                   PRS2_CURRENT_VARNO + rt_length, 
                   rt_index, 0);

+   ChangeVarNodes((Node *) rule_action->groupClause,
+                  PRS2_CURRENT_VARNO + rt_length, 
+                  rt_index, 0);
+   ChangeVarNodes((Node *) rule_action->havingQual,
+                  PRS2_CURRENT_VARNO + rt_length, 
+                  rt_index, 0);
                            .
                            .
                            .
&bsol;end{verbatim}
&bsol;pagebreak
&bsol;begin{verbatim}
    if (*modified && !badsql) 
    {
      AddQual(parsetree, rule_action->qual);
+     /* This will only work if the query made to the 
+      * view defined by the following groupClause 
+      * groups by the same attributes or does not use 
+      * groups at all! 
+      */
+      if (parsetree->groupClause == NULL)
+         parsetree->groupClause = 
+                    rule_action->groupClause;
+      AddHavingQual(parsetree, 
+                    rule_action->havingQual);
+      parsetree->hasAggs = 
+         (rule_action->hasAggs || parsetree->hasAggs);
+      parsetree->hasSubLinks = 
+         (rule_action->hasSubLinks || 
+          parsetree->hasSubLinks);
    }
  }
&bsol;end{verbatim}
%
<step> {&bsol;tt QueryRewriteSubLink()} &bsol;&bsol;
This function is called by {&bsol;tt QueryRewrite()} to process possibly
contained subqueries first. It searches for nested queries by
recursively tracing through the {&bsol;it parsetree} given as argument. The
additional statement makes sure that the {&bsol;it having clause} is also
examined.
%
&bsol;begin{verbatim}
  static void
  QueryRewriteSubLink(Node *node)
  {
    if (node == NULL)
       return;
    switch (nodeTag(node))
    {
      case T_SubLink:
      {
                            .
                            .
                            .
         QueryRewriteSubLink((Node *) query->qual);
+        QueryRewriteSubLink((Node *) 
+                            query->havingQual);
                            .
                            .
                            .
      }
                            .
                            .
                            .
    }
    return;
  }
&bsol;end{verbatim}
%
&bsol;pagebreak
%
<step> {&bsol;tt QueryRewrite()} &bsol;&bsol;
This function takes the {&bsol;it parsetree} of a query and rewrites it
using <productname>Postgres</productname>'s {&bsol;it rewrite system}. Before the query itself can be
rewritten, subqueries that are possibly part of the query have to be
processed. Therefore the function {&bsol;tt  QueryRewriteSubLink()} is
called for the {&bsol;it where clause} and for the {&bsol;it having clause}.
%
&bsol;begin{verbatim}
  List *
  QueryRewrite(Query *parsetree)
  {
    QueryRewriteSubLink(parsetree->qual);       
+   QueryRewriteSubLink(parsetree->havingQual);
    return QueryRewriteOne(parsetree);
  } 
&bsol;end{verbatim}
%
&bsol;end{itemize}
%
Here we present the changes applied to the functions that are contained
in the file {&bsol;tt $&bsol;ldots$/src/backend/rewrite/rewriteManip.c}:
%
&bsol;begin{itemize}
%
<step> {&bsol;tt OffsetVarNodes()} &bsol;&bsol;
Recursively steps through the {&bsol;it parsetree} given as the first
argument and increments the {&bsol;tt varno} and {&bsol;tt varnoold} fields of
every {&bsol;tt VAR} node found by the {&bsol;it offset} given as the second
argument. The additional statements are necessary to be able to handle
{&bsol;tt GroupClause} nodes and {&bsol;tt Sublink} nodes that may appear in the {&bsol;it
parsetree} from now on.
%
&bsol;begin{verbatim}
  void
  OffsetVarNodes(Node *node, int offset)
  {
     if (node == NULL)
        return;
     switch (nodeTag(node))
     {
                            .
                            .
                            .
+       /* This has to be done to make queries using 
+        * groupclauses work on views 
+        */
+        case T_GroupClause:
+        {
+          GroupClause *group = (GroupClause *) node;
+                         
+          OffsetVarNodes((Node *)(group->entry), 
+                         offset);
+        }
+        break;
                            .
                            .
                            .
+        case T_SubLink:
+        {
+          SubLink *sublink = (SubLink *) node;
+          List *tmp_oper, *tmp_lefthand;                               
+
&bsol;end{verbatim}
&bsol;pagebreak
&bsol;begin{verbatim}
+          /* We also have to adapt the variables used 
+           * in sublink->lefthand and sublink->oper 
+           */
+          OffsetVarNodes((Node *)(sublink->lefthand), 
+                         offset);
+
+          /* Make sure the first argument of 
+           * sublink->oper points to the same var as 
+           * sublink->lefthand does otherwise we will 
+           * run into troubles using aggregates (aggno 
+           * will not be set correctly) 
+           */
+          tmp_lefthand = sublink->lefthand;                            
+          foreach(tmp_oper, sublink->oper)
+          {                                
+            lfirst(((Expr *)lfirst(tmp_oper))->args) = 
+                                  lfirst(tmp_lefthand);
+            tmp_lefthand = lnext(tmp_lefthand);
+          }                                                            
+        }
+        break;
                            .
                            .
                            .
     }
  }
&bsol;end{verbatim}
%
<step> {&bsol;tt ChangeVarNodes()} &bsol;&bsol;
This function is similar to the above described function {&bsol;tt
OffsetVarNodes()} but instead of incrementing the fields {&bsol;tt varno}
and {&bsol;tt varnoold} of {&bsol;it all} {&bsol;tt VAR} nodes found, it processes
only those {&bsol;tt VAR} nodes whose {&bsol;tt varno} value matches the
parameter {&bsol;tt old&bsol;_varno} given as argument and whose {&bsol;tt
varlevelsup} value matches the parameter {&bsol;tt sublevels&bsol;_up}. Whenever
such a node is found, the {&bsol;tt varno} and {&bsol;tt varnoold} fields are
set to the value given in the parameter {&bsol;tt new&bsol;_varno}. The
additional statements are necessary to be able to handle {&bsol;tt GroupClause}
and {&bsol;tt Sublink} nodes.
%
&bsol;begin{verbatim}
  void
  ChangeVarNodes(Node *node, int old_varno, 
                 int new_varno, int sublevels_up)
  {
    if (node == NULL)
       return;
    switch (nodeTag(node))
    {
                            .
                            .
                            .
+     /* This has to be done to make queries using 
+      * groupclauses work on views */
+     case T_GroupClause:
+     {
+       GroupClause  *group = (GroupClause *) node;
+                       
&bsol;end{verbatim}
&bsol;pagebreak
&bsol;begin{verbatim}  
+       ChangeVarNodes((Node *)(group->entry),
+                      old_varno, new_varno, 
+                      sublevels_up);
+     }
+     break;
                            .
                            .
                            .
      case T_Var:
      {
                            .
                            .
                            .
        /* This is a hack: Whenever an attribute
         * from the "outside" query is used within
         * a nested subquery, the varlevelsup will 
         * be >0. Nodes having varlevelsup > 0 are  
         * forgotten to be processed. The call to 
         * OffsetVarNodes() should really be done at 
         * another place but this hack makes sure 
         * that also those VAR nodes are processed.
         */
+       if (var->varlevelsup > 0) 
+          OffsetVarNodes((Node *)var,3);
      }
      break;
                            .
                            .
                            .
      case T_SubLink:
      {
                            .
                            .
                            .
+       ChangeVarNodes((Node *) query->havingQual, 
+                      old_varno, new_varno,
+                      sublevels_up);
+       ChangeVarNodes((Node *) query->targetList, 
+                      old_varno, new_varno,
+                      sublevels_up);
+
+       /* We also have to adapt the variables used in 
+        * sublink->lefthand and sublink->oper 
+        */
+       ChangeVarNodes((Node *) (sublink->lefthand), 
+                      old_varno, new_varno,
+                      sublevels_up);
      }
      break;
                            .
                            .
                            .
    }
  }
&bsol;end{verbatim}
%
<step> {&bsol;tt AddHavingQual()} &bsol;&bsol;
This function adds the {&bsol;it operator tree} given by the parameter {&bsol;tt
havingQual} to the one attached to the field {&bsol;tt havingQual} of the
{&bsol;it parsetree} given by the parameter {&bsol;tt parsetree}. This is done
by adding a new {&bsol;tt AND} node and attaching the old and the new {&bsol;it
operator tree} as arguments to it. {&bsol;tt AddHavingQual()} has not been
existing until version 6.3.2. It has been created for the {&bsol;it having logic}.
%
&bsol;begin{verbatim}
  void
  AddHavingQual(Query *parsetree, Node *havingQual)
  {
    Node  *copy, *old;

    if (havingQual == NULL)
       return;

    copy = havingQual;

    old = parsetree->havingQual;
    if (old == NULL)
        parsetree->havingQual = copy;
    else
        parsetree->havingQual =
            (Node *) make_andclause(
                       makeList(parsetree->havingQual, 
                                copy, -1));
  }
&bsol;end{verbatim}
%
<step> {&bsol;tt AddNotHavingQual()} &bsol;&bsol;
This function is similar to the above described function  {&bsol;tt
AddHavingQual()}. It also adds the {&bsol;it operator tree} given by the
parameter {&bsol;tt havingQual} but prefixes it by a {&bsol;tt NOT} node. {&bsol;tt
AddNotHavingQual()} has also not been existing until version 6.3.2 and has been
created for the {&bsol;it having logic}.
%
&bsol;begin{verbatim}
  void
  AddNotHavingQual(Query *parsetree, 
                   Node *havingQual)
  {
    Node *copy;

    if (havingQual == NULL)
       return;

    copy = (Node *) make_notclause((Expr *)havingQual);
    AddHavingQual(parsetree, copy);
}
&bsol;end{verbatim}
%
<step> {&bsol;tt nodeHandleViewRule()} &bsol;&bsol;
This function is called by {&bsol;tt HandleViewRule()}. It replaces all
{&bsol;tt VAR} nodes of the {&bsol;it user query} evaluated against the {&bsol;it
view} (the fields of these {&bsol;tt VAR} nodes represent the positions of
the attributes in the {&bsol;it virtual} table) by {&bsol;tt VAR} nodes that
have already been prepared to represent the positions of the
corresponding attributes in the {&bsol;it physical} tables (given in the
{&bsol;it view definition}). The additional statements make sure that {&bsol;tt
GroupClause} nodes and {&bsol;tt Sublink} nodes are handled correctly.

&bsol;begin{verbatim}
  static void
  nodeHandleViewRule(Node **nodePtr, List *rtable, 
                     List *targetlist, int rt_index,
                     int *modified, int sublevels_up)
  {
    Node *node = *nodePtr;
    if (node == NULL)
       return;
    switch (nodeTag(node))
    {
                            .
                            .
                            .
+     /* This has to be done to make queries using 
+      * groupclauses work on views 
+      */
+     case T_GroupClause:
+     {
+       GroupClause  *group = (GroupClause *) node;
+       nodeHandleViewRule((Node **) (&(group->entry)), 
+                          rtable, targetlist, rt_index, 
+                          modified, sublevels_up);
+     }
+     break;
                            .
                            .
                            .
      case T_Var:
      {
                            .
                            .
                            .
        if (n == NULL)
        {
          *nodePtr = make_null(((Var *)node)->vartype);
        }                           
        else
+       /* This is a hack: The varlevelsup of the 
+        * original variable and the new one should 
+        * be the same. Normally we adapt the node 
+        * by changing a pointer to point to a var 
+        * contained in 'targetlist'. In the 
+        * targetlist all varlevelsups are 0 so if 
+        * we want to change it to the original 
+        * value we have to copy the node before! 
+        * (Maybe this will cause troubles with some 
+        * sophisticated queries on views?) 
+        */
+       {
+         if(this_varlevelsup>0)
+         {
+            *nodePtr = copyObject(n);
+         }
+         else 
+         {
+           *nodePtr = n;
+         }
+         ((Var *)*nodePtr)->varlevelsup = 
+                            this_varlevelsup;
+       }
        *modified = TRUE;
      }
      break;
                            .
                            .
                            .
      case T_SubLink:
      {
                            .
                            .
                            .
+       nodeHandleViewRule(
+                 (Node **) &(query->havingQual), 
+                 rtable, targetlist, rt_index, 
+                 modified, sublevels_up);
+       nodeHandleViewRule(
+                 (Node **) &(query->targetList), 
+                 rtable, targetlist, rt_index, 
+                 modified, sublevels_up);
+       /* We also have to adapt the variables used 
+        * in sublink->lefthand and sublink->oper 
+        */
+       nodeHandleViewRule(
+                 (Node **) &(sublink->lefthand), 
+                 rtable, targetlist, rt_index, 
+                 modified, sublevels_up);                              
+       /* Make sure the first argument of 
+        * sublink->oper points to the same var as 
+        * sublink->lefthand does otherwise we will 
+        * run into troubles using aggregates 
+        * (aggno will not be set correctly!)
+        */                             
+       pfree(lfirst(((Expr *) 
+                    lfirst(sublink->oper))->args));
+       tmp_lefthand = sublink->lefthand;                               
+       foreach(tmp_oper, sublink->oper)
+       {                                   
+          lfirst(((Expr *) lfirst(tmp_oper))->args) = 
+                                  lfirst(tmp_lefthand);
+          tmp_lefthand = lnext(tmp_lefthand);
+       }                                                               
      }
      break;
                            .
                            .
                            .
    }
  }
&bsol;end{verbatim}
%
<step> {&bsol;tt HandleViewRule()} &bsol;&bsol;
This function calls {&bsol;tt nodeHandleViewRule()} for the {&bsol;it where
clause}, the {&bsol;it targetlist}, the {&bsol;it group clause} and the {&bsol;it
having clause} of the {&bsol;it user query} evaluated against the given
{&bsol;it view}.
%
&bsol;begin{verbatim}
  void
  HandleViewRule(Query *parsetree, List *rtable,
                 List *targetlist, int rt_index,
                 int *modified)
  {
                            .
                            .
                            .
+   /* The variables in the havingQual and 
+    * groupClause also have to be adapted 
+    */
+   nodeHandleViewRule(&parsetree->havingQual, rtable, 
+                      targetlist, rt_index,
+                      modified, 0);
+   nodeHandleViewRule(
+           (Node **)(&(parsetree->groupClause)), 
+           rtable, targetlist, rt_index, modified, 0);
  }
&bsol;end{verbatim}
%
&bsol;end{itemize}
%
The following function is contained in {&bsol;tt
$&bsol;ldots$/src/backend/commands/view.c}:

&bsol;begin{itemize}
%
<step> {&bsol;tt UpdateRangeTableOfViewParse()} &bsol;&bsol;
This function updates the {&bsol;it range table} of the {&bsol;it parsetree}
given by the parameter {&bsol;tt viewParse}. The additional statement makes
sure that the {&bsol;tt VAR} nodes of the {&bsol;it having clause} are modified
in the same way as the {&bsol;tt VAR} nodes of the {&bsol;it where clause} are.
%
&bsol;begin{verbatim}
  static void
  UpdateRangeTableOfViewParse(char *viewName, 
                              Query *viewParse)
  {
                            .
                            .
                            .
    OffsetVarNodes(viewParse->qual, 2);

+   OffsetVarNodes(viewParse->havingQual, 2);
                            .
                            .
                            .
  }
&bsol;end{verbatim}
%
&bsol;end{itemize}


&bsol;subsubsection{Planner/Optimizer}

The {&bsol;it planner} builds a {&bsol;it queryplan} like the one shown in
figure &bsol;ref{plan_having} and in addition to that it takes the {&bsol;it operator
tree} attached to the field {&bsol;tt havingClause} of the {&bsol;tt Query} node
and attaches is to the {&bsol;tt qpqual} field of the {&bsol;tt AGG}
node. 

Unfortunately this is not the only thing to do. Remember from section
&bsol;ref{aggregates} {&bsol;it How Aggregate Functions are Implemented} that
the {&bsol;it targetlist} is searched for {&bsol;it aggregate functions} that
are appended to a list that will be attached to the field {&bsol;tt aggs}
of the {&bsol;tt AGG} node. This was sufficient as long as {&bsol;it aggregate
functions} have only been allowed to appear within the {&bsol;it
targetlist}. Now the {&bsol;it having clause} is another source of {&bsol;it
aggregate functions}. Consider the following example:
%
&bsol;begin{verbatim}
  select sno, max(pno)
  from sells
  group by sno
  having count(pno) > 1;
&bsol;end{verbatim}
%
Here the {&bsol;it aggregate functions} {&bsol;tt max} and {&bsol;tt count} are in
use. If only the {&bsol;it targetlist} is scanned (as it was the case before the
{&bsol;it having clause} had been implemented) we will only find and process the
{&bsol;it aggregate function} {&bsol;tt max}. The second function {&bsol;tt count} is
not processed and therefore any reference to the result of {&bsol;tt count}
from within the {&bsol;it having clause} will fail. The solution to this
problem is to scan the whole {&bsol;it operator tree} representing the {&bsol;it having
clause} for {&bsol;it aggregate functions} not contained in the {&bsol;it targetlist} yet
and add them to the list of {&bsol;it aggregate functions} attached to the
field {&bsol;tt aggs} of the {&bsol;tt AGG} node. The scanning is done by the
function &bsol;mbox{{&bsol;tt check&bsol;_having&bsol;_qual&bsol;_for&bsol;_aggs()}} which steps
recursively through the tree.&bsol;&bsol;
&bsol;&bsol;
While scanning the {&bsol;it having clause} for {&bsol;it aggregate functions}
not contained in the {&bsol;it targetlist} yet, an additional check is made to
make sure that {&bsol;it aggregate functions} are used within
the {&bsol;it having clause} (otherwise the query could have been
formulated using the {&bsol;it where clause}). Consider the following query
which is not a valid SQL92 query:
%
&bsol;begin{verbatim}
  testdb=> select sno, max(pno)
  testdb-> from sells
  testdb-> group by sno
  testdb-> having sno > 1;
  ERROR:  This could have been done in a where clause!!
  testdb=>
&bsol;end{verbatim}
%
There is no need to express this query using a {&bsol;it having clause},
this kind of qualification belongs to the {&bsol;it where clause}:
%
&bsol;begin{verbatim}
  select sno, max(pno)
  from sells
  where sno > 1
  group by sno;
&bsol;end{verbatim}
%
There is still an unsolved problem left. Consider the following query
where we want to know just the supplier numbers ({&bsol;tt sno}) of all
suppliers selling more than one part:
%
&bsol;begin{verbatim}
  select sno
  from sells
  group by sno
  having count(pno) > 1;
&bsol;end{verbatim}
%
The {&bsol;it planner} creates a {&bsol;it queryplan} (like the one shown in figure
&bsol;ref{plan_having}) where the {&bsol;it targetlists} of all nodes involved contain
only entries of those attributes listed after the {&bsol;tt select} keyword of
the query. Looking at the example above this means that the
{&bsol;it targetlists} of the {&bsol;tt AGG} node, the {&bsol;tt GRP} node the {&bsol;tt SORT}
node and the {&bsol;tt SeqScan} node contain only the entry for the
attribute {&bsol;tt sno}. As described earlier the {&bsol;it aggregation logic}
operates on attributes of the tuples returned by the subplan of
the {&bsol;tt AGG} node (i.e. the result of the {&bsol;tt GRP} node). Which
attributes are contained in the tuples handed back by a subplan is
determined by the {&bsol;it targetlist}. In the case of our example the attribute
{&bsol;tt pno} needed for the {&bsol;it aggregate function} {&bsol;tt count} is not
included and therefore the {&bsol;it aggregation} will fail. 

&bsol;pagebreak

&bsol;noindent The solution to this problem is given in the following
steps:
&bsol;begin{itemize}
<step> Make a copy of the actual {&bsol;it targetlist} of the {&bsol;tt AGG} node.
%
<step> Search the {&bsol;it operator tree} representing the {&bsol;it having clause}
for attributes that are not contained in the {&bsol;it targetlist} of the {&bsol;tt
AGG} node yet and add them to the previously made copy.
%
<step> The extended {&bsol;it targetlist} is used to create the subplan attached to
the {&bsol;tt lefttree} field of the {&bsol;tt AGG} node. That means that the
{&bsol;it targetlists} of the {&bsol;tt GRP} node, of the {&bsol;tt SORT} node and of the
{&bsol;tt SeqScan} node will now contain an entry for the attribute {&bsol;tt
pno}. The {&bsol;it targetlist} of the {&bsol;tt AGG} node itself will not be changed
because we do not want to include the attribute {&bsol;tt pno} into the
result returned by the whole query.
%
&bsol;end{itemize}
Care has to be taken that the {&bsol;tt varattno} fields of the {&bsol;tt VAR}
nodes used in the {&bsol;it targetlists} contain the position of the
corresponding attribute in the  {&bsol;it targetlist} of the subplan (i.e the
subplan delivering the tuples for further processing by the actual
node). &bsol;&bsol;
&bsol;&bsol;
The following part deals with the source code of the new and
changed functions involved in the planner/optimizer stage. The files
affected are: &bsol;&bsol;
&bsol;&bsol;
&bsol;indent {&bsol;tt $&bsol;ldots$/src/backend/optimizer/plan/setrefs.c} &bsol;&bsol;
&bsol;indent {&bsol;tt $&bsol;ldots$/src/backend/optimizer/plan/planner.c} &bsol;&bsol;
&bsol;&bsol;
Since all of the functions presented here are very long and would need
very much space if presented as a whole, we just list the most
important parts. &bsol;&bsol;
&bsol;&bsol;
The following two functions are new and have been
introduced for the {&bsol;it having logic}. They are contained in the file
{&bsol;tt $&bsol;ldots$/src/backend/optimizer/plan/setrefs.c}:
%
&bsol;begin{itemize}
%
<step> {&bsol;tt check&bsol;_having&bsol;_qual&bsol;_for&bsol;_aggs()} &bsol;&bsol;
This function takes the representation of a {&bsol;it having clause} given
by the parameter {&bsol;tt clause}, a {&bsol;it targetlist} given by the
parameter {&bsol;tt subplanTargetList} and a {&bsol;it group clause} given by
the parameter {&bsol;tt groupClause} as arguments and scans the
representation of the {&bsol;it having clause} recursively for {&bsol;it
aggregate functions}. If an {&bsol;it aggregate function} is found it is
attached to a list (internally called {&bsol;tt agg&bsol;_list}) and finally
returned by the function. 

Additionally the {&bsol;tt varno} field of every {&bsol;tt VAR} node found is
set to the position of the corresponding attribute in the {&bsol;it
targetlist} given by {&bsol;tt subplanTargetList}.

If the {&bsol;it having clause} contains a subquery the function also makes
sure, that every attribute from the {&bsol;it main query} that is used
within the subquery also appears in the {&bsol;it group clause} given by
{&bsol;tt groupClause}. If the attribute cannot be found in the {&bsol;it group
clause} an error message is printed to the screen and the query
processing is aborted.
%
&bsol;begin{verbatim}
  List *
  check_having_qual_for_aggs(Node *clause, 
                             List *subplanTargetList, 
                             List *groupClause)
  {
    List *t, *l1;
    List *agg_list = NIL;  
    int  contained_in_group_clause = 0;
  
    if (IsA(clause, Var))
    {
      TargetEntry *subplanVar;      

      subplanVar = match_varid((Var *) clause, 
                               subplanTargetList);      
      /* Change the varattno fields of the 
       * var node to point to the resdom->resnofields 
       * of the subplan (lefttree) 
       */         
      ((Var *) clause)->varattno = 
        subplanVar->resdom->resno;      
      return NIL;      
    }
    else 
      if (is_funcclause(clause) || not_clause(clause)  
          || or_clause(clause) || and_clause(clause))
      {
        int new_length=0, old_length=0;        

        /* This is a function. Recursively call this 
         * routine for its arguments... (i.e. for AND, 
         * OR, ... clauses!)
         */
        foreach(t, ((Expr *) clause)->args)
        {
          old_length=length((List *)agg_list);          
          agg_list = nconc(agg_list,
              check_having_qual_for_aggs(lfirst(t), 
                                 subplanTargetList,
                                 groupClause));          
          if(((new_length=length((List *)agg_list)) == 
              old_length) || (new_length == 0))
          {
            elog(ERROR,"This could have been done 
                                 in a where clause!!");
            return NIL;
          } 
        }
        return agg_list;
      }
      else 
        if (IsA(clause, Aggreg))
        {
          return lcons(clause,
                        check_having_qual_for_aggs(
                            ((Aggreg *)clause)->target, 
                            subplanTargetList,
                            groupClause));                
        }
        else 
                            .
                            .
                            .
  }
&bsol;end{verbatim}
%
<step> {&bsol;tt check&bsol;_having&bsol;_qual&bsol;_for&bsol;_vars()} &bsol;&bsol;
This function takes the representation of a {&bsol;it having clause} given
by the parameter {&bsol;tt clause} and the actual {&bsol;it targetlist}
given by the parameter {&bsol;tt targetlist&bsol;_so&bsol;_far} as arguments and
recursively scans the representation of the {&bsol;it having clause} for
attributes that are not included in the actual {&bsol;it targetlist}
yet. Whenever such an attribute is found it is added to the actual
{&bsol;it targetlist} which is finally returned by the function.

Attributes contained in the {&bsol;it having clause} but not in the {&bsol;it
targetlist} show up with queries like:
%
&bsol;begin{verbatim}
  select sid 
  from  part 
  group by sid 
  having min(pid) > 1;
&bsol;end{verbatim}
%
In the above query the attribute {&bsol;tt pid} is used in the {&bsol;it having
clause} but it does not appear in the {&bsol;it targetlist} (i.e. the list
of attributes after the keyword {&bsol;tt select}). Unfortunately only
those attributes are delivered by the subplan and can therefore be
used within the {&bsol;it having clause}. To become able to handle queries
like that correctly, we have to extend the actual {&bsol;it targetlist} by
those attributes used in the {&bsol;tt having clause} but not already
appearing in the {&bsol;it targetlist}.
%
&bsol;begin{verbatim}
  List *
  check_having_qual_for_vars(Node *clause, 
                             List *targetlist_so_far)
  {
    List     *t;

    if (IsA(clause, Var))
    {
      Rel         tmp_rel;
      
      tmp_rel.targetlist = targetlist_so_far;
      /* Check if the VAR is already contained in the 
       * targetlist 
       */
      if (tlist_member((Var *)clause, 
                  (List *)targetlist_so_far) == NULL)
      {
        add_tl_element(&tmp_rel, (Var *)clause); 
      }             
      return tmp_rel.targetlist;
    }
    else 
      if (is_funcclause(clause) || not_clause(clause)
          || or_clause(clause) || and_clause(clause))
      {
        /* This is a function. Recursively call this 
         * routine for its arguments...
         */
        foreach(t, ((Expr *) clause)->args)
        {
          targetlist_so_far = 
            check_having_qual_for_vars(lfirst(t), 
                            targetlist_so_far);
        }
        return targetlist_so_far;
      }
      else 
        if (IsA(clause, Aggreg))
        {
          targetlist_so_far = 
            check_having_qual_for_vars(
                            ((Aggreg *)clause)->target, 
                            targetlist_so_far);
          return targetlist_so_far;
        }
                            .
                            .
                            .
  }
&bsol;end{verbatim}
%
&bsol;end{itemize}
%
The next function is found in {&bsol;tt
$&bsol;ldots$/src/backend/optimizer/plan/planner.c}:
%
&bsol;begin{itemize}
%
<step> {&bsol;tt union&bsol;_planner()} &bsol;&bsol;
This function creates a {&bsol;it plan} from the {&bsol;it parsetree} given to
it by the parameter {&bsol;tt parse} that can be executed by the {&bsol;it
executor}. 

If {&bsol;it aggregate functions} are present (indicated by {&bsol;tt
parse->hasAggs} set to true) the first step is to extend the {&bsol;it
targetlist} by those attributes that are used within the {&bsol;it having
clause} (if any is present) but do not appear in the {&bsol;it select list}
(Refer to the description of {&bsol;tt check&bsol;_having&bsol;_qual&bsol;_for&bsol;_vars()}
above).

The next step is to call the function {&bsol;tt query&bsol;_planner()} creating
a {&bsol;it plan} without taking the {&bsol;it group clause}, the {&bsol;it aggregate
functions} and the {&bsol;it having clause} into account for the moment.

Next insert a {&bsol;tt GRP} node at the top of the {&bsol;it plan} according
to the {&bsol;it group clause} of the {&bsol;it parsetree} if any is present.  

Add an {&bsol;tt AGG} node to the top of the current {&bsol;it plan} if {&bsol;it
aggregate functions} are present and if a {&bsol;it having clause} is
present additionally perform the following steps:
%
&bsol;begin{itemize}
<step> Perform various transformations to the representation of the
{&bsol;it having clause} (e.g. transform it to CNF, $&bsol;ldots$).
<step> Attach the transformed representation of the {&bsol;it having clause} to the
field {&bsol;tt plan.qual} of the just created {&bsol;tt AGG} node.
<step> Examine the whole {&bsol;it having clause} and search for {&bsol;it
aggregate functions}. This is done using the function {&bsol;tt
check&bsol;_having&bsol;_qual&bsol;_for&bsol;_aggs()} which appends every {&bsol;it aggregate
function} found to a list that is finally returned.
<step> Append the list just created to the list already attached to the
field {&bsol;tt aggs} of the {&bsol;tt AGG} node (this list contains the {&bsol;it
aggregate functions} found in the {&bsol;it targetlist}).
<step> Make sure that  {&bsol;it aggregate functions} do appear in the 
{&bsol;it having clause}. This is done by comparing the length of the list
attached to {&bsol;tt aggs} before and after the call to {&bsol;tt
check&bsol;_having&bsol;_qual&bsol;_for&bsol;_aggs()}.  If the length has not changed, we
know that no {&bsol;it aggregate function} has been detected and that this
query could have been formulated using only a {&bsol;it where clause}. In
this case an error message is printed to the screen and the processing
is aborted.
&bsol;end{itemize}
%
&bsol;pagebreak
%
&bsol;begin{verbatim}
  Plan *
  union_planner(Query *parse)
  {
     List       *tlist = parse->targetList;

+    /* copy the original tlist, we will need the 
+     * original one for the AGG node later on */
+     List *new_tlist = new_unsorted_tlist(tlist); 
                            .
                            .
                            .
+         if (parse->hasAggs)
+         {
+           /* extend targetlist by variables not
+            * contained already but used in the 
+            * havingQual.
+            */
+           if (parse->havingQual != NULL)
+             {
+               new_tlist = 
+                 check_having_qual_for_vars(
+                              parse->havingQual,
+                              new_tlist);
+             }
+         }          
                            .
                            .
                            .
          /* Call the planner for everything
           * but groupclauses and aggregate funcs. 
           */
          result_plan = query_planner(parse,
                                  parse->commandType,
                                  new_tlist,
                                  (List *) parse->qual);
                            .
                            .
                            .
        /* If aggregate is present, insert the AGG node
         */
        if (parse->hasAggs)
        {
          int old_length=0, new_length=0;                
          /* Create the AGG node but use 'tlist' not 
           * 'new_tlist' as target list because we
           * don't want the additional attributes 
           * (only used for the havingQual, see 
           * above) to show up in the result. 
           */
          result_plan = (Plan *) make_agg(tlist, 
                                       result_plan);
                            .
                            .
                            .
+         /* Check every clause of the havingQual for 
+          * aggregates used and append them to 
+          * the list in result_plan->aggs 
+          */
+         foreach(clause, 
+                 ((Agg *) result_plan)->plan.qual)
+         {
+           /* Make sure there are aggregates in the 
+            * havingQual if so, the list must be 
+            * longer after check_having_qual_for_aggs 
+            */
+           old_length = 
+             length(((Agg *) result_plan)->aggs);                 
+                       
+           ((Agg *) result_plan)->aggs = 
+              nconc(((Agg *) result_plan)->aggs,
+                    check_having_qual_for_aggs(
+                      (Node *) lfirst(clause),
+                      ((Agg *)result_plan)->
+                          plan.lefttree->targetlist,
+                      ((List *) parse->groupClause)));
+           /* Have a look at the length of the returned 
+            * list. If there is no difference, no 
+            * aggregates have been found and that means 
+            * that the Qual belongs to the where clause 
+            */
+           if (((new_length = 
+                 length(((Agg *) result_plan)->aggs))== 
+                 old_length) || (new_length == 0))
+           {
+             elog(ERROR,"This could have been done in a 
+                                      where clause!!");
+             return (Plan *)NIL;
+           }
+         }
                            .
                            .
                            .
  }
&bsol;end{verbatim}
%
&bsol;end{itemize}

&bsol;subsubsection{Executor}

The {&bsol;it executor} takes the {&bsol;it queryplan} produced by the {&bsol;it
planner/optimizer} in the way just described and processes all {&bsol;it
aggregate functions} in the way described in section &bsol;ref{aggregates}
{&bsol;it The Implementation of Aggregate Functions} but before the tuple
derived is handed back the {&bsol;it operator tree} attached to the field
{&bsol;tt qpqual} is evaluated by calling the function {&bsol;tt
ExecQual()}. This function recursively steps through the {&bsol;it operator
tree} (i.e. the {&bsol;it having clause}) and evaluates the predicates
appearing there. Thanks to our changes that have been made to the {&bsol;it
planner} the values of all operands needed to evaluate the predicates
(e.g. the values of all {&bsol;it aggregate functions}) are already present
and can be accessed throughout the evaluation without any problems.

If the evaluation of the {&bsol;it having qualification} returns {&bsol;tt true}
the tuple is returned by the function {&bsol;tt execAgg()} otherwise it is
ignored and the next group is processed. &bsol;&bsol;
&bsol;&bsol;
The necessary changes and enhancements have been applied to the
following function in the file {&bsol;tt
$&bsol;ldots$/src/backend/executor/nodeAgg.c}:
%
&bsol;begin{itemize}
%
<step> {&bsol;tt execAgg()}
Whenever the {&bsol;it executor} gets to an {&bsol;tt AGG} node this function is
called. Before the {&bsol;it having logic} had been implemented, all the
{&bsol;it tuples} of the current group were fetched from the {&bsol;it
subplan} and all {&bsol;it aggregate functions} were applied to these
tuples. After that, the results were handed back to the calling
function.

Since the {&bsol;it having logic} has been implemented there is one
additional step executed. Before the results of applying the {&bsol;it
aggregate functions} are handed back, the function {&bsol;tt ExecQual()} is
called with the representation of the {&bsol;it having clause} as an
argument. If {&bsol;tt true} is returned, the results are handed back,
otherwise they are ignored and we start from the beginning for the
next group until a group meeting the restrictions given in the {&bsol;it
having clause} is found.
%
&bsol;begin{verbatim}
  TupleTableSlot *
  ExecAgg(Agg *node)
  {
                            .
                            .
                            .
        /* We loop retrieving groups until we find one 
         * matching node->plan.qual 
         */
+       do 
+       { 
                            .
                            .
                            .
          /* Apply *all* aggregate function to the 
           * tuples of the *current* group 
           */
                            .
                            .
                            .
          econtext->ecxt_scantuple = 
                   aggstate->csstate.css_ScanTupleSlot;
          resultSlot = ExecProject(projInfo, &isDone);

+         /* As long as the retrieved group does not 
+          * match the qualifications it is ignored and
+          * the next group is fetched 
+          */   
+         if(node->plan.qual != NULL)
+         {
+           qual_result =
+               ExecQual(node->plan.qual,
+                        econtext);
+         }     
+         if (oneTuple) pfree(oneTuple);
+       } 
+       while((node->plan.qual!=NULL) && 
+                               (qual_result!=true));   
        return resultSlot;
  }
&bsol;end{verbatim}
%
&bsol;end{itemize}

&bsol;section{The Realization of Union, Intersect and Except}
&bsol;label{union_impl}

SQL92 supports the well known set theoretic operations {&bsol;it union},
{&bsol;it intersect} and {&bsol;it set difference} (the {&bsol;it set difference} is
called {&bsol;it except} in SQL92). The operators are used to connect two
or more {&bsol;tt select} statements. Every {&bsol;tt select} statement returns
a set of tuples and the operators between the {&bsol;tt select} statements
tell how to merge the returned sets of tuples into one result
relation.
%
&bsol;begin{example}
&bsol;label{simple_set_ops}
Let the following tables be given:
%
&bsol;begin{verbatim}

XXX All these table examples have combinations of "-" and "+" which
causes problems inside an SGML comment. Mess them up to keep this
from happening for now. - thomas 1999-02-10

              A  C1|C2|C3         B  C1|C2|C3
                 MMPMMPMM            MMPMMPMM
                  1| a| b             1| a| b
                  2| a| b             5| a| b
                  3| c| d             3| c| d
                  4| e| f             8| e| f

                         C  C1|C2|C3
                            MMPMMPMM
                             4| e| f
                             8| e| f
&bsol;end{verbatim}
Now let's have a look at the results of the following queries:
&bsol;begin{verbatim}
  select * from A
  union
  select * from B;
&bsol;end{verbatim}
derives the set theoretic {&bsol;it union} of the two tables:
%
&bsol;begin{verbatim}
                            C1|C2|C3        
                            MMPMMPMM        
                             1| a| b        
                             2| a| b        
                             3| c| d        
                             4| e| f        
                             5| a| b
                             8| e| f
&bsol;end{verbatim}
%
The {&bsol;tt select} statements used may be more complex:
%
&bsol;begin{verbatim}
  select C1, C3 from A
    where C2 = 'a'
  union
  select C1, C2 from B
    where C3 = 'b';
&bsol;end{verbatim}
%

&bsol;noindent will return the following table:
%
&bsol;begin{verbatim}
                             C1|C3        
                             MMPMM        
                              1| b        
                              2| b        
                              1| a        
                              5| a        
&bsol;end{verbatim}
%
Note that the selected columns do not need to have identical names,
they only have to be of the same type. In the previous example we
selected for {&bsol;tt C1} and {&bsol;tt C3} in the first {&bsol;tt select} statement
and for {&bsol;tt C1} and {&bsol;tt C2} in the second one. The names of the
resulting columns are taken from the first {&bsol;tt select} statement. &bsol;&bsol;
&bsol;&bsol;
Let's have a look at a query using {&bsol;tt intersect}:
%
&bsol;begin{verbatim}
  select * from A
  intersect
  select * from B;
&bsol;end{verbatim}
%
will return:
&bsol;begin{verbatim}
                            C1|C2|C3        
                            MMPMMPMM        
                             1| a| b        
                             3| c| d        
&bsol;end{verbatim}
%
Here is an example using {&bsol;tt except}:
&bsol;begin{verbatim}
  select * from A
  except
  select * from B;
&bsol;end{verbatim}
%
will return:
&bsol;begin{verbatim}
                            C1|C2|C3        
                            MMPMMPMM        
                             2| a| b
                             4| e| f        
&bsol;end{verbatim}
%
The last examples were rather simple because they only used one set
operator at a time with only two operands. Now we look at some more
complex queries involving more {&bsol;it operators}:
%
&bsol;begin{verbatim}
  select * from A
  union 
  select * from B
  intersect 
  select * from C;
&bsol;end{verbatim}
%
will return:
%
&bsol;begin{verbatim}
                            C1|C2|C3        
                            MMPMMPMM        
                             4| e| f
                             8| e| f
&bsol;end{verbatim}
%
The above query performs the set theoretic computation $(A &bsol;cup B)
&bsol;cap C$. When no parentheses are used, the operations are considered to
be left associative, i.e. $A &bsol;cup B &bsol;cup C &bsol;cup D$ will be treated as
$((A &bsol;cup B) &bsol;cup C) &bsol;cup D$. &bsol;&bsol;
&bsol;&bsol;
The same query using parenthesis can lead to a completely different
result:
%
&bsol;begin{verbatim}
  select * from A
  union 
  (select * from B
   intersect 
   select * from C);
&bsol;end{verbatim}
%
performs  $A &bsol;cup (B &bsol;cap C)$ and will return:
%
&bsol;begin{verbatim}
                            C1|C2|C3        
                            MMPMMPMM        
                             1| a| b        
                             2| a| b        
                             3| c| d        
                             4| e| f        
                             8| e| f
&bsol;end{verbatim}
%
&bsol;end{example}
%
&bsol;subsection{How Unions have been Realized Until Version 6.3.2}

First we give a description of the implementation of {&bsol;it union} and
{&bsol;it union all} until version 6.3.2 because we need it to understand
the implementation of {&bsol;it intersect} and {&bsol;it except} described later. &bsol;&bsol;
&bsol;&bsol;
A {&bsol;it union} query is passed through the usual stages:
%
&bsol;begin{itemize}
<step> parser
<step> rewrite system
<step> planner/optimizer
<step> executor
&bsol;end{itemize}
%
and we will now describe what every single stage does to the query.
For our explanation we assume to process a simple query (i.e. a query
without {&bsol;it subselects}, {&bsol;it aggregates} and without involving {&bsol;it views})

&bsol;subsubsection{The Parser Stage}

As described earlier the {&bsol;it parser stage} can be divided into two parts:
%
&bsol;begin{itemize}
<step> the {&bsol;it parser} built up by the grammar rules given in {&bsol;tt gram.y}
and
<step> the {&bsol;it transformation routines} performing a lot of 
changes and analysis to the tree built up by the parser. Most of these
routines reside in {&bsol;tt analyze.c}.
&bsol;end{itemize}
%
%&bsol;pagebreak 
%
A {&bsol;it union} statement consists of two or more {&bsol;it select}
statements connected by the keyword {&bsol;tt union} as the following
example shows:
%
&bsol;begin{verbatim}
  select * from A 
    where C1=1
  union
  select * from B
    where C2 = 'a'
  union
  select * from C
    where C3 = 'f'
&bsol;end{verbatim}
%
The above {&bsol;it union} statement consists of three {&bsol;it select}
statements connected by the keyword {&bsol;tt union}. We will refer to the
first {&bsol;it select} statement by A, to the second one by B and to the
 third one by C for our further explanation (in the new notation our
query looks like this: &bsol;mbox{{&bsol;tt A union B union C}}).&bsol;&bsol;
&bsol;&bsol;
The {&bsol;it parser} (given by {&bsol;tt gram.y}) processes all three {&bsol;tt select}
statements, creates a {&bsol;tt SelectStmt} node for every {&bsol;tt select} and
attaches the {&bsol;tt where} qualifications, {&bsol;it targetlists} etc.  to the
corresponding nodes. Then it creates a list of the second and the
third {&bsol;tt SelectStmt} node (of B and C) and attaches it to the field
{&bsol;tt unionClause} of the first node (of A). Finally it hands back the
first node (node A) with the list of the remaining nodes attached as
shown in figure &bsol;ref{parser_union_back}.
%
&bsol;begin{figure}
&bsol;begin{center}
&bsol;epsfig{figure=figures/parser_union_back.ps}
&bsol;caption{Data structure handed back by the {&bsol;it parser}}
&bsol;label{parser_union_back}
&bsol;end{center}
&bsol;end{figure}
&bsol;&bsol;
&bsol;&bsol;
The following {&bsol;it transformation routines} process the data structure
handed back by the {&bsol;it parser}. First the top node (node A) is transformed
from a {&bsol;tt SelectStmt} node to a {&bsol;tt Query} node.  The {&bsol;it
targetlist}, the {&bsol;tt where} qualification etc. attached to it are
transformed as well. Next the list of the remaining nodes (attached to
{&bsol;tt unionClause} of node A) is transformed and in this step also a
check is made if the types and lengths of the {&bsol;it targetlists} of
the involved nodes are equal. The new {&bsol;tt Query} nodes are now handed
back in the same way as the {&bsol;tt SelectStmt} nodes were before
(i.e. the {&bsol;tt Query} nodes B and C are collected in a list which is
attached to {&bsol;tt unionClause} of {&bsol;tt Query} node A).

&bsol;subsubsection{The Rewrite System}

If any {&bsol;it rewrite rules} are present for the {&bsol;tt Query} nodes
(i.e. one of the {&bsol;it select} statements uses a {&bsol;it view}) the
necessary changes to the {&bsol;tt Query} nodes are performed (see section
&bsol;ref{view_impl} {&bsol;it Techniques To Implement Views}). Otherwise no
changes are made to the nodes in this stage.

&bsol;subsubsection{Planner/Optimizer}

This stage has to create a {&bsol;it plan} out of the {&bsol;it querytree}
produced by the {&bsol;it parser stage} that can be executed by the {&bsol;it
executor}. In most cases there are several ways (paths) with different
cost to get to the same result. It's the {&bsol;it planner/optimizer's}
task to find out which path is the cheapest and to create a {&bsol;it plan}
using this path.  The implementation of {&bsol;it unions} in <productname>Postgres</productname> is
based on the following idea: &bsol;&bsol;
&bsol;&bsol;
The set derived by evaluating $A &bsol;cup B$ must contain every member of
$A$ {&bsol;bf and} every member of $B$. So if we append the members of $B$
to the members of $A$ we are almost done. If there exist members 
common to $A$ and $B$ these members are now contained twice in our new
set, so the only thing left to do is to remove these duplicates. 

&bsol;pagebreak

&bsol;noindent In the case of our example the {&bsol;it planner} would build up the {&bsol;it
tree} shown in figure &bsol;ref{union_plan}. Every {&bsol;tt Query} node is
planned separately and results in a {&bsol;tt SeqScan} node in our
example. The three {&bsol;tt SeqScan} nodes are put together into a list
which is attached to {&bsol;tt unionplans} of an {&bsol;tt Append} node.
%
&bsol;begin{figure}[ht]
&bsol;begin{center}
&bsol;epsfig{figure=figures/union_plan.ps}
&bsol;caption{{&bsol;it Plan} for a union query}
&bsol;label{union_plan}
&bsol;end{center}
&bsol;end{figure}

&bsol;subsubsection{Executor}

The {&bsol;it executor} will process all the {&bsol;tt SeqScan} nodes and append all
the delivered tuples to a single {&bsol;it result relation}. Now it is
possible that duplicate tuples are contained in the {&bsol;it result relation}
which have to be removed. The removal is done by the {&bsol;tt Unique} node
and the sort is just performed to make its work easier.

&bsol;subsection{How Intersect, Except and Union Work Together}  

The last section showed that every stage ({&bsol;it parser stage}, {&bsol;it
planner/optimizer}, {&bsol;it executor}) of <productname>Postgres</productname> has to provide
features in order to support {&bsol;it union} statements. For the
implementation of {&bsol;it intersect} and {&bsol;it except} statements (and
statements involving all {&bsol;it set operators}) we choose a different approach
based on {&bsol;it query rewriting}. &bsol;&bsol;
&bsol;&bsol;
The idea is based on the fact that {&bsol;it intersect} and {&bsol;it except}
statements are redundant in SQL, i.e. for every {&bsol;it intersect} or
{&bsol;it except} statement it is possible to formulate a semantically
equivalent statement without using {&bsol;it intersect} or {&bsol;it except}.
%
&bsol;begin{example}
&bsol;label{transform_intersect}
This example shows how a query using {&bsol;it intersect} can be
transformed to a semantically equivalent query without an {&bsol;it
intersect}:
%
&bsol;pagebreak
%
&bsol;begin{verbatim}
  select C1, C3 from A
  where C1 = 1
  intersect
  select C1, C2 from B
  where C2 = 'c';
&bsol;end{verbatim}
%
is equivalent to:
%
&bsol;begin{verbatim}
  select C1, C3
  from A
  where C1 = 1 and
        (C1, C3) in (select C1, C2
                     from B
                     where C2 = 'c');
&bsol;end{verbatim}
%
This example shows how an {&bsol;it except} query can be transformed to an
{&bsol;it except}-less form:
%
&bsol;begin{verbatim}
  select C1, C2 from A
  where C2 = 'c'
  except
  select C1, C3 from B
  where C3 = 'f';
&bsol;end{verbatim}
%
is equivalent to:
%
&bsol;begin{verbatim}
  select C1, C2
  from A
  where C2 = 'c' and
        (C1, C2) not in (select C1, C3
                         from B
                         where C3 = 'f');
&bsol;end{verbatim}
%
&bsol;end{example}
%
The transformations used in example &bsol;ref{transform_intersect} are
always valid because they just implement the set theoretic definition
of {&bsol;it intersect} and {&bsol;it except}:
%
&bsol;begin{definition} 
&bsol;label{def_intersect}
~ &bsol;&bsol;
The {&bsol;it intersection} of two sets $A$ and $B$ is
defined as:
&bsol;begin{displaymath}
(A &bsol;cap B) := &bsol;{x &bsol;mid x &bsol;in A &bsol;wedge x &bsol;in B &bsol;}
&bsol;end{displaymath}
%
The {&bsol;it intersection} of $n$ sets $A_{1}, &bsol;ldots, A_{n}$ is defined as:
%
&bsol;begin{displaymath}
&bsol;bigcap_{i=1}^{n} A_{i} := &bsol;{x &bsol;mid &bsol;bigwedge_{i=1}^{n} x &bsol;in A_{i} &bsol;} 
&bsol;end{displaymath}
%
&bsol;end{definition}
%
&bsol;begin{definition} 
&bsol;label{def_except}
~ &bsol;&bsol;
The {&bsol;it difference} of two sets $A$ and $B$ is
defined as:
&bsol;begin{displaymath}
(A &bsol;backslash B) := &bsol;{x &bsol;mid x &bsol;in A &bsol;wedge x &bsol;not&bsol;in B &bsol;}
&bsol;end{displaymath}
%
&bsol;end{definition}
%
&bsol;begin{definition} 
&bsol;label{def_union}
~&bsol;&bsol;
The {&bsol;it union} of two sets $A$ and $B$ is
defined as:
&bsol;begin{displaymath}
(A &bsol;cup B) := &bsol;{x &bsol;mid x &bsol;in A &bsol;vee x &bsol;in B &bsol;}
&bsol;end{displaymath}
%
The {&bsol;it union} of $n$ sets $A_{1}, &bsol;ldots, A_{n}$ is defined as:
%
&bsol;begin{displaymath}
&bsol;bigcup_{i=1}^{n} A_{i} := &bsol;{x &bsol;mid &bsol;bigvee_{i=1}^{n} x &bsol;in A_{i} &bsol;} 
&bsol;end{displaymath}
%
&bsol;end{definition}

&bsol;begin{definition} Disjunctive Normal Form (DNF) &bsol;&bsol;
Let $F = C_{1} &bsol;vee &bsol;ldots &bsol;vee C_{n}$ be given where every $C_{i}$ is
of the form $(L_{i}^{1} &bsol;wedge &bsol;ldots &bsol;wedge L_{i}^{k_{i}})$ and
$L_{i}^{j}$ is a propositional variable or the negation of a
propositional variable. Now we say $F$ is in DNF.
&bsol;end{definition}
%
&bsol;begin{example} In the following example the $L_{i}^{j}$ are of the form
$x &bsol;in X$ or $&bsol;neg (x &bsol;in X)$: &bsol;&bsol;
&bsol;indent $((x &bsol;in A &bsol;wedge &bsol;neg (x &bsol;in B) &bsol;wedge x &bsol;in C) &bsol;vee (x &bsol;in D
&bsol;wedge x &bsol;in E))$ is a formula in DNF &bsol;&bsol;
&bsol;indent $((x &bsol;in A &bsol;vee x &bsol;in B) &bsol;wedge (x &bsol;in C &bsol;vee &bsol;neg (x &bsol;in D)))$
is not in DNF.
&bsol;end{example}
%
The transformation of any formula in propositional logic into DNF is done by
successively applying the following rules: &bsol;&bsol;
&bsol;&bsol;
&bsol;indent $(R1)~~&bsol;neg (F_{1} &bsol;vee F_{2}) &bsol;Rightarrow (&bsol;neg F_{1} &bsol;wedge &bsol;neg
F_{2})$ &bsol;&bsol;
&bsol;indent $(R2)~~&bsol;neg (F_{1} &bsol;wedge F_{2}) &bsol;Rightarrow (&bsol;neg F_{1} &bsol;vee &bsol;neg
F_{2})$ &bsol;&bsol;
&bsol;indent $(R3)~~F_{1} &bsol;wedge (F_{2} &bsol;vee F_{3}) &bsol;Rightarrow (F_{1} &bsol;wedge
F_{2}) &bsol;vee (F_{1} &bsol;wedge F_{3})$ &bsol;&bsol;
&bsol;indent $(R4)~~(F_{1} &bsol;vee F_{2}) &bsol;wedge F_{3} &bsol;Rightarrow (F_{1} &bsol;wedge
F_{3}) &bsol;vee (F_{2} &bsol;wedge F_{3})$ &bsol;&bsol;
&bsol;&bsol;
It can be shown that the transformation using the rules (R1) to
(R4) always terminates after a finite number of steps.

&bsol;subsubsection{Set Operations as Propositional Logic Formulas}

Using the definitions from above we can treat formulas
involving set theoretic operations as formulas of {&bsol;it propositional
logic}. As we will see later these formulas can easily be used in the
{&bsol;tt where-} and {&bsol;tt having} qualifications of the {&bsol;tt select}
statements involved in the query.
%
&bsol;begin{example}
Here are some examples: &bsol;&bsol; &bsol;&bsol;
%
&bsol;indent $((A &bsol;cup B) &bsol;cap C) := &bsol;{x &bsol;mid (x &bsol;in A &bsol;vee x &bsol;in B) &bsol;wedge x &bsol;in C
&bsol;}$ &bsol;&bsol;
&bsol;indent $((A &bsol;cup B) &bsol;cap (C &bsol;cup D)) := &bsol;{x &bsol;mid (x &bsol;in A &bsol;vee x &bsol;in B)
&bsol;wedge (x &bsol;in C &bsol;vee x &bsol;in D) &bsol;}$ &bsol;&bsol;
&bsol;indent $((A &bsol;cap B) &bsol;backslash C) := &bsol;{x &bsol;mid (x &bsol;in A &bsol;wedge x &bsol;in
B) &bsol;wedge x &bsol;not&bsol;in C &bsol;}$ &bsol;&bsol;
&bsol;indent $(A &bsol;backslash (B &bsol;cup C)) := &bsol;{x &bsol;mid x &bsol;in A &bsol;wedge &bsol;neg (x
&bsol;in B &bsol;vee x &bsol;in C) &bsol;}$ &bsol;&bsol;
&bsol;indent $(((A &bsol;cap B) &bsol;cup (C &bsol;backslash D)) &bsol;cap E) := &bsol;{((x &bsol;in A
&bsol;wedge x &bsol;in B) &bsol;vee (x &bsol;in C &bsol;wedge x &bsol;not&bsol;in D)) &bsol;wedge x &bsol;in E &bsol;}$
%
&bsol;end{example}
%
&bsol;subsection{Implementing Intersect and Except Using the
Union Capabilities}
%
We want to be able to use queries involving more than just one type of
set operation (e.g. only {&bsol;it union} or only {&bsol;it intersect}) at a
time, so we have to look for a solution that supports correct handling
of queries like that. As described above there is a solution for pure
{&bsol;it union} statements implemented already, so we have to develop an
approach that makes use of these {&bsol;it union} capabilities. &bsol;&bsol;
&bsol;&bsol;
As figure &bsol;ref{parser_union_back} illustrates, the operands of a {&bsol;it
union} operation are just {&bsol;tt Query} nodes (the first operand is the
top node and all further operands form a list which is attached to the
field {&bsol;tt unionClause} of the top node). So our goal will be to
transform every query involving set operations into this form. (Note
that the operands to the {&bsol;it union} operation may be complex,
i.e. {&bsol;it subselects}, {&bsol;it grouping}, {&bsol;it aggregates} etc. are allowed.)

The transformation of a query involving set operations in any order
into a query that can be accepted by the {&bsol;it union} logic is
equivalent to transforming the {&bsol;it membership formula} (see
definitions &bsol;ref{def_intersect}, &bsol;ref{def_except} and &bsol;ref{def_union})
in propositional logic into {&bsol;it disjunctive normal form} (DNF). The
transformation of any formula in propositional logic into DNF is
always possible in a finite number of steps.

&bsol;noindent The advantage of this {&bsol;it transformation technique} is the little
impact on the whole system and the implicit invocation of the {&bsol;it
planner/optimizer}. The only changes necessary are made to the {&bsol;it
parser stage} and the {&bsol;it rewrite system}. &bsol;&bsol;
&bsol;&bsol;
Here are some changes that had to be applied to the source code before
the {&bsol;it parser stage} and the {&bsol;it rewrite system} could be adapted:
%
&bsol;begin{itemize}
<step> Add the additional field {&bsol;tt intersectClause} to the data
structures {&bsol;tt Query} and {&bsol;tt InsertStmt} defined in the file {&bsol;tt
$&bsol;ldots$/src/include/nodes/parsenodes.h}:
%
&bsol;begin{verbatim}
  typedef struct Query
  {
    NodeTag    type;
    CmdType    commandType;   
            .
            .
            .
    Node       *havingQual;
+   List       *intersectClause;    
    List       *unionClause;       
    List       *base_relation_list_;
    List       *join_relation_list_;
  } Query;

  typedef struct InsertStmt
  {
    NodeTag    type;
            .
            .
            .
    bool       unionall;      
+   List       *intersectClause;  
  } InsertStmt;
&bsol;end{verbatim}
%
<step> Add the new keywords {&bsol;tt EXCEPT} and {&bsol;tt INTERSECT} to the
file {&bsol;tt $&bsol;ldots$/src/backend/parser/keywords.c}:
%
&bsol;begin{verbatim}
  static ScanKeyword ScanKeywords[] = {
    {"abort", ABORT_TRANS},
    {"action", ACTION},
              .
              .
              .     
    {"end", END_TRANS},
+   {"except", EXCEPT},
              .
              .
              .     
    {"instead", INSTEAD},
+   {"intersect", INTERSECT},
              .
              .
              .     
  };
&bsol;end{verbatim}
%
<step> <productname>Postgres</productname> contains functions to convert the internal
representation of a {&bsol;it parsetree} or {&bsol;it plantree} into an ASCII
representation (that can easily be printed to the screen (for
debugging purposes) or be stored in a file) and vice versa. These
functions have to be adapted to be able to deal with {&bsol;it intersects}
and {&bsol;it excepts}. These functions can be found in the files {&bsol;tt
$&bsol;ldots$/src/backend/nodes/outfuncs.c} and {&bsol;tt
$&bsol;ldots$/src/backend/nodes/readfuncs.c}:
%
&bsol;begin{verbatim}
  static void
  _outQuery(StringInfo str, Query *node)
  {
                            .
                            .
                            .
    appendStringInfo(str, " :unionClause ");
    _outNode(str, node->unionClause);
+   appendStringInfo(str, " :intersectClause ");
+   _outNode(str, node->intersectClause);
  }

  static Query *
  _readQuery()
  {
                            .
                            .
                            .
    token = lsptok(NULL, &length);
    local_node->unionClause = nodeRead(true);
+   token = lsptok(NULL, &length);
+   local_node->intersectClause = nodeRead(true);

    return (local_node);
  }
&bsol;end{verbatim}
%
<step> The function {&bsol;tt ExecReScan()} is called whenever a new
execution of a given {&bsol;it plan} has to be started (i.e. whenever we
have to start from the beginning with the first tuple again). The call
to this function happens implicitly. For the special kind of
subqueries we are using for the rewritten queries (see example
&bsol;ref{transform_intersect}) we have to take that also 
{&bsol;tt Group} nodes are processed. The function can be found in the file
{&bsol;tt $ldots$/backend/executor/execAmi.c}.
%
&bsol;begin{verbatim}
  void
  ExecReScan(Plan *node, ExprContext *exprCtxt, 
             Plan *parent)
  {
                            .
                            .
                            .
     switch (nodeTag(node))
     {
                            .
                            .
                            .
&bsol;end{verbatim}
&bsol;pagebreak
&bsol;begin{verbatim}
+      case T_Group:
+             ExecReScanGroup((Group *) node, 
+                              exprCtxt, parent);
+             break;
                            .
                            .
                            .
     }
  }
&bsol;end{verbatim}
%
<step> The function {&bsol;tt ExecReScanGroup()} is called by {&bsol;tt
ExecReScan()} described above whenever a {&bsol;tt Group} node is detected
and can be found in the file {&bsol;tt
$&bsol;ldots$/src/backend/executor/nodeGroup.c} . It has been created for
the {&bsol;it intersect} and {&bsol;it except} logic although it is actually
needed by the special kind of subselect (see above).
%
&bsol;begin{verbatim}
  void
  ExecReScanGroup(Group *node, ExprContext *exprCtxt, 
                  Plan *parent)
  {
    GroupState *grpstate = node->grpstate;
  
    grpstate->grp_useFirstTuple = FALSE;
    grpstate->grp_done = FALSE;
    grpstate->grp_firstTuple = (HeapTupleData *)NIL;
  
    /*
     * if chgParam of subnode is not null then plan 
     * will be re-scanned by first ExecProcNode.
     */
    if (((Plan *) node)->lefttree->chgParam == NULL)
      ExecReScan(((Plan *) node)->lefttree, 
                 exprCtxt, (Plan *) node);
  }
&bsol;end{verbatim}
%
&bsol;end{itemize}

&bsol;subsubsection{Parser}

The {&bsol;it parser} defined in the file {&bsol;tt
$&bsol;ldots$/src/backend/parser/gram.y} had to be modified in two ways:
%
&bsol;begin{itemize}
%
<step> The grammar had to be adapted to support the usage of
parenthesis (to be able to specify the order of execution of the set
operators). 
%
<step> The code building up the data structures handed back by the
{&bsol;it parser} had to be inserted.
%
&bsol;end{itemize}
%
Here is a part of the grammar that is responsible for {&bsol;tt select}
statements having the code building up the data structures inserted:
%
&bsol;pagebreak
%
&bsol;begin{verbatim}
  SelectStmt :  select_w_o_sort sort_clause
      {
                            .
                            .
                            .
         /* $1 holds the tree built up by the
          * rule 'select_w_o_sort'
          */
         Node *op = (Node *) $1;

         if IsA($1, SelectStmt) 
         {
           SelectStmt *n = (SelectStmt *)$1;
           n->sortClause = $2;
           $$ = (Node *)n;
         }
         else
         {
           /* Create a "flat list" of the operator
            * tree built up by 'select_w_o_sort' and
            * let select_list point to it 
            */
           create_select_list((Node *)op, 
                              &select_list, 
                              &unionall_present);
           /* Replace all the A_Expr nodes in the 
            * operator tree by Expr nodes.
            */
            op = A_Expr_to_Expr(op, &intersect_present);
                            .
                            .
                            .
            /* Get the leftmost SelectStmt node (which 
             * automatically represents the first Select 
             * Statement of the query!) */
            first_select = 
                   (SelectStmt *)lfirst(select_list);
            /* Attach the list of all SelectStmt nodes 
             * to unionClause 
             */
            first_select->unionClause = select_list;

            /* Attach the whole operator tree to 
             * intersectClause */
            first_select->intersectClause = 
                                         (List *) op;
            /* finally attach the sort clause */
            first_select->sortClause = $2;
  
            /* Now hand it back! */
            $$ = (Node *)first_select;
          }               
      }
  ; 
&bsol;end{verbatim}
&bsol;pagebreak
&bsol;begin{verbatim}
  select_w_o_sort :  '(' select_w_o_sort ')'
      {
        $$ = $2; 
      }
  |  SubSelect
      {
        $$ = $1; 
      }
  |  select_w_o_sort EXCEPT select_w_o_sort
      {
        $$ = (Node *)makeA_Expr(AND,NULL,$1,
                         makeA_Expr(NOT,NULL,NULL,$3));
      }
  |  select_w_o_sort UNION opt_union select_w_o_sort
      {       
        if (IsA($4, SelectStmt))
        {
          SelectStmt *n = (SelectStmt *)$4;
          n->unionall = $3;
        }
        $$ = (Node *)makeA_Expr(OR,NULL,$1,$4);
      }
  |  select_w_o_sort INTERSECT select_w_o_sort
      {
        $$ = (Node *)makeA_Expr(AND,NULL,$1,$3);
      }
  ; 
&bsol;end{verbatim}

% &bsol;pagebreak

&bsol;begin{verbatim}
  SubSelect :  SELECT opt_unique res_target_list2
               result from_clause where_clause
               group_clause having_clause
    {
      SelectStmt *n = makeNode(SelectStmt);
      n->unique = $2;
              .
              .
              .
      n->havingClause = $8;
      $$ = (Node *)n;
    }
  ;
&bsol;end{verbatim}
%
The keywords {&bsol;tt SELECT}, {&bsol;tt EXCEPT}, {&bsol;tt UNION}, {&bsol;tt INTERSECT}, {&bsol;tt
'('} and {&bsol;tt ')'} are {&bsol;it terminal symbols} and {&bsol;tt SelectStmt},
{&bsol;tt select&bsol;_w&bsol;_o&bsol;_sort}, {&bsol;tt sort&bsol;_clause}, {&bsol;tt opt&bsol;_union}, {&bsol;tt
SubSelect}, {&bsol;tt opt&bsol;_unique}, {&bsol;tt res&bsol;_target&bsol;_list2}, {&bsol;tt result},
{&bsol;tt from&bsol;_clause}, {&bsol;tt where&bsol;_clause}, {&bsol;tt group&bsol;_clause}, {&bsol;tt
having&bsol;_clause} are {&bsol;it nonterminal symbols}. The symbols {&bsol;tt
EXCEPT}, {&bsol;tt UNION} and {&bsol;tt INTERSECT} are {&bsol;it left
associative} meaning that a statement like:
%
&bsol;begin{verbatim}
  select * from A
  union 
  select * from B
  union
  select * from C;
&bsol;end{verbatim}
%
&bsol;pagebreak
will be treated as:
%
&bsol;begin{verbatim}
  ((select * from A
    union
    select * from B)
    union
    select * from C)
&bsol;end{verbatim}
%
The {&bsol;tt select&bsol;_w&bsol;_o&bsol;_sort} rule builds up an {&bsol;it operator tree}
using nodes of type {&bsol;tt A&bsol;_Expr}. For every {&bsol;it union} an {&bsol;tt OR}
node is created, for every {&bsol;it intersect} an {&bsol;tt AND} node and for
every {&bsol;it except} and {&bsol;tt AND NOT} node building up a representation
of a formula in propositional logic. If the query parsed did not
contain any set operations the rule hands back a {&bsol;tt SelectStmt} node
representing the query otherwise the top node of the {&bsol;it operator
tree} is returned. Figure
&bsol;ref{union_intersect_select_w_o_sort} shows a typical {&bsol;it operator tree}
returned by the {&bsol;tt select&bsol;_w&bsol;_o&bsol;_sort} rule.

&bsol;begin{figure}[ht]
&bsol;begin{flushright}
&bsol;epsfig{figure=figures/union_intersect_select_w_o_sort.ps}
&bsol;caption{{&bsol;it Operator tree} for $(A &bsol;cup B) &bsol;backslash (C &bsol;cap D)$}
&bsol;label{union_intersect_select_w_o_sort}
&bsol;end{flushright}
&bsol;end{figure}

&bsol;noindent The rule {&bsol;tt SelectStmt} transforms the {&bsol;it operator tree} built of
{&bsol;tt A&bsol;_Expr} nodes into an {&bsol;it operator tree} using {&bsol;tt Expr} nodes
by a call to the function {&bsol;tt A&bsol;_Expr&bsol;_to&bsol;_Expr()} which additionally
replaces every {&bsol;tt OR} node by an {&bsol;tt AND} node and vice
versa. This is performed in order to be able to use the function {&bsol;tt
cnfify()} later on. &bsol;&bsol;
&bsol;&bsol;
The {&bsol;it transformations} following the {&bsol;it parser} expect a {&bsol;tt
SelectStmt} node to be returned by the rule {&bsol;tt SelectStmt} and not
an {&bsol;it operator tree}.  So if the rule {&bsol;tt select&bsol;_w&bsol;_o&bsol;_sort} hands
back such a node (meaning that the query did not contain any set
operations) we just have to attach the data structure built up by the
{&bsol;tt sort&bsol;_clause} rule and are finished, but when we get an {&bsol;it
operator tree} we have to perform the following steps:
%
&bsol;begin{itemize}
%
<step> Create a flat list of all {&bsol;tt SelectStmt} nodes of the {&bsol;it
operator tree} (by a call to the function {&bsol;tt create&bsol;_select&bsol;_list()})
and attach the list to the field
&bsol;mbox{{&bsol;tt unionClause}} of the leftmost {&bsol;tt SelectStmt} (see next step).
%
<step> Find the leftmost leaf ({&bsol;tt SelectStmt} node) of the {&bsol;it operator
tree} (this is automatically the first member of the above created
list because of the technique {&bsol;tt create&bsol;_select&bsol;_list()} uses to
create the list).
%
<step> Attach the whole {&bsol;it operator tree} (including the leftmost node
itself) to the field &bsol;mbox{{&bsol;tt intersectClause}} of the leftmost {&bsol;tt
SelectStmt} node.
%
<step> Attach the data structure built up by the {&bsol;tt sort&bsol;_clause}
rule to the field {&bsol;tt sortClause} of the leftmost {&bsol;tt SelectStmt} node.
%
<step> Hand back the leftmost {&bsol;tt SelectStmt} node (with
the {&bsol;it operator tree}, the list of all {&bsol;tt SelectStmt} nodes and the {&bsol;tt
sortClause} attached to it).
%
&bsol;end{itemize}
%
&bsol;noindent Figure &bsol;ref{union_intersect_select} shows the final data structure
derived from the {&bsol;it operator tree} shown in figure
&bsol;ref{union_intersect_select_w_o_sort} handed back by the {&bsol;tt SelectStmt} rule:
%
&bsol;begin{figure}[ht]
&bsol;begin{flushright}
&bsol;epsfig{figure=figures/union_intersect_select.ps}
&bsol;caption{Data structure handed back by {&bsol;tt SelectStmt} rule}
&bsol;label{union_intersect_select}
&bsol;end{flushright}
&bsol;end{figure}

&bsol;pagebreak

&bsol;noindent Here is a description of the above used functions. They can
be found in the file {&bsol;tt $&bsol;ldots$/src/backend/parser/anlayze.c}.
%
&bsol;begin{itemize}
%
<step> {&bsol;tt create&bsol;_select&bsol;_list()}: &bsol;&bsol;
This function steps through the {&bsol;it tree} handed to it by the
parameter {&bsol;tt ptr} and creates a list of all {&bsol;tt SelectStmt} nodes
found. The list is handed back by the parameter {&bsol;tt
select&bsol;_list}. The function uses a recursive {&bsol;it depth first search}
algorithm to examine the {&bsol;it tree} leading to the fact that the
leftmost {&bsol;tt SelectStmt} node will appear first in the created list.
%
&bsol;begin{verbatim}
  void 
  create_select_list(Node *ptr, List **select_list, 
                     bool *unionall_present)
  {
    if(IsA(ptr, SelectStmt)) 
    {
      *select_list = lappend(*select_list, ptr);    
      if(((SelectStmt *)ptr)->unionall == TRUE) 
        *unionall_present = TRUE;    
      return;    
    }
  
    /* Recursively call for all arguments. 
     * A NOT expr has no lexpr! 
     */
    if (((A_Expr *)ptr)->lexpr != NULL) 
      create_select_list(((A_Expr *)ptr)->lexpr, 
                       select_list, unionall_present);
    create_select_list(((A_Expr *)ptr)->rexpr, 
                       select_list, unionall_present);
}
&bsol;end{verbatim}
%
<step> {&bsol;tt A&bsol;_Expr&bsol;_to&bsol;_Expr()}: &bsol;&bsol;
This function recursively steps through the {&bsol;it operator tree} handed
to it by the parameter {&bsol;tt ptr} and replaces {&bsol;tt A&bsol;_Expr} nodes by
{&bsol;tt Expr} nodes. Additionally it exchanges {&bsol;tt AND} nodes with {&bsol;tt
OR} nodes and vice versa.  The reason for this exchange is easy to
understand. We implement {&bsol;it intersect} and {&bsol;it except} clauses by
rewriting these queries to semantically equivalent queries that use
{&bsol;tt IN} and {&bsol;tt NOT IN} subselects. To be able to use all three
operations ({&bsol;it unions}, {&bsol;it intersects} and {&bsol;it excepts}) in one
complex query, we have to translate the queries into {&bsol;it Disjunctive
Normal Form} (DNF). Unfortunately there is no function {&bsol;tt dnfify()},
but there is a function {&bsol;tt cnfify()} which produces DNF when we
exchange {&bsol;tt AND} nodes with {&bsol;tt OR} nodes and vice versa before
calling {&bsol;tt cnfify()} and exchange them again in the result.  
%
&bsol;begin{verbatim}
  Node *
  A_Expr_to_Expr(Node *ptr, 
                 bool *intersect_present)
  {
    Node *result;
  
    switch(nodeTag(ptr))
    {
      case T_A_Expr:
      {
        A_Expr *a = (A_Expr *)ptr;
        
        switch (a->oper)
        {
          case AND:
          {
            Expr *expr = makeNode(Expr);
            Node *lexpr = 
               A_Expr_to_Expr(((A_Expr *)ptr)->lexpr, 
                              intersect_present);
            Node *rexpr = 
               A_Expr_to_Expr(((A_Expr *)ptr)->rexpr, 
                              intersect_present);

            *intersect_present = TRUE;
              
            expr->typeOid = BOOLOID;
            expr->opType = OR_EXPR;
            expr->args = makeList(lexpr, rexpr, -1);
            result = (Node *) expr;
            break;            
          }               
          case OR:
          {
            Expr *expr = makeNode(Expr);
            Node *lexpr = 
               A_Expr_to_Expr(((A_Expr *)ptr)->lexpr, 
                              intersect_present);
            Node *rexpr = 
               A_Expr_to_Expr(((A_Expr *)ptr)->rexpr, 
                              intersect_present);

            expr->typeOid = BOOLOID;
            expr->opType = AND_EXPR;
            expr->args = makeList(lexpr, rexpr, -1);
            result = (Node *) expr;
            break;            
          }
          case NOT:
          {
            Expr *expr = makeNode(Expr);
            Node *rexpr = 
               A_Expr_to_Expr(((A_Expr *)ptr)->rexpr, 
                              intersect_present);

            expr->typeOid = BOOLOID;
            expr->opType = NOT_EXPR;
            expr->args = makeList(rexpr, -1);
            result = (Node *) expr;
            break;            
          }
        }       
        break;  
      }
      default:
      {
        result = ptr;
      }      
    }
  }
  return result;  
}
&bsol;end{verbatim}
%
&bsol;end{itemize}

&bsol;noindent Note that the {&bsol;tt stmtmulti} and {&bsol;tt OptStmtMulti} rules had to be
changed in order to avoid {&bsol;it shift/reduce} conflicts. The old rules
allowed an invalid syntax (e.g. the concatenation of two statements
without a ';' inbetween) which will be prevented now. The new rules
have the second line commented out as shown below:
%
&bsol;begin{verbatim}  
  stmtmulti       :  stmtmulti stmt ';'
               /* |  stmtmulti stmt */
                  |  stmt ';'
                  ;

  OptStmtMulti    :  OptStmtMulti OptimizableStmt ';'
               /* |  OptStmtMulti OptimizableStmt */
                  |  OptimizableStmt ';'
                  ;
&bsol;end{verbatim}
%


&bsol;subsubsection{Transformations}

This step normally transforms every {&bsol;tt SelectStmt} node found into a
{&bsol;tt Query} node and does a lot of transformations to the {&bsol;it targetlist},
the {&bsol;tt where} qualification etc. As mentioned above this stage
expects a {&bsol;tt SelectStmt} node and cannot handle an {&bsol;tt A&bsol;_Expr}
node. That's why we did the changes to the {&bsol;it operator tree} shown in
figure &bsol;ref{union_intersect_select}. &bsol;&bsol;
&bsol;&bsol;
In this stage only very few changes have been necessary: 
%
&bsol;begin{itemize}
<step> The transformation of the list attached to {&bsol;tt unionClause} is
prevented. The raw list is now passed through instead and the necessary
transformations are performed at a later point in time.
<step> The additionally introduced field {&bsol;tt intersectClause} is also
passed untouched through this stage.
&bsol;end{itemize}   

&bsol;noindent The changes described in the above paragraph have been
applied to the functions {&bsol;tt transformInsertStmt()} and {&bsol;tt
transformSelectStmt()} which are contained in the file {&bsol;tt
$&bsol;ldots$/src/backend/parser/analyze.c}:
%
&bsol;begin{itemize}
%
<step> {&bsol;tt transformInsertStmt()}:
%
&bsol;begin{verbatim}
  static Query *
  transformInsertStmt(ParseState *pstate, 
                      InsertStmt *stmt)
  {
                            .
                            .
                            .
&bsol;end{verbatim}
&bsol;pagebreak
&bsol;begin{verbatim}
    /* Just pass through the unionClause and 
     * intersectClause. We will process it in 
     * the function Except_Intersect_Rewrite() 
     */
    qry->unionClause = stmt->unionClause;
    qry->intersectClause = stmt->intersectClause;
                            .
                            .
                            .

    return (Query *) qry;
  }
&bsol;end{verbatim}
%
<step> {&bsol;tt transformSelectStmt()}:
%
&bsol;begin{verbatim}
  static Query *
  transformSelectStmt(ParseState *pstate, 
                      SelectStmt *stmt)
  {
                            .
                            .
                            .
    /* Just pass through the unionClause and 
     * intersectClause. We will process it in 
     * the function Except_Intersect_Rewrite() 
     */
    qry->unionClause = stmt->unionClause;
    qry->intersectClause = stmt->intersectClause;
                            .
                            .
                            .
    return (Query *) qry;
  }
&bsol;end{verbatim}
%
&bsol;end{itemize}

&bsol;subsubsection{The Rewrite System}

In this stage the information contained in the {&bsol;it operator tree} attached
to the topmost {&bsol;tt SelectStmt} node is used to form a tree of {&bsol;tt
Query} nodes representing the rewritten query (i.e. the semantically
equivalent query that contains only {&bsol;it union} but no {&bsol;it intersect}
or {&bsol;it except} operations). &bsol;&bsol;
&bsol;&bsol;
The following steps have to be performed:
%
&bsol;begin{itemize}
<step> Save the {&bsol;tt sortClause}, {&bsol;tt uniqueFlag}, {&bsol;tt targetList}
fields etc. of the topmost {&bsol;tt Query} node because the topmost node
may change during the rewrite process (remember (only) the topmost
{&bsol;tt SelectStmt} node has already been transformed to a {&bsol;tt Query}
node).
%
<step> Recursively step through the {&bsol;it operator tree} and transform 
every {&bsol;tt SelectStmt} node to a {&bsol;tt Query} node using the function
{&bsol;tt intersect&bsol;_tree&bsol;_analyze()} described below. The one node already
transformed (the topmost node) is still contained in the {&bsol;it operator
tree} and must not be transformed again because this would cause
troubles in the {&bsol;it transforming logic}.
%
&bsol;begin{figure}[ht]
&bsol;begin{center}
&bsol;epsfig{figure=figures/union_intersect_dnf.ps}
&bsol;caption{Data structure of $(A &bsol;cup B) &bsol;backslash C$  after transformation to DNF}
&bsol;label{union_intersect_dnf}
&bsol;end{center}
&bsol;end{figure}
%
<step> Transform the new {&bsol;it operator tree} into DNF (disjunctive normal
form). <productname>Postgres</productname> does not provide any function for the transformation
into DNF but it provides a function {&bsol;tt cnfify()} that performs a
transformation into CNF (conjunctive normal form). So we can easily
make use of this function when we exchange every {&bsol;tt OR} with an {&bsol;tt
AND} and vice versa before calling {&bsol;tt cnfify()} as we did already in
the {&bsol;it parser} (compare figure &bsol;ref{union_intersect_select_w_o_sort}
to figure &bsol;ref{union_intersect_select}). When {&bsol;tt cnfify()} is called
with a special flag, the {&bsol;tt removeAndFlag} set to {&bsol;tt true} it
returns a list where the entries can be thought of being connected
together by {&bsol;tt ANDs}, so the explicit {&bsol;tt AND} nodes are removed.

After {&bsol;tt cnfify()} has been called we normally would have to
exchange {&bsol;tt OR} and {&bsol;tt AND} nodes again. We skip this step by
simply treating every {&bsol;tt OR} node as an {&bsol;tt AND} node throughout
the following steps (remember, that there are no {&bsol;tt AND} nodes left
that have to be treated as {&bsol;tt OR} nodes because of the {&bsol;tt
removeAndFlag}).

&bsol;noindent Figure &bsol;ref{union_intersect_dnf} shows what the data
structure looks like after the transformation to DNF has taken place
for the following query:
%
&bsol;begin{verbatim}
  (select * from A
   union
   select * from B)
   except
   select * from C;
&bsol;end{verbatim}
%
<step> For every entry of the list returned by {&bsol;tt cnfify()} (i.e. for every  
{&bsol;it operator tree} which may only contain {&bsol;tt OR} and {&bsol;tt NOT}
operator nodes and {&bsol;tt Query} nodes as leaves) contained in the {&bsol;tt
union&bsol;_list} perform the following steps:
%
&bsol;begin{itemize}
%
<step> Check if the {&bsol;it targetlists} of all {&bsol;tt Query} nodes appearing are
compatible (i.e. all {&bsol;it targetlists} have the same number of attributes
and the corresponding attributes are of the same type)
%
<step> There must be at least one positive {&bsol;tt
OR} node (i.e. at least one {&bsol;tt OR} node which is not preceded by a
{&bsol;tt NOT} node). Create a list of all {&bsol;tt Query} nodes (or of {&bsol;tt
Query} nodes preceded by {&bsol;tt NOT} nodes if {&bsol;tt OR NOT} is found)
with the non negated node first using the function {&bsol;tt
create&bsol;_list()} described below.
%
<step> The first (non negated) node of the list will be the topmost   
{&bsol;tt Query} node of the current {&bsol;it union} operand. For all other
nodes found in the list add an {&bsol;tt IN} subselect ({&bsol;tt NOT IN}
subselect if the {&bsol;tt Query} node is preceded by a {&bsol;tt NOT}) to the
{&bsol;tt where} qualification of the topmost node. Adding a
subselect to the {&bsol;tt where} qualification is done by logically
{&bsol;tt AND}ing it to the original qualification. 
%
<step> Append the {&bsol;tt Query} node setup in the last steps to a list which
is hold by the pointer {&bsol;tt union&bsol;_list}.
&bsol;end{itemize}
%
<step> Take the first node of {&bsol;tt union&bsol;_list} as the new topmost node
of the whole query and attach the rest of  the list to the
field {&bsol;tt unionClause} of this topmost node. Since the new topmost
node might differ from the original one (i.e. from the node which was
topmost when we entered the {&bsol;it rewrite stage}) we have to attach the
fields saved in the first step to the new topmost node (i.e. the {&bsol;tt
sortClause}, {&bsol;tt targetList}, {&bsol;tt unionFlag}, etc.).
%
<step> Hand the new topmost {&bsol;tt Query} node back. Now the normal
{&bsol;it query rewriting} takes place (in order to handle views if
present) and then the {&bsol;it planner/optimizer} and {&bsol;it executor}
functions are called to get a result. There have no changes been made
to the code of these stages.
%
&bsol;end{itemize}
Figure &bsol;ref{union_operand} shows the rewritten data structure of the
query:
&bsol;begin{verbatim}
   select C1, C2 from A
   intersect
   select C1, C3 from C;
&bsol;end{verbatim}
%
% &bsol;clearpage
%
&bsol;noindent against the tables defined in example &bsol;ref{simple_set_ops}.
The rewritten data structure represents the query:
&bsol;begin{verbatim}
  select C1, C2 form A
  where (C1, C2) in 
        (select C1,C3 from C);
&bsol;end{verbatim}
%
&bsol;noindent The field {&bsol;tt lefttree} of the {&bsol;tt Sublink} node points to a list
where every entry points to a {&bsol;tt VAR} node of the {&bsol;it targetlist} of the
topmost node (node A). The field {&bsol;tt oper} of the {&bsol;tt Sublink} node
points to a list holding a pointer to an {&bsol;tt Expr} node for every
attribute of the topmost {&bsol;it targetlist}. Every {&bsol;tt Expr} node is used to
compare a {&bsol;tt VAR} node of the topmost {&bsol;it targetlist} with the
corresponding {&bsol;tt VAR} node of the subselect's {&bsol;it targetlist}. So the
first argument of every {&bsol;tt Expr} node points to a {&bsol;tt VAR} node of
the topmost {&bsol;it targetlist} and the second argument points to the
corresponding {&bsol;tt VAR} node of the subselect's {&bsol;it targetlist}.
%
&bsol;begin{figure}[ht]
&bsol;begin{flushright}
&bsol;epsfig{figure=figures/union_operand.ps}
&bsol;caption{Data structure of $A &bsol;cap C$ after query rewriting}
&bsol;label{union_operand}
&bsol;end{flushright}
&bsol;end{figure}
%
&bsol;clearpage
%
&bsol;noindent If the user's query involves {&bsol;it union} as well as {&bsol;it
intersect} or {&bsol;it except} there will be more {&bsol;tt Query} nodes of the
form shown in figure &bsol;ref{union_operand}. One will be the topmost node
(as described above) and the others will be collected in a list which
is attached to the field {&bsol;tt unionClause} of the topmost node. (The
{&bsol;it intersectClause} fields of all {&bsol;tt Query} nodes will be set to
{&bsol;tt NULL} because they are no longer needed.) &bsol;&bsol;
&bsol;&bsol;
%
The function {&bsol;tt pg&bsol;_parse&bsol;_and&bsol;_plan()} is responsible for invoking the
rewrite procedure. It can be found in the file {&bsol;tt
$&bsol;ldots$/src/backend/tcop/postgres.c}.
%
&bsol;begin{verbatim}
  List *
  pg_parse_and_plan(char *query_string, Oid *typev,
                    int nargs, 
                    List **queryListP,
                    CommandDest dest) 
  {
                            .
                            .
                            .
    /* Rewrite Union, Intersect and Except Queries
     * to normal Union Queries using IN and NOT 
     * IN subselects */
    if(querytree->intersectClause != NIL) 
    {       
      querytree = Except_Intersect_Rewrite(querytree);
    }
                            .
                            .
                            .
  }
&bsol;end{verbatim}
%
Here are the functions that have been added to perform the
functionality described above. They can be found in the file {&bsol;tt
$&bsol;ldots$/src/backend/rewrite/rewriteHandler.c}.
%
&bsol;begin{itemize}
<step> {&bsol;tt Except&bsol;_Intersect&bsol;_Rewrite()} &bsol;&bsol;
Rewrites queries involving {&bsol;it union clauses}, {&bsol;it intersect
clauses} and {&bsol;it except clauses} to semantiacally equivalent queries
that use {&bsol;tt IN} and {&bsol;tt NOT IN} subselects instead.

The {&bsol;it operator tree} is attached to {&bsol;tt intersectClause} (see rule
{&bsol;tt SelectStmt} above) of the {&bsol;it parsetree} given as an
argument. First we save some clauses (the {&bsol;tt sortClause}, the {&bsol;tt
unique flag} etc.).  Then we translate the {&bsol;it operator tree} to DNF
({&bsol;it Disjunctive Normal Form}) by {&bsol;tt cnfify()}. Note that {&bsol;tt
cnfify()} produces CNF but as we exchanged {&bsol;tt AND} nodes with {&bsol;tt
OR} nodes within function {&bsol;tt A&bsol;_Expr&bsol;_to&bsol;_Expr()} earlier we get DNF
when we exchange {&bsol;tt AND} nodes and {&bsol;tt OR} nodes again in the
result. Now we create a new (rewritten) query by examining the new
{&bsol;it operator tree} which is in DNF now. For every {&bsol;tt AND} node we
create an entry in the {&bsol;it union list} and for every {&bsol;tt OR} node we
create an {&bsol;tt IN} subselect. ({&bsol;tt NOT IN} subselects are created for
{&bsol;tt OR NOT} nodes). The first entry of the {&bsol;it union list} is handed
back but before that the saved clauses ({&bsol;tt sortClause} etc.) are
restored to the new top node. Note that the new top node can differ
from the one of the {&bsol;it parsetree} given as argument because of the
translation into DNF. That's why we had to save the {&bsol;tt sortClause}
etc.
%
&bsol;pagebreak
%
&bsol;begin{verbatim}
  Query *                                                         
  Except_Intersect_Rewrite (Query *parsetree)                     
  {                                                               
                              .
                              .
                              .
    /* Save some fields, to be able to restore them               
     * to the resulting top node at the end of the                
     * function                                                   
     */                                                           
    sortClause = parsetree->sortClause;                           
    uniqueFlag = parsetree->uniqueFlag;                           
    into = parsetree->into;                                       
    isBinary = parsetree->isBinary;                               
    isPortal = parsetree->isPortal;                               
                                                                  
    /* Transform the SelectStmt nodes into Query nodes            
     * as usually done by transformSelectStmt() earlier.          
     * /                                                          
    intersectClause =                                             
      (List *)intersect_tree_analyze(                             
              (Node *)parsetree->intersectClause,                 
              (Node *)lfirst(parsetree->unionClause),             
              (Node *)parsetree);                                 
                              .                                   
                              .                                   
                              .                                   
    /* Transform the operator tree to DNF */
    intersectClause = 
                cnfify((Expr *)intersectClause, true);                      
    /* For every entry of the intersectClause list we             
     * generate one entry in the union_list                       
     */                                                           
    foreach(intersect, intersectClause)                           
    {                                                             
      /* For every OR we create an IN subselect and               
       * for every OR NOT we create a NOT IN subselect,           
       */                                                         
      intersect_list = NIL;                                       
      create_list((Node *)lfirst(intersect),                      
                  &intersect_list);
      /* The first node will become the Select Query 
       * node, all other nodes are transformed into 
       * subselects under this node!                                         
       */                                                         
      intersect_node = (Query *)lfirst(intersect_list);           
      intersect_list = lnext(intersect_list);                     
                              .                                   
                              .                                   
                              .                                   
      /* Transform all remaining nodes into subselects
       * and add them to the qualifications of the 
       * Select Query node                                               
       */                                                         
      while(intersect_list != NIL)                                
      {                                                           
        n = makeNode(SubLink);                                    
                                                                  
        /* Here we got an OR so transform it to an                
         * IN subselect                                           
         */                                                       
        if(IsA(lfirst(intersect_list), Query))                    
        {                                                         
                              .                                   
                              .                                   
                              .                                   
          n->subselect = lfirst(intersect_list);                  
          op = "=";                                               
          n->subLinkType = ANY_SUBLINK;                           
          n->useor = false;                                       
        }                                                         

        /* Here we got an OR NOT node so transform        
         * it to a NOT IN  subselect                                      
         */                                                       
        else                                                      
        {                                                         
                              .                                   
                              .                                   
                              .                                   
          n->subselect = 
             (Node *)lfirst(((Expr *)
                   lfirst(intersect_list))->args);       
          op = "<>";                                              
          n->subLinkType = ALL_SUBLINK;                           
          n->useor = true;                                        
        }

        /* Prepare the lefthand side of the Sublinks:             
         * All the entries of the targetlist must be              
         * (IN) or must not be (NOT IN) the subselect             
         */                                                       
        foreach(elist, intersect_node->targetList)                
        {                                                         
          Node        *expr = lfirst(elist);                      
          TargetEntry *tent = (TargetEntry *)expr;                
                                                                  
          n->lefthand = 
                 lappend(n->lefthand, tent->expr);         
        }

        /* The first arguments of oper also have to be            
         * created for the sublink (they are the same             
         * as the lefthand side!)                                 
         */                                                       
        left_expr = n->lefthand;                                  
        right_expr = 
             ((Query *)(n->subselect))->targetList;
        foreach(elist, left_expr)                                 
        {                                                         
          Node         *lexpr = lfirst(elist);                    
          Node         *rexpr = lfirst(right_expr);               
          TargetEntry *tent = (TargetEntry *) rexpr;              
          Expr         *op_expr;                                  
                                                                  
          op_expr = make_op(op, lexpr, tent->expr);         
          n->oper = lappend(n->oper, op_expr);                    
          right_expr = lnext(right_expr);                         
        }

        /* If the Select Query node has aggregates                
         * in use add all the subselects to the                   
         * HAVING qual else to the WHERE qual                     
         */                                                       
        if(intersect_node->hasAggs == false)                      
        {                                                         
          AddQual(intersect_node, (Node *)n);                     
        }                                                         
        else                                                      
        {                                                         
          AddHavingQual(intersect_node, (Node *)n);               
        }

        /* Now we got sublinks */                                 
        intersect_node->hasSubLinks = true;                       
        intersect_list = lnext(intersect_list);                   
      }
      intersect_node->intersectClause = NIL;                      
      union_list = lappend(union_list, intersect_node);           
    }                                                             

    /* The first entry to union_list is our                       
     * new top node                                               
     */                                                           
    result = (Query *)lfirst(union_list);                         
                                                                  
    /* attach the rest to unionClause */                          
    result->unionClause = lnext(union_list);                      
                                                                  
    /* Attach all the items saved in the                          
     * beginning of the function */                               
    result->sortClause = sortClause;                              
    result->uniqueFlag = uniqueFlag;                              
    result->into = into;                                          
    result->isPortal = isPortal;                                  
    result->isBinary = isBinary;                                  
                              .                                   
                              .                                   
                              .                                   
    return  result;                                               
  }
&bsol;end{verbatim}
%
<step> {&bsol;tt create&bsol;_list()} &bsol;&bsol;
Create a list of nodes that are either {&bsol;tt Query} nodes or {&bsol;tt NOT}
nodes followed by a {&bsol;tt Query} node. The {&bsol;it tree} given in {&bsol;tt
ptr} contains at least one {&bsol;it non negated} {&bsol;tt Query} node. This
node is put to the beginning of the list.
%
&bsol;begin{verbatim}
  void create_list(Node *ptr, 
                   List **intersect_list)
  {
    List *arg;   

    if(IsA(ptr,Query))
    {
      /* The non negated node is attached at the 
       * beginning (lcons) */
      *intersect_list = lcons(ptr, *intersect_list);
      return;      
    }  
    if(IsA(ptr,Expr))
    {
      if(((Expr *)ptr)->opType == NOT_EXPR)
      {
        /* negated nodes are appended to the 
         * end (lappend) 
         */
        *intersect_list = 
               lappend(*intersect_list, ptr);        
        return;         
      }
      else
      {
        foreach(arg, ((Expr *)ptr)->args)
        {
          create_list(lfirst(arg), intersect_list);
        }     
        return;         
      }
      return;      
    }
  }
&bsol;end{verbatim}
%
<step> {&bsol;tt intersect&bsol;_tree&bsol;_analyze()} &bsol;&bsol;
%
The nodes given in {&bsol;tt tree} are not transformed yet so process them
using {&bsol;tt parse&bsol;_analyze()}.  The node given in {&bsol;tt first&bsol;_select}
has already been processed, so don't transform it again but return a
pointer to the already processed version given in {&bsol;tt parsetree}
instead.
%
&bsol;begin{verbatim}
  Node *intersect_tree_analyze(Node *tree, 
                Node *first_select, Node *parsetree)
  {
    Node *result; 
    List *arg;

    if(IsA(tree, SelectStmt))
    {
      List *qtrees;

      /* If we get to the tree given in first_select 
       * return parsetree instead of performing 
       * parse_analyze() */
      if(tree == first_select)
      {
        result = parsetree;
      }
      else 
      {    
        /* transform the unprocessed Query nodes */ 
        qtrees = parse_analyze(lcons(tree, NIL), NULL);
        result = (Node *) lfirst(qtrees);
      }      
    }  
    if(IsA(tree,Expr))
    {
      /* Call recursively for every argument */
       foreach(arg, ((Expr *)tree)->args)
       {
         lfirst(arg) = 
             intersect_tree_analyze(lfirst(arg), 
                          first_select, parsetree);
       }
       result = tree;      
    }
    return result;  
  }
&bsol;end{verbatim}
%

&bsol;end{itemize}

**********************************************************
**********************************************************
**********************************************************
**********************************************************
**********************************************************
]]>

 </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:
-->
