Updatable views

Started by Alvaro Herreraover 19 years ago44 messages
#1Alvaro Herrera
alvherre@commandprompt.com
4 attachment(s)

Hi,

This is the patch for updatable views I've been able to come up with. A
nasty bug was just discovered in the upcoming Mammoth Replicator release
so I'm not sure if I'm going to have time to work more on it soon.

So, I'll appreciate if somebody else takes the responsability to fix the
remaining issues. I've put a lot of XXX's and some FIXME's. Some
functions are in need of some comments as well.

The new files are src/backend/rewrite/viewUpdate.c and
src/include/rewrite/viewUpdate.h. The third file, upd-views.sql, is
intended to be a new regression test. Extra points if the table therein
is completed correctly.

I haven't tested the array stuff at all.

Comments from Bernd and Jaime are especially welcome if I've broken
something that used to work on their patch :-)

--
Alvaro Herrera http://www.CommandPrompt.com/
The PostgreSQL Company - Command Prompt, Inc.

Attachments:

upd-views-2.patchtext/plain; charset=us-asciiDownload
Index: doc/src/sgml/catalogs.sgml
===================================================================
RCS file: /home/alvherre/cvs/pgsql/doc/src/sgml/catalogs.sgml,v
retrieving revision 2.129
diff -c -p -r2.129 catalogs.sgml
*** doc/src/sgml/catalogs.sgml	31 Jul 2006 20:08:55 -0000	2.129
--- doc/src/sgml/catalogs.sgml	17 Aug 2006 03:34:45 -0000
***************
*** 3502,3507 ****
--- 3502,3519 ----
       </row>
  
       <row>
+       <entry><structfield>ev_kind</structfield></entry>
+       <entry><type>char</type></entry>
+       <entry></entry>
+       <entry>  
+        <literal>l</> = with local check option,   
+        <literal>c</> = with cascaded check option,
+        <literal>n</> = no check option specified,
+        <literal>e</> = rule was created by user 
+       </entry>
+      </row>
+ 
+      <row>
        <entry><structfield>ev_qual</structfield></entry>
        <entry><type>text</type></entry>
        <entry></entry>
Index: doc/src/sgml/information_schema.sgml
===================================================================
RCS file: /home/alvherre/cvs/pgsql/doc/src/sgml/information_schema.sgml,v
retrieving revision 1.26
diff -c -p -r1.26 information_schema.sgml
*** doc/src/sgml/information_schema.sgml	2 May 2006 18:07:51 -0000	1.26
--- doc/src/sgml/information_schema.sgml	17 Aug 2006 03:34:45 -0000
*************** ORDER BY c.ordinal_position;
*** 5085,5091 ****
       <row>
        <entry><literal>check_option</literal></entry>
        <entry><type>character_data</type></entry>
!       <entry>Applies to a feature not available in <productname>PostgreSQL</></entry>
       </row>
  
       <row>
--- 5085,5095 ----
       <row>
        <entry><literal>check_option</literal></entry>
        <entry><type>character_data</type></entry>
!       <entry>
!        The level of integrity checking in updatable views,
!        either <literal>LOCAL</literal>, <literal>CASCADED</literal>
!        or <literal>NONE</literal>
!      </entry>
       </row>
  
       <row>
Index: doc/src/sgml/intro.sgml
===================================================================
RCS file: /home/alvherre/cvs/pgsql/doc/src/sgml/intro.sgml,v
retrieving revision 1.31
diff -c -p -r1.31 intro.sgml
*** doc/src/sgml/intro.sgml	10 Mar 2006 19:10:48 -0000	1.31
--- doc/src/sgml/intro.sgml	17 Aug 2006 03:34:45 -0000
***************
*** 110,116 ****
       <simpara>triggers</simpara>
      </listitem>
      <listitem>
!      <simpara>views</simpara>
      </listitem>
      <listitem>
       <simpara>transactional integrity</simpara>
--- 110,116 ----
       <simpara>triggers</simpara>
      </listitem>
      <listitem>
!      <simpara>updatable views</simpara>
      </listitem>
      <listitem>
       <simpara>transactional integrity</simpara>
Index: doc/src/sgml/ref/create_view.sgml
===================================================================
RCS file: /home/alvherre/cvs/pgsql/doc/src/sgml/ref/create_view.sgml,v
retrieving revision 1.31
diff -c -p -r1.31 create_view.sgml
*** doc/src/sgml/ref/create_view.sgml	1 Nov 2005 21:09:50 -0000	1.31
--- doc/src/sgml/ref/create_view.sgml	17 Aug 2006 03:34:45 -0000
*************** PostgreSQL documentation
*** 22,27 ****
--- 22,28 ----
  <synopsis>
  CREATE [ OR REPLACE ] [ TEMP | TEMPORARY ] VIEW <replaceable class="PARAMETER">name</replaceable> [ ( <replaceable class="PARAMETER">column_name</replaceable> [, ...] ) ]
      AS <replaceable class="PARAMETER">query</replaceable>
+     [ WITH [ CASCADED | LOCAL ] CHECK OPTION ]
  </synopsis>
   </refsynopsisdiv>
  
*************** CREATE [ OR REPLACE ] [ TEMP | TEMPORARY
*** 109,114 ****
--- 110,150 ----
       </para>
      </listitem>
     </varlistentry>
+ 
+    <variablelist>
+      <varlistentry>
+       <term><literal>CHECK OPTION</literal></term>
+       <listitem>
+        <para>
+         This option has to do with updatable views.  All
+         <command>INSERT</> and <command>UPDATE</> commands on the view
+         will be checked to ensure data satisfy the view-defining
+         condition (that is, the new data would be visible through the
+         view).  If they do not, the update will be rejected.
+        </para>
+       </listitem>
+      </varlistentry>
+ 
+      <varlistentry>
+       <term><literal>LOCAL</literal></term>
+       <listitem>
+        <para>
+         Check for integrity on this view.
+        </para>
+       </listitem>
+      </varlistentry>
+ 
+      <varlistentry>
+       <term><literal>CASCADED</literal></term>
+       <listitem>
+        <para>
+         Check for integrity on this view and on any dependent
+         view.  <literal>CASCADED</> is assumed if neither
+         <literal>CASCADED</> nor <literal>LOCAL</> is specified.
+        </para>
+       </listitem>
+      </varlistentry>
+    
    </variablelist>
   </refsect1>
  
*************** CREATE [ OR REPLACE ] [ TEMP | TEMPORARY
*** 116,126 ****
    <title>Notes</title>
  
     <para>
!     Currently, views are read only: the system will not allow an insert,
!     update, or delete on a view.  You can get the effect of an updatable
!     view by creating rules that rewrite inserts, etc. on the view into
!     appropriate actions on other tables.  For more information see
!     <xref linkend="sql-createrule" endterm="sql-createrule-title">.
     </para>
  
     <para>
--- 152,201 ----
    <title>Notes</title>
  
     <para>
!     Currently, views are updatable following SQL92 specifications, that
!     is: 
!    </para>
! 
!    <itemizedlist>
!     <listitem>
!      <para>
!       Views with just one base table (or another updatable view)
!      </para>
!     </listitem>
! 
!     <listitem>
!      <para>No aggregate functions</para>
!     </listitem>
! 
!     <listitem>
!      <para>
!       No <literal>HAVING</literal>, <literal>DISTINCT</literal> nor
!       <literal>GROUP BY</literal> clauses
!      </para>
!     </listitem>
! 
!     <listitem>
!      <para>
!       No <literal>UNION</literal>, <literal>INTERSECT</literal>,
!       <literal>EXCEPT</literal>clauses
!      </para>
!     </listitem>
!    </itemizedlist>
! 
!    <para>
!     Views are insertable only if you provide in the defining
!     <command>SELECT</command> statement all columns that are NOT NULL and don't
!     have a default value.
!    </para>
! 
!    <para>
!     The updatable views implementation is based on the rule system.  Because of
!     this, you can get the same effect in more complex views by creating your
!     own rules that rewrite the <command>INSERT</command>,
!     <command>UPDATE</command> and <command>UPDATE</command> actions on the view
!     into appropriate actions on other tables. You can also replace
!     automatically generated rules with your own rules. For more information,
!     refer to <xref linkend="sql-createrule" endterm="sql-createrule-title">.
     </para>
  
     <para>
*************** CREATE VIEW comedies AS
*** 171,225 ****
    <title>Compatibility</title>
  
    <para>
-    The SQL standard specifies some additional capabilities for the
-    <command>CREATE VIEW</command> statement:
- <synopsis>
- CREATE VIEW <replaceable class="parameter">name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ]
-     AS <replaceable class="PARAMETER">query</replaceable>
-     [ WITH [ CASCADED | LOCAL ] CHECK OPTION ]
- </synopsis>
-   </para>
- 
-   <para>
-    The optional clauses for the full SQL command are:
- 
-    <variablelist>
-      <varlistentry>
-       <term><literal>CHECK OPTION</literal></term>
-       <listitem>
-        <para>
-         This option has to do with updatable views.  All
-         <command>INSERT</> and <command>UPDATE</> commands on the view
-         will be checked to ensure data satisfy the view-defining
-         condition (that is, the new data would be visible through the
-         view). If they do not, the update will be rejected.
-        </para>
-       </listitem>
-      </varlistentry>
- 
-      <varlistentry>
-       <term><literal>LOCAL</literal></term>
-       <listitem>
-        <para>
-         Check for integrity on this view.
-        </para>
-       </listitem>
-      </varlistentry>
- 
-      <varlistentry>
-       <term><literal>CASCADED</literal></term>
-       <listitem>
-        <para>
-         Check for integrity on this view and on any dependent
-         view. <literal>CASCADED</> is assumed if neither
-         <literal>CASCADED</> nor <literal>LOCAL</> is specified.
-        </para>
-       </listitem>
-      </varlistentry>
-    </variablelist>
-   </para>
- 
-   <para>
     <command>CREATE OR REPLACE VIEW</command> is a
     <productname>PostgreSQL</productname> language extension.
     So is the concept of a temporary view.
--- 246,251 ----
Index: src/backend/catalog/information_schema.sql
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/backend/catalog/information_schema.sql,v
retrieving revision 1.33
diff -c -p -r1.33 information_schema.sql
*** src/backend/catalog/information_schema.sql	2 Apr 2006 17:38:13 -0000	1.33
--- src/backend/catalog/information_schema.sql	17 Aug 2006 03:34:45 -0000
*************** CREATE VIEW views AS
*** 2126,2132 ****
                    ELSE null END
               AS character_data) AS view_definition,
  
!            CAST('NONE' AS character_data) AS check_option,
  
             CAST(
               CASE WHEN EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 2 AND is_instead)
--- 2126,2143 ----
                    ELSE null END
               AS character_data) AS view_definition,
  
!            CAST(
!              CASE WHEN EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 2 AND is_instead AND ev_kind = 'l')
!                     OR EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 3 AND is_instead AND ev_kind = 'l')
!                     OR EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 4 AND is_instead AND ev_kind = 'l')
!                   THEN 'LOCAL'
!                   WHEN EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 2 AND is_instead AND ev_kind = 'c')
!                     OR EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 3 AND is_instead AND ev_kind = 'c')
!                     OR EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 4 AND is_instead AND ev_kind = 'c')
!                   THEN 'CASCADED'
!                   ELSE 'NONE' 
!              END
!            AS character_data) AS check_option,
  
             CAST(
               CASE WHEN EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 2 AND is_instead)
Index: src/backend/commands/view.c
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/backend/commands/view.c,v
retrieving revision 1.96
diff -c -p -r1.96 view.c
*** src/backend/commands/view.c	13 Jul 2006 16:49:14 -0000	1.96
--- src/backend/commands/view.c	20 Aug 2006 19:55:36 -0000
***************
*** 29,41 ****
--- 29,44 ----
  #include "rewrite/rewriteDefine.h"
  #include "rewrite/rewriteManip.h"
  #include "rewrite/rewriteSupport.h"
+ #include "rewrite/viewUpdate.h"
  #include "utils/acl.h"
  #include "utils/lsyscache.h"
+ #include "utils/memutils.h"
  
  
  static void checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc);
  static bool isViewOnTempTable_walker(Node *node, void *context);
  
+ 
  /*---------------------------------------------------------------------
   * isViewOnTempTable
   *
*************** FormViewRetrieveRule(const RangeVar *vie
*** 281,330 ****
  }
  
  static void
! DefineViewRules(const RangeVar *view, Query *viewParse, bool replace)
  {
  	RuleStmt   *retrieve_rule;
  
- #ifdef NOTYET
- 	RuleStmt   *replace_rule;
- 	RuleStmt   *append_rule;
- 	RuleStmt   *delete_rule;
- #endif
- 
  	retrieve_rule = FormViewRetrieveRule(view, viewParse, replace);
  
! #ifdef NOTYET
! 	replace_rule = FormViewReplaceRule(view, viewParse);
! 	append_rule = FormViewAppendRule(view, viewParse);
! 	delete_rule = FormViewDeleteRule(view, viewParse);
! #endif
! 
! 	DefineQueryRewrite(retrieve_rule);
! 
! #ifdef NOTYET
! 	DefineQueryRewrite(replace_rule);
! 	DefineQueryRewrite(append_rule);
! 	DefineQueryRewrite(delete_rule);
! #endif
  
  }
  
! /*---------------------------------------------------------------
   * UpdateRangeTableOfViewParse
   *
!  * Update the range table of the given parsetree.
!  * This update consists of adding two new entries IN THE BEGINNING
!  * of the range table (otherwise the rule system will die a slow,
!  * horrible and painful death, and we do not want that now, do we?)
!  * one for the OLD relation and one for the NEW one (both of
   * them refer in fact to the "view" relation).
   *
!  * Of course we must also increase the 'varnos' of all the Var nodes
!  * by 2...
   *
!  * These extra RT entries are not actually used in the query,
!  * except for run-time permission checking.
!  *---------------------------------------------------------------
   */
  static Query *
  UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
--- 284,315 ----
  }
  
  static void
! DefineViewRules(const RangeVar *view, Query *viewParse, bool replace,
! 				bool checkOption, bool cascade)
  {
  	RuleStmt   *retrieve_rule;
  
  	retrieve_rule = FormViewRetrieveRule(view, viewParse, replace);
  
! 	DefineQueryRewrite(retrieve_rule, 
! 					   makeViewCheckOption(checkOption, cascade));
  
+ 	CreateViewUpdateRules(viewParse, view, checkOption, cascade);
  }
  
! /*
   * UpdateRangeTableOfViewParse
   *
!  * Update the range table of the given parsetree.  This update consists of
!  * adding two new entries IN THE BEGINNING of the range table (otherwise the
!  * rule system will die a slow, horrible and painful death, and we do not want
!  * that now, do we?) one for the OLD relation and one for the NEW one (both of
   * them refer in fact to the "view" relation).
   *
!  * Of course we must also increase the 'varnos' of all the Var nodes by 2...
   *
!  * These extra RT entries are not actually used in the query, except for
!  * run-time permission checking.
   */
  static Query *
  UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
*************** UpdateRangeTableOfViewParse(Oid viewOid,
*** 388,394 ****
   *-------------------------------------------------------------------
   */
  void
! DefineView(RangeVar *view, Query *viewParse, bool replace)
  {
  	Oid			viewOid;
  
--- 373,380 ----
   *-------------------------------------------------------------------
   */
  void
! DefineView(RangeVar *view, Query *viewParse, bool replace, bool checkOption,
! 		   bool cascade)
  {
  	Oid			viewOid;
  
*************** DefineView(RangeVar *view, Query *viewPa
*** 429,435 ****
  	/*
  	 * Now create the rules associated with the view.
  	 */
! 	DefineViewRules(view, viewParse, replace);
  }
  
  /*
--- 415,421 ----
  	/*
  	 * Now create the rules associated with the view.
  	 */
! 	DefineViewRules(view, viewParse, replace, checkOption, cascade);
  }
  
  /*
Index: src/backend/parser/gram.y
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/backend/parser/gram.y,v
retrieving revision 2.556
diff -c -p -r2.556 gram.y
*** src/backend/parser/gram.y	12 Aug 2006 18:58:54 -0000	2.556
--- src/backend/parser/gram.y	19 Aug 2006 19:48:37 -0000
*************** AlterOwnerStmt: ALTER AGGREGATE func_nam
*** 4473,4479 ****
   *****************************************************************************/
  
  RuleStmt:	CREATE opt_or_replace RULE name AS
! 			{ QueryIsRule=TRUE; }
  			ON event TO qualified_name where_clause
  			DO opt_instead RuleActionList
  				{
--- 4473,4479 ----
   *****************************************************************************/
  
  RuleStmt:	CREATE opt_or_replace RULE name AS
! 			{ QueryIsRule = true; }
  			ON event TO qualified_name where_clause
  			DO opt_instead RuleActionList
  				{
*************** RuleStmt:	CREATE opt_or_replace RULE nam
*** 4486,4492 ****
  					n->instead = $13;
  					n->actions = $14;
  					$$ = (Node *)n;
! 					QueryIsRule=FALSE;
  				}
  		;
  
--- 4486,4492 ----
  					n->instead = $13;
  					n->actions = $14;
  					$$ = (Node *)n;
! 					QueryIsRule = false;
  				}
  		;
  
*************** RuleActionList:
*** 4499,4511 ****
  /* the thrashing around here is to discard "empty" statements... */
  RuleActionMulti:
  			RuleActionMulti ';' RuleActionStmtOrEmpty
! 				{ if ($3 != NULL)
  					$$ = lappend($1, $3);
  				  else
  					$$ = $1;
  				}
  			| RuleActionStmtOrEmpty
! 				{ if ($1 != NULL)
  					$$ = list_make1($1);
  				  else
  					$$ = NIL;
--- 4499,4513 ----
  /* the thrashing around here is to discard "empty" statements... */
  RuleActionMulti:
  			RuleActionMulti ';' RuleActionStmtOrEmpty
! 				{
! 				  if ($3 != NULL)
  					$$ = lappend($1, $3);
  				  else
  					$$ = $1;
  				}
  			| RuleActionStmtOrEmpty
! 				{
! 				  if ($1 != NULL)
  					$$ = list_make1($1);
  				  else
  					$$ = NIL;
*************** ViewStmt: CREATE OptTemp VIEW qualified_
*** 4770,4775 ****
--- 4772,4778 ----
  					n->view->istemp = $2;
  					n->aliases = $5;
  					n->query = (Query *) $7;
+ 					n->options = $8;
  					$$ = (Node *) n;
  				}
  		| CREATE OR REPLACE OptTemp VIEW qualified_name opt_column_list
*************** ViewStmt: CREATE OptTemp VIEW qualified_
*** 4781,4786 ****
--- 4784,4790 ----
  					n->view->istemp = $4;
  					n->aliases = $7;
  					n->query = (Query *) $9;
+ 					n->options = $10;
  					$$ = (Node *) n;
  				}
  		;
*************** ViewStmt: CREATE OptTemp VIEW qualified_
*** 4792,4812 ****
  opt_check_option:
  		WITH_CHECK OPTION
  				{
! 					ereport(ERROR,
! 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
! 							 errmsg("WITH CHECK OPTION is not implemented")));
  				}
  		| WITH_CASCADED CHECK OPTION
  				{
! 					ereport(ERROR,
! 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
! 							 errmsg("WITH CHECK OPTION is not implemented")));
  				}
  		| WITH_LOCAL CHECK OPTION
  				{
! 					ereport(ERROR,
! 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
! 							 errmsg("WITH CHECK OPTION is not implemented")));
  				}
  		| /* EMPTY */							{ $$ = NIL; }
  		;
--- 4796,4810 ----
  opt_check_option:
  		WITH_CHECK OPTION
  				{
! 					$$ = list_make1((Node *)makeString("cascaded"));
  				}
  		| WITH_CASCADED CHECK OPTION
  				{
! 					$$ = list_make1((Node *)makeString("cascaded"));
  				}
  		| WITH_LOCAL CHECK OPTION
  				{
! 					$$ = list_make1((Node *)makeString("local"));
  				}
  		| /* EMPTY */							{ $$ = NIL; }
  		;
Index: src/backend/parser/keywords.c
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/backend/parser/keywords.c,v
retrieving revision 1.175
diff -c -p -r1.175 keywords.c
*** src/backend/parser/keywords.c	12 Aug 2006 02:52:05 -0000	1.175
--- src/backend/parser/keywords.c	17 Aug 2006 03:34:45 -0000
*************** static const ScanKeyword ScanKeywords[] 
*** 67,72 ****
--- 67,73 ----
  	{"cache", CACHE},
  	{"called", CALLED},
  	{"cascade", CASCADE},
+ 	{"cascaded", CASCADED},
  	{"case", CASE},
  	{"cast", CAST},
  	{"chain", CHAIN},
Index: src/backend/rewrite/Makefile
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/backend/rewrite/Makefile,v
retrieving revision 1.15
diff -c -p -r1.15 Makefile
*** src/backend/rewrite/Makefile	29 Nov 2003 19:51:55 -0000	1.15
--- src/backend/rewrite/Makefile	20 Aug 2006 19:47:51 -0000
*************** top_builddir = ../../..
*** 13,19 ****
  include $(top_builddir)/src/Makefile.global
  
  OBJS = rewriteRemove.o rewriteDefine.o \
!        rewriteHandler.o rewriteManip.o rewriteSupport.o
  
  all: SUBSYS.o
  
--- 13,20 ----
  include $(top_builddir)/src/Makefile.global
  
  OBJS = rewriteRemove.o rewriteDefine.o \
!        rewriteHandler.o rewriteManip.o rewriteSupport.o \
!        viewUpdate.o
  
  all: SUBSYS.o
  
Index: src/backend/rewrite/rewriteDefine.c
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/backend/rewrite/rewriteDefine.c,v
retrieving revision 1.112
diff -c -p -r1.112 rewriteDefine.c
*** src/backend/rewrite/rewriteDefine.c	12 Aug 2006 20:05:55 -0000	1.112
--- src/backend/rewrite/rewriteDefine.c	17 Aug 2006 03:34:45 -0000
***************
*** 23,28 ****
--- 23,29 ----
  #include "parser/parse_expr.h"
  #include "rewrite/rewriteDefine.h"
  #include "rewrite/rewriteManip.h"
+ #include "rewrite/rewriteRemove.h"
  #include "rewrite/rewriteSupport.h"
  #include "storage/smgr.h"
  #include "utils/acl.h"
*************** InsertRule(char *rulname,
*** 47,52 ****
--- 48,54 ----
  		   Oid eventrel_oid,
  		   AttrNumber evslot_index,
  		   bool evinstead,
+ 		   char evkind,
  		   Node *event_qual,
  		   List *action,
  		   bool replace)
*************** InsertRule(char *rulname,
*** 78,83 ****
--- 80,86 ----
  	values[i++] = Int16GetDatum(evslot_index);	/* ev_attr */
  	values[i++] = CharGetDatum(evtype + '0');	/* ev_type */
  	values[i++] = BoolGetDatum(evinstead);		/* is_instead */
+ 	values[i++] = CharGetDatum(evkind);         /* ev_kind */
  	values[i++] = DirectFunctionCall1(textin, CStringGetDatum(evqual)); /* ev_qual */
  	values[i++] = DirectFunctionCall1(textin, CStringGetDatum(actiontree));		/* ev_action */
  
*************** InsertRule(char *rulname,
*** 97,107 ****
  	if (HeapTupleIsValid(oldtup))
  	{
  		if (!replace)
! 			ereport(ERROR,
! 					(errcode(ERRCODE_DUPLICATE_OBJECT),
! 					 errmsg("rule \"%s\" for relation \"%s\" already exists",
! 							rulname, get_rel_name(eventrel_oid))));
  
  		/*
  		 * When replacing, we don't need to replace every attribute
  		 */
--- 100,131 ----
  	if (HeapTupleIsValid(oldtup))
  	{
  		if (!replace)
! 		{
! 			/*
! 			 * If REPLACE was not used we still have to check if the
! 			 * rule is implicit: then we have to replace it anyways.
! 			 */
! 			char	old_tup_is_implicit;
! 			bool	isnull;
! 			Datum	dat;
! 
! 			dat = heap_getattr(oldtup,
! 									 Anum_pg_rewrite_ev_kind,
! 									 RelationGetDescr(pg_rewrite_desc),
! 									 &isnull);
! 			/* should not happen */
! 			if (!isnull) 
! 				elog(ERROR, "got null field in ev_kind where not null expected");
! 			
! 			old_tup_is_implicit = DatumGetChar(dat);
  
+ 			if (old_tup_is_implicit == NO_OPTION_EXPLICIT)
+ 				ereport(ERROR,
+ 						(errcode(ERRCODE_DUPLICATE_OBJECT),
+ 						 errmsg("rule \"%s\" for relation \"%s\" already exists",
+ 								rulname, get_rel_name(eventrel_oid))));
+ 		}
+ 		
  		/*
  		 * When replacing, we don't need to replace every attribute
  		 */
*************** InsertRule(char *rulname,
*** 109,114 ****
--- 133,139 ----
  		replaces[Anum_pg_rewrite_ev_attr - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_type - 1] = 'r';
  		replaces[Anum_pg_rewrite_is_instead - 1] = 'r';
+ 		replaces[Anum_pg_rewrite_ev_kind - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_qual - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_action - 1] = 'r';
  
*************** InsertRule(char *rulname,
*** 177,183 ****
  }
  
  void
! DefineQueryRewrite(RuleStmt *stmt)
  {
  	RangeVar   *event_obj = stmt->relation;
  	Node	   *event_qual = stmt->whereClause;
--- 202,208 ----
  }
  
  void
! DefineQueryRewrite(RuleStmt *stmt, char ev_kind)
  {
  	RangeVar   *event_obj = stmt->relation;
  	Node	   *event_qual = stmt->whereClause;
*************** DefineQueryRewrite(RuleStmt *stmt)
*** 444,449 ****
--- 469,484 ----
  	}
  	setRuleCheckAsUser_Expr(event_qual, GetUserId());
  
+ 	/*
+ 	 * Implicit rules should be dropped automatically when someone
+ 	 * wants to have its *own* rules on the view. is_implicit is set
+ 	 * to NO_OPTION_EXPLICIT in this case so we drop all implicit 
+ 	 * rules on the specified event type immediately.
+ 	 */
+ 
+ 	if (ev_kind == NO_OPTION_EXPLICIT)
+ 		 deleteImplicitRulesOnEvent(event_relation, event_type);
+ 
  	/* discard rule if it's null action and not INSTEAD; it's a no-op */
  	if (action != NIL || is_instead)
  	{
*************** DefineQueryRewrite(RuleStmt *stmt)
*** 452,457 ****
--- 487,493 ----
  							ev_relid,
  							event_attno,
  							is_instead,
+ 							ev_kind,
  							event_qual,
  							action,
  							replace);
*************** DefineQueryRewrite(RuleStmt *stmt)
*** 469,483 ****
  	}
  
  	/*
! 	 * IF the relation is becoming a view, delete the storage files associated
  	 * with it.  NB: we had better have AccessExclusiveLock to do this ...
  	 *
  	 * XXX what about getting rid of its TOAST table?  For now, we don't.
  	 */
  	if (RelisBecomingView)
  	{
! 		RelationOpenSmgr(event_relation);
  		smgrscheduleunlink(event_relation->rd_smgr, event_relation->rd_istemp);
  	}
  
  	/* Close rel, but keep lock till commit... */
--- 505,526 ----
  	}
  
  	/*
! 	 * If the relation is becoming a view, delete the storage files associated
  	 * with it.  NB: we had better have AccessExclusiveLock to do this ...
  	 *
  	 * XXX what about getting rid of its TOAST table?  For now, we don't.
  	 */
  	if (RelisBecomingView)
  	{
! 		/*
! 		 * XXX -- Why this change?
! 		 *
! 		 RelationOpenSmgr(event_relation);
! 		 */
! 		if (event_relation->rd_smgr == NULL)
! 			event_relation->rd_smgr = smgropen(event_relation->rd_node);
  		smgrscheduleunlink(event_relation->rd_smgr, event_relation->rd_istemp);
+ 		event_relation->rd_smgr = NULL;
  	}
  
  	/* Close rel, but keep lock till commit... */
Index: src/backend/rewrite/rewriteHandler.c
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/backend/rewrite/rewriteHandler.c,v
retrieving revision 1.165
diff -c -p -r1.165 rewriteHandler.c
*** src/backend/rewrite/rewriteHandler.c	2 Aug 2006 01:59:47 -0000	1.165
--- src/backend/rewrite/rewriteHandler.c	20 Aug 2006 01:20:23 -0000
***************
*** 15,20 ****
--- 15,21 ----
  
  #include "access/heapam.h"
  #include "catalog/pg_type.h"
+ #include "catalog/pg_rewrite.h"
  #include "nodes/makefuncs.h"
  #include "optimizer/clauses.h"
  #include "parser/analyze.h"
*************** typedef struct rewrite_event
*** 34,45 ****
  	CmdType		event;			/* type of rule being fired */
  } rewrite_event;
  
  static bool acquireLocksOnSubLinks(Node *node, void *context);
  static Query *rewriteRuleAction(Query *parsetree,
  				  Query *rule_action,
  				  Node *rule_qual,
  				  int rt_index,
! 				  CmdType event);
  static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index);
  static void rewriteTargetList(Query *parsetree, Relation target_relation,
  							  List **attrno_list);
--- 35,55 ----
  	CmdType		event;			/* type of rule being fired */
  } rewrite_event;
  
+ /* Rule rewrite status for updatable views */
+ typedef struct view_update_event
+ {
+ 	bool viewUpdate;
+ 	bool needCheckOption;
+ 	char checkMode;	
+ } view_update_event;
+ 
  static bool acquireLocksOnSubLinks(Node *node, void *context);
  static Query *rewriteRuleAction(Query *parsetree,
  				  Query *rule_action,
  				  Node *rule_qual,
  				  int rt_index,
!                   CmdType event,
! 				  view_update_event *view_event);
  static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index);
  static void rewriteTargetList(Query *parsetree, Relation target_relation,
  							  List **attrno_list);
*************** rewriteRuleAction(Query *parsetree,
*** 257,263 ****
  				  Query *rule_action,
  				  Node *rule_qual,
  				  int rt_index,
! 				  CmdType event)
  {
  	int			current_varno,
  				new_varno;
--- 267,274 ----
  				  Query *rule_action,
  				  Node *rule_qual,
  				  int rt_index,
! 				  CmdType event,
! 				  view_update_event *view_event)
  {
  	int			current_varno,
  				new_varno;
*************** rewriteRuleAction(Query *parsetree,
*** 387,393 ****
  	 * queries one w/rule_qual, one w/NOT rule_qual. Also add user query qual
  	 * onto rule action
  	 */
! 	AddQual(sub_action, rule_qual);
  
  	AddQual(sub_action, parsetree->jointree->quals);
  
--- 398,405 ----
  	 * queries one w/rule_qual, one w/NOT rule_qual. Also add user query qual
  	 * onto rule action
  	 */
! 	if (view_event->needCheckOption)
! 		AddQual(sub_action, rule_qual);
  
  	AddQual(sub_action, parsetree->jointree->quals);
  
*************** build_column_default(Relation rel, int a
*** 820,825 ****
--- 832,850 ----
  		}
  	}
  
+ #if 0
+ 	/*
+ 	 * I will do this only in case of relkind == RELKIND_VIEW.
+ 	 * This is the last attempt to get a value for expr before we
+ 	 * consider that expr must be NULL.
+ 	 */
+ 	if (expr == NULL && rel->rd_rel->relkind == RELKIND_VIEW)
+ 	{
+ 		expr = (Node *)makeNode(SetToDefault);
+ 		return expr;
+ 	}
+ #endif
+ 		
  	if (expr == NULL)
  	{
  		/*
*************** CopyAndAddInvertedQual(Query *parsetree,
*** 1362,1367 ****
--- 1387,1394 ----
   * Return value:
   *	list of rule actions adjusted for use with this query
   *
+  *	view_event -- FIXME -- what is this for?
+  *
   * Qualified INSTEAD rules generate their action with the qualification
   * condition added.  They also generate a modified version of the original
   * query with the negated qualification added, so that it will run only for
*************** fireRules(Query *parsetree,
*** 1376,1381 ****
--- 1403,1409 ----
  		  int rt_index,
  		  CmdType event,
  		  List *locks,
+ 		  view_update_event *view_event,
  		  bool *instead_flag,
  		  Query **qual_product)
  {
*************** fireRules(Query *parsetree,
*** 1390,1400 ****
  		QuerySource qsrc;
  		ListCell   *r;
  
  		/* Determine correct QuerySource value for actions */
  		if (rule_lock->isInstead)
  		{
! 			if (event_qual != NULL)
! 				qsrc = QSRC_QUAL_INSTEAD_RULE;
  			else
  			{
  				qsrc = QSRC_INSTEAD_RULE;
--- 1418,1507 ----
  		QuerySource qsrc;
  		ListCell   *r;
  
+ 		/*
+ 		 * First check: look if this rule is an implicit view update rule. If
+ 		 * false, always apply any rule qualification.
+ 		 */
+ 		if (rule_lock->ev_kind == NO_OPTION_EXPLICIT)
+ 		{
+ 			view_event->viewUpdate = false;
+ 			view_event->needCheckOption = true;
+ 			view_event->checkMode = rule_lock->ev_kind;
+ 		}
+ 		
+ 		/*
+ 		 * Second check: Look if we are already in a view update or not.  If
+ 		 * true and the event check mode is set to LOCAL_OPTION_IMPLICIT in
+ 		 * conjunction with viewUpdate = true, we don't need to apply the check
+ 		 * option otherwise.
+ 		 */
+ 		else if (!view_event->viewUpdate &&
+ 				 ((rule_lock->ev_kind == LOCAL_OPTION_IMPLICIT) ||
+ 				  (rule_lock->ev_kind == CASCADED_OPTION_IMPLICIT)))
+ 				 
+ 		{
+ 			/* apply check option, but only once */
+ 			view_event->viewUpdate = true;
+ 			view_event->needCheckOption = true;
+ 			view_event->checkMode = rule_lock->ev_kind;
+ 		}
+ 
+ 		/*
+ 		 * Third check: Look if we are in a recursive view update in
+ 		 * conjunction with a CASCADED CHECK OPTION. If true, we always need to
+ 		 * apply any check options found.
+ 		 */
+ 		else if (view_event->viewUpdate &&
+ 				 (view_event->checkMode == CASCADED_OPTION_IMPLICIT) &&
+ 				 (rule_lock->ev_kind != NO_OPTION_EXPLICIT))
+ 		{
+ 			view_event->needCheckOption = true;
+ 		}
+ 
+ 		/*
+ 		 * 4th check: make sure we reset the view update event if we are in a
+ 		 * recursive view update and passed the first view already. If we had a
+ 		 * LOCAL CHECK OPTION, we have to make sure we don't fire any check
+ 		 * options anymore.
+ 		 */
+ 		else if (view_event->viewUpdate &&
+ 				 (view_event->checkMode == LOCAL_OPTION_IMPLICIT) &&
+ 				 (rule_lock->ev_kind != NO_OPTION_EXPLICIT))
+ 		{
+ 			view_event->needCheckOption = false;
+ 			/* force LOCAL check mode */
+ 			view_event->checkMode = LOCAL_OPTION_IMPLICIT;
+ 		}
+ 
  		/* Determine correct QuerySource value for actions */
  		if (rule_lock->isInstead)
  		{
! 			if (event_qual != NULL) 
! 			{				
! 				/*
! 				 * Check out wether we need to apply any
! 				 * rule qualification to a view update rule.
! 				 * We only bother on implicit rules that aren't
! 				 * marked with NO_OPTION_EXPLICIT
! 				 */
! 				if ((rule_lock->ev_kind != NO_OPTION_EXPLICIT)
! 					&& (view_event->viewUpdate))
! 				{
! 					if (view_event->needCheckOption)
! 					{
! 						qsrc = QSRC_QUAL_INSTEAD_RULE;
! 					}
! 					else
! 					{
! 						qsrc = QSRC_INSTEAD_RULE;
! 						*instead_flag = true;
! 					}
! 				} 
! 				else 
! 				{
! 					qsrc = QSRC_QUAL_INSTEAD_RULE;
! 				}
! 			}
  			else
  			{
  				qsrc = QSRC_INSTEAD_RULE;
*************** fireRules(Query *parsetree,
*** 1438,1444 ****
  				continue;
  
  			rule_action = rewriteRuleAction(parsetree, rule_action,
! 											event_qual, rt_index, event);
  
  			rule_action->querySource = qsrc;
  			rule_action->canSetTag = false;		/* might change later */
--- 1545,1552 ----
  				continue;
  
  			rule_action = rewriteRuleAction(parsetree, rule_action,
! 											event_qual, rt_index, event,
! 											view_event);
  
  			rule_action->querySource = qsrc;
  			rule_action->canSetTag = false;		/* might change later */
*************** fireRules(Query *parsetree,
*** 1459,1465 ****
   * infinite recursion.
   */
  static List *
! RewriteQuery(Query *parsetree, List *rewrite_events)
  {
  	CmdType		event = parsetree->commandType;
  	bool		instead = false;
--- 1567,1574 ----
   * infinite recursion.
   */
  static List *
! RewriteQuery(Query *parsetree, List *rewrite_events, 
! 			 view_update_event *view_event)
  {
  	CmdType		event = parsetree->commandType;
  	bool		instead = false;
*************** RewriteQuery(Query *parsetree, List *rew
*** 1550,1555 ****
--- 1659,1665 ----
  										result_relation,
  										event,
  										locks,
+ 										view_event,
  										&instead,
  										&qual_product);
  
*************** RewriteQuery(Query *parsetree, List *rew
*** 1583,1589 ****
  					Query	   *pt = (Query *) lfirst(n);
  					List	   *newstuff;
  
! 					newstuff = RewriteQuery(pt, rewrite_events);
  					rewritten = list_concat(rewritten, newstuff);
  				}
  
--- 1693,1699 ----
  					Query	   *pt = (Query *) lfirst(n);
  					List	   *newstuff;
  
! 					newstuff = RewriteQuery(pt, rewrite_events, view_event);
  					rewritten = list_concat(rewritten, newstuff);
  				}
  
*************** QueryRewrite(Query *parsetree)
*** 1646,1658 ****
  	CmdType		origCmdType;
  	bool		foundOriginalQuery;
  	Query	   *lastInstead;
  
  	/*
  	 * Step 1
  	 *
  	 * Apply all non-SELECT rules possibly getting 0 or many queries
  	 */
! 	querylist = RewriteQuery(parsetree, NIL);
  
  	/*
  	 * Step 2
--- 1756,1772 ----
  	CmdType		origCmdType;
  	bool		foundOriginalQuery;
  	Query	   *lastInstead;
+ 	view_update_event v_event;
  
  	/*
  	 * Step 1
  	 *
  	 * Apply all non-SELECT rules possibly getting 0 or many queries
  	 */
! 	v_event.viewUpdate      = false;
! 	v_event.needCheckOption = false;
! 	v_event.checkMode       = NO_OPTION_EXPLICIT;
! 	querylist = RewriteQuery(parsetree, NIL, &v_event);
  
  	/*
  	 * Step 2
Index: src/backend/rewrite/rewriteRemove.c
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/backend/rewrite/rewriteRemove.c,v
retrieving revision 1.65
diff -c -p -r1.65 rewriteRemove.c
*** src/backend/rewrite/rewriteRemove.c	16 Jun 2006 20:23:44 -0000	1.65
--- src/backend/rewrite/rewriteRemove.c	17 Aug 2006 03:34:45 -0000
*************** RemoveRewriteRule(Oid owningRel, const c
*** 89,94 ****
--- 89,138 ----
  	performDeletion(&object, behavior);
  }
  
+ /*
+  * deleteImplicitRulesOnEvent
+  * 
+  * This will delete implicit rules, if any exists, on the event in the relation
+  */
+ void 
+ deleteImplicitRulesOnEvent(Relation rel, CmdType event_type)
+ {
+ 	RuleLock *rulelocks = rel->rd_rules;
+ 	int nlocks;
+ 	int i;
+ 
+ 	/*
+ 	 * Select rules are implicit (are they marked as implicit??) 
+ 	 * but we don't want to delete them
+ 	 */
+ 	if (event_type == CMD_SELECT)
+ 		return;
+ 
+ 	/*
+ 	 * If there are no rules on the relation we waste no more time
+ 	 */
+ 	if (rulelocks == NULL)
+ 		return;
+ 
+ 	nlocks = rulelocks->numLocks;
+ 
+ 	/*
+ 	 * Look at all rules looking for the ones that are on the event and are
+ 	 * implicit
+ 	 */
+ 	for (i = 0; i < nlocks; i++)
+ 	{
+ 		RewriteRule *oneLock = rulelocks->rules[i];		
+ 
+ 		if (oneLock->event == event_type 
+ 			&& (oneLock->ev_kind != NO_OPTION_EXPLICIT)) 
+ 		{
+ 			RemoveRewriteRuleById(oneLock->ruleId);
+ 			deleteDependencyRecordsFor(RewriteRelationId, oneLock->ruleId);
+ 		}
+ 	}
+ }
+ 
  
  /*
   * Guts of rule deletion.
Index: src/backend/tcop/utility.c
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/backend/tcop/utility.c,v
retrieving revision 1.265
diff -c -p -r1.265 utility.c
*** src/backend/tcop/utility.c	12 Aug 2006 20:05:56 -0000	1.265
--- src/backend/tcop/utility.c	17 Aug 2006 03:34:45 -0000
***************
*** 20,25 ****
--- 20,26 ----
  #include "access/xact.h"
  #include "catalog/catalog.h"
  #include "catalog/namespace.h"
+ #include "catalog/pg_rewrite.h"
  #include "catalog/toasting.h"
  #include "commands/alter.h"
  #include "commands/async.h"
*************** ProcessUtility(Node *parsetree,
*** 764,771 ****
  		case T_ViewStmt:		/* CREATE VIEW */
  			{
  				ViewStmt   *stmt = (ViewStmt *) parsetree;
  
! 				DefineView(stmt->view, stmt->query, stmt->replace);
  			}
  			break;
  
--- 765,787 ----
  		case T_ViewStmt:		/* CREATE VIEW */
  			{
  				ViewStmt   *stmt = (ViewStmt *) parsetree;
+ 				bool		checkOption = false;
+ 				bool		cascade = false;
+ 				ListCell   *cell;
  
! 				if (list_length(stmt->options) > 0)
! 					checkOption = true;
! 
! 				foreach(cell, stmt->options)
! 				{
! 					Value *val = (Value *) lfirst(cell);
! 
! 					if (strncmp(strVal(val), "cascade", strlen("cascade")) == 0)
! 						cascade = true;
! 				}
! 
! 				DefineView(stmt->view, stmt->query, stmt->replace, 
! 						   checkOption, cascade);
  			}
  			break;
  
*************** ProcessUtility(Node *parsetree,
*** 803,809 ****
  			break;
  
  		case T_RuleStmt:		/* CREATE RULE */
! 			DefineQueryRewrite((RuleStmt *) parsetree);
  			break;
  
  		case T_CreateSeqStmt:
--- 819,825 ----
  			break;
  
  		case T_RuleStmt:		/* CREATE RULE */
! 			DefineQueryRewrite((RuleStmt *) parsetree, NO_OPTION_EXPLICIT);
  			break;
  
  		case T_CreateSeqStmt:
Index: src/backend/utils/adt/ruleutils.c
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/backend/utils/adt/ruleutils.c,v
retrieving revision 1.231
diff -c -p -r1.231 ruleutils.c
*** src/backend/utils/adt/ruleutils.c	12 Aug 2006 02:52:05 -0000	1.231
--- src/backend/utils/adt/ruleutils.c	18 Aug 2006 03:02:15 -0000
***************
*** 18,23 ****
--- 18,24 ----
  #include "catalog/pg_depend.h"
  #include "catalog/pg_opclass.h"
  #include "catalog/pg_operator.h"
+ #include "catalog/pg_rewrite.h"
  #include "catalog/pg_trigger.h"
  #include "executor/spi.h"
  #include "funcapi.h"
*************** make_viewdef(StringInfo buf, HeapTuple r
*** 1683,1688 ****
--- 1684,1690 ----
  	Oid			ev_class;
  	int2		ev_attr;
  	bool		is_instead;
+ 	char        ev_kind;
  	char	   *ev_qual;
  	char	   *ev_action;
  	List	   *actions = NIL;
*************** make_viewdef(StringInfo buf, HeapTuple r
*** 1705,1710 ****
--- 1707,1715 ----
  	fno = SPI_fnumber(rulettc, "is_instead");
  	is_instead = (bool) SPI_getbinval(ruletup, rulettc, fno, &isnull);
  
+ 	fno = SPI_fnumber(rulettc, "ev_kind");
+ 	ev_kind = (char) SPI_getbinval(ruletup, rulettc, fno, &isnull);
+ 
  	fno = SPI_fnumber(rulettc, "ev_qual");
  	ev_qual = SPI_getvalue(ruletup, rulettc, fno);
  
*************** make_viewdef(StringInfo buf, HeapTuple r
*** 1732,1737 ****
--- 1737,1761 ----
  
  	get_query_def(query, buf, NIL, RelationGetDescr(ev_relation),
  				  prettyFlags, 0);
+ 
+ 	/*
+ 	 * Support for updatable views: append the check option if
+ 	 * required. If any pretty print flags is enabled, we need
+ 	 * to do a linebreak before.
+ 	 */
+ 	if (ev_kind != NO_OPTION_EXPLICIT || ev_kind != NO_OPTION_IMPLICIT)
+ 	{
+ 		if (prettyFlags & PRETTYFLAG_INDENT)
+ 			appendStringInfo(buf, "\n");
+ 
+ 		appendStringInfoSpaces(buf, 1);
+ 
+ 		if (ev_kind == LOCAL_OPTION_IMPLICIT)
+ 			appendStringInfo(buf, " WITH LOCAL CHECK OPTION");
+ 		else if (ev_kind == CASCADED_OPTION_IMPLICIT)
+ 			appendStringInfo(buf, " WITH CASCADED CHECK OPTION");
+ 	}
+ 
  	appendStringInfo(buf, ";");
  
  	heap_close(ev_relation, AccessShareLock);
Index: src/backend/utils/cache/relcache.c
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/backend/utils/cache/relcache.c,v
retrieving revision 1.247
diff -c -p -r1.247 relcache.c
*** src/backend/utils/cache/relcache.c	31 Jul 2006 20:09:05 -0000	1.247
--- src/backend/utils/cache/relcache.c	17 Aug 2006 03:34:45 -0000
*************** RelationBuildRuleLock(Relation relation)
*** 646,651 ****
--- 646,652 ----
  		rule->event = rewrite_form->ev_type - '0';
  		rule->attrno = rewrite_form->ev_attr;
  		rule->isInstead = rewrite_form->is_instead;
+ 		rule->ev_kind = rewrite_form->ev_kind;
  
  		/*
  		 * Must use heap_getattr to fetch ev_action and ev_qual.  Also,
*************** equalRuleLocks(RuleLock *rlock1, RuleLoc
*** 748,753 ****
--- 749,756 ----
  				return false;
  			if (!equal(rule1->actions, rule2->actions))
  				return false;
+ 			if(rule1->ev_kind != rule2->ev_kind)
+ 				return false;
  		}
  	}
  	else if (rlock2 != NULL)
Index: src/bin/pg_dump/pg_dump.c
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/bin/pg_dump/pg_dump.c,v
retrieving revision 1.446
diff -c -p -r1.446 pg_dump.c
*** src/bin/pg_dump/pg_dump.c	4 Aug 2006 18:32:15 -0000	1.446
--- src/bin/pg_dump/pg_dump.c	17 Aug 2006 03:34:45 -0000
*************** int			optreset;
*** 51,56 ****
--- 51,57 ----
  #include "catalog/pg_proc.h"
  #include "catalog/pg_trigger.h"
  #include "catalog/pg_type.h"
+ #include "catalog/pg_rewrite.h"
  #include "commands/sequence.h"
  #include "libpq/libpq-fs.h"
  #include "mb/pg_wchar.h"
*************** getRules(int *numRules)
*** 3632,3637 ****
--- 3633,3639 ----
  	int			i_ruletable;
  	int			i_ev_type;
  	int			i_is_instead;
+ 	int			i_ev_kind;
  
  	/* Make sure we are in proper schema */
  	selectSourceSchema("pg_catalog");
*************** getRules(int *numRules)
*** 3640,3646 ****
  	{
  		appendPQExpBuffer(query, "SELECT "
  						  "tableoid, oid, rulename, "
! 						  "ev_class as ruletable, ev_type, is_instead "
  						  "FROM pg_rewrite "
  						  "ORDER BY oid");
  	}
--- 3642,3649 ----
  	{
  		appendPQExpBuffer(query, "SELECT "
  						  "tableoid, oid, rulename, "
! 						  "ev_class as ruletable, ev_type, is_instead, "
! 						  "ev_kind "
  						  "FROM pg_rewrite "
  						  "ORDER BY oid");
  	}
*************** getRules(int *numRules)
*** 3649,3655 ****
  		appendPQExpBuffer(query, "SELECT "
  						  "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
  						  "oid, rulename, "
! 						  "ev_class as ruletable, ev_type, is_instead "
  						  "FROM pg_rewrite "
  						  "ORDER BY oid");
  	}
--- 3652,3659 ----
  		appendPQExpBuffer(query, "SELECT "
  						  "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
  						  "oid, rulename, "
! 						  "ev_class as ruletable, ev_type, is_instead, "
! 						  "ev_kind "
  						  "FROM pg_rewrite "
  						  "ORDER BY oid");
  	}
*************** getRules(int *numRules)
*** 3669,3674 ****
--- 3673,3679 ----
  	i_ruletable = PQfnumber(res, "ruletable");
  	i_ev_type = PQfnumber(res, "ev_type");
  	i_is_instead = PQfnumber(res, "is_instead");
+ 	i_ev_kind = PQfnumber(res, "ev_kind");
  
  	for (i = 0; i < ntups; i++)
  	{
*************** getRules(int *numRules)
*** 3692,3713 ****
  		ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
  		ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
  		ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
  		if (ruleinfo[i].ruletable)
  		{
  			/*
! 			 * If the table is a view, force its ON SELECT rule to be sorted
! 			 * before the view itself --- this ensures that any dependencies
! 			 * for the rule affect the table's positioning. Other rules are
! 			 * forced to appear after their table.
  			 */
! 			if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
! 				ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
! 			{
! 				addObjectDependency(&ruleinfo[i].ruletable->dobj,
! 									ruleinfo[i].dobj.dumpId);
! 				/* We'll merge the rule into CREATE VIEW, if possible */
! 				ruleinfo[i].separate = false;
! 			}
  			else
  			{
  				addObjectDependency(&ruleinfo[i].dobj,
--- 3697,3731 ----
  		ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
  		ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
  		ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
+ 		ruleinfo[i].ev_kind = *(PQgetvalue(res, i, i_ev_kind));
  		if (ruleinfo[i].ruletable)
  		{
  			/*
! 			 * If the table is a view, force its ON SELECT rule to be
! 			 * sorted before the view itself --- this ensures that any
! 			 * dependencies for the rule affect the table's positioning.
! 			 * Other rules are forced to appear after their table.
! 			 *
! 			 * Do the same for implicit rules (for updateable views support).
  			 */
! 			if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW) 
! 				if (ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
! 				{
! 					addObjectDependency(&ruleinfo[i].ruletable->dobj,
! 										ruleinfo[i].dobj.dumpId);
! 					/* We'll merge the rule into CREATE VIEW, if possible */
! 					ruleinfo[i].separate = false;
! 				}
! 				else
! 					if (ruleinfo[i].ev_kind != NO_OPTION_EXPLICIT)
! 					{
! 						addObjectDependency(&ruleinfo[i].ruletable->dobj,
! 											ruleinfo[i].dobj.dumpId);
! 						/* We'll merge the rule into CREATE VIEW, if possible */
! 						ruleinfo[i].separate = false;
! 					}
! 					else
! 						ruleinfo[i].separate = true;
  			else
  			{
  				addObjectDependency(&ruleinfo[i].dobj,
Index: src/bin/pg_dump/pg_dump.h
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/bin/pg_dump/pg_dump.h,v
retrieving revision 1.128
diff -c -p -r1.128 pg_dump.h
*** src/bin/pg_dump/pg_dump.h	1 Aug 2006 18:05:04 -0000	1.128
--- src/bin/pg_dump/pg_dump.h	17 Aug 2006 03:34:45 -0000
*************** typedef struct _ruleInfo
*** 261,268 ****
  	TableInfo  *ruletable;		/* link to table the rule is for */
  	char		ev_type;
  	bool		is_instead;
  	bool		separate;		/* TRUE if must dump as separate item */
! 	/* separate is always true for non-ON SELECT rules */
  } RuleInfo;
  
  typedef struct _triggerInfo
--- 261,272 ----
  	TableInfo  *ruletable;		/* link to table the rule is for */
  	char		ev_type;
  	bool		is_instead;
+ 	char		ev_kind;
  	bool		separate;		/* TRUE if must dump as separate item */
! 	/* 
! 	 * separate is true for non-ON SELECT rules and 
! 	 * for implicit rules (for updateable views support) 
! 	 */
  } RuleInfo;
  
  typedef struct _triggerInfo
Index: src/bin/pg_dump/pg_dump_sort.c
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/bin/pg_dump/pg_dump_sort.c,v
retrieving revision 1.15
diff -c -p -r1.15 pg_dump_sort.c
*** src/bin/pg_dump/pg_dump_sort.c	14 Jul 2006 14:52:26 -0000	1.15
--- src/bin/pg_dump/pg_dump_sort.c	17 Aug 2006 03:34:45 -0000
*************** repairDependencyLoop(DumpableObject **lo
*** 816,821 ****
--- 816,862 ----
  		}
  	}
  
+ 	/* View and its implicit rule */
+ 	if (nLoop == 2 &&
+ 		loop[0]->objType == DO_TABLE &&
+ 		loop[1]->objType == DO_RULE &&
+ 		((RuleInfo *) loop[1])->ev_kind != 'e' &&
+ 		((RuleInfo *) loop[1])->ruletable == (TableInfo *) loop[0])
+ 	{
+ 		repairViewRuleLoop(loop[0], loop[1]);
+ 		return;
+ 	}
+ 	if (nLoop == 2 &&
+ 		loop[1]->objType == DO_TABLE &&
+ 		loop[0]->objType == DO_RULE &&
+ 		((RuleInfo *) loop[0])->ev_kind != 'e' &&
+ 		((RuleInfo *) loop[0])->ruletable == (TableInfo *) loop[1])
+ 	{
+ 		repairViewRuleLoop(loop[1], loop[0]);
+ 		return;
+ 	}
+ 
+ 	/* Indirect loop involving view and implicit rule */
+ 	if (nLoop > 2)
+ 	{
+ 		for (i = 0; i < nLoop; i++)
+ 		{
+ 			if (loop[i]->objType == DO_TABLE)
+ 			{
+ 				for (j = 0; j < nLoop; j++)
+ 				{
+ 					if (loop[j]->objType == DO_RULE &&
+ 						((RuleInfo *) loop[j])->ev_kind != 'e' &&
+ 						((RuleInfo *) loop[j])->ruletable == (TableInfo *) loop[i])
+ 					{
+ 						repairViewRuleMultiLoop(loop[i], loop[j]);
+ 						return;
+ 					}
+ 				}
+ 			}
+ 		}
+ 	}
+ 
  	/* Table and CHECK constraint */
  	if (nLoop == 2 &&
  		loop[0]->objType == DO_TABLE &&
Index: src/include/catalog/catversion.h
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/include/catalog/catversion.h,v
retrieving revision 1.349
diff -c -p -r1.349 catversion.h
*** src/include/catalog/catversion.h	12 Aug 2006 02:52:06 -0000	1.349
--- src/include/catalog/catversion.h	17 Aug 2006 03:34:45 -0000
***************
*** 53,58 ****
   */
  
  /*							yyyymmddN */
! #define CATALOG_VERSION_NO	200608101
  
  #endif
--- 53,58 ----
   */
  
  /*							yyyymmddN */
! #define CATALOG_VERSION_NO	200608121
  
  #endif
Index: src/include/catalog/pg_proc.h
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/include/catalog/pg_proc.h,v
retrieving revision 1.420
diff -c -p -r1.420 pg_proc.h
*** src/include/catalog/pg_proc.h	6 Aug 2006 03:53:44 -0000	1.420
--- src/include/catalog/pg_proc.h	17 Aug 2006 03:34:45 -0000
*************** DATA(insert OID = 2557 ( bool				   PGNS
*** 3841,3846 ****
--- 3841,3847 ----
  DESCR("convert int4 to boolean");
  DATA(insert OID = 2558 ( int4				   PGNSP PGUID 12 f f t f i 1  23 "16" _null_ _null_ _null_ bool_int4 - _null_ ));
  DESCR("convert boolean to int4");
+ /* internal function required for view update rules */
  DATA(insert OID = 2559 ( lastval			   PGNSP PGUID 12 f f t f v 0 20 "" _null_ _null_ _null_	lastval - _null_ ));
  DESCR("current value from last used sequence");
  
*************** DESCR("GiST support");
*** 3894,3899 ****
--- 3895,3904 ----
  DATA(insert OID = 2592 (  gist_circle_compress	PGNSP PGUID 12 f f t f i 1 2281 "2281" _null_ _null_ _null_ gist_circle_compress - _null_ ));
  DESCR("GiST support");
  
+ /* functions for view update facility */
+ DATA(insert OID = 2570 ( pg_view_update_error       PGNSP PGUID 12 f f f f i 1 16 "16" _null_ _null_ _null_ pg_view_update_error - _null_));
+ DESCR("evaluates boolean input for view update check option");
+ 
  /* GIN */
  DATA(insert OID = 2730 (  gingettuple	   PGNSP PGUID 12 f f t f v 2 16 "2281 2281" _null_ _null_ _null_  gingettuple - _null_ ));
  DESCR("gin(internal)");
Index: src/include/catalog/pg_rewrite.h
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/include/catalog/pg_rewrite.h,v
retrieving revision 1.26
diff -c -p -r1.26 pg_rewrite.h
*** src/include/catalog/pg_rewrite.h	5 Mar 2006 15:58:55 -0000	1.26
--- src/include/catalog/pg_rewrite.h	17 Aug 2006 03:34:45 -0000
*************** CATALOG(pg_rewrite,2618)
*** 43,48 ****
--- 43,49 ----
  	int2		ev_attr;
  	char		ev_type;
  	bool		is_instead;
+ 	char		ev_kind;
  
  	/* NB: remaining fields must be accessed via heap_getattr */
  	text		ev_qual;
*************** typedef FormData_pg_rewrite *Form_pg_rew
*** 60,72 ****
   *		compiler constants for pg_rewrite
   * ----------------
   */
! #define Natts_pg_rewrite				7
  #define Anum_pg_rewrite_rulename		1
  #define Anum_pg_rewrite_ev_class		2
  #define Anum_pg_rewrite_ev_attr			3
  #define Anum_pg_rewrite_ev_type			4
  #define Anum_pg_rewrite_is_instead		5
! #define Anum_pg_rewrite_ev_qual			6
! #define Anum_pg_rewrite_ev_action		7
  
  #endif   /* PG_REWRITE_H */
--- 61,82 ----
   *		compiler constants for pg_rewrite
   * ----------------
   */
! #define Natts_pg_rewrite				8
  #define Anum_pg_rewrite_rulename		1
  #define Anum_pg_rewrite_ev_class		2
  #define Anum_pg_rewrite_ev_attr			3
  #define Anum_pg_rewrite_ev_type			4
  #define Anum_pg_rewrite_is_instead		5
! #define Anum_pg_rewrite_ev_kind			6
! #define Anum_pg_rewrite_ev_qual			7
! #define Anum_pg_rewrite_ev_action		8
! 
! /*
!  * Possible values for ev_kind 
!  */
! #define LOCAL_OPTION_IMPLICIT    'l' /* WITH LOCAL CHECK OPTION */
! #define CASCADED_OPTION_IMPLICIT 'c' /* WITH CASCADED CHECK OPTION */
! #define NO_OPTION_IMPLICIT       'n' /* no check option specified */
! #define NO_OPTION_EXPLICIT       'e' /* rule was created by user */
  
  #endif   /* PG_REWRITE_H */
Index: src/include/commands/view.h
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/include/commands/view.h,v
retrieving revision 1.23
diff -c -p -r1.23 view.h
*** src/include/commands/view.h	5 Mar 2006 15:58:55 -0000	1.23
--- src/include/commands/view.h	17 Aug 2006 03:34:45 -0000
***************
*** 16,22 ****
  
  #include "nodes/parsenodes.h"
  
! extern void DefineView(RangeVar *view, Query *view_parse, bool replace);
  extern void RemoveView(const RangeVar *view, DropBehavior behavior);
  
  #endif   /* VIEW_H */
--- 16,24 ----
  
  #include "nodes/parsenodes.h"
  
! extern void DefineView(RangeVar *view, Query *view_parse, bool replace, 
! 					   bool checkOption, bool cascade);
! 
  extern void RemoveView(const RangeVar *view, DropBehavior behavior);
  
  #endif   /* VIEW_H */
Index: src/include/nodes/parsenodes.h
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/include/nodes/parsenodes.h,v
retrieving revision 1.323
diff -c -p -r1.323 parsenodes.h
*** src/include/nodes/parsenodes.h	12 Aug 2006 20:05:56 -0000	1.323
--- src/include/nodes/parsenodes.h	19 Aug 2006 19:07:27 -0000
*************** typedef struct ViewStmt
*** 1677,1682 ****
--- 1677,1683 ----
  	List	   *aliases;		/* target column names */
  	Query	   *query;			/* the SQL statement */
  	bool		replace;		/* replace an existing view? */
+ 	List	   *options;        /* view check options, NIL means no check */
  } ViewStmt;
  
  /* ----------------------
Index: src/include/nodes/relation.h
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/include/nodes/relation.h,v
retrieving revision 1.126
diff -c -p -r1.126 relation.h
*** src/include/nodes/relation.h	1 Jul 2006 18:38:33 -0000	1.126
--- src/include/nodes/relation.h	18 Aug 2006 23:29:13 -0000
*************** typedef struct RelOptInfo
*** 260,266 ****
  
  	/* information about a base rel (not set for join rels!) */
  	Index		relid;
! 	RTEKind		rtekind;		/* RELATION, SUBQUERY, or FUNCTION */
  	AttrNumber	min_attr;		/* smallest attrno of rel (often <0) */
  	AttrNumber	max_attr;		/* largest attrno of rel */
  	Relids	   *attr_needed;	/* array indexed [min_attr .. max_attr] */
--- 260,266 ----
  
  	/* information about a base rel (not set for join rels!) */
  	Index		relid;
! 	RTEKind		rtekind;		/* see parsenodes.h */
  	AttrNumber	min_attr;		/* smallest attrno of rel (often <0) */
  	AttrNumber	max_attr;		/* largest attrno of rel */
  	Relids	   *attr_needed;	/* array indexed [min_attr .. max_attr] */
Index: src/include/rewrite/prs2lock.h
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/include/rewrite/prs2lock.h,v
retrieving revision 1.21
diff -c -p -r1.21 prs2lock.h
*** src/include/rewrite/prs2lock.h	5 Mar 2006 15:58:58 -0000	1.21
--- src/include/rewrite/prs2lock.h	17 Aug 2006 03:34:45 -0000
*************** typedef struct RewriteRule
*** 29,34 ****
--- 29,35 ----
  	Node	   *qual;
  	List	   *actions;
  	bool		isInstead;
+ 	char        ev_kind;
  } RewriteRule;
  
  /*
Index: src/include/rewrite/rewriteDefine.h
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/include/rewrite/rewriteDefine.h,v
retrieving revision 1.21
diff -c -p -r1.21 rewriteDefine.h
*** src/include/rewrite/rewriteDefine.h	5 Mar 2006 15:58:58 -0000	1.21
--- src/include/rewrite/rewriteDefine.h	17 Aug 2006 03:34:45 -0000
***************
*** 16,22 ****
  
  #include "nodes/parsenodes.h"
  
! extern void DefineQueryRewrite(RuleStmt *args);
  
  extern void RenameRewriteRule(Oid owningRel, const char *oldName,
  				  const char *newName);
--- 16,23 ----
  
  #include "nodes/parsenodes.h"
  
! extern void DefineQueryRewrite(RuleStmt *args,
! 							   char     ev_kind);
  
  extern void RenameRewriteRule(Oid owningRel, const char *oldName,
  				  const char *newName);
Index: src/include/rewrite/rewriteRemove.h
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/include/rewrite/rewriteRemove.h,v
retrieving revision 1.22
diff -c -p -r1.22 rewriteRemove.h
*** src/include/rewrite/rewriteRemove.h	16 Jun 2006 20:23:45 -0000	1.22
--- src/include/rewrite/rewriteRemove.h	17 Aug 2006 03:34:45 -0000
***************
*** 20,24 ****
--- 20,25 ----
  extern void RemoveRewriteRule(Oid owningRel, const char *ruleName,
  				  DropBehavior behavior, bool missing_ok);
  extern void RemoveRewriteRuleById(Oid ruleOid);
+ extern void deleteImplicitRulesOnEvent(Relation rel, CmdType event_type);
  
  #endif   /* REWRITEREMOVE_H */
Index: src/include/rewrite/rewriteSupport.h
===================================================================
RCS file: /home/alvherre/cvs/pgsql/src/include/rewrite/rewriteSupport.h,v
retrieving revision 1.28
diff -c -p -r1.28 rewriteSupport.h
*** src/include/rewrite/rewriteSupport.h	5 Mar 2006 15:58:58 -0000	1.28
--- src/include/rewrite/rewriteSupport.h	17 Aug 2006 03:34:45 -0000
***************
*** 17,22 ****
--- 17,33 ----
  /* The ON SELECT rule of a view is always named this: */
  #define ViewSelectRuleName	"_RETURN"
  
+ /*------------------------------------------------------------------------------
+  * some names to be used for implicit view update rules
+  *------------------------------------------------------------------------------
+  */
+ #define INSERTRULENAME "_INSERT"
+ #define DELETERULENAME "_DELETE"
+ #define UPDATERULENAME "_UPDATE"
+ #define NOTHING_INSERTRULENAME "_NOTHING_INSERT"
+ #define NOTHING_UPDATERULENAME "_NOTHING_UPDATE"
+ #define NOTHING_DELETERULENAME "_NOTHING_DELETE"
+ 
  extern bool IsDefinedRewriteRule(Oid owningRel, const char *ruleName);
  
  extern void SetRelationRuleStatus(Oid relationId, bool relHasRules,
viewUpdate.ctext/x-csrc; charset=us-asciiDownload
viewUpdate.htext/x-chdr; charset=us-asciiDownload
upd-views.sqltext/plain; charset=us-asciiDownload
#2Bernd Helmle
mailings@oopsware.de
In reply to: Alvaro Herrera (#1)
1 attachment(s)
Re: Updatable views

--On Montag, August 21, 2006 02:07:41 -0400 Alvaro Herrera
<alvherre@commandprompt.com> wrote:

Hi,

This is the patch for updatable views I've been able to come up with. A
nasty bug was just discovered in the upcoming Mammoth Replicator release
so I'm not sure if I'm going to have time to work more on it soon.

So, I'll appreciate if somebody else takes the responsability to fix the
remaining issues. I've put a lot of XXX's and some FIXME's.
Some
functions are in need of some comments as well.

I'll try to complete the missing comments and to make some statements
cleaner.

The new files are src/backend/rewrite/viewUpdate.c and
src/include/rewrite/viewUpdate.h. The third file, upd-views.sql, is
intended to be a new regression test. Extra points if the table therein
is completed correctly.

I haven't tested the array stuff at all.

Comments from Bernd and Jaime are especially welcome if I've broken
something that used to work on their patch :-)

I see that the current patch doesn't support subqueries in the WHERE-clause
anymore.
You can find one example in the attached SQL-script. Is there a reason why
you
dropped this?

--
Thanks

Bernd

Attachments:

regress_view_update_check_option2.sqlapplication/octet-stream; name=regress_view_update_check_option2.sqlDownload
#3Alvaro Herrera
alvherre@commandprompt.com
In reply to: Bernd Helmle (#2)
Re: Updatable views

Bernd Helmle wrote:

I'll try to complete the missing comments and to make some statements
cleaner.

Thanks.

--On Montag, August 21, 2006 02:07:41 -0400 Alvaro Herrera
<alvherre@commandprompt.com> wrote:

The new files are src/backend/rewrite/viewUpdate.c and
src/include/rewrite/viewUpdate.h. The third file, upd-views.sql, is
intended to be a new regression test. Extra points if the table therein
is completed correctly.

I haven't tested the array stuff at all.

Comments from Bernd and Jaime are especially welcome if I've broken
something that used to work on their patch :-)

I see that the current patch doesn't support subqueries in the WHERE-clause
anymore.
You can find one example in the attached SQL-script. Is there a reason why
you dropped this?

Nope, no reason. If you can find _where_ I broke it, that would be the
first clue to unbreaking it ;-)

--
Alvaro Herrera http://www.CommandPrompt.com/
PostgreSQL Replication, Consulting, Custom Development, 24x7 support

#4Alvaro Herrera
alvherre@commandprompt.com
In reply to: Bernd Helmle (#2)
Re: Updatable views

Bernd Helmle wrote:

Comments from Bernd and Jaime are especially welcome if I've broken
something that used to work on their patch :-)

I see that the current patch doesn't support subqueries in the WHERE-clause
anymore.
You can find one example in the attached SQL-script. Is there a reason
why you dropped this?

Hum, turns out that you had this code in the patch:

/*
if ( query->hasSubLinks == true )
{
elog( WARNING, "Subqueries violates SQL92 view update rules!" );
return false;
}
*/

I figured I'd remove the comments, and then forgot ... If you remove
the piece of code from the viewUpdate.c file, your sample script works.

--
Alvaro Herrera http://www.CommandPrompt.com/
The PostgreSQL Company - Command Prompt, Inc.

#5Bernd Helmle
mailings@oopsware.de
In reply to: Alvaro Herrera (#1)
Re: Updatable views

--On Montag, August 21, 2006 02:07:41 -0400 Alvaro Herrera
<alvherre@commandprompt.com> wrote:

So, I'll appreciate if somebody else takes the responsability to fix the
remaining issues. I've put a lot of XXX's and some FIXME's. Some
functions are in need of some comments as well.

While working on Alvaro's suggestions to fix the code i got the opinion
that we need to reject any attempts to name a user defined rule
as

"_INSERT"
"_NOTHING_INSERT"
"_DELETE"
"_NOTHING_DELETE"
"_UPDATE"
"_NOTHING_UPDATE"

because this confuses the code when replacing an existing implicit
rule with its own user defined one:

bernd@[local]:bernd #= create or replace view v_second as select id, name,
usr from second where usr =
current_user with check option;
NOTICE: CREATE VIEW will create implicit INSERT/UPDATE/DELETE rules
CREATE VIEW
bernd@[local]:bernd #= CREATE OR REPLACE RULE "_INSERT" AS ON INSERT TO
v_second DO INSTEAD NOTHING;
ERROR: tuple already updated by self

This is because the code tries to drop the existing implicit insert rule
from pg_rewrite
and then to replace it with the new one (note the "_INSERT" caption of the
rule, any
other labeled rule works as expected).

We could avoid this by using a CommandCounterIncrement() (brute force
method),
but it seems to me that we should do the same here as with "_RETURN" rules
at the moment.

Any comments?

--
Thanks

Bernd

#6Tom Lane
tgl@sss.pgh.pa.us
In reply to: Bernd Helmle (#5)
Re: Updatable views

Bernd Helmle <mailings@oopsware.de> writes:

While working on Alvaro's suggestions to fix the code i got the opinion
that we need to reject any attempts to name a user defined rule
as

"_INSERT"
"_NOTHING_INSERT"
"_DELETE"
"_NOTHING_DELETE"
"_UPDATE"
"_NOTHING_UPDATE"

If the code is dependent on recognizing names to know what it's doing,
then I'd say you have a fundamentally broken approach. Consider adding
a flag column to pg_rewrite to distinguish these rules, instead.

regards, tom lane

#7Jaime Casanova
systemguards@gmail.com
In reply to: Tom Lane (#6)
Re: Updatable views

On 8/24/06, Tom Lane <tgl@sss.pgh.pa.us> wrote:

Bernd Helmle <mailings@oopsware.de> writes:

While working on Alvaro's suggestions to fix the code i got the opinion
that we need to reject any attempts to name a user defined rule
as

"_INSERT"
"_NOTHING_INSERT"
"_DELETE"
"_NOTHING_DELETE"
"_UPDATE"
"_NOTHING_UPDATE"

If the code is dependent on recognizing names to know what it's doing,
then I'd say you have a fundamentally broken approach. Consider adding
a flag column to pg_rewrite to distinguish these rules, instead.

Actually the code delete implicit rules based on a field added to
pg_rewrite but that catalog has a unique index on ev_class, rulename:
"pg_rewrite_rel_rulename_index" UNIQUE, btree (ev_class, rulename)

i guess bernd's comment is about this index giving an error if we try
to insert the new rule with the same name on the same event...

--
regards,
Jaime Casanova

"Programming today is a race between software engineers striving to
build bigger and better idiot-proof programs and the universe trying
to produce bigger and better idiots.
So far, the universe is winning."
Richard Cook

#8Bernd Helmle
mailings@oopsware.de
In reply to: Tom Lane (#6)
Re: [HACKERS] Updatable views

--On Donnerstag, August 24, 2006 11:00:45 -0400 Tom Lane
<tgl@sss.pgh.pa.us> wrote:

If the code is dependent on recognizing names to know what it's doing,
then I'd say you have a fundamentally broken approach. Consider adding
a flag column to pg_rewrite to distinguish these rules, instead.

This is the approach the code already follows (it uses an additional
ev_kind column which distinguishes rules between implicit rules with
no, local or cascaded check option and explicit ones).

Turns out that i was thinking too difficult when looking at the code which
drops implicit rules....sorry for the noise.

--
Thanks

Bernd

#9Bernd Helmle
mailings@oopsware.de
In reply to: Jaime Casanova (#7)
Re: [HACKERS] Updatable views

--On Donnerstag, August 24, 2006 11:02:43 -0500 Jaime Casanova
<systemguards@gmail.com> wrote:

Actually the code delete implicit rules based on a field added to
pg_rewrite but that catalog has a unique index on ev_class, rulename:
"pg_rewrite_rel_rulename_index" UNIQUE, btree (ev_class, rulename)

i guess bernd's comment is about this index giving an error if we try
to insert the new rule with the same name on the same event...

No, this wasn't the problem, since we are going to drop any implicit
rule that collides with an user defined one (however, this approach is
discussable, but nobody has put his comments on this yet and i think this
is important for backwards compatibility). I don't think we need ev_kind in
the
index at all, in my opinion implicit and user defined rules of the same
event
shouldn't live together (_RETURN rules are marked as implicit ones now, too)

--
Thanks

Bernd

#10Bernd Helmle
mailings@oopsware.de
In reply to: Alvaro Herrera (#1)
4 attachment(s)
Re: Updatable views

--On Montag, August 21, 2006 02:07:41 -0400 Alvaro Herrera
<alvherre@commandprompt.com> wrote:

Hi,

This is the patch for updatable views I've been able to come up with. A
nasty bug was just discovered in the upcoming Mammoth Replicator release
so I'm not sure if I'm going to have time to work more on it soon.

So, I'll appreciate if somebody else takes the responsability to fix the
remaining issues. I've put a lot of XXX's and some FIXME's. Some
functions are in need of some comments as well.

The new files are src/backend/rewrite/viewUpdate.c and
src/include/rewrite/viewUpdate.h. The third file, upd-views.sql, is
intended to be a new regression test. Extra points if the table therein
is completed correctly.

I haven't tested the array stuff at all.

Comments from Bernd and Jaime are especially welcome if I've broken
something that used to work on their patch :-)

Here's the current reworked version of the patch. I've fixed some broken
code in the patch
and ifdef'ed the DEFAULT stuff out (Jaime is working on that), some
functions got
some more detailed comments and i've dropped some functions which aren't
used
anymore due to some redesign of the code.

If someone wants to look at the current updatable view patch, please look
at this current
version.

--
Thanks

Bernd

Attachments:

pgsql_view_update.patchapplication/octet-stream; name=pgsql_view_update.patchDownload
? pgsql_view_update.patch
? upd-views-2.txt
? src/backend/parser/semantic.cache
? src/backend/rewrite/semantic.cache
? src/backend/rewrite/viewUpdate.c
? src/include/catalog/semantic.cache
? src/include/nodes/semantic.cache
? src/include/parser/semantic.cache
? src/include/rewrite/semantic.cache
? src/include/rewrite/viewUpdate.h
Index: doc/src/sgml/catalogs.sgml
===================================================================
RCS file: /projects/cvsroot/pgsql/doc/src/sgml/catalogs.sgml,v
retrieving revision 2.129
diff -c -r2.129 catalogs.sgml
*** doc/src/sgml/catalogs.sgml	31 Jul 2006 20:08:55 -0000	2.129
--- doc/src/sgml/catalogs.sgml	24 Aug 2006 20:18:09 -0000
***************
*** 3502,3507 ****
--- 3502,3519 ----
       </row>
  
       <row>
+       <entry><structfield>ev_kind</structfield></entry>
+       <entry><type>char</type></entry>
+       <entry></entry>
+       <entry>  
+        <literal>l</> = with local check option,   
+        <literal>c</> = with cascaded check option,
+        <literal>n</> = no check option specified,
+        <literal>e</> = rule was created by user 
+       </entry>
+      </row>
+ 
+      <row>
        <entry><structfield>ev_qual</structfield></entry>
        <entry><type>text</type></entry>
        <entry></entry>
Index: doc/src/sgml/information_schema.sgml
===================================================================
RCS file: /projects/cvsroot/pgsql/doc/src/sgml/information_schema.sgml,v
retrieving revision 1.26
diff -c -r1.26 information_schema.sgml
*** doc/src/sgml/information_schema.sgml	2 May 2006 18:07:51 -0000	1.26
--- doc/src/sgml/information_schema.sgml	24 Aug 2006 20:18:12 -0000
***************
*** 5085,5091 ****
       <row>
        <entry><literal>check_option</literal></entry>
        <entry><type>character_data</type></entry>
!       <entry>Applies to a feature not available in <productname>PostgreSQL</></entry>
       </row>
  
       <row>
--- 5085,5095 ----
       <row>
        <entry><literal>check_option</literal></entry>
        <entry><type>character_data</type></entry>
!       <entry>
!        The level of integrity checking in updatable views,
!        either <literal>LOCAL</literal>, <literal>CASCADED</literal>
!        or <literal>NONE</literal>
!      </entry>
       </row>
  
       <row>
Index: doc/src/sgml/intro.sgml
===================================================================
RCS file: /projects/cvsroot/pgsql/doc/src/sgml/intro.sgml,v
retrieving revision 1.31
diff -c -r1.31 intro.sgml
*** doc/src/sgml/intro.sgml	10 Mar 2006 19:10:48 -0000	1.31
--- doc/src/sgml/intro.sgml	24 Aug 2006 20:18:13 -0000
***************
*** 110,116 ****
       <simpara>triggers</simpara>
      </listitem>
      <listitem>
!      <simpara>views</simpara>
      </listitem>
      <listitem>
       <simpara>transactional integrity</simpara>
--- 110,116 ----
       <simpara>triggers</simpara>
      </listitem>
      <listitem>
!      <simpara>updatable views</simpara>
      </listitem>
      <listitem>
       <simpara>transactional integrity</simpara>
Index: doc/src/sgml/ref/create_view.sgml
===================================================================
RCS file: /projects/cvsroot/pgsql/doc/src/sgml/ref/create_view.sgml,v
retrieving revision 1.31
diff -c -r1.31 create_view.sgml
*** doc/src/sgml/ref/create_view.sgml	1 Nov 2005 21:09:50 -0000	1.31
--- doc/src/sgml/ref/create_view.sgml	24 Aug 2006 20:18:16 -0000
***************
*** 22,27 ****
--- 22,28 ----
  <synopsis>
  CREATE [ OR REPLACE ] [ TEMP | TEMPORARY ] VIEW <replaceable class="PARAMETER">name</replaceable> [ ( <replaceable class="PARAMETER">column_name</replaceable> [, ...] ) ]
      AS <replaceable class="PARAMETER">query</replaceable>
+     [ WITH [ CASCADED | LOCAL ] CHECK OPTION ]
  </synopsis>
   </refsynopsisdiv>
  
***************
*** 109,114 ****
--- 110,150 ----
       </para>
      </listitem>
     </varlistentry>
+ 
+    <variablelist>
+      <varlistentry>
+       <term><literal>CHECK OPTION</literal></term>
+       <listitem>
+        <para>
+         This option has to do with updatable views.  All
+         <command>INSERT</> and <command>UPDATE</> commands on the view
+         will be checked to ensure data satisfy the view-defining
+         condition (that is, the new data would be visible through the
+         view).  If they do not, the update will be rejected.
+        </para>
+       </listitem>
+      </varlistentry>
+ 
+      <varlistentry>
+       <term><literal>LOCAL</literal></term>
+       <listitem>
+        <para>
+         Check for integrity on this view.
+        </para>
+       </listitem>
+      </varlistentry>
+ 
+      <varlistentry>
+       <term><literal>CASCADED</literal></term>
+       <listitem>
+        <para>
+         Check for integrity on this view and on any dependent
+         view.  <literal>CASCADED</> is assumed if neither
+         <literal>CASCADED</> nor <literal>LOCAL</> is specified.
+        </para>
+       </listitem>
+      </varlistentry>
+    
    </variablelist>
   </refsect1>
  
***************
*** 116,126 ****
    <title>Notes</title>
  
     <para>
!     Currently, views are read only: the system will not allow an insert,
!     update, or delete on a view.  You can get the effect of an updatable
!     view by creating rules that rewrite inserts, etc. on the view into
!     appropriate actions on other tables.  For more information see
!     <xref linkend="sql-createrule" endterm="sql-createrule-title">.
     </para>
  
     <para>
--- 152,201 ----
    <title>Notes</title>
  
     <para>
!     Currently, views are updatable following SQL92 specifications, that
!     is: 
!    </para>
! 
!    <itemizedlist>
!     <listitem>
!      <para>
!       Views with just one base table (or another updatable view)
!      </para>
!     </listitem>
! 
!     <listitem>
!      <para>No aggregate functions</para>
!     </listitem>
! 
!     <listitem>
!      <para>
!       No <literal>HAVING</literal>, <literal>DISTINCT</literal> nor
!       <literal>GROUP BY</literal> clauses
!      </para>
!     </listitem>
! 
!     <listitem>
!      <para>
!       No <literal>UNION</literal>, <literal>INTERSECT</literal>,
!       <literal>EXCEPT</literal>clauses
!      </para>
!     </listitem>
!    </itemizedlist>
! 
!    <para>
!     Views are insertable only if you provide in the defining
!     <command>SELECT</command> statement all columns that are NOT NULL and don't
!     have a default value.
!    </para>
! 
!    <para>
!     The updatable views implementation is based on the rule system.  Because of
!     this, you can get the same effect in more complex views by creating your
!     own rules that rewrite the <command>INSERT</command>,
!     <command>UPDATE</command> and <command>UPDATE</command> actions on the view
!     into appropriate actions on other tables. You can also replace
!     automatically generated rules with your own rules. For more information,
!     refer to <xref linkend="sql-createrule" endterm="sql-createrule-title">.
     </para>
  
     <para>
***************
*** 171,225 ****
    <title>Compatibility</title>
  
    <para>
-    The SQL standard specifies some additional capabilities for the
-    <command>CREATE VIEW</command> statement:
- <synopsis>
- CREATE VIEW <replaceable class="parameter">name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ]
-     AS <replaceable class="PARAMETER">query</replaceable>
-     [ WITH [ CASCADED | LOCAL ] CHECK OPTION ]
- </synopsis>
-   </para>
- 
-   <para>
-    The optional clauses for the full SQL command are:
- 
-    <variablelist>
-      <varlistentry>
-       <term><literal>CHECK OPTION</literal></term>
-       <listitem>
-        <para>
-         This option has to do with updatable views.  All
-         <command>INSERT</> and <command>UPDATE</> commands on the view
-         will be checked to ensure data satisfy the view-defining
-         condition (that is, the new data would be visible through the
-         view). If they do not, the update will be rejected.
-        </para>
-       </listitem>
-      </varlistentry>
- 
-      <varlistentry>
-       <term><literal>LOCAL</literal></term>
-       <listitem>
-        <para>
-         Check for integrity on this view.
-        </para>
-       </listitem>
-      </varlistentry>
- 
-      <varlistentry>
-       <term><literal>CASCADED</literal></term>
-       <listitem>
-        <para>
-         Check for integrity on this view and on any dependent
-         view. <literal>CASCADED</> is assumed if neither
-         <literal>CASCADED</> nor <literal>LOCAL</> is specified.
-        </para>
-       </listitem>
-      </varlistentry>
-    </variablelist>
-   </para>
- 
-   <para>
     <command>CREATE OR REPLACE VIEW</command> is a
     <productname>PostgreSQL</productname> language extension.
     So is the concept of a temporary view.
--- 246,251 ----
Index: src/backend/catalog/information_schema.sql
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/catalog/information_schema.sql,v
retrieving revision 1.33
diff -c -r1.33 information_schema.sql
*** src/backend/catalog/information_schema.sql	2 Apr 2006 17:38:13 -0000	1.33
--- src/backend/catalog/information_schema.sql	24 Aug 2006 20:18:29 -0000
***************
*** 2126,2132 ****
                    ELSE null END
               AS character_data) AS view_definition,
  
!            CAST('NONE' AS character_data) AS check_option,
  
             CAST(
               CASE WHEN EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 2 AND is_instead)
--- 2126,2143 ----
                    ELSE null END
               AS character_data) AS view_definition,
  
!            CAST(
!              CASE WHEN EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 2 AND is_instead AND ev_kind = 'l')
!                     OR EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 3 AND is_instead AND ev_kind = 'l')
!                     OR EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 4 AND is_instead AND ev_kind = 'l')
!                   THEN 'LOCAL'
!                   WHEN EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 2 AND is_instead AND ev_kind = 'c')
!                     OR EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 3 AND is_instead AND ev_kind = 'c')
!                     OR EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 4 AND is_instead AND ev_kind = 'c')
!                   THEN 'CASCADED'
!                   ELSE 'NONE' 
!              END
!            AS character_data) AS check_option,
  
             CAST(
               CASE WHEN EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 2 AND is_instead)
Index: src/backend/commands/view.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/commands/view.c,v
retrieving revision 1.97
diff -c -r1.97 view.c
*** src/backend/commands/view.c	21 Aug 2006 00:57:24 -0000	1.97
--- src/backend/commands/view.c	24 Aug 2006 20:18:30 -0000
***************
*** 29,41 ****
--- 29,44 ----
  #include "rewrite/rewriteDefine.h"
  #include "rewrite/rewriteManip.h"
  #include "rewrite/rewriteSupport.h"
+ #include "rewrite/viewUpdate.h"
  #include "utils/acl.h"
  #include "utils/lsyscache.h"
+ #include "utils/memutils.h"
  
  
  static void checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc);
  static bool isViewOnTempTable_walker(Node *node, void *context);
  
+ 
  /*---------------------------------------------------------------------
   * isViewOnTempTable
   *
***************
*** 280,329 ****
  }
  
  static void
! DefineViewRules(const RangeVar *view, Query *viewParse, bool replace)
  {
  	RuleStmt   *retrieve_rule;
  
- #ifdef NOTYET
- 	RuleStmt   *replace_rule;
- 	RuleStmt   *append_rule;
- 	RuleStmt   *delete_rule;
- #endif
- 
  	retrieve_rule = FormViewRetrieveRule(view, viewParse, replace);
  
! #ifdef NOTYET
! 	replace_rule = FormViewReplaceRule(view, viewParse);
! 	append_rule = FormViewAppendRule(view, viewParse);
! 	delete_rule = FormViewDeleteRule(view, viewParse);
! #endif
! 
! 	DefineQueryRewrite(retrieve_rule);
! 
! #ifdef NOTYET
! 	DefineQueryRewrite(replace_rule);
! 	DefineQueryRewrite(append_rule);
! 	DefineQueryRewrite(delete_rule);
! #endif
  
  }
  
! /*---------------------------------------------------------------
   * UpdateRangeTableOfViewParse
   *
!  * Update the range table of the given parsetree.
!  * This update consists of adding two new entries IN THE BEGINNING
!  * of the range table (otherwise the rule system will die a slow,
!  * horrible and painful death, and we do not want that now, do we?)
!  * one for the OLD relation and one for the NEW one (both of
   * them refer in fact to the "view" relation).
   *
!  * Of course we must also increase the 'varnos' of all the Var nodes
!  * by 2...
   *
!  * These extra RT entries are not actually used in the query,
!  * except for run-time permission checking.
!  *---------------------------------------------------------------
   */
  static Query *
  UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
--- 283,314 ----
  }
  
  static void
! DefineViewRules(const RangeVar *view, Query *viewParse, bool replace,
! 				bool checkOption, bool cascade)
  {
  	RuleStmt   *retrieve_rule;
  
  	retrieve_rule = FormViewRetrieveRule(view, viewParse, replace);
  
! 	DefineQueryRewrite(retrieve_rule, 
! 					   makeViewCheckOption(checkOption, cascade));
  
+ 	CreateViewUpdateRules(viewParse, view, checkOption, cascade);
  }
  
! /*
   * UpdateRangeTableOfViewParse
   *
!  * Update the range table of the given parsetree.  This update consists of
!  * adding two new entries IN THE BEGINNING of the range table (otherwise the
!  * rule system will die a slow, horrible and painful death, and we do not want
!  * that now, do we?) one for the OLD relation and one for the NEW one (both of
   * them refer in fact to the "view" relation).
   *
!  * Of course we must also increase the 'varnos' of all the Var nodes by 2...
   *
!  * These extra RT entries are not actually used in the query, except for
!  * run-time permission checking.
   */
  static Query *
  UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
***************
*** 387,393 ****
   *-------------------------------------------------------------------
   */
  void
! DefineView(RangeVar *view, Query *viewParse, bool replace)
  {
  	Oid			viewOid;
  
--- 372,379 ----
   *-------------------------------------------------------------------
   */
  void
! DefineView(RangeVar *view, Query *viewParse, bool replace, bool checkOption,
! 		   bool cascade)
  {
  	Oid			viewOid;
  
***************
*** 428,434 ****
  	/*
  	 * Now create the rules associated with the view.
  	 */
! 	DefineViewRules(view, viewParse, replace);
  }
  
  /*
--- 414,420 ----
  	/*
  	 * Now create the rules associated with the view.
  	 */
! 	DefineViewRules(view, viewParse, replace, checkOption, cascade);
  }
  
  /*
Index: src/backend/parser/gram.y
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/parser/gram.y,v
retrieving revision 2.557
diff -c -r2.557 gram.y
*** src/backend/parser/gram.y	21 Aug 2006 00:57:25 -0000	2.557
--- src/backend/parser/gram.y	24 Aug 2006 20:18:34 -0000
***************
*** 4475,4481 ****
   *****************************************************************************/
  
  RuleStmt:	CREATE opt_or_replace RULE name AS
! 			{ QueryIsRule=TRUE; }
  			ON event TO qualified_name where_clause
  			DO opt_instead RuleActionList
  				{
--- 4475,4481 ----
   *****************************************************************************/
  
  RuleStmt:	CREATE opt_or_replace RULE name AS
! 			{ QueryIsRule = true; }
  			ON event TO qualified_name where_clause
  			DO opt_instead RuleActionList
  				{
***************
*** 4488,4494 ****
  					n->instead = $13;
  					n->actions = $14;
  					$$ = (Node *)n;
! 					QueryIsRule=FALSE;
  				}
  		;
  
--- 4488,4494 ----
  					n->instead = $13;
  					n->actions = $14;
  					$$ = (Node *)n;
! 					QueryIsRule = false;
  				}
  		;
  
***************
*** 4501,4513 ****
  /* the thrashing around here is to discard "empty" statements... */
  RuleActionMulti:
  			RuleActionMulti ';' RuleActionStmtOrEmpty
! 				{ if ($3 != NULL)
  					$$ = lappend($1, $3);
  				  else
  					$$ = $1;
  				}
  			| RuleActionStmtOrEmpty
! 				{ if ($1 != NULL)
  					$$ = list_make1($1);
  				  else
  					$$ = NIL;
--- 4501,4515 ----
  /* the thrashing around here is to discard "empty" statements... */
  RuleActionMulti:
  			RuleActionMulti ';' RuleActionStmtOrEmpty
! 				{
! 				  if ($3 != NULL)
  					$$ = lappend($1, $3);
  				  else
  					$$ = $1;
  				}
  			| RuleActionStmtOrEmpty
! 				{
! 				  if ($1 != NULL)
  					$$ = list_make1($1);
  				  else
  					$$ = NIL;
***************
*** 4772,4777 ****
--- 4774,4780 ----
  					n->view->istemp = $2;
  					n->aliases = $5;
  					n->query = (Query *) $7;
+ 					n->options = $8;
  					$$ = (Node *) n;
  				}
  		| CREATE OR REPLACE OptTemp VIEW qualified_name opt_column_list
***************
*** 4783,4788 ****
--- 4786,4792 ----
  					n->view->istemp = $4;
  					n->aliases = $7;
  					n->query = (Query *) $9;
+ 					n->options = $10;
  					$$ = (Node *) n;
  				}
  		;
***************
*** 4794,4814 ****
  opt_check_option:
  		WITH_CHECK OPTION
  				{
! 					ereport(ERROR,
! 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
! 							 errmsg("WITH CHECK OPTION is not implemented")));
  				}
  		| WITH_CASCADED CHECK OPTION
  				{
! 					ereport(ERROR,
! 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
! 							 errmsg("WITH CHECK OPTION is not implemented")));
  				}
  		| WITH_LOCAL CHECK OPTION
  				{
! 					ereport(ERROR,
! 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
! 							 errmsg("WITH CHECK OPTION is not implemented")));
  				}
  		| /* EMPTY */							{ $$ = NIL; }
  		;
--- 4798,4812 ----
  opt_check_option:
  		WITH_CHECK OPTION
  				{
! 					$$ = list_make1((Node *)makeString("cascaded"));
  				}
  		| WITH_CASCADED CHECK OPTION
  				{
! 					$$ = list_make1((Node *)makeString("cascaded"));
  				}
  		| WITH_LOCAL CHECK OPTION
  				{
! 					$$ = list_make1((Node *)makeString("local"));
  				}
  		| /* EMPTY */							{ $$ = NIL; }
  		;
Index: src/backend/parser/keywords.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/parser/keywords.c,v
retrieving revision 1.175
diff -c -r1.175 keywords.c
*** src/backend/parser/keywords.c	12 Aug 2006 02:52:05 -0000	1.175
--- src/backend/parser/keywords.c	24 Aug 2006 20:18:34 -0000
***************
*** 67,72 ****
--- 67,73 ----
  	{"cache", CACHE},
  	{"called", CALLED},
  	{"cascade", CASCADE},
+ 	{"cascaded", CASCADED},
  	{"case", CASE},
  	{"cast", CAST},
  	{"chain", CHAIN},
Index: src/backend/rewrite/Makefile
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/rewrite/Makefile,v
retrieving revision 1.15
diff -c -r1.15 Makefile
*** src/backend/rewrite/Makefile	29 Nov 2003 19:51:55 -0000	1.15
--- src/backend/rewrite/Makefile	24 Aug 2006 20:18:34 -0000
***************
*** 13,19 ****
  include $(top_builddir)/src/Makefile.global
  
  OBJS = rewriteRemove.o rewriteDefine.o \
!        rewriteHandler.o rewriteManip.o rewriteSupport.o
  
  all: SUBSYS.o
  
--- 13,20 ----
  include $(top_builddir)/src/Makefile.global
  
  OBJS = rewriteRemove.o rewriteDefine.o \
!        rewriteHandler.o rewriteManip.o rewriteSupport.o \
!        viewUpdate.o
  
  all: SUBSYS.o
  
Index: src/backend/rewrite/rewriteDefine.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/rewrite/rewriteDefine.c,v
retrieving revision 1.112
diff -c -r1.112 rewriteDefine.c
*** src/backend/rewrite/rewriteDefine.c	12 Aug 2006 20:05:55 -0000	1.112
--- src/backend/rewrite/rewriteDefine.c	24 Aug 2006 20:18:35 -0000
***************
*** 23,28 ****
--- 23,29 ----
  #include "parser/parse_expr.h"
  #include "rewrite/rewriteDefine.h"
  #include "rewrite/rewriteManip.h"
+ #include "rewrite/rewriteRemove.h"
  #include "rewrite/rewriteSupport.h"
  #include "storage/smgr.h"
  #include "utils/acl.h"
***************
*** 44,58 ****
  static Oid
  InsertRule(char *rulname,
  		   int evtype,
! 		   Oid eventrel_oid,
  		   AttrNumber evslot_index,
  		   bool evinstead,
  		   Node *event_qual,
  		   List *action,
  		   bool replace)
  {
  	char	   *evqual = nodeToString(event_qual);
  	char	   *actiontree = nodeToString((Node *) action);
  	int			i;
  	Datum		values[Natts_pg_rewrite];
  	char		nulls[Natts_pg_rewrite];
--- 45,62 ----
  static Oid
  InsertRule(char *rulname,
  		   int evtype,
! 		   /*Oid eventrel_oid,*/
! 		   Relation event_relation,
  		   AttrNumber evslot_index,
  		   bool evinstead,
+ 		   char evkind,
  		   Node *event_qual,
  		   List *action,
  		   bool replace)
  {
  	char	   *evqual = nodeToString(event_qual);
  	char	   *actiontree = nodeToString((Node *) action);
+ 	Oid        eventrel_oid = RelationGetRelid(event_relation);
  	int			i;
  	Datum		values[Natts_pg_rewrite];
  	char		nulls[Natts_pg_rewrite];
***************
*** 78,83 ****
--- 82,88 ----
  	values[i++] = Int16GetDatum(evslot_index);	/* ev_attr */
  	values[i++] = CharGetDatum(evtype + '0');	/* ev_type */
  	values[i++] = BoolGetDatum(evinstead);		/* is_instead */
+ 	values[i++] = CharGetDatum(evkind);         /* ev_kind */
  	values[i++] = DirectFunctionCall1(textin, CStringGetDatum(evqual)); /* ev_qual */
  	values[i++] = DirectFunctionCall1(textin, CStringGetDatum(actiontree));		/* ev_action */
  
***************
*** 96,114 ****
  
  	if (HeapTupleIsValid(oldtup))
  	{
  		if (!replace)
! 			ereport(ERROR,
! 					(errcode(ERRCODE_DUPLICATE_OBJECT),
! 					 errmsg("rule \"%s\" for relation \"%s\" already exists",
! 							rulname, get_rel_name(eventrel_oid))));
  
  		/*
  		 * When replacing, we don't need to replace every attribute
  		 */
  		MemSet(replaces, ' ', sizeof(replaces));
  		replaces[Anum_pg_rewrite_ev_attr - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_type - 1] = 'r';
  		replaces[Anum_pg_rewrite_is_instead - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_qual - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_action - 1] = 'r';
  
--- 101,160 ----
  
  	if (HeapTupleIsValid(oldtup))
  	{
+ 		Datum dat;
+ 		char old_tup_is_implicit;		
+ 		bool isnull;
+ 
+ 		dat = heap_getattr(oldtup,
+ 						   Anum_pg_rewrite_ev_kind,
+ 						   RelationGetDescr(pg_rewrite_desc),
+ 						   &isnull);
+ 		
+ 		if (isnull) 
+ 			/* should not happen */
+ 			elog(ERROR, "got null field in ev_kind where not null expected");
+ 		
  		if (!replace)
! 		{
! 			/*
! 			 * If REPLACE was not used we still have to check if the
! 			 * rule is implicit: then we have to replace it anyways.
! 			 */
! 			
! 			old_tup_is_implicit = DatumGetChar(dat);
! 			
! 			if (old_tup_is_implicit == NO_OPTION_EXPLICIT)
! 			{
! 				ereport(ERROR,
! 						(errcode(ERRCODE_DUPLICATE_OBJECT),
! 						 errmsg("rule \"%s\" for relation \"%s\" already exists",
! 								rulname, get_rel_name(eventrel_oid))));
! 			}
! 		}
  
  		/*
+ 		 * If we are about to replace an implicit rule
+ 		 * with an user defined rule, we need to drop all
+ 		 * implicit rules on the same action (for implicit 
+ 		 * conditional rules we have DO INSTEAD NOTHING RULES
+ 		 * present and vice versa...). We have to be careful not
+ 		 * to drop the current rule we want to replace...
+ 		 */
+ 		if ((old_tup_is_implicit != NO_OPTION_EXPLICIT)
+ 			&& (evkind == NO_OPTION_EXPLICIT))
+ 		{
+ 			deleteImplicitRulesOnEvent(event_relation, evtype,
+ 									   HeapTupleGetOid(oldtup));
+ 		}
+ 		
+ 		/*
  		 * When replacing, we don't need to replace every attribute
  		 */
  		MemSet(replaces, ' ', sizeof(replaces));
  		replaces[Anum_pg_rewrite_ev_attr - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_type - 1] = 'r';
  		replaces[Anum_pg_rewrite_is_instead - 1] = 'r';
+ 		replaces[Anum_pg_rewrite_ev_kind - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_qual - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_action - 1] = 'r';
  
***************
*** 124,129 ****
--- 170,186 ----
  	}
  	else
  	{
+ 		/*
+ 		 * Implicit rules should be dropped automatically when someone
+ 		 * wants to have its *own* rules on the view. is_implicit is set
+ 		 * to NO_OPTION_EXPLICIT in this case so we drop all implicit 
+ 		 * rules on the specified event type immediately.
+ 		 */
+ 
+ 		if (evkind == NO_OPTION_EXPLICIT)
+ 			deleteImplicitRulesOnEvent(event_relation, evtype,
+ 									   InvalidOid);
+ 
  		tup = heap_formtuple(pg_rewrite_desc->rd_att, values, nulls);
  
  		rewriteObjectId = simple_heap_insert(pg_rewrite_desc, tup);
***************
*** 177,183 ****
  }
  
  void
! DefineQueryRewrite(RuleStmt *stmt)
  {
  	RangeVar   *event_obj = stmt->relation;
  	Node	   *event_qual = stmt->whereClause;
--- 234,240 ----
  }
  
  void
! DefineQueryRewrite(RuleStmt *stmt, char ev_kind)
  {
  	RangeVar   *event_obj = stmt->relation;
  	Node	   *event_qual = stmt->whereClause;
***************
*** 443,457 ****
  		setRuleCheckAsUser_Query(query, GetUserId());
  	}
  	setRuleCheckAsUser_Expr(event_qual, GetUserId());
! 
  	/* discard rule if it's null action and not INSTEAD; it's a no-op */
  	if (action != NIL || is_instead)
  	{
  		ruleId = InsertRule(stmt->rulename,
  							event_type,
! 							ev_relid,
  							event_attno,
  							is_instead,
  							event_qual,
  							action,
  							replace);
--- 500,515 ----
  		setRuleCheckAsUser_Query(query, GetUserId());
  	}
  	setRuleCheckAsUser_Expr(event_qual, GetUserId());
! 	
  	/* discard rule if it's null action and not INSTEAD; it's a no-op */
  	if (action != NIL || is_instead)
  	{
  		ruleId = InsertRule(stmt->rulename,
  							event_type,
! 							event_relation,
  							event_attno,
  							is_instead,
+ 							ev_kind,
  							event_qual,
  							action,
  							replace);
***************
*** 469,475 ****
  	}
  
  	/*
! 	 * IF the relation is becoming a view, delete the storage files associated
  	 * with it.  NB: we had better have AccessExclusiveLock to do this ...
  	 *
  	 * XXX what about getting rid of its TOAST table?  For now, we don't.
--- 527,533 ----
  	}
  
  	/*
! 	 * If the relation is becoming a view, delete the storage files associated
  	 * with it.  NB: we had better have AccessExclusiveLock to do this ...
  	 *
  	 * XXX what about getting rid of its TOAST table?  For now, we don't.
Index: src/backend/rewrite/rewriteHandler.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/rewrite/rewriteHandler.c,v
retrieving revision 1.165
diff -c -r1.165 rewriteHandler.c
*** src/backend/rewrite/rewriteHandler.c	2 Aug 2006 01:59:47 -0000	1.165
--- src/backend/rewrite/rewriteHandler.c	24 Aug 2006 20:18:37 -0000
***************
*** 15,20 ****
--- 15,21 ----
  
  #include "access/heapam.h"
  #include "catalog/pg_type.h"
+ #include "catalog/pg_rewrite.h"
  #include "nodes/makefuncs.h"
  #include "optimizer/clauses.h"
  #include "parser/analyze.h"
***************
*** 34,45 ****
  	CmdType		event;			/* type of rule being fired */
  } rewrite_event;
  
  static bool acquireLocksOnSubLinks(Node *node, void *context);
  static Query *rewriteRuleAction(Query *parsetree,
  				  Query *rule_action,
  				  Node *rule_qual,
  				  int rt_index,
! 				  CmdType event);
  static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index);
  static void rewriteTargetList(Query *parsetree, Relation target_relation,
  							  List **attrno_list);
--- 35,55 ----
  	CmdType		event;			/* type of rule being fired */
  } rewrite_event;
  
+ /* Rule rewrite status for updatable views */
+ typedef struct view_update_event
+ {
+ 	bool viewUpdate;
+ 	bool needCheckOption;
+ 	char checkMode;	
+ } view_update_event;
+ 
  static bool acquireLocksOnSubLinks(Node *node, void *context);
  static Query *rewriteRuleAction(Query *parsetree,
  				  Query *rule_action,
  				  Node *rule_qual,
  				  int rt_index,
!                   CmdType event,
! 				  view_update_event *view_event);
  static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index);
  static void rewriteTargetList(Query *parsetree, Relation target_relation,
  							  List **attrno_list);
***************
*** 257,263 ****
  				  Query *rule_action,
  				  Node *rule_qual,
  				  int rt_index,
! 				  CmdType event)
  {
  	int			current_varno,
  				new_varno;
--- 267,274 ----
  				  Query *rule_action,
  				  Node *rule_qual,
  				  int rt_index,
! 				  CmdType event,
! 				  view_update_event *view_event)
  {
  	int			current_varno,
  				new_varno;
***************
*** 387,393 ****
  	 * queries one w/rule_qual, one w/NOT rule_qual. Also add user query qual
  	 * onto rule action
  	 */
! 	AddQual(sub_action, rule_qual);
  
  	AddQual(sub_action, parsetree->jointree->quals);
  
--- 398,405 ----
  	 * queries one w/rule_qual, one w/NOT rule_qual. Also add user query qual
  	 * onto rule action
  	 */
! 	if (view_event->needCheckOption)
! 		AddQual(sub_action, rule_qual);
  
  	AddQual(sub_action, parsetree->jointree->quals);
  
***************
*** 820,825 ****
--- 832,850 ----
  		}
  	}
  
+ #if 0
+  	/*
+  	 * I will do this only in case of relkind == RELKIND_VIEW.
+  	 * This is the last attempt to get a value for expr before we
+  	 * consider that expr must be NULL.
+  	 */
+  	if (expr == NULL && rel->rd_rel->relkind == RELKIND_VIEW)
+  	{
+  		expr = (Node *)makeNode(SetToDefault);
+  		return expr;
+  	}
+ #endif
+ 
  	if (expr == NULL)
  	{
  		/*
***************
*** 1359,1367 ****
--- 1384,1400 ----
   *					(must be initialized to FALSE)
   *	*qual_product - filled with modified original query if any qualified
   *					INSTEAD rule is found (must be initialized to NULL)
+  *	view_event - Holds the current state of the rules recursion. This
+  *               is important especially for implicit view update rules
+  *               created by the system to apply rule conditions based
+  *               on a view's CHECK OPTION. view_event is expected to
+  *               to be initialized by QueryRewrite().
   * Return value:
   *	list of rule actions adjusted for use with this query
   *
+ 
+  *               
+  *
   * Qualified INSTEAD rules generate their action with the qualification
   * condition added.  They also generate a modified version of the original
   * query with the negated qualification added, so that it will run only for
***************
*** 1376,1381 ****
--- 1409,1415 ----
  		  int rt_index,
  		  CmdType event,
  		  List *locks,
+ 		  view_update_event *view_event,
  		  bool *instead_flag,
  		  Query **qual_product)
  {
***************
*** 1390,1400 ****
  		QuerySource qsrc;
  		ListCell   *r;
  
  		/* Determine correct QuerySource value for actions */
  		if (rule_lock->isInstead)
  		{
! 			if (event_qual != NULL)
! 				qsrc = QSRC_QUAL_INSTEAD_RULE;
  			else
  			{
  				qsrc = QSRC_INSTEAD_RULE;
--- 1424,1524 ----
  		QuerySource qsrc;
  		ListCell   *r;
  
+ 		/*
+ 		 * Apply information to the view_event structure and save the
+ 		 * current recursion state of fireRules(). We distinguish
+ 		 * implicit and explicit rules, the first one are created
+ 		 * by the system to implement updatable views. We need to know
+ 		 * about the check option applied to such an implicit rule and
+ 		 * the current "depth" of the recursion, e.g. LOCAL CHECK
+ 		 * OPTION should be applied only once for implicit rules in
+ 		 * a cascading view update recursion and explicit conditional
+ 		 * rules need to be applied always.
+ 		 *
+ 		 *
+ 		 * First check: look if this rule is an implicit view update rule. If
+ 		 * false, always apply any rule qualification.
+ 		 */
+ 		if (rule_lock->ev_kind == NO_OPTION_EXPLICIT)
+ 		{
+ 			view_event->viewUpdate = false;
+ 			view_event->needCheckOption = true;
+ 			view_event->checkMode = rule_lock->ev_kind;
+ 		}
+ 		
+ 		/*
+ 		 * Second check: Look if we are already in a view update or not.  If
+ 		 * true and the event check mode is set to LOCAL_OPTION_IMPLICIT in
+ 		 * conjunction with viewUpdate = true, we don't need to apply the check
+ 		 * option otherwise.
+ 		 */
+ 		else if (!view_event->viewUpdate &&
+ 				 ((rule_lock->ev_kind == LOCAL_OPTION_IMPLICIT) ||
+ 				  (rule_lock->ev_kind == CASCADED_OPTION_IMPLICIT)))
+ 				 
+ 		{
+ 			/* apply check option, but only once */
+ 			view_event->viewUpdate = true;
+ 			view_event->needCheckOption = true;
+ 			view_event->checkMode = rule_lock->ev_kind;
+ 		}
+ 
+ 		/*
+ 		 * Third check: Look if we are in a recursive view update in
+ 		 * conjunction with a CASCADED CHECK OPTION. If true, we always need to
+ 		 * apply any check options found.
+ 		 */
+ 		else if (view_event->viewUpdate &&
+ 				 (view_event->checkMode == CASCADED_OPTION_IMPLICIT) &&
+ 				 (rule_lock->ev_kind != NO_OPTION_EXPLICIT))
+ 		{
+ 			view_event->needCheckOption = true;
+ 		}
+ 
+ 		/*
+ 		 * 4th check: make sure we reset the view update event if we are in a
+ 		 * recursive view update and passed the first view already. If we had a
+ 		 * LOCAL CHECK OPTION, we have to make sure we don't fire any check
+ 		 * options anymore.
+ 		 */
+ 		else if (view_event->viewUpdate &&
+ 				 (view_event->checkMode == LOCAL_OPTION_IMPLICIT) &&
+ 				 (rule_lock->ev_kind != NO_OPTION_EXPLICIT))
+ 		{
+ 			view_event->needCheckOption = false;
+ 			/* force LOCAL check mode */
+ 			view_event->checkMode = LOCAL_OPTION_IMPLICIT;
+ 		}
+ 
  		/* Determine correct QuerySource value for actions */
  		if (rule_lock->isInstead)
  		{
! 			if (event_qual != NULL) 
! 			{				
! 				/*
! 				 * Check out wether we need to apply any
! 				 * rule qualification to a view update rule.
! 				 * We only bother on implicit rules that aren't
! 				 * marked with NO_OPTION_EXPLICIT
! 				 */
! 				if ((rule_lock->ev_kind != NO_OPTION_EXPLICIT)
! 					&& (view_event->viewUpdate))
! 				{
! 					if (view_event->needCheckOption)
! 					{
! 						qsrc = QSRC_QUAL_INSTEAD_RULE;
! 					}
! 					else
! 					{
! 						qsrc = QSRC_INSTEAD_RULE;
! 						*instead_flag = true;
! 					}
! 				} 
! 				else 
! 				{
! 					qsrc = QSRC_QUAL_INSTEAD_RULE;
! 				}
! 			}
  			else
  			{
  				qsrc = QSRC_INSTEAD_RULE;
***************
*** 1438,1444 ****
  				continue;
  
  			rule_action = rewriteRuleAction(parsetree, rule_action,
! 											event_qual, rt_index, event);
  
  			rule_action->querySource = qsrc;
  			rule_action->canSetTag = false;		/* might change later */
--- 1562,1569 ----
  				continue;
  
  			rule_action = rewriteRuleAction(parsetree, rule_action,
! 											event_qual, rt_index, event,
! 											view_event);
  
  			rule_action->querySource = qsrc;
  			rule_action->canSetTag = false;		/* might change later */
***************
*** 1459,1465 ****
   * infinite recursion.
   */
  static List *
! RewriteQuery(Query *parsetree, List *rewrite_events)
  {
  	CmdType		event = parsetree->commandType;
  	bool		instead = false;
--- 1584,1591 ----
   * infinite recursion.
   */
  static List *
! RewriteQuery(Query *parsetree, List *rewrite_events, 
! 			 view_update_event *view_event)
  {
  	CmdType		event = parsetree->commandType;
  	bool		instead = false;
***************
*** 1550,1555 ****
--- 1676,1682 ----
  										result_relation,
  										event,
  										locks,
+ 										view_event,
  										&instead,
  										&qual_product);
  
***************
*** 1583,1589 ****
  					Query	   *pt = (Query *) lfirst(n);
  					List	   *newstuff;
  
! 					newstuff = RewriteQuery(pt, rewrite_events);
  					rewritten = list_concat(rewritten, newstuff);
  				}
  
--- 1710,1716 ----
  					Query	   *pt = (Query *) lfirst(n);
  					List	   *newstuff;
  
! 					newstuff = RewriteQuery(pt, rewrite_events, view_event);
  					rewritten = list_concat(rewritten, newstuff);
  				}
  
***************
*** 1646,1658 ****
  	CmdType		origCmdType;
  	bool		foundOriginalQuery;
  	Query	   *lastInstead;
  
  	/*
  	 * Step 1
  	 *
  	 * Apply all non-SELECT rules possibly getting 0 or many queries
  	 */
! 	querylist = RewriteQuery(parsetree, NIL);
  
  	/*
  	 * Step 2
--- 1773,1789 ----
  	CmdType		origCmdType;
  	bool		foundOriginalQuery;
  	Query	   *lastInstead;
+ 	view_update_event v_event;
  
  	/*
  	 * Step 1
  	 *
  	 * Apply all non-SELECT rules possibly getting 0 or many queries
  	 */
! 	v_event.viewUpdate      = false;
! 	v_event.needCheckOption = false;
! 	v_event.checkMode       = NO_OPTION_EXPLICIT;
! 	querylist = RewriteQuery(parsetree, NIL, &v_event);
  
  	/*
  	 * Step 2
Index: src/backend/rewrite/rewriteRemove.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/rewrite/rewriteRemove.c,v
retrieving revision 1.65
diff -c -r1.65 rewriteRemove.c
*** src/backend/rewrite/rewriteRemove.c	16 Jun 2006 20:23:44 -0000	1.65
--- src/backend/rewrite/rewriteRemove.c	24 Aug 2006 20:18:37 -0000
***************
*** 89,94 ****
--- 89,146 ----
  	performDeletion(&object, behavior);
  }
  
+ /*
+  * deleteImplicitRulesOnEvent
+  * 
+  * This will delete implicit rules, if any exists, on the event in the
+  * relation.
+  * You can use exceptOid to exclude a specific implicit
+  * rule from deletion, use InvalidOid if you want to
+  * safely delete all implicit rules.
+  */
+ void 
+ deleteImplicitRulesOnEvent(Relation rel, CmdType event_type,
+ 						   Oid exceptOid)
+ {
+ 	RuleLock *rulelocks = rel->rd_rules;
+ 	int nlocks;
+ 	int i;
+ 
+ 	/*
+ 	 * Select rules are implicit (are they marked as implicit??) 
+ 	 * but we don't want to delete them
+ 	 */
+ 	if (event_type == CMD_SELECT)
+ 		return;
+ 
+ 	/*
+ 	 * If there are no rules on the relation we waste no more time
+ 	 */
+ 	if (rulelocks == NULL)
+ 		return;
+ 
+ 	nlocks = rulelocks->numLocks;
+ 
+ 	/*
+ 	 * Look at all rules looking for the ones that are on the event and are
+ 	 * implicit
+ 	 */
+ 	for (i = 0; i < nlocks; i++)
+ 	{
+ 		RewriteRule *oneLock = rulelocks->rules[i];		
+ 		
+ 		if ((oneLock->event == event_type)
+ 			&& (oneLock->ev_kind != NO_OPTION_EXPLICIT)
+ 			&& (oneLock->ruleId != exceptOid))
+ 		{
+ 			RemoveRewriteRuleById(oneLock->ruleId);
+ 			elog(DEBUG1, "removing implicit rule with oid %d\n", 
+ 				 oneLock->ruleId);
+ 			deleteDependencyRecordsFor(RewriteRelationId, oneLock->ruleId);
+ 		}
+ 	}
+ }
+ 
  
  /*
   * Guts of rule deletion.
Index: src/backend/tcop/utility.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/tcop/utility.c,v
retrieving revision 1.266
diff -c -r1.266 utility.c
*** src/backend/tcop/utility.c	15 Aug 2006 18:26:58 -0000	1.266
--- src/backend/tcop/utility.c	24 Aug 2006 20:18:38 -0000
***************
*** 20,25 ****
--- 20,26 ----
  #include "access/xact.h"
  #include "catalog/catalog.h"
  #include "catalog/namespace.h"
+ #include "catalog/pg_rewrite.h"
  #include "catalog/toasting.h"
  #include "commands/alter.h"
  #include "commands/async.h"
***************
*** 764,771 ****
  		case T_ViewStmt:		/* CREATE VIEW */
  			{
  				ViewStmt   *stmt = (ViewStmt *) parsetree;
  
! 				DefineView(stmt->view, stmt->query, stmt->replace);
  			}
  			break;
  
--- 765,787 ----
  		case T_ViewStmt:		/* CREATE VIEW */
  			{
  				ViewStmt   *stmt = (ViewStmt *) parsetree;
+ 				bool		checkOption = false;
+ 				bool		cascade = false;
+ 				ListCell   *cell;
  
! 				if (list_length(stmt->options) > 0)
! 					checkOption = true;
! 
! 				foreach(cell, stmt->options)
! 				{
! 					Value *val = (Value *) lfirst(cell);
! 
! 					if (strncmp(strVal(val), "cascade", strlen("cascade")) == 0)
! 						cascade = true;
! 				}
! 
! 				DefineView(stmt->view, stmt->query, stmt->replace, 
! 						   checkOption, cascade);
  			}
  			break;
  
***************
*** 803,809 ****
  			break;
  
  		case T_RuleStmt:		/* CREATE RULE */
! 			DefineQueryRewrite((RuleStmt *) parsetree);
  			break;
  
  		case T_CreateSeqStmt:
--- 819,825 ----
  			break;
  
  		case T_RuleStmt:		/* CREATE RULE */
! 			DefineQueryRewrite((RuleStmt *) parsetree, NO_OPTION_EXPLICIT);
  			break;
  
  		case T_CreateSeqStmt:
Index: src/backend/utils/adt/ruleutils.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/utils/adt/ruleutils.c,v
retrieving revision 1.232
diff -c -r1.232 ruleutils.c
*** src/backend/utils/adt/ruleutils.c	21 Aug 2006 00:57:25 -0000	1.232
--- src/backend/utils/adt/ruleutils.c	24 Aug 2006 20:18:59 -0000
***************
*** 18,23 ****
--- 18,24 ----
  #include "catalog/pg_depend.h"
  #include "catalog/pg_opclass.h"
  #include "catalog/pg_operator.h"
+ #include "catalog/pg_rewrite.h"
  #include "catalog/pg_trigger.h"
  #include "executor/spi.h"
  #include "funcapi.h"
***************
*** 1683,1688 ****
--- 1684,1690 ----
  	Oid			ev_class;
  	int2		ev_attr;
  	bool		is_instead;
+ 	char        ev_kind;
  	char	   *ev_qual;
  	char	   *ev_action;
  	List	   *actions = NIL;
***************
*** 1705,1710 ****
--- 1707,1715 ----
  	fno = SPI_fnumber(rulettc, "is_instead");
  	is_instead = (bool) SPI_getbinval(ruletup, rulettc, fno, &isnull);
  
+ 	fno = SPI_fnumber(rulettc, "ev_kind");
+ 	ev_kind = (char) SPI_getbinval(ruletup, rulettc, fno, &isnull);
+ 
  	fno = SPI_fnumber(rulettc, "ev_qual");
  	ev_qual = SPI_getvalue(ruletup, rulettc, fno);
  
***************
*** 1732,1737 ****
--- 1737,1761 ----
  
  	get_query_def(query, buf, NIL, RelationGetDescr(ev_relation),
  				  prettyFlags, 0);
+ 
+ 	/*
+ 	 * Support for updatable views: append the check option if
+ 	 * required. If any pretty print flags is enabled, we need
+ 	 * to do a linebreak before.
+ 	 */
+ 	if (ev_kind != NO_OPTION_EXPLICIT || ev_kind != NO_OPTION_IMPLICIT)
+ 	{
+ 		if (prettyFlags & PRETTYFLAG_INDENT)
+ 			appendStringInfo(buf, "\n");
+ 
+ 		appendStringInfoSpaces(buf, 1);
+ 
+ 		if (ev_kind == LOCAL_OPTION_IMPLICIT)
+ 			appendStringInfo(buf, " WITH LOCAL CHECK OPTION");
+ 		else if (ev_kind == CASCADED_OPTION_IMPLICIT)
+ 			appendStringInfo(buf, " WITH CASCADED CHECK OPTION");
+ 	}
+ 
  	appendStringInfo(buf, ";");
  
  	heap_close(ev_relation, AccessShareLock);
Index: src/backend/utils/cache/relcache.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/utils/cache/relcache.c,v
retrieving revision 1.247
diff -c -r1.247 relcache.c
*** src/backend/utils/cache/relcache.c	31 Jul 2006 20:09:05 -0000	1.247
--- src/backend/utils/cache/relcache.c	24 Aug 2006 20:18:59 -0000
***************
*** 646,651 ****
--- 646,652 ----
  		rule->event = rewrite_form->ev_type - '0';
  		rule->attrno = rewrite_form->ev_attr;
  		rule->isInstead = rewrite_form->is_instead;
+ 		rule->ev_kind = rewrite_form->ev_kind;
  
  		/*
  		 * Must use heap_getattr to fetch ev_action and ev_qual.  Also,
***************
*** 748,753 ****
--- 749,756 ----
  				return false;
  			if (!equal(rule1->actions, rule2->actions))
  				return false;
+ 			if(rule1->ev_kind != rule2->ev_kind)
+ 				return false;
  		}
  	}
  	else if (rlock2 != NULL)
Index: src/bin/pg_dump/pg_dump.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/bin/pg_dump/pg_dump.c,v
retrieving revision 1.447
diff -c -r1.447 pg_dump.c
*** src/bin/pg_dump/pg_dump.c	21 Aug 2006 00:57:25 -0000	1.447
--- src/bin/pg_dump/pg_dump.c	24 Aug 2006 20:19:05 -0000
***************
*** 51,56 ****
--- 51,57 ----
  #include "catalog/pg_proc.h"
  #include "catalog/pg_trigger.h"
  #include "catalog/pg_type.h"
+ #include "catalog/pg_rewrite.h"
  #include "commands/sequence.h"
  #include "libpq/libpq-fs.h"
  #include "mb/pg_wchar.h"
***************
*** 3658,3663 ****
--- 3659,3665 ----
  	int			i_ruletable;
  	int			i_ev_type;
  	int			i_is_instead;
+ 	int			i_ev_kind;
  
  	/* Make sure we are in proper schema */
  	selectSourceSchema("pg_catalog");
***************
*** 3666,3672 ****
  	{
  		appendPQExpBuffer(query, "SELECT "
  						  "tableoid, oid, rulename, "
! 						  "ev_class as ruletable, ev_type, is_instead "
  						  "FROM pg_rewrite "
  						  "ORDER BY oid");
  	}
--- 3668,3675 ----
  	{
  		appendPQExpBuffer(query, "SELECT "
  						  "tableoid, oid, rulename, "
! 						  "ev_class as ruletable, ev_type, is_instead, "
! 						  "ev_kind "
  						  "FROM pg_rewrite "
  						  "ORDER BY oid");
  	}
***************
*** 3675,3681 ****
  		appendPQExpBuffer(query, "SELECT "
  						  "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
  						  "oid, rulename, "
! 						  "ev_class as ruletable, ev_type, is_instead "
  						  "FROM pg_rewrite "
  						  "ORDER BY oid");
  	}
--- 3678,3685 ----
  		appendPQExpBuffer(query, "SELECT "
  						  "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
  						  "oid, rulename, "
! 						  "ev_class as ruletable, ev_type, is_instead, "
! 						  "ev_kind "
  						  "FROM pg_rewrite "
  						  "ORDER BY oid");
  	}
***************
*** 3695,3700 ****
--- 3699,3705 ----
  	i_ruletable = PQfnumber(res, "ruletable");
  	i_ev_type = PQfnumber(res, "ev_type");
  	i_is_instead = PQfnumber(res, "is_instead");
+ 	i_ev_kind = PQfnumber(res, "ev_kind");
  
  	for (i = 0; i < ntups; i++)
  	{
***************
*** 3718,3739 ****
  		ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
  		ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
  		ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
  		if (ruleinfo[i].ruletable)
  		{
  			/*
! 			 * If the table is a view, force its ON SELECT rule to be sorted
! 			 * before the view itself --- this ensures that any dependencies
! 			 * for the rule affect the table's positioning. Other rules are
! 			 * forced to appear after their table.
  			 */
! 			if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
! 				ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
! 			{
! 				addObjectDependency(&ruleinfo[i].ruletable->dobj,
! 									ruleinfo[i].dobj.dumpId);
! 				/* We'll merge the rule into CREATE VIEW, if possible */
! 				ruleinfo[i].separate = false;
! 			}
  			else
  			{
  				addObjectDependency(&ruleinfo[i].dobj,
--- 3723,3757 ----
  		ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
  		ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
  		ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
+ 		ruleinfo[i].ev_kind = *(PQgetvalue(res, i, i_ev_kind));
  		if (ruleinfo[i].ruletable)
  		{
  			/*
! 			 * If the table is a view, force its ON SELECT rule to be
! 			 * sorted before the view itself --- this ensures that any
! 			 * dependencies for the rule affect the table's positioning.
! 			 * Other rules are forced to appear after their table.
! 			 *
! 			 * Do the same for implicit rules (for updateable views support).
  			 */
! 			if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW) 
! 				if (ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
! 				{
! 					addObjectDependency(&ruleinfo[i].ruletable->dobj,
! 										ruleinfo[i].dobj.dumpId);
! 					/* We'll merge the rule into CREATE VIEW, if possible */
! 					ruleinfo[i].separate = false;
! 				}
! 				else
! 					if (ruleinfo[i].ev_kind != NO_OPTION_EXPLICIT)
! 					{
! 						addObjectDependency(&ruleinfo[i].ruletable->dobj,
! 											ruleinfo[i].dobj.dumpId);
! 						/* We'll merge the rule into CREATE VIEW, if possible */
! 						ruleinfo[i].separate = false;
! 					}
! 					else
! 						ruleinfo[i].separate = true;
  			else
  			{
  				addObjectDependency(&ruleinfo[i].dobj,
Index: src/bin/pg_dump/pg_dump.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/bin/pg_dump/pg_dump.h,v
retrieving revision 1.129
diff -c -r1.129 pg_dump.h
*** src/bin/pg_dump/pg_dump.h	21 Aug 2006 00:57:25 -0000	1.129
--- src/bin/pg_dump/pg_dump.h	24 Aug 2006 20:19:06 -0000
***************
*** 260,267 ****
  	TableInfo  *ruletable;		/* link to table the rule is for */
  	char		ev_type;
  	bool		is_instead;
  	bool		separate;		/* TRUE if must dump as separate item */
! 	/* separate is always true for non-ON SELECT rules */
  } RuleInfo;
  
  typedef struct _triggerInfo
--- 260,271 ----
  	TableInfo  *ruletable;		/* link to table the rule is for */
  	char		ev_type;
  	bool		is_instead;
+ 	char		ev_kind;
  	bool		separate;		/* TRUE if must dump as separate item */
! 	/* 
! 	 * separate is true for non-ON SELECT rules and 
! 	 * for implicit rules (for updateable views support) 
! 	 */
  } RuleInfo;
  
  typedef struct _triggerInfo
Index: src/bin/pg_dump/pg_dump_sort.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/bin/pg_dump/pg_dump_sort.c,v
retrieving revision 1.15
diff -c -r1.15 pg_dump_sort.c
*** src/bin/pg_dump/pg_dump_sort.c	14 Jul 2006 14:52:26 -0000	1.15
--- src/bin/pg_dump/pg_dump_sort.c	24 Aug 2006 20:19:07 -0000
***************
*** 816,821 ****
--- 816,862 ----
  		}
  	}
  
+ 	/* View and its implicit rule */
+ 	if (nLoop == 2 &&
+ 		loop[0]->objType == DO_TABLE &&
+ 		loop[1]->objType == DO_RULE &&
+ 		((RuleInfo *) loop[1])->ev_kind != 'e' &&
+ 		((RuleInfo *) loop[1])->ruletable == (TableInfo *) loop[0])
+ 	{
+ 		repairViewRuleLoop(loop[0], loop[1]);
+ 		return;
+ 	}
+ 	if (nLoop == 2 &&
+ 		loop[1]->objType == DO_TABLE &&
+ 		loop[0]->objType == DO_RULE &&
+ 		((RuleInfo *) loop[0])->ev_kind != 'e' &&
+ 		((RuleInfo *) loop[0])->ruletable == (TableInfo *) loop[1])
+ 	{
+ 		repairViewRuleLoop(loop[1], loop[0]);
+ 		return;
+ 	}
+ 
+ 	/* Indirect loop involving view and implicit rule */
+ 	if (nLoop > 2)
+ 	{
+ 		for (i = 0; i < nLoop; i++)
+ 		{
+ 			if (loop[i]->objType == DO_TABLE)
+ 			{
+ 				for (j = 0; j < nLoop; j++)
+ 				{
+ 					if (loop[j]->objType == DO_RULE &&
+ 						((RuleInfo *) loop[j])->ev_kind != 'e' &&
+ 						((RuleInfo *) loop[j])->ruletable == (TableInfo *) loop[i])
+ 					{
+ 						repairViewRuleMultiLoop(loop[i], loop[j]);
+ 						return;
+ 					}
+ 				}
+ 			}
+ 		}
+ 	}
+ 
  	/* Table and CHECK constraint */
  	if (nLoop == 2 &&
  		loop[0]->objType == DO_TABLE &&
Index: src/include/catalog/pg_proc.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/catalog/pg_proc.h,v
retrieving revision 1.422
diff -c -r1.422 pg_proc.h
*** src/include/catalog/pg_proc.h	19 Aug 2006 01:36:33 -0000	1.422
--- src/include/catalog/pg_proc.h	24 Aug 2006 20:19:16 -0000
***************
*** 3845,3850 ****
--- 3845,3851 ----
  DESCR("convert int4 to boolean");
  DATA(insert OID = 2558 ( int4				   PGNSP PGUID 12 f f t f i 1  23 "16" _null_ _null_ _null_ bool_int4 - _null_ ));
  DESCR("convert boolean to int4");
+ /* internal function required for view update rules */
  DATA(insert OID = 2559 ( lastval			   PGNSP PGUID 12 f f t f v 0 20 "" _null_ _null_ _null_	lastval - _null_ ));
  DESCR("current value from last used sequence");
  
***************
*** 3898,3903 ****
--- 3899,3908 ----
  DATA(insert OID = 2592 (  gist_circle_compress	PGNSP PGUID 12 f f t f i 1 2281 "2281" _null_ _null_ _null_ gist_circle_compress - _null_ ));
  DESCR("GiST support");
  
+ /* functions for view update facility */
+ DATA(insert OID = 2570 ( pg_view_update_error       PGNSP PGUID 12 f f f f i 1 16 "16" _null_ _null_ _null_ pg_view_update_error - _null_));
+ DESCR("evaluates boolean input for view update check option");
+ 
  /* GIN */
  DATA(insert OID = 2730 (  gingettuple	   PGNSP PGUID 12 f f t f v 2 16 "2281 2281" _null_ _null_ _null_  gingettuple - _null_ ));
  DESCR("gin(internal)");
Index: src/include/catalog/pg_rewrite.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/catalog/pg_rewrite.h,v
retrieving revision 1.26
diff -c -r1.26 pg_rewrite.h
*** src/include/catalog/pg_rewrite.h	5 Mar 2006 15:58:55 -0000	1.26
--- src/include/catalog/pg_rewrite.h	24 Aug 2006 20:19:16 -0000
***************
*** 43,48 ****
--- 43,49 ----
  	int2		ev_attr;
  	char		ev_type;
  	bool		is_instead;
+ 	char		ev_kind;
  
  	/* NB: remaining fields must be accessed via heap_getattr */
  	text		ev_qual;
***************
*** 60,72 ****
   *		compiler constants for pg_rewrite
   * ----------------
   */
! #define Natts_pg_rewrite				7
  #define Anum_pg_rewrite_rulename		1
  #define Anum_pg_rewrite_ev_class		2
  #define Anum_pg_rewrite_ev_attr			3
  #define Anum_pg_rewrite_ev_type			4
  #define Anum_pg_rewrite_is_instead		5
! #define Anum_pg_rewrite_ev_qual			6
! #define Anum_pg_rewrite_ev_action		7
  
  #endif   /* PG_REWRITE_H */
--- 61,84 ----
   *		compiler constants for pg_rewrite
   * ----------------
   */
! #define Natts_pg_rewrite				8
  #define Anum_pg_rewrite_rulename		1
  #define Anum_pg_rewrite_ev_class		2
  #define Anum_pg_rewrite_ev_attr			3
  #define Anum_pg_rewrite_ev_type			4
  #define Anum_pg_rewrite_is_instead		5
! #define Anum_pg_rewrite_ev_kind			6
! #define Anum_pg_rewrite_ev_qual			7
! #define Anum_pg_rewrite_ev_action		8
! 
! /*
!  * Possible values for ev_kind 
!  */
! #define LOCAL_OPTION_IMPLICIT    'l' /* WITH LOCAL CHECK OPTION */
! #define CASCADED_OPTION_IMPLICIT 'c' /* WITH CASCADED CHECK OPTION */
! #define NO_OPTION_IMPLICIT       'n' /* no check option specified */
! #define NO_OPTION_NOTHING_RULE   'r' /* identifier for implicit
! 										INSTEAD NOTHING	RULE */
! #define NO_OPTION_EXPLICIT       'e' /* rule was created by user */
  
  #endif   /* PG_REWRITE_H */
Index: src/include/commands/view.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/commands/view.h,v
retrieving revision 1.23
diff -c -r1.23 view.h
*** src/include/commands/view.h	5 Mar 2006 15:58:55 -0000	1.23
--- src/include/commands/view.h	24 Aug 2006 20:19:16 -0000
***************
*** 16,22 ****
  
  #include "nodes/parsenodes.h"
  
! extern void DefineView(RangeVar *view, Query *view_parse, bool replace);
  extern void RemoveView(const RangeVar *view, DropBehavior behavior);
  
  #endif   /* VIEW_H */
--- 16,24 ----
  
  #include "nodes/parsenodes.h"
  
! extern void DefineView(RangeVar *view, Query *view_parse, bool replace, 
! 					   bool checkOption, bool cascade);
! 
  extern void RemoveView(const RangeVar *view, DropBehavior behavior);
  
  #endif   /* VIEW_H */
Index: src/include/nodes/parsenodes.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/nodes/parsenodes.h,v
retrieving revision 1.324
diff -c -r1.324 parsenodes.h
*** src/include/nodes/parsenodes.h	21 Aug 2006 00:57:26 -0000	1.324
--- src/include/nodes/parsenodes.h	24 Aug 2006 20:19:18 -0000
***************
*** 1672,1677 ****
--- 1672,1678 ----
  	List	   *aliases;		/* target column names */
  	Query	   *query;			/* the SQL statement */
  	bool		replace;		/* replace an existing view? */
+ 	List	   *options;        /* view check options, NIL means no check */
  } ViewStmt;
  
  /* ----------------------
Index: src/include/nodes/relation.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/nodes/relation.h,v
retrieving revision 1.126
diff -c -r1.126 relation.h
*** src/include/nodes/relation.h	1 Jul 2006 18:38:33 -0000	1.126
--- src/include/nodes/relation.h	24 Aug 2006 20:19:18 -0000
***************
*** 260,266 ****
  
  	/* information about a base rel (not set for join rels!) */
  	Index		relid;
! 	RTEKind		rtekind;		/* RELATION, SUBQUERY, or FUNCTION */
  	AttrNumber	min_attr;		/* smallest attrno of rel (often <0) */
  	AttrNumber	max_attr;		/* largest attrno of rel */
  	Relids	   *attr_needed;	/* array indexed [min_attr .. max_attr] */
--- 260,266 ----
  
  	/* information about a base rel (not set for join rels!) */
  	Index		relid;
! 	RTEKind		rtekind;		/* see parsenodes.h */
  	AttrNumber	min_attr;		/* smallest attrno of rel (often <0) */
  	AttrNumber	max_attr;		/* largest attrno of rel */
  	Relids	   *attr_needed;	/* array indexed [min_attr .. max_attr] */
Index: src/include/rewrite/prs2lock.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/rewrite/prs2lock.h,v
retrieving revision 1.21
diff -c -r1.21 prs2lock.h
*** src/include/rewrite/prs2lock.h	5 Mar 2006 15:58:58 -0000	1.21
--- src/include/rewrite/prs2lock.h	24 Aug 2006 20:19:18 -0000
***************
*** 29,34 ****
--- 29,35 ----
  	Node	   *qual;
  	List	   *actions;
  	bool		isInstead;
+ 	char        ev_kind;
  } RewriteRule;
  
  /*
Index: src/include/rewrite/rewriteDefine.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/rewrite/rewriteDefine.h,v
retrieving revision 1.21
diff -c -r1.21 rewriteDefine.h
*** src/include/rewrite/rewriteDefine.h	5 Mar 2006 15:58:58 -0000	1.21
--- src/include/rewrite/rewriteDefine.h	24 Aug 2006 20:19:18 -0000
***************
*** 16,22 ****
  
  #include "nodes/parsenodes.h"
  
! extern void DefineQueryRewrite(RuleStmt *args);
  
  extern void RenameRewriteRule(Oid owningRel, const char *oldName,
  				  const char *newName);
--- 16,23 ----
  
  #include "nodes/parsenodes.h"
  
! extern void DefineQueryRewrite(RuleStmt *args,
! 							   char     ev_kind);
  
  extern void RenameRewriteRule(Oid owningRel, const char *oldName,
  				  const char *newName);
Index: src/include/rewrite/rewriteRemove.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/rewrite/rewriteRemove.h,v
retrieving revision 1.22
diff -c -r1.22 rewriteRemove.h
*** src/include/rewrite/rewriteRemove.h	16 Jun 2006 20:23:45 -0000	1.22
--- src/include/rewrite/rewriteRemove.h	24 Aug 2006 20:19:18 -0000
***************
*** 20,24 ****
--- 20,26 ----
  extern void RemoveRewriteRule(Oid owningRel, const char *ruleName,
  				  DropBehavior behavior, bool missing_ok);
  extern void RemoveRewriteRuleById(Oid ruleOid);
+ extern void deleteImplicitRulesOnEvent(Relation rel, CmdType event_type, 
+                                        Oid exceptOid);
  
  #endif   /* REWRITEREMOVE_H */
Index: src/include/rewrite/rewriteSupport.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/rewrite/rewriteSupport.h,v
retrieving revision 1.28
diff -c -r1.28 rewriteSupport.h
*** src/include/rewrite/rewriteSupport.h	5 Mar 2006 15:58:58 -0000	1.28
--- src/include/rewrite/rewriteSupport.h	24 Aug 2006 20:19:18 -0000
***************
*** 17,22 ****
--- 17,33 ----
  /* The ON SELECT rule of a view is always named this: */
  #define ViewSelectRuleName	"_RETURN"
  
+ /*------------------------------------------------------------------------------
+  * some names to be used for implicit view update rules
+  *------------------------------------------------------------------------------
+  */
+ #define INSERTRULENAME "_INSERT"
+ #define DELETERULENAME "_DELETE"
+ #define UPDATERULENAME "_UPDATE"
+ #define NOTHING_INSERTRULENAME "_NOTHING_INSERT"
+ #define NOTHING_UPDATERULENAME "_NOTHING_UPDATE"
+ #define NOTHING_DELETERULENAME "_NOTHING_DELETE"
+ 
  extern bool IsDefinedRewriteRule(Oid owningRel, const char *ruleName);
  
  extern void SetRelationRuleStatus(Oid relationId, bool relHasRules,
viewUpdate.ctext/x-csrc; charset=iso-8859-1; name=viewUpdate.cDownload
viewUpdate.htext/x-chdr; charset=iso-8859-1; name=viewUpdate.hDownload
upd-views.txttext/plain; charset=iso-8859-1; name=upd-views.txtDownload
#11Bernd Helmle
mailings@oopsware.de
In reply to: Bernd Helmle (#10)
4 attachment(s)
Re: Updatable views

--On Donnerstag, August 24, 2006 22:25:46 +0200 Bernd Helmle
<mailings@oopsware.de> wrote:

--On Montag, August 21, 2006 02:07:41 -0400 Alvaro Herrera
<alvherre@commandprompt.com> wrote:

If someone wants to look at the current updatable view patch, please look
at this current
version.

I did some more rework based on additional suggestions from Alvaro, so
please
find the current updatable view patch attached. I've rewritten functions to
use expression_tree_walker() and added additional comments. If you find
anything more to improve, feel free to drop your comments. Thanks to
Alvarro for its comments again.

--
Thanks

Bernd

Attachments:

pgsql_view-update.patchapplication/octet-stream; name=pgsql_view-update.patchDownload
Index: doc/src/sgml/catalogs.sgml
===================================================================
RCS file: /projects/cvsroot/pgsql/doc/src/sgml/catalogs.sgml,v
retrieving revision 2.130
diff -c -r2.130 catalogs.sgml
*** doc/src/sgml/catalogs.sgml	25 Aug 2006 04:06:44 -0000	2.130
--- doc/src/sgml/catalogs.sgml	29 Aug 2006 15:44:49 -0000
***************
*** 3513,3518 ****
--- 3513,3531 ----
       </row>
  
       <row>
+       <entry><structfield>ev_kind</structfield></entry>
+       <entry><type>char</type></entry>
+       <entry></entry>
+       <entry>  
+        <literal>l</> = with local check option,   
+        <literal>c</> = with cascaded check option,
+        <literal>n</> = no check option specified,
+        <literal>e</> = rule was created by user 
+        <literal>p</> = implicit DO INSTEAD NOTHING rule for check option
+       </entry>
+      </row>
+ 
+      <row>
        <entry><structfield>ev_qual</structfield></entry>
        <entry><type>text</type></entry>
        <entry></entry>
Index: doc/src/sgml/information_schema.sgml
===================================================================
RCS file: /projects/cvsroot/pgsql/doc/src/sgml/information_schema.sgml,v
retrieving revision 1.26
diff -c -r1.26 information_schema.sgml
*** doc/src/sgml/information_schema.sgml	2 May 2006 18:07:51 -0000	1.26
--- doc/src/sgml/information_schema.sgml	29 Aug 2006 15:44:52 -0000
***************
*** 5085,5091 ****
       <row>
        <entry><literal>check_option</literal></entry>
        <entry><type>character_data</type></entry>
!       <entry>Applies to a feature not available in <productname>PostgreSQL</></entry>
       </row>
  
       <row>
--- 5085,5095 ----
       <row>
        <entry><literal>check_option</literal></entry>
        <entry><type>character_data</type></entry>
!       <entry>
!        The level of integrity checking in updatable views,
!        either <literal>LOCAL</literal>, <literal>CASCADED</literal>
!        or <literal>NONE</literal>
!      </entry>
       </row>
  
       <row>
Index: doc/src/sgml/intro.sgml
===================================================================
RCS file: /projects/cvsroot/pgsql/doc/src/sgml/intro.sgml,v
retrieving revision 1.31
diff -c -r1.31 intro.sgml
*** doc/src/sgml/intro.sgml	10 Mar 2006 19:10:48 -0000	1.31
--- doc/src/sgml/intro.sgml	29 Aug 2006 15:44:52 -0000
***************
*** 110,116 ****
       <simpara>triggers</simpara>
      </listitem>
      <listitem>
!      <simpara>views</simpara>
      </listitem>
      <listitem>
       <simpara>transactional integrity</simpara>
--- 110,116 ----
       <simpara>triggers</simpara>
      </listitem>
      <listitem>
!      <simpara>updatable views</simpara>
      </listitem>
      <listitem>
       <simpara>transactional integrity</simpara>
Index: doc/src/sgml/ref/create_view.sgml
===================================================================
RCS file: /projects/cvsroot/pgsql/doc/src/sgml/ref/create_view.sgml,v
retrieving revision 1.31
diff -c -r1.31 create_view.sgml
*** doc/src/sgml/ref/create_view.sgml	1 Nov 2005 21:09:50 -0000	1.31
--- doc/src/sgml/ref/create_view.sgml	29 Aug 2006 15:44:52 -0000
***************
*** 22,27 ****
--- 22,28 ----
  <synopsis>
  CREATE [ OR REPLACE ] [ TEMP | TEMPORARY ] VIEW <replaceable class="PARAMETER">name</replaceable> [ ( <replaceable class="PARAMETER">column_name</replaceable> [, ...] ) ]
      AS <replaceable class="PARAMETER">query</replaceable>
+     [ WITH [ CASCADED | LOCAL ] CHECK OPTION ]
  </synopsis>
   </refsynopsisdiv>
  
***************
*** 109,114 ****
--- 110,150 ----
       </para>
      </listitem>
     </varlistentry>
+ 
+    <variablelist>
+      <varlistentry>
+       <term><literal>CHECK OPTION</literal></term>
+       <listitem>
+        <para>
+         This option has to do with updatable views.  All
+         <command>INSERT</> and <command>UPDATE</> commands on the view
+         will be checked to ensure data satisfy the view-defining
+         condition (that is, the new data would be visible through the
+         view).  If they do not, the update will be rejected.
+        </para>
+       </listitem>
+      </varlistentry>
+ 
+      <varlistentry>
+       <term><literal>LOCAL</literal></term>
+       <listitem>
+        <para>
+         Check for integrity on this view.
+        </para>
+       </listitem>
+      </varlistentry>
+ 
+      <varlistentry>
+       <term><literal>CASCADED</literal></term>
+       <listitem>
+        <para>
+         Check for integrity on this view and on any dependent
+         view.  <literal>CASCADED</> is assumed if neither
+         <literal>CASCADED</> nor <literal>LOCAL</> is specified.
+        </para>
+       </listitem>
+      </varlistentry>
+    
    </variablelist>
   </refsect1>
  
***************
*** 116,126 ****
    <title>Notes</title>
  
     <para>
!     Currently, views are read only: the system will not allow an insert,
!     update, or delete on a view.  You can get the effect of an updatable
!     view by creating rules that rewrite inserts, etc. on the view into
!     appropriate actions on other tables.  For more information see
!     <xref linkend="sql-createrule" endterm="sql-createrule-title">.
     </para>
  
     <para>
--- 152,201 ----
    <title>Notes</title>
  
     <para>
!     Currently, views are updatable following SQL92 specifications, that
!     is: 
!    </para>
! 
!    <itemizedlist>
!     <listitem>
!      <para>
!       Views with just one base table (or another updatable view)
!      </para>
!     </listitem>
! 
!     <listitem>
!      <para>No aggregate functions</para>
!     </listitem>
! 
!     <listitem>
!      <para>
!       No <literal>HAVING</literal>, <literal>DISTINCT</literal> nor
!       <literal>GROUP BY</literal> clauses
!      </para>
!     </listitem>
! 
!     <listitem>
!      <para>
!       No <literal>UNION</literal>, <literal>INTERSECT</literal>,
!       <literal>EXCEPT</literal>clauses
!      </para>
!     </listitem>
!    </itemizedlist>
! 
!    <para>
!     Views are insertable only if you provide in the defining
!     <command>SELECT</command> statement all columns that are NOT NULL and don't
!     have a default value.
!    </para>
! 
!    <para>
!     The updatable views implementation is based on the rule system.  Because of
!     this, you can get the same effect in more complex views by creating your
!     own rules that rewrite the <command>INSERT</command>,
!     <command>UPDATE</command> and <command>UPDATE</command> actions on the view
!     into appropriate actions on other tables. You can also replace
!     automatically generated rules with your own rules. For more information,
!     refer to <xref linkend="sql-createrule" endterm="sql-createrule-title">.
     </para>
  
     <para>
***************
*** 171,225 ****
    <title>Compatibility</title>
  
    <para>
-    The SQL standard specifies some additional capabilities for the
-    <command>CREATE VIEW</command> statement:
- <synopsis>
- CREATE VIEW <replaceable class="parameter">name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ]
-     AS <replaceable class="PARAMETER">query</replaceable>
-     [ WITH [ CASCADED | LOCAL ] CHECK OPTION ]
- </synopsis>
-   </para>
- 
-   <para>
-    The optional clauses for the full SQL command are:
- 
-    <variablelist>
-      <varlistentry>
-       <term><literal>CHECK OPTION</literal></term>
-       <listitem>
-        <para>
-         This option has to do with updatable views.  All
-         <command>INSERT</> and <command>UPDATE</> commands on the view
-         will be checked to ensure data satisfy the view-defining
-         condition (that is, the new data would be visible through the
-         view). If they do not, the update will be rejected.
-        </para>
-       </listitem>
-      </varlistentry>
- 
-      <varlistentry>
-       <term><literal>LOCAL</literal></term>
-       <listitem>
-        <para>
-         Check for integrity on this view.
-        </para>
-       </listitem>
-      </varlistentry>
- 
-      <varlistentry>
-       <term><literal>CASCADED</literal></term>
-       <listitem>
-        <para>
-         Check for integrity on this view and on any dependent
-         view. <literal>CASCADED</> is assumed if neither
-         <literal>CASCADED</> nor <literal>LOCAL</> is specified.
-        </para>
-       </listitem>
-      </varlistentry>
-    </variablelist>
-   </para>
- 
-   <para>
     <command>CREATE OR REPLACE VIEW</command> is a
     <productname>PostgreSQL</productname> language extension.
     So is the concept of a temporary view.
--- 246,251 ----
Index: src/backend/catalog/information_schema.sql
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/catalog/information_schema.sql,v
retrieving revision 1.33
diff -c -r1.33 information_schema.sql
*** src/backend/catalog/information_schema.sql	2 Apr 2006 17:38:13 -0000	1.33
--- src/backend/catalog/information_schema.sql	29 Aug 2006 15:44:55 -0000
***************
*** 2126,2132 ****
                    ELSE null END
               AS character_data) AS view_definition,
  
!            CAST('NONE' AS character_data) AS check_option,
  
             CAST(
               CASE WHEN EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 2 AND is_instead)
--- 2126,2143 ----
                    ELSE null END
               AS character_data) AS view_definition,
  
!            CAST(
!              CASE WHEN EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 2 AND is_instead AND ev_kind = 'l')
!                     OR EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 3 AND is_instead AND ev_kind = 'l')
!                     OR EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 4 AND is_instead AND ev_kind = 'l')
!                   THEN 'LOCAL'
!                   WHEN EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 2 AND is_instead AND ev_kind = 'c')
!                     OR EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 3 AND is_instead AND ev_kind = 'c')
!                     OR EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 4 AND is_instead AND ev_kind = 'c')
!                   THEN 'CASCADED'
!                   ELSE 'NONE' 
!              END
!            AS character_data) AS check_option,
  
             CAST(
               CASE WHEN EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 2 AND is_instead)
Index: src/backend/commands/view.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/commands/view.c,v
retrieving revision 1.97
diff -c -r1.97 view.c
*** src/backend/commands/view.c	21 Aug 2006 00:57:24 -0000	1.97
--- src/backend/commands/view.c	29 Aug 2006 15:44:57 -0000
***************
*** 29,41 ****
--- 29,44 ----
  #include "rewrite/rewriteDefine.h"
  #include "rewrite/rewriteManip.h"
  #include "rewrite/rewriteSupport.h"
+ #include "rewrite/viewUpdate.h"
  #include "utils/acl.h"
  #include "utils/lsyscache.h"
+ #include "utils/memutils.h"
  
  
  static void checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc);
  static bool isViewOnTempTable_walker(Node *node, void *context);
  
+ 
  /*---------------------------------------------------------------------
   * isViewOnTempTable
   *
***************
*** 280,329 ****
  }
  
  static void
! DefineViewRules(const RangeVar *view, Query *viewParse, bool replace)
  {
  	RuleStmt   *retrieve_rule;
  
- #ifdef NOTYET
- 	RuleStmt   *replace_rule;
- 	RuleStmt   *append_rule;
- 	RuleStmt   *delete_rule;
- #endif
- 
  	retrieve_rule = FormViewRetrieveRule(view, viewParse, replace);
  
! #ifdef NOTYET
! 	replace_rule = FormViewReplaceRule(view, viewParse);
! 	append_rule = FormViewAppendRule(view, viewParse);
! 	delete_rule = FormViewDeleteRule(view, viewParse);
! #endif
! 
! 	DefineQueryRewrite(retrieve_rule);
! 
! #ifdef NOTYET
! 	DefineQueryRewrite(replace_rule);
! 	DefineQueryRewrite(append_rule);
! 	DefineQueryRewrite(delete_rule);
! #endif
  
  }
  
! /*---------------------------------------------------------------
   * UpdateRangeTableOfViewParse
   *
!  * Update the range table of the given parsetree.
!  * This update consists of adding two new entries IN THE BEGINNING
!  * of the range table (otherwise the rule system will die a slow,
!  * horrible and painful death, and we do not want that now, do we?)
!  * one for the OLD relation and one for the NEW one (both of
   * them refer in fact to the "view" relation).
   *
!  * Of course we must also increase the 'varnos' of all the Var nodes
!  * by 2...
   *
!  * These extra RT entries are not actually used in the query,
!  * except for run-time permission checking.
!  *---------------------------------------------------------------
   */
  static Query *
  UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
--- 283,314 ----
  }
  
  static void
! DefineViewRules(const RangeVar *view, Query *viewParse, bool replace,
! 				bool checkOption, bool cascade)
  {
  	RuleStmt   *retrieve_rule;
  
  	retrieve_rule = FormViewRetrieveRule(view, viewParse, replace);
  
! 	DefineQueryRewrite(retrieve_rule, 
! 					   makeViewCheckOption(checkOption, cascade));
  
+ 	CreateViewUpdateRules(viewParse, view, checkOption, cascade);
  }
  
! /*
   * UpdateRangeTableOfViewParse
   *
!  * Update the range table of the given parsetree.  This update consists of
!  * adding two new entries IN THE BEGINNING of the range table (otherwise the
!  * rule system will die a slow, horrible and painful death, and we do not want
!  * that now, do we?) one for the OLD relation and one for the NEW one (both of
   * them refer in fact to the "view" relation).
   *
!  * Of course we must also increase the 'varnos' of all the Var nodes by 2...
   *
!  * These extra RT entries are not actually used in the query, except for
!  * run-time permission checking.
   */
  static Query *
  UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
***************
*** 387,393 ****
   *-------------------------------------------------------------------
   */
  void
! DefineView(RangeVar *view, Query *viewParse, bool replace)
  {
  	Oid			viewOid;
  
--- 372,379 ----
   *-------------------------------------------------------------------
   */
  void
! DefineView(RangeVar *view, Query *viewParse, bool replace, bool checkOption,
! 		   bool cascade)
  {
  	Oid			viewOid;
  
***************
*** 428,434 ****
  	/*
  	 * Now create the rules associated with the view.
  	 */
! 	DefineViewRules(view, viewParse, replace);
  }
  
  /*
--- 414,420 ----
  	/*
  	 * Now create the rules associated with the view.
  	 */
! 	DefineViewRules(view, viewParse, replace, checkOption, cascade);
  }
  
  /*
Index: src/backend/parser/gram.y
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/parser/gram.y,v
retrieving revision 2.558
diff -c -r2.558 gram.y
*** src/backend/parser/gram.y	25 Aug 2006 04:06:51 -0000	2.558
--- src/backend/parser/gram.y	29 Aug 2006 15:45:11 -0000
***************
*** 4494,4500 ****
   *****************************************************************************/
  
  RuleStmt:	CREATE opt_or_replace RULE name AS
! 			{ QueryIsRule=TRUE; }
  			ON event TO qualified_name where_clause
  			DO opt_instead RuleActionList
  				{
--- 4494,4500 ----
   *****************************************************************************/
  
  RuleStmt:	CREATE opt_or_replace RULE name AS
! 			{ QueryIsRule = true; }
  			ON event TO qualified_name where_clause
  			DO opt_instead RuleActionList
  				{
***************
*** 4507,4513 ****
  					n->instead = $13;
  					n->actions = $14;
  					$$ = (Node *)n;
! 					QueryIsRule=FALSE;
  				}
  		;
  
--- 4507,4513 ----
  					n->instead = $13;
  					n->actions = $14;
  					$$ = (Node *)n;
! 					QueryIsRule = false;
  				}
  		;
  
***************
*** 4520,4532 ****
  /* the thrashing around here is to discard "empty" statements... */
  RuleActionMulti:
  			RuleActionMulti ';' RuleActionStmtOrEmpty
! 				{ if ($3 != NULL)
  					$$ = lappend($1, $3);
  				  else
  					$$ = $1;
  				}
  			| RuleActionStmtOrEmpty
! 				{ if ($1 != NULL)
  					$$ = list_make1($1);
  				  else
  					$$ = NIL;
--- 4520,4534 ----
  /* the thrashing around here is to discard "empty" statements... */
  RuleActionMulti:
  			RuleActionMulti ';' RuleActionStmtOrEmpty
! 				{
! 				  if ($3 != NULL)
  					$$ = lappend($1, $3);
  				  else
  					$$ = $1;
  				}
  			| RuleActionStmtOrEmpty
! 				{
! 				  if ($1 != NULL)
  					$$ = list_make1($1);
  				  else
  					$$ = NIL;
***************
*** 4791,4796 ****
--- 4793,4799 ----
  					n->view->istemp = $2;
  					n->aliases = $5;
  					n->query = (Query *) $7;
+ 					n->options = $8;
  					$$ = (Node *) n;
  				}
  		| CREATE OR REPLACE OptTemp VIEW qualified_name opt_column_list
***************
*** 4802,4807 ****
--- 4805,4811 ----
  					n->view->istemp = $4;
  					n->aliases = $7;
  					n->query = (Query *) $9;
+ 					n->options = $10;
  					$$ = (Node *) n;
  				}
  		;
***************
*** 4813,4833 ****
  opt_check_option:
  		WITH_CHECK OPTION
  				{
! 					ereport(ERROR,
! 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
! 							 errmsg("WITH CHECK OPTION is not implemented")));
  				}
  		| WITH_CASCADED CHECK OPTION
  				{
! 					ereport(ERROR,
! 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
! 							 errmsg("WITH CHECK OPTION is not implemented")));
  				}
  		| WITH_LOCAL CHECK OPTION
  				{
! 					ereport(ERROR,
! 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
! 							 errmsg("WITH CHECK OPTION is not implemented")));
  				}
  		| /* EMPTY */							{ $$ = NIL; }
  		;
--- 4817,4831 ----
  opt_check_option:
  		WITH_CHECK OPTION
  				{
! 					$$ = list_make1((Node *)makeString("cascaded"));
  				}
  		| WITH_CASCADED CHECK OPTION
  				{
! 					$$ = list_make1((Node *)makeString("cascaded"));
  				}
  		| WITH_LOCAL CHECK OPTION
  				{
! 					$$ = list_make1((Node *)makeString("local"));
  				}
  		| /* EMPTY */							{ $$ = NIL; }
  		;
Index: src/backend/parser/keywords.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/parser/keywords.c,v
retrieving revision 1.176
diff -c -r1.176 keywords.c
*** src/backend/parser/keywords.c	25 Aug 2006 04:06:52 -0000	1.176
--- src/backend/parser/keywords.c	29 Aug 2006 15:45:11 -0000
***************
*** 67,72 ****
--- 67,73 ----
  	{"cache", CACHE},
  	{"called", CALLED},
  	{"cascade", CASCADE},
+ 	{"cascaded", CASCADED},
  	{"case", CASE},
  	{"cast", CAST},
  	{"chain", CHAIN},
Index: src/backend/rewrite/Makefile
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/rewrite/Makefile,v
retrieving revision 1.15
diff -c -r1.15 Makefile
*** src/backend/rewrite/Makefile	29 Nov 2003 19:51:55 -0000	1.15
--- src/backend/rewrite/Makefile	29 Aug 2006 15:45:11 -0000
***************
*** 13,19 ****
  include $(top_builddir)/src/Makefile.global
  
  OBJS = rewriteRemove.o rewriteDefine.o \
!        rewriteHandler.o rewriteManip.o rewriteSupport.o
  
  all: SUBSYS.o
  
--- 13,20 ----
  include $(top_builddir)/src/Makefile.global
  
  OBJS = rewriteRemove.o rewriteDefine.o \
!        rewriteHandler.o rewriteManip.o rewriteSupport.o \
!        viewUpdate.o
  
  all: SUBSYS.o
  
Index: src/backend/rewrite/rewriteDefine.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/rewrite/rewriteDefine.c,v
retrieving revision 1.112
diff -c -r1.112 rewriteDefine.c
*** src/backend/rewrite/rewriteDefine.c	12 Aug 2006 20:05:55 -0000	1.112
--- src/backend/rewrite/rewriteDefine.c	29 Aug 2006 15:45:14 -0000
***************
*** 23,28 ****
--- 23,29 ----
  #include "parser/parse_expr.h"
  #include "rewrite/rewriteDefine.h"
  #include "rewrite/rewriteManip.h"
+ #include "rewrite/rewriteRemove.h"
  #include "rewrite/rewriteSupport.h"
  #include "storage/smgr.h"
  #include "utils/acl.h"
***************
*** 44,58 ****
  static Oid
  InsertRule(char *rulname,
  		   int evtype,
! 		   Oid eventrel_oid,
  		   AttrNumber evslot_index,
  		   bool evinstead,
  		   Node *event_qual,
  		   List *action,
  		   bool replace)
  {
  	char	   *evqual = nodeToString(event_qual);
  	char	   *actiontree = nodeToString((Node *) action);
  	int			i;
  	Datum		values[Natts_pg_rewrite];
  	char		nulls[Natts_pg_rewrite];
--- 45,62 ----
  static Oid
  InsertRule(char *rulname,
  		   int evtype,
! 		   /*Oid eventrel_oid,*/
! 		   Relation event_relation,
  		   AttrNumber evslot_index,
  		   bool evinstead,
+ 		   char evkind,
  		   Node *event_qual,
  		   List *action,
  		   bool replace)
  {
  	char	   *evqual = nodeToString(event_qual);
  	char	   *actiontree = nodeToString((Node *) action);
+ 	Oid        eventrel_oid = RelationGetRelid(event_relation);
  	int			i;
  	Datum		values[Natts_pg_rewrite];
  	char		nulls[Natts_pg_rewrite];
***************
*** 78,83 ****
--- 82,88 ----
  	values[i++] = Int16GetDatum(evslot_index);	/* ev_attr */
  	values[i++] = CharGetDatum(evtype + '0');	/* ev_type */
  	values[i++] = BoolGetDatum(evinstead);		/* is_instead */
+ 	values[i++] = CharGetDatum(evkind);         /* ev_kind */
  	values[i++] = DirectFunctionCall1(textin, CStringGetDatum(evqual)); /* ev_qual */
  	values[i++] = DirectFunctionCall1(textin, CStringGetDatum(actiontree));		/* ev_action */
  
***************
*** 96,114 ****
  
  	if (HeapTupleIsValid(oldtup))
  	{
  		if (!replace)
! 			ereport(ERROR,
! 					(errcode(ERRCODE_DUPLICATE_OBJECT),
! 					 errmsg("rule \"%s\" for relation \"%s\" already exists",
! 							rulname, get_rel_name(eventrel_oid))));
  
  		/*
  		 * When replacing, we don't need to replace every attribute
  		 */
  		MemSet(replaces, ' ', sizeof(replaces));
  		replaces[Anum_pg_rewrite_ev_attr - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_type - 1] = 'r';
  		replaces[Anum_pg_rewrite_is_instead - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_qual - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_action - 1] = 'r';
  
--- 101,160 ----
  
  	if (HeapTupleIsValid(oldtup))
  	{
+ 		char old_tup_is_implicit = evkind;
+ 		Datum dat;
+ 		bool isnull;
+ 
+ 		dat = heap_getattr(oldtup,
+ 						   Anum_pg_rewrite_ev_kind,
+ 						   RelationGetDescr(pg_rewrite_desc),
+ 						   &isnull);
+ 		
+ 		if (isnull) 
+ 			/* should not happen */
+ 			elog(ERROR, "got null field in ev_kind where not null expected");
+ 		
  		if (!replace)
! 		{
! 			/*
! 			 * If REPLACE was not used we still have to check if the
! 			 * rule is implicit: then we have to replace it anyways.
! 			 */
! 			
! 			old_tup_is_implicit = DatumGetChar(dat);
! 			
! 			if (old_tup_is_implicit == NO_OPTION_EXPLICIT)
! 			{
! 				ereport(ERROR,
! 						(errcode(ERRCODE_DUPLICATE_OBJECT),
! 						 errmsg("rule \"%s\" for relation \"%s\" already exists",
! 								rulname, get_rel_name(eventrel_oid))));
! 			}
! 		}
  
  		/*
+ 		 * If we are about to replace an implicit rule
+ 		 * with an user defined rule, we need to drop all
+ 		 * implicit rules on the same action (for implicit 
+ 		 * conditional rules we have DO INSTEAD NOTHING RULES
+ 		 * present and vice versa...). We have to be careful not
+ 		 * to drop the current rule we want to replace...
+ 		 */
+ 		if ((old_tup_is_implicit != NO_OPTION_EXPLICIT)
+ 			&& (evkind == NO_OPTION_EXPLICIT))
+ 		{
+ 			deleteImplicitRulesOnEvent(event_relation, evtype,
+ 									   HeapTupleGetOid(oldtup));
+ 		}
+ 		
+ 		/*
  		 * When replacing, we don't need to replace every attribute
  		 */
  		MemSet(replaces, ' ', sizeof(replaces));
  		replaces[Anum_pg_rewrite_ev_attr - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_type - 1] = 'r';
  		replaces[Anum_pg_rewrite_is_instead - 1] = 'r';
+ 		replaces[Anum_pg_rewrite_ev_kind - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_qual - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_action - 1] = 'r';
  
***************
*** 124,129 ****
--- 170,186 ----
  	}
  	else
  	{
+ 		/*
+ 		 * Implicit rules should be dropped automatically when someone
+ 		 * wants to have its *own* rules on the view. is_implicit is set
+ 		 * to NO_OPTION_EXPLICIT in this case so we drop all implicit 
+ 		 * rules on the specified event type immediately.
+ 		 */
+ 
+ 		if (evkind == NO_OPTION_EXPLICIT)
+ 			deleteImplicitRulesOnEvent(event_relation, evtype,
+ 									   InvalidOid);
+ 
  		tup = heap_formtuple(pg_rewrite_desc->rd_att, values, nulls);
  
  		rewriteObjectId = simple_heap_insert(pg_rewrite_desc, tup);
***************
*** 177,183 ****
  }
  
  void
! DefineQueryRewrite(RuleStmt *stmt)
  {
  	RangeVar   *event_obj = stmt->relation;
  	Node	   *event_qual = stmt->whereClause;
--- 234,240 ----
  }
  
  void
! DefineQueryRewrite(RuleStmt *stmt, char ev_kind)
  {
  	RangeVar   *event_obj = stmt->relation;
  	Node	   *event_qual = stmt->whereClause;
***************
*** 443,457 ****
  		setRuleCheckAsUser_Query(query, GetUserId());
  	}
  	setRuleCheckAsUser_Expr(event_qual, GetUserId());
! 
  	/* discard rule if it's null action and not INSTEAD; it's a no-op */
  	if (action != NIL || is_instead)
  	{
  		ruleId = InsertRule(stmt->rulename,
  							event_type,
! 							ev_relid,
  							event_attno,
  							is_instead,
  							event_qual,
  							action,
  							replace);
--- 500,515 ----
  		setRuleCheckAsUser_Query(query, GetUserId());
  	}
  	setRuleCheckAsUser_Expr(event_qual, GetUserId());
! 	
  	/* discard rule if it's null action and not INSTEAD; it's a no-op */
  	if (action != NIL || is_instead)
  	{
  		ruleId = InsertRule(stmt->rulename,
  							event_type,
! 							event_relation,
  							event_attno,
  							is_instead,
+ 							ev_kind,
  							event_qual,
  							action,
  							replace);
***************
*** 469,475 ****
  	}
  
  	/*
! 	 * IF the relation is becoming a view, delete the storage files associated
  	 * with it.  NB: we had better have AccessExclusiveLock to do this ...
  	 *
  	 * XXX what about getting rid of its TOAST table?  For now, we don't.
--- 527,533 ----
  	}
  
  	/*
! 	 * If the relation is becoming a view, delete the storage files associated
  	 * with it.  NB: we had better have AccessExclusiveLock to do this ...
  	 *
  	 * XXX what about getting rid of its TOAST table?  For now, we don't.
Index: src/backend/rewrite/rewriteHandler.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/rewrite/rewriteHandler.c,v
retrieving revision 1.165
diff -c -r1.165 rewriteHandler.c
*** src/backend/rewrite/rewriteHandler.c	2 Aug 2006 01:59:47 -0000	1.165
--- src/backend/rewrite/rewriteHandler.c	29 Aug 2006 15:45:16 -0000
***************
*** 15,20 ****
--- 15,21 ----
  
  #include "access/heapam.h"
  #include "catalog/pg_type.h"
+ #include "catalog/pg_rewrite.h"
  #include "nodes/makefuncs.h"
  #include "optimizer/clauses.h"
  #include "parser/analyze.h"
***************
*** 34,45 ****
  	CmdType		event;			/* type of rule being fired */
  } rewrite_event;
  
  static bool acquireLocksOnSubLinks(Node *node, void *context);
  static Query *rewriteRuleAction(Query *parsetree,
  				  Query *rule_action,
  				  Node *rule_qual,
  				  int rt_index,
! 				  CmdType event);
  static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index);
  static void rewriteTargetList(Query *parsetree, Relation target_relation,
  							  List **attrno_list);
--- 35,55 ----
  	CmdType		event;			/* type of rule being fired */
  } rewrite_event;
  
+ /* Rule rewrite status for updatable views */
+ typedef struct view_update_event
+ {
+ 	bool viewUpdate;
+ 	bool needCheckOption;
+ 	char checkMode;	
+ } view_update_event;
+ 
  static bool acquireLocksOnSubLinks(Node *node, void *context);
  static Query *rewriteRuleAction(Query *parsetree,
  				  Query *rule_action,
  				  Node *rule_qual,
  				  int rt_index,
!                   CmdType event,
! 				  view_update_event *view_event);
  static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index);
  static void rewriteTargetList(Query *parsetree, Relation target_relation,
  							  List **attrno_list);
***************
*** 257,263 ****
  				  Query *rule_action,
  				  Node *rule_qual,
  				  int rt_index,
! 				  CmdType event)
  {
  	int			current_varno,
  				new_varno;
--- 267,274 ----
  				  Query *rule_action,
  				  Node *rule_qual,
  				  int rt_index,
! 				  CmdType event,
! 				  view_update_event *view_event)
  {
  	int			current_varno,
  				new_varno;
***************
*** 387,393 ****
  	 * queries one w/rule_qual, one w/NOT rule_qual. Also add user query qual
  	 * onto rule action
  	 */
! 	AddQual(sub_action, rule_qual);
  
  	AddQual(sub_action, parsetree->jointree->quals);
  
--- 398,405 ----
  	 * queries one w/rule_qual, one w/NOT rule_qual. Also add user query qual
  	 * onto rule action
  	 */
! 	if (view_event->needCheckOption)
! 		AddQual(sub_action, rule_qual);
  
  	AddQual(sub_action, parsetree->jointree->quals);
  
***************
*** 820,825 ****
--- 832,850 ----
  		}
  	}
  
+ #if 0
+  	/*
+  	 * I will do this only in case of relkind == RELKIND_VIEW.
+  	 * This is the last attempt to get a value for expr before we
+  	 * consider that expr must be NULL.
+  	 */
+  	if (expr == NULL && rel->rd_rel->relkind == RELKIND_VIEW)
+  	{
+  		expr = (Node *)makeNode(SetToDefault);
+  		return expr;
+  	}
+ #endif
+ 
  	if (expr == NULL)
  	{
  		/*
***************
*** 1359,1367 ****
--- 1384,1400 ----
   *					(must be initialized to FALSE)
   *	*qual_product - filled with modified original query if any qualified
   *					INSTEAD rule is found (must be initialized to NULL)
+  *	view_event - Holds the current state of the rules recursion. This
+  *               is important especially for implicit view update rules
+  *               created by the system to apply rule conditions based
+  *               on a view's CHECK OPTION. view_event is expected to
+  *               to be initialized by QueryRewrite().
   * Return value:
   *	list of rule actions adjusted for use with this query
   *
+ 
+  *               
+  *
   * Qualified INSTEAD rules generate their action with the qualification
   * condition added.  They also generate a modified version of the original
   * query with the negated qualification added, so that it will run only for
***************
*** 1376,1381 ****
--- 1409,1415 ----
  		  int rt_index,
  		  CmdType event,
  		  List *locks,
+ 		  view_update_event *view_event,
  		  bool *instead_flag,
  		  Query **qual_product)
  {
***************
*** 1390,1400 ****
  		QuerySource qsrc;
  		ListCell   *r;
  
  		/* Determine correct QuerySource value for actions */
  		if (rule_lock->isInstead)
  		{
! 			if (event_qual != NULL)
! 				qsrc = QSRC_QUAL_INSTEAD_RULE;
  			else
  			{
  				qsrc = QSRC_INSTEAD_RULE;
--- 1424,1524 ----
  		QuerySource qsrc;
  		ListCell   *r;
  
+ 		/*
+ 		 * Apply information to the view_event structure and save the
+ 		 * current recursion state of fireRules(). We distinguish
+ 		 * implicit and explicit rules, the first one are created
+ 		 * by the system to implement updatable views. We need to know
+ 		 * about the check option applied to such an implicit rule and
+ 		 * the current "depth" of the recursion, e.g. LOCAL CHECK
+ 		 * OPTION should be applied only once for implicit rules in
+ 		 * a cascading view update recursion and explicit conditional
+ 		 * rules need to be applied always.
+ 		 *
+ 		 *
+ 		 * First check: look if this rule is an implicit view update rule. If
+ 		 * false, always apply any rule qualification.
+ 		 */
+ 		if (rule_lock->ev_kind == NO_OPTION_EXPLICIT)
+ 		{
+ 			view_event->viewUpdate = false;
+ 			view_event->needCheckOption = true;
+ 			view_event->checkMode = rule_lock->ev_kind;
+ 		}
+ 		
+ 		/*
+ 		 * Second check: Look if we are already in a view update or not.  If
+ 		 * true and the event check mode is set to LOCAL_OPTION_IMPLICIT in
+ 		 * conjunction with viewUpdate = true, we don't need to apply the check
+ 		 * option otherwise.
+ 		 */
+ 		else if (!view_event->viewUpdate &&
+ 				 ((rule_lock->ev_kind == LOCAL_OPTION_IMPLICIT) ||
+ 				  (rule_lock->ev_kind == CASCADED_OPTION_IMPLICIT)))
+ 				 
+ 		{
+ 			/* apply check option, but only once */
+ 			view_event->viewUpdate = true;
+ 			view_event->needCheckOption = true;
+ 			view_event->checkMode = rule_lock->ev_kind;
+ 		}
+ 
+ 		/*
+ 		 * Third check: Look if we are in a recursive view update in
+ 		 * conjunction with a CASCADED CHECK OPTION. If true, we always need to
+ 		 * apply any check options found.
+ 		 */
+ 		else if (view_event->viewUpdate &&
+ 				 (view_event->checkMode == CASCADED_OPTION_IMPLICIT) &&
+ 				 (rule_lock->ev_kind != NO_OPTION_EXPLICIT))
+ 		{
+ 			view_event->needCheckOption = true;
+ 		}
+ 
+ 		/*
+ 		 * 4th check: make sure we reset the view update event if we are in a
+ 		 * recursive view update and passed the first view already. If we had a
+ 		 * LOCAL CHECK OPTION, we have to make sure we don't fire any check
+ 		 * options anymore.
+ 		 */
+ 		else if (view_event->viewUpdate &&
+ 				 (view_event->checkMode == LOCAL_OPTION_IMPLICIT) &&
+ 				 (rule_lock->ev_kind != NO_OPTION_EXPLICIT))
+ 		{
+ 			view_event->needCheckOption = false;
+ 			/* force LOCAL check mode */
+ 			view_event->checkMode = LOCAL_OPTION_IMPLICIT;
+ 		}
+ 
  		/* Determine correct QuerySource value for actions */
  		if (rule_lock->isInstead)
  		{
! 			if (event_qual != NULL) 
! 			{				
! 				/*
! 				 * Check out wether we need to apply any
! 				 * rule qualification to a view update rule.
! 				 * We only bother on implicit rules that aren't
! 				 * marked with NO_OPTION_EXPLICIT
! 				 */
! 				if ((rule_lock->ev_kind != NO_OPTION_EXPLICIT)
! 					&& (view_event->viewUpdate))
! 				{
! 					if (view_event->needCheckOption)
! 					{
! 						qsrc = QSRC_QUAL_INSTEAD_RULE;
! 					}
! 					else
! 					{
! 						qsrc = QSRC_INSTEAD_RULE;
! 						*instead_flag = true;
! 					}
! 				} 
! 				else 
! 				{
! 					qsrc = QSRC_QUAL_INSTEAD_RULE;
! 				}
! 			}
  			else
  			{
  				qsrc = QSRC_INSTEAD_RULE;
***************
*** 1438,1444 ****
  				continue;
  
  			rule_action = rewriteRuleAction(parsetree, rule_action,
! 											event_qual, rt_index, event);
  
  			rule_action->querySource = qsrc;
  			rule_action->canSetTag = false;		/* might change later */
--- 1562,1569 ----
  				continue;
  
  			rule_action = rewriteRuleAction(parsetree, rule_action,
! 											event_qual, rt_index, event,
! 											view_event);
  
  			rule_action->querySource = qsrc;
  			rule_action->canSetTag = false;		/* might change later */
***************
*** 1459,1465 ****
   * infinite recursion.
   */
  static List *
! RewriteQuery(Query *parsetree, List *rewrite_events)
  {
  	CmdType		event = parsetree->commandType;
  	bool		instead = false;
--- 1584,1591 ----
   * infinite recursion.
   */
  static List *
! RewriteQuery(Query *parsetree, List *rewrite_events, 
! 			 view_update_event *view_event)
  {
  	CmdType		event = parsetree->commandType;
  	bool		instead = false;
***************
*** 1550,1555 ****
--- 1676,1682 ----
  										result_relation,
  										event,
  										locks,
+ 										view_event,
  										&instead,
  										&qual_product);
  
***************
*** 1583,1589 ****
  					Query	   *pt = (Query *) lfirst(n);
  					List	   *newstuff;
  
! 					newstuff = RewriteQuery(pt, rewrite_events);
  					rewritten = list_concat(rewritten, newstuff);
  				}
  
--- 1710,1716 ----
  					Query	   *pt = (Query *) lfirst(n);
  					List	   *newstuff;
  
! 					newstuff = RewriteQuery(pt, rewrite_events, view_event);
  					rewritten = list_concat(rewritten, newstuff);
  				}
  
***************
*** 1646,1658 ****
  	CmdType		origCmdType;
  	bool		foundOriginalQuery;
  	Query	   *lastInstead;
  
  	/*
  	 * Step 1
  	 *
  	 * Apply all non-SELECT rules possibly getting 0 or many queries
  	 */
! 	querylist = RewriteQuery(parsetree, NIL);
  
  	/*
  	 * Step 2
--- 1773,1789 ----
  	CmdType		origCmdType;
  	bool		foundOriginalQuery;
  	Query	   *lastInstead;
+ 	view_update_event v_event;
  
  	/*
  	 * Step 1
  	 *
  	 * Apply all non-SELECT rules possibly getting 0 or many queries
  	 */
! 	v_event.viewUpdate      = false;
! 	v_event.needCheckOption = false;
! 	v_event.checkMode       = NO_OPTION_EXPLICIT;
! 	querylist = RewriteQuery(parsetree, NIL, &v_event);
  
  	/*
  	 * Step 2
Index: src/backend/rewrite/rewriteRemove.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/rewrite/rewriteRemove.c,v
retrieving revision 1.65
diff -c -r1.65 rewriteRemove.c
*** src/backend/rewrite/rewriteRemove.c	16 Jun 2006 20:23:44 -0000	1.65
--- src/backend/rewrite/rewriteRemove.c	29 Aug 2006 15:45:16 -0000
***************
*** 89,94 ****
--- 89,146 ----
  	performDeletion(&object, behavior);
  }
  
+ /*
+  * deleteImplicitRulesOnEvent
+  * 
+  * This will delete implicit rules, if any exists, on the event in the
+  * relation.
+  * You can use exceptOid to exclude a specific implicit
+  * rule from deletion, use InvalidOid if you want to
+  * safely delete all implicit rules.
+  */
+ void 
+ deleteImplicitRulesOnEvent(Relation rel, CmdType event_type,
+ 						   Oid exceptOid)
+ {
+ 	RuleLock *rulelocks = rel->rd_rules;
+ 	int nlocks;
+ 	int i;
+ 
+ 	/*
+ 	 * Select rules are implicit (are they marked as implicit??) 
+ 	 * but we don't want to delete them
+ 	 */
+ 	if (event_type == CMD_SELECT)
+ 		return;
+ 
+ 	/*
+ 	 * If there are no rules on the relation we waste no more time
+ 	 */
+ 	if (rulelocks == NULL)
+ 		return;
+ 
+ 	nlocks = rulelocks->numLocks;
+ 
+ 	/*
+ 	 * Look at all rules looking for the ones that are on the event and are
+ 	 * implicit
+ 	 */
+ 	for (i = 0; i < nlocks; i++)
+ 	{
+ 		RewriteRule *oneLock = rulelocks->rules[i];		
+ 		
+ 		if ((oneLock->event == event_type)
+ 			&& (oneLock->ev_kind != NO_OPTION_EXPLICIT)
+ 			&& (oneLock->ruleId != exceptOid))
+ 		{
+ 			RemoveRewriteRuleById(oneLock->ruleId);
+ 			elog(DEBUG1, "removing implicit rule with oid %d\n", 
+ 				 oneLock->ruleId);
+ 			deleteDependencyRecordsFor(RewriteRelationId, oneLock->ruleId);
+ 		}
+ 	}
+ }
+ 
  
  /*
   * Guts of rule deletion.
Index: src/backend/tcop/utility.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/tcop/utility.c,v
retrieving revision 1.267
diff -c -r1.267 utility.c
*** src/backend/tcop/utility.c	25 Aug 2006 04:06:53 -0000	1.267
--- src/backend/tcop/utility.c	29 Aug 2006 15:45:18 -0000
***************
*** 20,25 ****
--- 20,26 ----
  #include "access/xact.h"
  #include "catalog/catalog.h"
  #include "catalog/namespace.h"
+ #include "catalog/pg_rewrite.h"
  #include "catalog/toasting.h"
  #include "commands/alter.h"
  #include "commands/async.h"
***************
*** 764,771 ****
  		case T_ViewStmt:		/* CREATE VIEW */
  			{
  				ViewStmt   *stmt = (ViewStmt *) parsetree;
  
! 				DefineView(stmt->view, stmt->query, stmt->replace);
  			}
  			break;
  
--- 765,787 ----
  		case T_ViewStmt:		/* CREATE VIEW */
  			{
  				ViewStmt   *stmt = (ViewStmt *) parsetree;
+ 				bool		checkOption = false;
+ 				bool		cascade = false;
+ 				ListCell   *cell;
  
! 				if (list_length(stmt->options) > 0)
! 					checkOption = true;
! 
! 				foreach(cell, stmt->options)
! 				{
! 					Value *val = (Value *) lfirst(cell);
! 
! 					if (strncmp(strVal(val), "cascade", strlen("cascade")) == 0)
! 						cascade = true;
! 				}
! 
! 				DefineView(stmt->view, stmt->query, stmt->replace, 
! 						   checkOption, cascade);
  			}
  			break;
  
***************
*** 807,813 ****
  			break;
  
  		case T_RuleStmt:		/* CREATE RULE */
! 			DefineQueryRewrite((RuleStmt *) parsetree);
  			break;
  
  		case T_CreateSeqStmt:
--- 823,829 ----
  			break;
  
  		case T_RuleStmt:		/* CREATE RULE */
! 			DefineQueryRewrite((RuleStmt *) parsetree, NO_OPTION_EXPLICIT);
  			break;
  
  		case T_CreateSeqStmt:
Index: src/backend/utils/adt/ruleutils.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/utils/adt/ruleutils.c,v
retrieving revision 1.232
diff -c -r1.232 ruleutils.c
*** src/backend/utils/adt/ruleutils.c	21 Aug 2006 00:57:25 -0000	1.232
--- src/backend/utils/adt/ruleutils.c	29 Aug 2006 15:45:22 -0000
***************
*** 18,23 ****
--- 18,24 ----
  #include "catalog/pg_depend.h"
  #include "catalog/pg_opclass.h"
  #include "catalog/pg_operator.h"
+ #include "catalog/pg_rewrite.h"
  #include "catalog/pg_trigger.h"
  #include "executor/spi.h"
  #include "funcapi.h"
***************
*** 1683,1688 ****
--- 1684,1690 ----
  	Oid			ev_class;
  	int2		ev_attr;
  	bool		is_instead;
+ 	char        ev_kind;
  	char	   *ev_qual;
  	char	   *ev_action;
  	List	   *actions = NIL;
***************
*** 1705,1710 ****
--- 1707,1715 ----
  	fno = SPI_fnumber(rulettc, "is_instead");
  	is_instead = (bool) SPI_getbinval(ruletup, rulettc, fno, &isnull);
  
+ 	fno = SPI_fnumber(rulettc, "ev_kind");
+ 	ev_kind = (char) SPI_getbinval(ruletup, rulettc, fno, &isnull);
+ 
  	fno = SPI_fnumber(rulettc, "ev_qual");
  	ev_qual = SPI_getvalue(ruletup, rulettc, fno);
  
***************
*** 1732,1737 ****
--- 1737,1761 ----
  
  	get_query_def(query, buf, NIL, RelationGetDescr(ev_relation),
  				  prettyFlags, 0);
+ 
+ 	/*
+ 	 * Support for updatable views: append the check option if
+ 	 * required. If any pretty print flags is enabled, we need
+ 	 * to do a linebreak before.
+ 	 */
+ 	if (ev_kind != NO_OPTION_EXPLICIT || ev_kind != NO_OPTION_IMPLICIT)
+ 	{
+ 		if (prettyFlags & PRETTYFLAG_INDENT)
+ 			appendStringInfo(buf, "\n");
+ 
+ 		appendStringInfoSpaces(buf, 1);
+ 
+ 		if (ev_kind == LOCAL_OPTION_IMPLICIT)
+ 			appendStringInfo(buf, " WITH LOCAL CHECK OPTION");
+ 		else if (ev_kind == CASCADED_OPTION_IMPLICIT)
+ 			appendStringInfo(buf, " WITH CASCADED CHECK OPTION");
+ 	}
+ 
  	appendStringInfo(buf, ";");
  
  	heap_close(ev_relation, AccessShareLock);
Index: src/backend/utils/cache/relcache.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/utils/cache/relcache.c,v
retrieving revision 1.247
diff -c -r1.247 relcache.c
*** src/backend/utils/cache/relcache.c	31 Jul 2006 20:09:05 -0000	1.247
--- src/backend/utils/cache/relcache.c	29 Aug 2006 15:45:30 -0000
***************
*** 646,651 ****
--- 646,652 ----
  		rule->event = rewrite_form->ev_type - '0';
  		rule->attrno = rewrite_form->ev_attr;
  		rule->isInstead = rewrite_form->is_instead;
+ 		rule->ev_kind = rewrite_form->ev_kind;
  
  		/*
  		 * Must use heap_getattr to fetch ev_action and ev_qual.  Also,
***************
*** 748,753 ****
--- 749,756 ----
  				return false;
  			if (!equal(rule1->actions, rule2->actions))
  				return false;
+ 			if(rule1->ev_kind != rule2->ev_kind)
+ 				return false;
  		}
  	}
  	else if (rlock2 != NULL)
Index: src/bin/pg_dump/pg_dump.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/bin/pg_dump/pg_dump.c,v
retrieving revision 1.447
diff -c -r1.447 pg_dump.c
*** src/bin/pg_dump/pg_dump.c	21 Aug 2006 00:57:25 -0000	1.447
--- src/bin/pg_dump/pg_dump.c	29 Aug 2006 15:45:43 -0000
***************
*** 51,56 ****
--- 51,57 ----
  #include "catalog/pg_proc.h"
  #include "catalog/pg_trigger.h"
  #include "catalog/pg_type.h"
+ #include "catalog/pg_rewrite.h"
  #include "commands/sequence.h"
  #include "libpq/libpq-fs.h"
  #include "mb/pg_wchar.h"
***************
*** 3658,3663 ****
--- 3659,3665 ----
  	int			i_ruletable;
  	int			i_ev_type;
  	int			i_is_instead;
+ 	int			i_ev_kind;
  
  	/* Make sure we are in proper schema */
  	selectSourceSchema("pg_catalog");
***************
*** 3666,3672 ****
  	{
  		appendPQExpBuffer(query, "SELECT "
  						  "tableoid, oid, rulename, "
! 						  "ev_class as ruletable, ev_type, is_instead "
  						  "FROM pg_rewrite "
  						  "ORDER BY oid");
  	}
--- 3668,3675 ----
  	{
  		appendPQExpBuffer(query, "SELECT "
  						  "tableoid, oid, rulename, "
! 						  "ev_class as ruletable, ev_type, is_instead, "
! 						  "ev_kind "
  						  "FROM pg_rewrite "
  						  "ORDER BY oid");
  	}
***************
*** 3675,3681 ****
  		appendPQExpBuffer(query, "SELECT "
  						  "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
  						  "oid, rulename, "
! 						  "ev_class as ruletable, ev_type, is_instead "
  						  "FROM pg_rewrite "
  						  "ORDER BY oid");
  	}
--- 3678,3685 ----
  		appendPQExpBuffer(query, "SELECT "
  						  "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
  						  "oid, rulename, "
! 						  "ev_class as ruletable, ev_type, is_instead, "
! 						  "ev_kind "
  						  "FROM pg_rewrite "
  						  "ORDER BY oid");
  	}
***************
*** 3695,3700 ****
--- 3699,3705 ----
  	i_ruletable = PQfnumber(res, "ruletable");
  	i_ev_type = PQfnumber(res, "ev_type");
  	i_is_instead = PQfnumber(res, "is_instead");
+ 	i_ev_kind = PQfnumber(res, "ev_kind");
  
  	for (i = 0; i < ntups; i++)
  	{
***************
*** 3718,3739 ****
  		ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
  		ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
  		ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
  		if (ruleinfo[i].ruletable)
  		{
  			/*
! 			 * If the table is a view, force its ON SELECT rule to be sorted
! 			 * before the view itself --- this ensures that any dependencies
! 			 * for the rule affect the table's positioning. Other rules are
! 			 * forced to appear after their table.
  			 */
! 			if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
! 				ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
! 			{
! 				addObjectDependency(&ruleinfo[i].ruletable->dobj,
! 									ruleinfo[i].dobj.dumpId);
! 				/* We'll merge the rule into CREATE VIEW, if possible */
! 				ruleinfo[i].separate = false;
! 			}
  			else
  			{
  				addObjectDependency(&ruleinfo[i].dobj,
--- 3723,3757 ----
  		ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
  		ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
  		ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
+ 		ruleinfo[i].ev_kind = *(PQgetvalue(res, i, i_ev_kind));
  		if (ruleinfo[i].ruletable)
  		{
  			/*
! 			 * If the table is a view, force its ON SELECT rule to be
! 			 * sorted before the view itself --- this ensures that any
! 			 * dependencies for the rule affect the table's positioning.
! 			 * Other rules are forced to appear after their table.
! 			 *
! 			 * Do the same for implicit rules (for updateable views support).
  			 */
! 			if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW) 
! 				if (ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
! 				{
! 					addObjectDependency(&ruleinfo[i].ruletable->dobj,
! 										ruleinfo[i].dobj.dumpId);
! 					/* We'll merge the rule into CREATE VIEW, if possible */
! 					ruleinfo[i].separate = false;
! 				}
! 				else
! 					if (ruleinfo[i].ev_kind != NO_OPTION_EXPLICIT)
! 					{
! 						addObjectDependency(&ruleinfo[i].ruletable->dobj,
! 											ruleinfo[i].dobj.dumpId);
! 						/* We'll merge the rule into CREATE VIEW, if possible */
! 						ruleinfo[i].separate = false;
! 					}
! 					else
! 						ruleinfo[i].separate = true;
  			else
  			{
  				addObjectDependency(&ruleinfo[i].dobj,
Index: src/bin/pg_dump/pg_dump.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/bin/pg_dump/pg_dump.h,v
retrieving revision 1.129
diff -c -r1.129 pg_dump.h
*** src/bin/pg_dump/pg_dump.h	21 Aug 2006 00:57:25 -0000	1.129
--- src/bin/pg_dump/pg_dump.h	29 Aug 2006 15:45:44 -0000
***************
*** 260,267 ****
  	TableInfo  *ruletable;		/* link to table the rule is for */
  	char		ev_type;
  	bool		is_instead;
  	bool		separate;		/* TRUE if must dump as separate item */
! 	/* separate is always true for non-ON SELECT rules */
  } RuleInfo;
  
  typedef struct _triggerInfo
--- 260,271 ----
  	TableInfo  *ruletable;		/* link to table the rule is for */
  	char		ev_type;
  	bool		is_instead;
+ 	char		ev_kind;
  	bool		separate;		/* TRUE if must dump as separate item */
! 	/* 
! 	 * separate is true for non-ON SELECT rules and 
! 	 * for implicit rules (for updateable views support) 
! 	 */
  } RuleInfo;
  
  typedef struct _triggerInfo
Index: src/bin/pg_dump/pg_dump_sort.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/bin/pg_dump/pg_dump_sort.c,v
retrieving revision 1.15
diff -c -r1.15 pg_dump_sort.c
*** src/bin/pg_dump/pg_dump_sort.c	14 Jul 2006 14:52:26 -0000	1.15
--- src/bin/pg_dump/pg_dump_sort.c	29 Aug 2006 15:45:46 -0000
***************
*** 816,821 ****
--- 816,862 ----
  		}
  	}
  
+ 	/* View and its implicit rule */
+ 	if (nLoop == 2 &&
+ 		loop[0]->objType == DO_TABLE &&
+ 		loop[1]->objType == DO_RULE &&
+ 		((RuleInfo *) loop[1])->ev_kind != 'e' &&
+ 		((RuleInfo *) loop[1])->ruletable == (TableInfo *) loop[0])
+ 	{
+ 		repairViewRuleLoop(loop[0], loop[1]);
+ 		return;
+ 	}
+ 	if (nLoop == 2 &&
+ 		loop[1]->objType == DO_TABLE &&
+ 		loop[0]->objType == DO_RULE &&
+ 		((RuleInfo *) loop[0])->ev_kind != 'e' &&
+ 		((RuleInfo *) loop[0])->ruletable == (TableInfo *) loop[1])
+ 	{
+ 		repairViewRuleLoop(loop[1], loop[0]);
+ 		return;
+ 	}
+ 
+ 	/* Indirect loop involving view and implicit rule */
+ 	if (nLoop > 2)
+ 	{
+ 		for (i = 0; i < nLoop; i++)
+ 		{
+ 			if (loop[i]->objType == DO_TABLE)
+ 			{
+ 				for (j = 0; j < nLoop; j++)
+ 				{
+ 					if (loop[j]->objType == DO_RULE &&
+ 						((RuleInfo *) loop[j])->ev_kind != 'e' &&
+ 						((RuleInfo *) loop[j])->ruletable == (TableInfo *) loop[i])
+ 					{
+ 						repairViewRuleMultiLoop(loop[i], loop[j]);
+ 						return;
+ 					}
+ 				}
+ 			}
+ 		}
+ 	}
+ 
  	/* Table and CHECK constraint */
  	if (nLoop == 2 &&
  		loop[0]->objType == DO_TABLE &&
Index: src/include/catalog/pg_proc.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/catalog/pg_proc.h,v
retrieving revision 1.422
diff -c -r1.422 pg_proc.h
*** src/include/catalog/pg_proc.h	19 Aug 2006 01:36:33 -0000	1.422
--- src/include/catalog/pg_proc.h	29 Aug 2006 15:45:50 -0000
***************
*** 3845,3850 ****
--- 3845,3851 ----
  DESCR("convert int4 to boolean");
  DATA(insert OID = 2558 ( int4				   PGNSP PGUID 12 f f t f i 1  23 "16" _null_ _null_ _null_ bool_int4 - _null_ ));
  DESCR("convert boolean to int4");
+ /* internal function required for view update rules */
  DATA(insert OID = 2559 ( lastval			   PGNSP PGUID 12 f f t f v 0 20 "" _null_ _null_ _null_	lastval - _null_ ));
  DESCR("current value from last used sequence");
  
***************
*** 3898,3903 ****
--- 3899,3908 ----
  DATA(insert OID = 2592 (  gist_circle_compress	PGNSP PGUID 12 f f t f i 1 2281 "2281" _null_ _null_ _null_ gist_circle_compress - _null_ ));
  DESCR("GiST support");
  
+ /* functions for view update facility */
+ DATA(insert OID = 2570 ( pg_view_update_error       PGNSP PGUID 12 f f f f i 1 16 "16" _null_ _null_ _null_ pg_view_update_error - _null_));
+ DESCR("evaluates boolean input for view update check option");
+ 
  /* GIN */
  DATA(insert OID = 2730 (  gingettuple	   PGNSP PGUID 12 f f t f v 2 16 "2281 2281" _null_ _null_ _null_  gingettuple - _null_ ));
  DESCR("gin(internal)");
Index: src/include/catalog/pg_rewrite.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/catalog/pg_rewrite.h,v
retrieving revision 1.26
diff -c -r1.26 pg_rewrite.h
*** src/include/catalog/pg_rewrite.h	5 Mar 2006 15:58:55 -0000	1.26
--- src/include/catalog/pg_rewrite.h	29 Aug 2006 15:45:50 -0000
***************
*** 43,48 ****
--- 43,49 ----
  	int2		ev_attr;
  	char		ev_type;
  	bool		is_instead;
+ 	char		ev_kind;
  
  	/* NB: remaining fields must be accessed via heap_getattr */
  	text		ev_qual;
***************
*** 60,72 ****
   *		compiler constants for pg_rewrite
   * ----------------
   */
! #define Natts_pg_rewrite				7
  #define Anum_pg_rewrite_rulename		1
  #define Anum_pg_rewrite_ev_class		2
  #define Anum_pg_rewrite_ev_attr			3
  #define Anum_pg_rewrite_ev_type			4
  #define Anum_pg_rewrite_is_instead		5
! #define Anum_pg_rewrite_ev_qual			6
! #define Anum_pg_rewrite_ev_action		7
  
  #endif   /* PG_REWRITE_H */
--- 61,84 ----
   *		compiler constants for pg_rewrite
   * ----------------
   */
! #define Natts_pg_rewrite				8
  #define Anum_pg_rewrite_rulename		1
  #define Anum_pg_rewrite_ev_class		2
  #define Anum_pg_rewrite_ev_attr			3
  #define Anum_pg_rewrite_ev_type			4
  #define Anum_pg_rewrite_is_instead		5
! #define Anum_pg_rewrite_ev_kind			6
! #define Anum_pg_rewrite_ev_qual			7
! #define Anum_pg_rewrite_ev_action		8
! 
! /*
!  * Possible values for ev_kind 
!  */
! #define LOCAL_OPTION_IMPLICIT    'l' /* WITH LOCAL CHECK OPTION */
! #define CASCADED_OPTION_IMPLICIT 'c' /* WITH CASCADED CHECK OPTION */
! #define NO_OPTION_IMPLICIT       'n' /* no check option specified */
! #define NO_OPTION_NOTHING_RULE   'r' /* identifier for implicit
! 										INSTEAD NOTHING	RULE */
! #define NO_OPTION_EXPLICIT       'e' /* rule was created by user */
  
  #endif   /* PG_REWRITE_H */
Index: src/include/commands/view.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/commands/view.h,v
retrieving revision 1.23
diff -c -r1.23 view.h
*** src/include/commands/view.h	5 Mar 2006 15:58:55 -0000	1.23
--- src/include/commands/view.h	29 Aug 2006 15:45:50 -0000
***************
*** 16,22 ****
  
  #include "nodes/parsenodes.h"
  
! extern void DefineView(RangeVar *view, Query *view_parse, bool replace);
  extern void RemoveView(const RangeVar *view, DropBehavior behavior);
  
  #endif   /* VIEW_H */
--- 16,24 ----
  
  #include "nodes/parsenodes.h"
  
! extern void DefineView(RangeVar *view, Query *view_parse, bool replace, 
! 					   bool checkOption, bool cascade);
! 
  extern void RemoveView(const RangeVar *view, DropBehavior behavior);
  
  #endif   /* VIEW_H */
Index: src/include/nodes/parsenodes.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/nodes/parsenodes.h,v
retrieving revision 1.325
diff -c -r1.325 parsenodes.h
*** src/include/nodes/parsenodes.h	25 Aug 2006 04:06:56 -0000	1.325
--- src/include/nodes/parsenodes.h	29 Aug 2006 15:45:52 -0000
***************
*** 1673,1678 ****
--- 1673,1679 ----
  	List	   *aliases;		/* target column names */
  	Query	   *query;			/* the SQL statement */
  	bool		replace;		/* replace an existing view? */
+ 	List	   *options;        /* view check options, NIL means no check */
  } ViewStmt;
  
  /* ----------------------
Index: src/include/nodes/relation.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/nodes/relation.h,v
retrieving revision 1.126
diff -c -r1.126 relation.h
*** src/include/nodes/relation.h	1 Jul 2006 18:38:33 -0000	1.126
--- src/include/nodes/relation.h	29 Aug 2006 15:45:53 -0000
***************
*** 260,266 ****
  
  	/* information about a base rel (not set for join rels!) */
  	Index		relid;
! 	RTEKind		rtekind;		/* RELATION, SUBQUERY, or FUNCTION */
  	AttrNumber	min_attr;		/* smallest attrno of rel (often <0) */
  	AttrNumber	max_attr;		/* largest attrno of rel */
  	Relids	   *attr_needed;	/* array indexed [min_attr .. max_attr] */
--- 260,266 ----
  
  	/* information about a base rel (not set for join rels!) */
  	Index		relid;
! 	RTEKind		rtekind;		/* see parsenodes.h */
  	AttrNumber	min_attr;		/* smallest attrno of rel (often <0) */
  	AttrNumber	max_attr;		/* largest attrno of rel */
  	Relids	   *attr_needed;	/* array indexed [min_attr .. max_attr] */
Index: src/include/rewrite/prs2lock.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/rewrite/prs2lock.h,v
retrieving revision 1.21
diff -c -r1.21 prs2lock.h
*** src/include/rewrite/prs2lock.h	5 Mar 2006 15:58:58 -0000	1.21
--- src/include/rewrite/prs2lock.h	29 Aug 2006 15:45:54 -0000
***************
*** 29,34 ****
--- 29,35 ----
  	Node	   *qual;
  	List	   *actions;
  	bool		isInstead;
+ 	char        ev_kind;
  } RewriteRule;
  
  /*
Index: src/include/rewrite/rewriteDefine.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/rewrite/rewriteDefine.h,v
retrieving revision 1.21
diff -c -r1.21 rewriteDefine.h
*** src/include/rewrite/rewriteDefine.h	5 Mar 2006 15:58:58 -0000	1.21
--- src/include/rewrite/rewriteDefine.h	29 Aug 2006 15:45:54 -0000
***************
*** 16,22 ****
  
  #include "nodes/parsenodes.h"
  
! extern void DefineQueryRewrite(RuleStmt *args);
  
  extern void RenameRewriteRule(Oid owningRel, const char *oldName,
  				  const char *newName);
--- 16,23 ----
  
  #include "nodes/parsenodes.h"
  
! extern void DefineQueryRewrite(RuleStmt *args,
! 							   char     ev_kind);
  
  extern void RenameRewriteRule(Oid owningRel, const char *oldName,
  				  const char *newName);
Index: src/include/rewrite/rewriteRemove.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/rewrite/rewriteRemove.h,v
retrieving revision 1.22
diff -c -r1.22 rewriteRemove.h
*** src/include/rewrite/rewriteRemove.h	16 Jun 2006 20:23:45 -0000	1.22
--- src/include/rewrite/rewriteRemove.h	29 Aug 2006 15:45:54 -0000
***************
*** 20,24 ****
--- 20,26 ----
  extern void RemoveRewriteRule(Oid owningRel, const char *ruleName,
  				  DropBehavior behavior, bool missing_ok);
  extern void RemoveRewriteRuleById(Oid ruleOid);
+ extern void deleteImplicitRulesOnEvent(Relation rel, CmdType event_type, 
+                                        Oid exceptOid);
  
  #endif   /* REWRITEREMOVE_H */
Index: src/include/rewrite/rewriteSupport.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/rewrite/rewriteSupport.h,v
retrieving revision 1.28
diff -c -r1.28 rewriteSupport.h
*** src/include/rewrite/rewriteSupport.h	5 Mar 2006 15:58:58 -0000	1.28
--- src/include/rewrite/rewriteSupport.h	29 Aug 2006 15:45:54 -0000
***************
*** 17,22 ****
--- 17,33 ----
  /* The ON SELECT rule of a view is always named this: */
  #define ViewSelectRuleName	"_RETURN"
  
+ /*------------------------------------------------------------------------------
+  * some names to be used for implicit view update rules
+  *------------------------------------------------------------------------------
+  */
+ #define INSERTRULENAME "_INSERT"
+ #define DELETERULENAME "_DELETE"
+ #define UPDATERULENAME "_UPDATE"
+ #define NOTHING_INSERTRULENAME "_NOTHING_INSERT"
+ #define NOTHING_UPDATERULENAME "_NOTHING_UPDATE"
+ #define NOTHING_DELETERULENAME "_NOTHING_DELETE"
+ 
  extern bool IsDefinedRewriteRule(Oid owningRel, const char *ruleName);
  
  extern void SetRelationRuleStatus(Oid relationId, bool relHasRules,
viewUpdate.ctext/x-csrc; charset=iso-8859-1; name=viewUpdate.cDownload
viewUpdate.htext/x-chdr; charset=iso-8859-1; name=viewUpdate.hDownload
upd-views.txttext/plain; charset=iso-8859-1; name=upd-views.txtDownload
#12Alvaro Herrera
alvherre@commandprompt.com
In reply to: Bernd Helmle (#11)
Re: Updatable views

Bernd Helmle wrote:

--On Donnerstag, August 24, 2006 22:25:46 +0200 Bernd Helmle
<mailings@oopsware.de> wrote:

--On Montag, August 21, 2006 02:07:41 -0400 Alvaro Herrera
<alvherre@commandprompt.com> wrote:

If someone wants to look at the current updatable view patch, please look
at this current
version.

I did some more rework based on additional suggestions from Alvaro, so
please
find the current updatable view patch attached. I've rewritten functions to
use expression_tree_walker() and added additional comments. If you find
anything more to improve, feel free to drop your comments. Thanks to
Alvarro for its comments again.

Note that pg_rewrite.h does not match catalogs.sgml.

--
Alvaro Herrera http://www.CommandPrompt.com/
The PostgreSQL Company - Command Prompt, Inc.

#13Bernd Helmle
mailings@oopsware.de
In reply to: Alvaro Herrera (#12)
4 attachment(s)
Re: Updatable views

--On Dienstag, August 29, 2006 13:15:25 -0400 Alvaro Herrera
<alvherre@commandprompt.com> wrote:

Note that pg_rewrite.h does not match catalogs.sgml.

Oops, fixed.

--
Thanks

Bernd

Attachments:

viewUpdate.ctext/x-csrc; charset=iso-8859-1; name=viewUpdate.cDownload
viewUpdate.htext/x-chdr; charset=iso-8859-1; name=viewUpdate.hDownload
pgsql_view-update.patchapplication/octet-stream; name=pgsql_view-update.patchDownload
Index: doc/src/sgml/catalogs.sgml
===================================================================
RCS file: /projects/cvsroot/pgsql/doc/src/sgml/catalogs.sgml,v
retrieving revision 2.130
diff -c -r2.130 catalogs.sgml
*** doc/src/sgml/catalogs.sgml	25 Aug 2006 04:06:44 -0000	2.130
--- doc/src/sgml/catalogs.sgml	30 Aug 2006 07:47:05 -0000
***************
*** 3513,3518 ****
--- 3513,3531 ----
       </row>
  
       <row>
+       <entry><structfield>ev_kind</structfield></entry>
+       <entry><type>char</type></entry>
+       <entry></entry>
+       <entry>  
+        <literal>l</> = with local check option,   
+        <literal>c</> = with cascaded check option,
+        <literal>n</> = no check option specified,
+        <literal>e</> = rule was created by user 
+        <literal>r</> = implicit DO INSTEAD NOTHING rule for check option
+       </entry>
+      </row>
+ 
+      <row>
        <entry><structfield>ev_qual</structfield></entry>
        <entry><type>text</type></entry>
        <entry></entry>
Index: doc/src/sgml/information_schema.sgml
===================================================================
RCS file: /projects/cvsroot/pgsql/doc/src/sgml/information_schema.sgml,v
retrieving revision 1.26
diff -c -r1.26 information_schema.sgml
*** doc/src/sgml/information_schema.sgml	2 May 2006 18:07:51 -0000	1.26
--- doc/src/sgml/information_schema.sgml	30 Aug 2006 07:47:07 -0000
***************
*** 5085,5091 ****
       <row>
        <entry><literal>check_option</literal></entry>
        <entry><type>character_data</type></entry>
!       <entry>Applies to a feature not available in <productname>PostgreSQL</></entry>
       </row>
  
       <row>
--- 5085,5095 ----
       <row>
        <entry><literal>check_option</literal></entry>
        <entry><type>character_data</type></entry>
!       <entry>
!        The level of integrity checking in updatable views,
!        either <literal>LOCAL</literal>, <literal>CASCADED</literal>
!        or <literal>NONE</literal>
!      </entry>
       </row>
  
       <row>
Index: doc/src/sgml/intro.sgml
===================================================================
RCS file: /projects/cvsroot/pgsql/doc/src/sgml/intro.sgml,v
retrieving revision 1.31
diff -c -r1.31 intro.sgml
*** doc/src/sgml/intro.sgml	10 Mar 2006 19:10:48 -0000	1.31
--- doc/src/sgml/intro.sgml	30 Aug 2006 07:47:07 -0000
***************
*** 110,116 ****
       <simpara>triggers</simpara>
      </listitem>
      <listitem>
!      <simpara>views</simpara>
      </listitem>
      <listitem>
       <simpara>transactional integrity</simpara>
--- 110,116 ----
       <simpara>triggers</simpara>
      </listitem>
      <listitem>
!      <simpara>updatable views</simpara>
      </listitem>
      <listitem>
       <simpara>transactional integrity</simpara>
Index: doc/src/sgml/ref/create_view.sgml
===================================================================
RCS file: /projects/cvsroot/pgsql/doc/src/sgml/ref/create_view.sgml,v
retrieving revision 1.31
diff -c -r1.31 create_view.sgml
*** doc/src/sgml/ref/create_view.sgml	1 Nov 2005 21:09:50 -0000	1.31
--- doc/src/sgml/ref/create_view.sgml	30 Aug 2006 07:47:08 -0000
***************
*** 22,27 ****
--- 22,28 ----
  <synopsis>
  CREATE [ OR REPLACE ] [ TEMP | TEMPORARY ] VIEW <replaceable class="PARAMETER">name</replaceable> [ ( <replaceable class="PARAMETER">column_name</replaceable> [, ...] ) ]
      AS <replaceable class="PARAMETER">query</replaceable>
+     [ WITH [ CASCADED | LOCAL ] CHECK OPTION ]
  </synopsis>
   </refsynopsisdiv>
  
***************
*** 109,114 ****
--- 110,150 ----
       </para>
      </listitem>
     </varlistentry>
+ 
+    <variablelist>
+      <varlistentry>
+       <term><literal>CHECK OPTION</literal></term>
+       <listitem>
+        <para>
+         This option has to do with updatable views.  All
+         <command>INSERT</> and <command>UPDATE</> commands on the view
+         will be checked to ensure data satisfy the view-defining
+         condition (that is, the new data would be visible through the
+         view).  If they do not, the update will be rejected.
+        </para>
+       </listitem>
+      </varlistentry>
+ 
+      <varlistentry>
+       <term><literal>LOCAL</literal></term>
+       <listitem>
+        <para>
+         Check for integrity on this view.
+        </para>
+       </listitem>
+      </varlistentry>
+ 
+      <varlistentry>
+       <term><literal>CASCADED</literal></term>
+       <listitem>
+        <para>
+         Check for integrity on this view and on any dependent
+         view.  <literal>CASCADED</> is assumed if neither
+         <literal>CASCADED</> nor <literal>LOCAL</> is specified.
+        </para>
+       </listitem>
+      </varlistentry>
+    
    </variablelist>
   </refsect1>
  
***************
*** 116,126 ****
    <title>Notes</title>
  
     <para>
!     Currently, views are read only: the system will not allow an insert,
!     update, or delete on a view.  You can get the effect of an updatable
!     view by creating rules that rewrite inserts, etc. on the view into
!     appropriate actions on other tables.  For more information see
!     <xref linkend="sql-createrule" endterm="sql-createrule-title">.
     </para>
  
     <para>
--- 152,201 ----
    <title>Notes</title>
  
     <para>
!     Currently, views are updatable following SQL92 specifications, that
!     is: 
!    </para>
! 
!    <itemizedlist>
!     <listitem>
!      <para>
!       Views with just one base table (or another updatable view)
!      </para>
!     </listitem>
! 
!     <listitem>
!      <para>No aggregate functions</para>
!     </listitem>
! 
!     <listitem>
!      <para>
!       No <literal>HAVING</literal>, <literal>DISTINCT</literal> nor
!       <literal>GROUP BY</literal> clauses
!      </para>
!     </listitem>
! 
!     <listitem>
!      <para>
!       No <literal>UNION</literal>, <literal>INTERSECT</literal>,
!       <literal>EXCEPT</literal>clauses
!      </para>
!     </listitem>
!    </itemizedlist>
! 
!    <para>
!     Views are insertable only if you provide in the defining
!     <command>SELECT</command> statement all columns that are NOT NULL and don't
!     have a default value.
!    </para>
! 
!    <para>
!     The updatable views implementation is based on the rule system.  Because of
!     this, you can get the same effect in more complex views by creating your
!     own rules that rewrite the <command>INSERT</command>,
!     <command>UPDATE</command> and <command>UPDATE</command> actions on the view
!     into appropriate actions on other tables. You can also replace
!     automatically generated rules with your own rules. For more information,
!     refer to <xref linkend="sql-createrule" endterm="sql-createrule-title">.
     </para>
  
     <para>
***************
*** 171,225 ****
    <title>Compatibility</title>
  
    <para>
-    The SQL standard specifies some additional capabilities for the
-    <command>CREATE VIEW</command> statement:
- <synopsis>
- CREATE VIEW <replaceable class="parameter">name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ]
-     AS <replaceable class="PARAMETER">query</replaceable>
-     [ WITH [ CASCADED | LOCAL ] CHECK OPTION ]
- </synopsis>
-   </para>
- 
-   <para>
-    The optional clauses for the full SQL command are:
- 
-    <variablelist>
-      <varlistentry>
-       <term><literal>CHECK OPTION</literal></term>
-       <listitem>
-        <para>
-         This option has to do with updatable views.  All
-         <command>INSERT</> and <command>UPDATE</> commands on the view
-         will be checked to ensure data satisfy the view-defining
-         condition (that is, the new data would be visible through the
-         view). If they do not, the update will be rejected.
-        </para>
-       </listitem>
-      </varlistentry>
- 
-      <varlistentry>
-       <term><literal>LOCAL</literal></term>
-       <listitem>
-        <para>
-         Check for integrity on this view.
-        </para>
-       </listitem>
-      </varlistentry>
- 
-      <varlistentry>
-       <term><literal>CASCADED</literal></term>
-       <listitem>
-        <para>
-         Check for integrity on this view and on any dependent
-         view. <literal>CASCADED</> is assumed if neither
-         <literal>CASCADED</> nor <literal>LOCAL</> is specified.
-        </para>
-       </listitem>
-      </varlistentry>
-    </variablelist>
-   </para>
- 
-   <para>
     <command>CREATE OR REPLACE VIEW</command> is a
     <productname>PostgreSQL</productname> language extension.
     So is the concept of a temporary view.
--- 246,251 ----
Index: src/backend/catalog/information_schema.sql
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/catalog/information_schema.sql,v
retrieving revision 1.33
diff -c -r1.33 information_schema.sql
*** src/backend/catalog/information_schema.sql	2 Apr 2006 17:38:13 -0000	1.33
--- src/backend/catalog/information_schema.sql	30 Aug 2006 07:47:10 -0000
***************
*** 2126,2132 ****
                    ELSE null END
               AS character_data) AS view_definition,
  
!            CAST('NONE' AS character_data) AS check_option,
  
             CAST(
               CASE WHEN EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 2 AND is_instead)
--- 2126,2143 ----
                    ELSE null END
               AS character_data) AS view_definition,
  
!            CAST(
!              CASE WHEN EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 2 AND is_instead AND ev_kind = 'l')
!                     OR EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 3 AND is_instead AND ev_kind = 'l')
!                     OR EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 4 AND is_instead AND ev_kind = 'l')
!                   THEN 'LOCAL'
!                   WHEN EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 2 AND is_instead AND ev_kind = 'c')
!                     OR EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 3 AND is_instead AND ev_kind = 'c')
!                     OR EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 4 AND is_instead AND ev_kind = 'c')
!                   THEN 'CASCADED'
!                   ELSE 'NONE' 
!              END
!            AS character_data) AS check_option,
  
             CAST(
               CASE WHEN EXISTS (SELECT 1 FROM pg_rewrite WHERE ev_class = c.oid AND ev_type = 2 AND is_instead)
Index: src/backend/commands/view.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/commands/view.c,v
retrieving revision 1.97
diff -c -r1.97 view.c
*** src/backend/commands/view.c	21 Aug 2006 00:57:24 -0000	1.97
--- src/backend/commands/view.c	30 Aug 2006 07:47:12 -0000
***************
*** 29,41 ****
--- 29,44 ----
  #include "rewrite/rewriteDefine.h"
  #include "rewrite/rewriteManip.h"
  #include "rewrite/rewriteSupport.h"
+ #include "rewrite/viewUpdate.h"
  #include "utils/acl.h"
  #include "utils/lsyscache.h"
+ #include "utils/memutils.h"
  
  
  static void checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc);
  static bool isViewOnTempTable_walker(Node *node, void *context);
  
+ 
  /*---------------------------------------------------------------------
   * isViewOnTempTable
   *
***************
*** 280,329 ****
  }
  
  static void
! DefineViewRules(const RangeVar *view, Query *viewParse, bool replace)
  {
  	RuleStmt   *retrieve_rule;
  
- #ifdef NOTYET
- 	RuleStmt   *replace_rule;
- 	RuleStmt   *append_rule;
- 	RuleStmt   *delete_rule;
- #endif
- 
  	retrieve_rule = FormViewRetrieveRule(view, viewParse, replace);
  
! #ifdef NOTYET
! 	replace_rule = FormViewReplaceRule(view, viewParse);
! 	append_rule = FormViewAppendRule(view, viewParse);
! 	delete_rule = FormViewDeleteRule(view, viewParse);
! #endif
! 
! 	DefineQueryRewrite(retrieve_rule);
! 
! #ifdef NOTYET
! 	DefineQueryRewrite(replace_rule);
! 	DefineQueryRewrite(append_rule);
! 	DefineQueryRewrite(delete_rule);
! #endif
  
  }
  
! /*---------------------------------------------------------------
   * UpdateRangeTableOfViewParse
   *
!  * Update the range table of the given parsetree.
!  * This update consists of adding two new entries IN THE BEGINNING
!  * of the range table (otherwise the rule system will die a slow,
!  * horrible and painful death, and we do not want that now, do we?)
!  * one for the OLD relation and one for the NEW one (both of
   * them refer in fact to the "view" relation).
   *
!  * Of course we must also increase the 'varnos' of all the Var nodes
!  * by 2...
   *
!  * These extra RT entries are not actually used in the query,
!  * except for run-time permission checking.
!  *---------------------------------------------------------------
   */
  static Query *
  UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
--- 283,314 ----
  }
  
  static void
! DefineViewRules(const RangeVar *view, Query *viewParse, bool replace,
! 				bool checkOption, bool cascade)
  {
  	RuleStmt   *retrieve_rule;
  
  	retrieve_rule = FormViewRetrieveRule(view, viewParse, replace);
  
! 	DefineQueryRewrite(retrieve_rule, 
! 					   makeViewCheckOption(checkOption, cascade));
  
+ 	CreateViewUpdateRules(viewParse, view, checkOption, cascade);
  }
  
! /*
   * UpdateRangeTableOfViewParse
   *
!  * Update the range table of the given parsetree.  This update consists of
!  * adding two new entries IN THE BEGINNING of the range table (otherwise the
!  * rule system will die a slow, horrible and painful death, and we do not want
!  * that now, do we?) one for the OLD relation and one for the NEW one (both of
   * them refer in fact to the "view" relation).
   *
!  * Of course we must also increase the 'varnos' of all the Var nodes by 2...
   *
!  * These extra RT entries are not actually used in the query, except for
!  * run-time permission checking.
   */
  static Query *
  UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
***************
*** 387,393 ****
   *-------------------------------------------------------------------
   */
  void
! DefineView(RangeVar *view, Query *viewParse, bool replace)
  {
  	Oid			viewOid;
  
--- 372,379 ----
   *-------------------------------------------------------------------
   */
  void
! DefineView(RangeVar *view, Query *viewParse, bool replace, bool checkOption,
! 		   bool cascade)
  {
  	Oid			viewOid;
  
***************
*** 428,434 ****
  	/*
  	 * Now create the rules associated with the view.
  	 */
! 	DefineViewRules(view, viewParse, replace);
  }
  
  /*
--- 414,420 ----
  	/*
  	 * Now create the rules associated with the view.
  	 */
! 	DefineViewRules(view, viewParse, replace, checkOption, cascade);
  }
  
  /*
Index: src/backend/parser/gram.y
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/parser/gram.y,v
retrieving revision 2.558
diff -c -r2.558 gram.y
*** src/backend/parser/gram.y	25 Aug 2006 04:06:51 -0000	2.558
--- src/backend/parser/gram.y	30 Aug 2006 07:47:28 -0000
***************
*** 4494,4500 ****
   *****************************************************************************/
  
  RuleStmt:	CREATE opt_or_replace RULE name AS
! 			{ QueryIsRule=TRUE; }
  			ON event TO qualified_name where_clause
  			DO opt_instead RuleActionList
  				{
--- 4494,4500 ----
   *****************************************************************************/
  
  RuleStmt:	CREATE opt_or_replace RULE name AS
! 			{ QueryIsRule = true; }
  			ON event TO qualified_name where_clause
  			DO opt_instead RuleActionList
  				{
***************
*** 4507,4513 ****
  					n->instead = $13;
  					n->actions = $14;
  					$$ = (Node *)n;
! 					QueryIsRule=FALSE;
  				}
  		;
  
--- 4507,4513 ----
  					n->instead = $13;
  					n->actions = $14;
  					$$ = (Node *)n;
! 					QueryIsRule = false;
  				}
  		;
  
***************
*** 4520,4532 ****
  /* the thrashing around here is to discard "empty" statements... */
  RuleActionMulti:
  			RuleActionMulti ';' RuleActionStmtOrEmpty
! 				{ if ($3 != NULL)
  					$$ = lappend($1, $3);
  				  else
  					$$ = $1;
  				}
  			| RuleActionStmtOrEmpty
! 				{ if ($1 != NULL)
  					$$ = list_make1($1);
  				  else
  					$$ = NIL;
--- 4520,4534 ----
  /* the thrashing around here is to discard "empty" statements... */
  RuleActionMulti:
  			RuleActionMulti ';' RuleActionStmtOrEmpty
! 				{
! 				  if ($3 != NULL)
  					$$ = lappend($1, $3);
  				  else
  					$$ = $1;
  				}
  			| RuleActionStmtOrEmpty
! 				{
! 				  if ($1 != NULL)
  					$$ = list_make1($1);
  				  else
  					$$ = NIL;
***************
*** 4791,4796 ****
--- 4793,4799 ----
  					n->view->istemp = $2;
  					n->aliases = $5;
  					n->query = (Query *) $7;
+ 					n->options = $8;
  					$$ = (Node *) n;
  				}
  		| CREATE OR REPLACE OptTemp VIEW qualified_name opt_column_list
***************
*** 4802,4807 ****
--- 4805,4811 ----
  					n->view->istemp = $4;
  					n->aliases = $7;
  					n->query = (Query *) $9;
+ 					n->options = $10;
  					$$ = (Node *) n;
  				}
  		;
***************
*** 4813,4833 ****
  opt_check_option:
  		WITH_CHECK OPTION
  				{
! 					ereport(ERROR,
! 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
! 							 errmsg("WITH CHECK OPTION is not implemented")));
  				}
  		| WITH_CASCADED CHECK OPTION
  				{
! 					ereport(ERROR,
! 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
! 							 errmsg("WITH CHECK OPTION is not implemented")));
  				}
  		| WITH_LOCAL CHECK OPTION
  				{
! 					ereport(ERROR,
! 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
! 							 errmsg("WITH CHECK OPTION is not implemented")));
  				}
  		| /* EMPTY */							{ $$ = NIL; }
  		;
--- 4817,4831 ----
  opt_check_option:
  		WITH_CHECK OPTION
  				{
! 					$$ = list_make1((Node *)makeString("cascaded"));
  				}
  		| WITH_CASCADED CHECK OPTION
  				{
! 					$$ = list_make1((Node *)makeString("cascaded"));
  				}
  		| WITH_LOCAL CHECK OPTION
  				{
! 					$$ = list_make1((Node *)makeString("local"));
  				}
  		| /* EMPTY */							{ $$ = NIL; }
  		;
Index: src/backend/parser/keywords.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/parser/keywords.c,v
retrieving revision 1.176
diff -c -r1.176 keywords.c
*** src/backend/parser/keywords.c	25 Aug 2006 04:06:52 -0000	1.176
--- src/backend/parser/keywords.c	30 Aug 2006 07:47:31 -0000
***************
*** 67,72 ****
--- 67,73 ----
  	{"cache", CACHE},
  	{"called", CALLED},
  	{"cascade", CASCADE},
+ 	{"cascaded", CASCADED},
  	{"case", CASE},
  	{"cast", CAST},
  	{"chain", CHAIN},
Index: src/backend/rewrite/Makefile
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/rewrite/Makefile,v
retrieving revision 1.15
diff -c -r1.15 Makefile
*** src/backend/rewrite/Makefile	29 Nov 2003 19:51:55 -0000	1.15
--- src/backend/rewrite/Makefile	30 Aug 2006 07:47:31 -0000
***************
*** 13,19 ****
  include $(top_builddir)/src/Makefile.global
  
  OBJS = rewriteRemove.o rewriteDefine.o \
!        rewriteHandler.o rewriteManip.o rewriteSupport.o
  
  all: SUBSYS.o
  
--- 13,20 ----
  include $(top_builddir)/src/Makefile.global
  
  OBJS = rewriteRemove.o rewriteDefine.o \
!        rewriteHandler.o rewriteManip.o rewriteSupport.o \
!        viewUpdate.o
  
  all: SUBSYS.o
  
Index: src/backend/rewrite/rewriteDefine.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/rewrite/rewriteDefine.c,v
retrieving revision 1.112
diff -c -r1.112 rewriteDefine.c
*** src/backend/rewrite/rewriteDefine.c	12 Aug 2006 20:05:55 -0000	1.112
--- src/backend/rewrite/rewriteDefine.c	30 Aug 2006 07:47:32 -0000
***************
*** 23,28 ****
--- 23,29 ----
  #include "parser/parse_expr.h"
  #include "rewrite/rewriteDefine.h"
  #include "rewrite/rewriteManip.h"
+ #include "rewrite/rewriteRemove.h"
  #include "rewrite/rewriteSupport.h"
  #include "storage/smgr.h"
  #include "utils/acl.h"
***************
*** 44,58 ****
  static Oid
  InsertRule(char *rulname,
  		   int evtype,
! 		   Oid eventrel_oid,
  		   AttrNumber evslot_index,
  		   bool evinstead,
  		   Node *event_qual,
  		   List *action,
  		   bool replace)
  {
  	char	   *evqual = nodeToString(event_qual);
  	char	   *actiontree = nodeToString((Node *) action);
  	int			i;
  	Datum		values[Natts_pg_rewrite];
  	char		nulls[Natts_pg_rewrite];
--- 45,62 ----
  static Oid
  InsertRule(char *rulname,
  		   int evtype,
! 		   /*Oid eventrel_oid,*/
! 		   Relation event_relation,
  		   AttrNumber evslot_index,
  		   bool evinstead,
+ 		   char evkind,
  		   Node *event_qual,
  		   List *action,
  		   bool replace)
  {
  	char	   *evqual = nodeToString(event_qual);
  	char	   *actiontree = nodeToString((Node *) action);
+ 	Oid        eventrel_oid = RelationGetRelid(event_relation);
  	int			i;
  	Datum		values[Natts_pg_rewrite];
  	char		nulls[Natts_pg_rewrite];
***************
*** 78,83 ****
--- 82,88 ----
  	values[i++] = Int16GetDatum(evslot_index);	/* ev_attr */
  	values[i++] = CharGetDatum(evtype + '0');	/* ev_type */
  	values[i++] = BoolGetDatum(evinstead);		/* is_instead */
+ 	values[i++] = CharGetDatum(evkind);         /* ev_kind */
  	values[i++] = DirectFunctionCall1(textin, CStringGetDatum(evqual)); /* ev_qual */
  	values[i++] = DirectFunctionCall1(textin, CStringGetDatum(actiontree));		/* ev_action */
  
***************
*** 96,114 ****
  
  	if (HeapTupleIsValid(oldtup))
  	{
  		if (!replace)
! 			ereport(ERROR,
! 					(errcode(ERRCODE_DUPLICATE_OBJECT),
! 					 errmsg("rule \"%s\" for relation \"%s\" already exists",
! 							rulname, get_rel_name(eventrel_oid))));
  
  		/*
  		 * When replacing, we don't need to replace every attribute
  		 */
  		MemSet(replaces, ' ', sizeof(replaces));
  		replaces[Anum_pg_rewrite_ev_attr - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_type - 1] = 'r';
  		replaces[Anum_pg_rewrite_is_instead - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_qual - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_action - 1] = 'r';
  
--- 101,160 ----
  
  	if (HeapTupleIsValid(oldtup))
  	{
+ 		char old_tup_is_implicit = evkind;
+ 		Datum dat;
+ 		bool isnull;
+ 
+ 		dat = heap_getattr(oldtup,
+ 						   Anum_pg_rewrite_ev_kind,
+ 						   RelationGetDescr(pg_rewrite_desc),
+ 						   &isnull);
+ 		
+ 		if (isnull) 
+ 			/* should not happen */
+ 			elog(ERROR, "got null field in ev_kind where not null expected");
+ 		
  		if (!replace)
! 		{
! 			/*
! 			 * If REPLACE was not used we still have to check if the
! 			 * rule is implicit: then we have to replace it anyways.
! 			 */
! 			
! 			old_tup_is_implicit = DatumGetChar(dat);
! 			
! 			if (old_tup_is_implicit == NO_OPTION_EXPLICIT)
! 			{
! 				ereport(ERROR,
! 						(errcode(ERRCODE_DUPLICATE_OBJECT),
! 						 errmsg("rule \"%s\" for relation \"%s\" already exists",
! 								rulname, get_rel_name(eventrel_oid))));
! 			}
! 		}
  
  		/*
+ 		 * If we are about to replace an implicit rule
+ 		 * with an user defined rule, we need to drop all
+ 		 * implicit rules on the same action (for implicit 
+ 		 * conditional rules we have DO INSTEAD NOTHING RULES
+ 		 * present and vice versa...). We have to be careful not
+ 		 * to drop the current rule we want to replace...
+ 		 */
+ 		if ((old_tup_is_implicit != NO_OPTION_EXPLICIT)
+ 			&& (evkind == NO_OPTION_EXPLICIT))
+ 		{
+ 			deleteImplicitRulesOnEvent(event_relation, evtype,
+ 									   HeapTupleGetOid(oldtup));
+ 		}
+ 		
+ 		/*
  		 * When replacing, we don't need to replace every attribute
  		 */
  		MemSet(replaces, ' ', sizeof(replaces));
  		replaces[Anum_pg_rewrite_ev_attr - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_type - 1] = 'r';
  		replaces[Anum_pg_rewrite_is_instead - 1] = 'r';
+ 		replaces[Anum_pg_rewrite_ev_kind - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_qual - 1] = 'r';
  		replaces[Anum_pg_rewrite_ev_action - 1] = 'r';
  
***************
*** 124,129 ****
--- 170,186 ----
  	}
  	else
  	{
+ 		/*
+ 		 * Implicit rules should be dropped automatically when someone
+ 		 * wants to have its *own* rules on the view. is_implicit is set
+ 		 * to NO_OPTION_EXPLICIT in this case so we drop all implicit 
+ 		 * rules on the specified event type immediately.
+ 		 */
+ 
+ 		if (evkind == NO_OPTION_EXPLICIT)
+ 			deleteImplicitRulesOnEvent(event_relation, evtype,
+ 									   InvalidOid);
+ 
  		tup = heap_formtuple(pg_rewrite_desc->rd_att, values, nulls);
  
  		rewriteObjectId = simple_heap_insert(pg_rewrite_desc, tup);
***************
*** 177,183 ****
  }
  
  void
! DefineQueryRewrite(RuleStmt *stmt)
  {
  	RangeVar   *event_obj = stmt->relation;
  	Node	   *event_qual = stmt->whereClause;
--- 234,240 ----
  }
  
  void
! DefineQueryRewrite(RuleStmt *stmt, char ev_kind)
  {
  	RangeVar   *event_obj = stmt->relation;
  	Node	   *event_qual = stmt->whereClause;
***************
*** 443,457 ****
  		setRuleCheckAsUser_Query(query, GetUserId());
  	}
  	setRuleCheckAsUser_Expr(event_qual, GetUserId());
! 
  	/* discard rule if it's null action and not INSTEAD; it's a no-op */
  	if (action != NIL || is_instead)
  	{
  		ruleId = InsertRule(stmt->rulename,
  							event_type,
! 							ev_relid,
  							event_attno,
  							is_instead,
  							event_qual,
  							action,
  							replace);
--- 500,515 ----
  		setRuleCheckAsUser_Query(query, GetUserId());
  	}
  	setRuleCheckAsUser_Expr(event_qual, GetUserId());
! 	
  	/* discard rule if it's null action and not INSTEAD; it's a no-op */
  	if (action != NIL || is_instead)
  	{
  		ruleId = InsertRule(stmt->rulename,
  							event_type,
! 							event_relation,
  							event_attno,
  							is_instead,
+ 							ev_kind,
  							event_qual,
  							action,
  							replace);
***************
*** 469,475 ****
  	}
  
  	/*
! 	 * IF the relation is becoming a view, delete the storage files associated
  	 * with it.  NB: we had better have AccessExclusiveLock to do this ...
  	 *
  	 * XXX what about getting rid of its TOAST table?  For now, we don't.
--- 527,533 ----
  	}
  
  	/*
! 	 * If the relation is becoming a view, delete the storage files associated
  	 * with it.  NB: we had better have AccessExclusiveLock to do this ...
  	 *
  	 * XXX what about getting rid of its TOAST table?  For now, we don't.
Index: src/backend/rewrite/rewriteHandler.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/rewrite/rewriteHandler.c,v
retrieving revision 1.165
diff -c -r1.165 rewriteHandler.c
*** src/backend/rewrite/rewriteHandler.c	2 Aug 2006 01:59:47 -0000	1.165
--- src/backend/rewrite/rewriteHandler.c	30 Aug 2006 07:47:34 -0000
***************
*** 15,20 ****
--- 15,21 ----
  
  #include "access/heapam.h"
  #include "catalog/pg_type.h"
+ #include "catalog/pg_rewrite.h"
  #include "nodes/makefuncs.h"
  #include "optimizer/clauses.h"
  #include "parser/analyze.h"
***************
*** 34,45 ****
  	CmdType		event;			/* type of rule being fired */
  } rewrite_event;
  
  static bool acquireLocksOnSubLinks(Node *node, void *context);
  static Query *rewriteRuleAction(Query *parsetree,
  				  Query *rule_action,
  				  Node *rule_qual,
  				  int rt_index,
! 				  CmdType event);
  static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index);
  static void rewriteTargetList(Query *parsetree, Relation target_relation,
  							  List **attrno_list);
--- 35,55 ----
  	CmdType		event;			/* type of rule being fired */
  } rewrite_event;
  
+ /* Rule rewrite status for updatable views */
+ typedef struct view_update_event
+ {
+ 	bool viewUpdate;
+ 	bool needCheckOption;
+ 	char checkMode;	
+ } view_update_event;
+ 
  static bool acquireLocksOnSubLinks(Node *node, void *context);
  static Query *rewriteRuleAction(Query *parsetree,
  				  Query *rule_action,
  				  Node *rule_qual,
  				  int rt_index,
!                   CmdType event,
! 				  view_update_event *view_event);
  static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index);
  static void rewriteTargetList(Query *parsetree, Relation target_relation,
  							  List **attrno_list);
***************
*** 257,263 ****
  				  Query *rule_action,
  				  Node *rule_qual,
  				  int rt_index,
! 				  CmdType event)
  {
  	int			current_varno,
  				new_varno;
--- 267,274 ----
  				  Query *rule_action,
  				  Node *rule_qual,
  				  int rt_index,
! 				  CmdType event,
! 				  view_update_event *view_event)
  {
  	int			current_varno,
  				new_varno;
***************
*** 387,393 ****
  	 * queries one w/rule_qual, one w/NOT rule_qual. Also add user query qual
  	 * onto rule action
  	 */
! 	AddQual(sub_action, rule_qual);
  
  	AddQual(sub_action, parsetree->jointree->quals);
  
--- 398,405 ----
  	 * queries one w/rule_qual, one w/NOT rule_qual. Also add user query qual
  	 * onto rule action
  	 */
! 	if (view_event->needCheckOption)
! 		AddQual(sub_action, rule_qual);
  
  	AddQual(sub_action, parsetree->jointree->quals);
  
***************
*** 820,825 ****
--- 832,850 ----
  		}
  	}
  
+ #if 0
+  	/*
+  	 * I will do this only in case of relkind == RELKIND_VIEW.
+  	 * This is the last attempt to get a value for expr before we
+  	 * consider that expr must be NULL.
+  	 */
+  	if (expr == NULL && rel->rd_rel->relkind == RELKIND_VIEW)
+  	{
+  		expr = (Node *)makeNode(SetToDefault);
+  		return expr;
+  	}
+ #endif
+ 
  	if (expr == NULL)
  	{
  		/*
***************
*** 1359,1367 ****
--- 1384,1400 ----
   *					(must be initialized to FALSE)
   *	*qual_product - filled with modified original query if any qualified
   *					INSTEAD rule is found (must be initialized to NULL)
+  *	view_event - Holds the current state of the rules recursion. This
+  *               is important especially for implicit view update rules
+  *               created by the system to apply rule conditions based
+  *               on a view's CHECK OPTION. view_event is expected to
+  *               to be initialized by QueryRewrite().
   * Return value:
   *	list of rule actions adjusted for use with this query
   *
+ 
+  *               
+  *
   * Qualified INSTEAD rules generate their action with the qualification
   * condition added.  They also generate a modified version of the original
   * query with the negated qualification added, so that it will run only for
***************
*** 1376,1381 ****
--- 1409,1415 ----
  		  int rt_index,
  		  CmdType event,
  		  List *locks,
+ 		  view_update_event *view_event,
  		  bool *instead_flag,
  		  Query **qual_product)
  {
***************
*** 1390,1400 ****
  		QuerySource qsrc;
  		ListCell   *r;
  
  		/* Determine correct QuerySource value for actions */
  		if (rule_lock->isInstead)
  		{
! 			if (event_qual != NULL)
! 				qsrc = QSRC_QUAL_INSTEAD_RULE;
  			else
  			{
  				qsrc = QSRC_INSTEAD_RULE;
--- 1424,1524 ----
  		QuerySource qsrc;
  		ListCell   *r;
  
+ 		/*
+ 		 * Apply information to the view_event structure and save the
+ 		 * current recursion state of fireRules(). We distinguish
+ 		 * implicit and explicit rules, the first one are created
+ 		 * by the system to implement updatable views. We need to know
+ 		 * about the check option applied to such an implicit rule and
+ 		 * the current "depth" of the recursion, e.g. LOCAL CHECK
+ 		 * OPTION should be applied only once for implicit rules in
+ 		 * a cascading view update recursion and explicit conditional
+ 		 * rules need to be applied always.
+ 		 *
+ 		 *
+ 		 * First check: look if this rule is an implicit view update rule. If
+ 		 * false, always apply any rule qualification.
+ 		 */
+ 		if (rule_lock->ev_kind == NO_OPTION_EXPLICIT)
+ 		{
+ 			view_event->viewUpdate = false;
+ 			view_event->needCheckOption = true;
+ 			view_event->checkMode = rule_lock->ev_kind;
+ 		}
+ 		
+ 		/*
+ 		 * Second check: Look if we are already in a view update or not.  If
+ 		 * true and the event check mode is set to LOCAL_OPTION_IMPLICIT in
+ 		 * conjunction with viewUpdate = true, we don't need to apply the check
+ 		 * option otherwise.
+ 		 */
+ 		else if (!view_event->viewUpdate &&
+ 				 ((rule_lock->ev_kind == LOCAL_OPTION_IMPLICIT) ||
+ 				  (rule_lock->ev_kind == CASCADED_OPTION_IMPLICIT)))
+ 				 
+ 		{
+ 			/* apply check option, but only once */
+ 			view_event->viewUpdate = true;
+ 			view_event->needCheckOption = true;
+ 			view_event->checkMode = rule_lock->ev_kind;
+ 		}
+ 
+ 		/*
+ 		 * Third check: Look if we are in a recursive view update in
+ 		 * conjunction with a CASCADED CHECK OPTION. If true, we always need to
+ 		 * apply any check options found.
+ 		 */
+ 		else if (view_event->viewUpdate &&
+ 				 (view_event->checkMode == CASCADED_OPTION_IMPLICIT) &&
+ 				 (rule_lock->ev_kind != NO_OPTION_EXPLICIT))
+ 		{
+ 			view_event->needCheckOption = true;
+ 		}
+ 
+ 		/*
+ 		 * 4th check: make sure we reset the view update event if we are in a
+ 		 * recursive view update and passed the first view already. If we had a
+ 		 * LOCAL CHECK OPTION, we have to make sure we don't fire any check
+ 		 * options anymore.
+ 		 */
+ 		else if (view_event->viewUpdate &&
+ 				 (view_event->checkMode == LOCAL_OPTION_IMPLICIT) &&
+ 				 (rule_lock->ev_kind != NO_OPTION_EXPLICIT))
+ 		{
+ 			view_event->needCheckOption = false;
+ 			/* force LOCAL check mode */
+ 			view_event->checkMode = LOCAL_OPTION_IMPLICIT;
+ 		}
+ 
  		/* Determine correct QuerySource value for actions */
  		if (rule_lock->isInstead)
  		{
! 			if (event_qual != NULL) 
! 			{				
! 				/*
! 				 * Check out wether we need to apply any
! 				 * rule qualification to a view update rule.
! 				 * We only bother on implicit rules that aren't
! 				 * marked with NO_OPTION_EXPLICIT
! 				 */
! 				if ((rule_lock->ev_kind != NO_OPTION_EXPLICIT)
! 					&& (view_event->viewUpdate))
! 				{
! 					if (view_event->needCheckOption)
! 					{
! 						qsrc = QSRC_QUAL_INSTEAD_RULE;
! 					}
! 					else
! 					{
! 						qsrc = QSRC_INSTEAD_RULE;
! 						*instead_flag = true;
! 					}
! 				} 
! 				else 
! 				{
! 					qsrc = QSRC_QUAL_INSTEAD_RULE;
! 				}
! 			}
  			else
  			{
  				qsrc = QSRC_INSTEAD_RULE;
***************
*** 1438,1444 ****
  				continue;
  
  			rule_action = rewriteRuleAction(parsetree, rule_action,
! 											event_qual, rt_index, event);
  
  			rule_action->querySource = qsrc;
  			rule_action->canSetTag = false;		/* might change later */
--- 1562,1569 ----
  				continue;
  
  			rule_action = rewriteRuleAction(parsetree, rule_action,
! 											event_qual, rt_index, event,
! 											view_event);
  
  			rule_action->querySource = qsrc;
  			rule_action->canSetTag = false;		/* might change later */
***************
*** 1459,1465 ****
   * infinite recursion.
   */
  static List *
! RewriteQuery(Query *parsetree, List *rewrite_events)
  {
  	CmdType		event = parsetree->commandType;
  	bool		instead = false;
--- 1584,1591 ----
   * infinite recursion.
   */
  static List *
! RewriteQuery(Query *parsetree, List *rewrite_events, 
! 			 view_update_event *view_event)
  {
  	CmdType		event = parsetree->commandType;
  	bool		instead = false;
***************
*** 1550,1555 ****
--- 1676,1682 ----
  										result_relation,
  										event,
  										locks,
+ 										view_event,
  										&instead,
  										&qual_product);
  
***************
*** 1583,1589 ****
  					Query	   *pt = (Query *) lfirst(n);
  					List	   *newstuff;
  
! 					newstuff = RewriteQuery(pt, rewrite_events);
  					rewritten = list_concat(rewritten, newstuff);
  				}
  
--- 1710,1716 ----
  					Query	   *pt = (Query *) lfirst(n);
  					List	   *newstuff;
  
! 					newstuff = RewriteQuery(pt, rewrite_events, view_event);
  					rewritten = list_concat(rewritten, newstuff);
  				}
  
***************
*** 1646,1658 ****
  	CmdType		origCmdType;
  	bool		foundOriginalQuery;
  	Query	   *lastInstead;
  
  	/*
  	 * Step 1
  	 *
  	 * Apply all non-SELECT rules possibly getting 0 or many queries
  	 */
! 	querylist = RewriteQuery(parsetree, NIL);
  
  	/*
  	 * Step 2
--- 1773,1789 ----
  	CmdType		origCmdType;
  	bool		foundOriginalQuery;
  	Query	   *lastInstead;
+ 	view_update_event v_event;
  
  	/*
  	 * Step 1
  	 *
  	 * Apply all non-SELECT rules possibly getting 0 or many queries
  	 */
! 	v_event.viewUpdate      = false;
! 	v_event.needCheckOption = false;
! 	v_event.checkMode       = NO_OPTION_EXPLICIT;
! 	querylist = RewriteQuery(parsetree, NIL, &v_event);
  
  	/*
  	 * Step 2
Index: src/backend/rewrite/rewriteRemove.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/rewrite/rewriteRemove.c,v
retrieving revision 1.65
diff -c -r1.65 rewriteRemove.c
*** src/backend/rewrite/rewriteRemove.c	16 Jun 2006 20:23:44 -0000	1.65
--- src/backend/rewrite/rewriteRemove.c	30 Aug 2006 07:47:34 -0000
***************
*** 89,94 ****
--- 89,146 ----
  	performDeletion(&object, behavior);
  }
  
+ /*
+  * deleteImplicitRulesOnEvent
+  * 
+  * This will delete implicit rules, if any exists, on the event in the
+  * relation.
+  * You can use exceptOid to exclude a specific implicit
+  * rule from deletion, use InvalidOid if you want to
+  * safely delete all implicit rules.
+  */
+ void 
+ deleteImplicitRulesOnEvent(Relation rel, CmdType event_type,
+ 						   Oid exceptOid)
+ {
+ 	RuleLock *rulelocks = rel->rd_rules;
+ 	int nlocks;
+ 	int i;
+ 
+ 	/*
+ 	 * Select rules are implicit (are they marked as implicit??) 
+ 	 * but we don't want to delete them
+ 	 */
+ 	if (event_type == CMD_SELECT)
+ 		return;
+ 
+ 	/*
+ 	 * If there are no rules on the relation we waste no more time
+ 	 */
+ 	if (rulelocks == NULL)
+ 		return;
+ 
+ 	nlocks = rulelocks->numLocks;
+ 
+ 	/*
+ 	 * Look at all rules looking for the ones that are on the event and are
+ 	 * implicit
+ 	 */
+ 	for (i = 0; i < nlocks; i++)
+ 	{
+ 		RewriteRule *oneLock = rulelocks->rules[i];		
+ 		
+ 		if ((oneLock->event == event_type)
+ 			&& (oneLock->ev_kind != NO_OPTION_EXPLICIT)
+ 			&& (oneLock->ruleId != exceptOid))
+ 		{
+ 			RemoveRewriteRuleById(oneLock->ruleId);
+ 			elog(DEBUG1, "removing implicit rule with oid %d\n", 
+ 				 oneLock->ruleId);
+ 			deleteDependencyRecordsFor(RewriteRelationId, oneLock->ruleId);
+ 		}
+ 	}
+ }
+ 
  
  /*
   * Guts of rule deletion.
Index: src/backend/tcop/utility.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/tcop/utility.c,v
retrieving revision 1.267
diff -c -r1.267 utility.c
*** src/backend/tcop/utility.c	25 Aug 2006 04:06:53 -0000	1.267
--- src/backend/tcop/utility.c	30 Aug 2006 07:47:35 -0000
***************
*** 20,25 ****
--- 20,26 ----
  #include "access/xact.h"
  #include "catalog/catalog.h"
  #include "catalog/namespace.h"
+ #include "catalog/pg_rewrite.h"
  #include "catalog/toasting.h"
  #include "commands/alter.h"
  #include "commands/async.h"
***************
*** 764,771 ****
  		case T_ViewStmt:		/* CREATE VIEW */
  			{
  				ViewStmt   *stmt = (ViewStmt *) parsetree;
  
! 				DefineView(stmt->view, stmt->query, stmt->replace);
  			}
  			break;
  
--- 765,787 ----
  		case T_ViewStmt:		/* CREATE VIEW */
  			{
  				ViewStmt   *stmt = (ViewStmt *) parsetree;
+ 				bool		checkOption = false;
+ 				bool		cascade = false;
+ 				ListCell   *cell;
  
! 				if (list_length(stmt->options) > 0)
! 					checkOption = true;
! 
! 				foreach(cell, stmt->options)
! 				{
! 					Value *val = (Value *) lfirst(cell);
! 
! 					if (strncmp(strVal(val), "cascade", strlen("cascade")) == 0)
! 						cascade = true;
! 				}
! 
! 				DefineView(stmt->view, stmt->query, stmt->replace, 
! 						   checkOption, cascade);
  			}
  			break;
  
***************
*** 807,813 ****
  			break;
  
  		case T_RuleStmt:		/* CREATE RULE */
! 			DefineQueryRewrite((RuleStmt *) parsetree);
  			break;
  
  		case T_CreateSeqStmt:
--- 823,829 ----
  			break;
  
  		case T_RuleStmt:		/* CREATE RULE */
! 			DefineQueryRewrite((RuleStmt *) parsetree, NO_OPTION_EXPLICIT);
  			break;
  
  		case T_CreateSeqStmt:
Index: src/backend/utils/adt/ruleutils.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/utils/adt/ruleutils.c,v
retrieving revision 1.232
diff -c -r1.232 ruleutils.c
*** src/backend/utils/adt/ruleutils.c	21 Aug 2006 00:57:25 -0000	1.232
--- src/backend/utils/adt/ruleutils.c	30 Aug 2006 07:47:41 -0000
***************
*** 18,23 ****
--- 18,24 ----
  #include "catalog/pg_depend.h"
  #include "catalog/pg_opclass.h"
  #include "catalog/pg_operator.h"
+ #include "catalog/pg_rewrite.h"
  #include "catalog/pg_trigger.h"
  #include "executor/spi.h"
  #include "funcapi.h"
***************
*** 1683,1688 ****
--- 1684,1690 ----
  	Oid			ev_class;
  	int2		ev_attr;
  	bool		is_instead;
+ 	char        ev_kind;
  	char	   *ev_qual;
  	char	   *ev_action;
  	List	   *actions = NIL;
***************
*** 1705,1710 ****
--- 1707,1715 ----
  	fno = SPI_fnumber(rulettc, "is_instead");
  	is_instead = (bool) SPI_getbinval(ruletup, rulettc, fno, &isnull);
  
+ 	fno = SPI_fnumber(rulettc, "ev_kind");
+ 	ev_kind = (char) SPI_getbinval(ruletup, rulettc, fno, &isnull);
+ 
  	fno = SPI_fnumber(rulettc, "ev_qual");
  	ev_qual = SPI_getvalue(ruletup, rulettc, fno);
  
***************
*** 1732,1737 ****
--- 1737,1761 ----
  
  	get_query_def(query, buf, NIL, RelationGetDescr(ev_relation),
  				  prettyFlags, 0);
+ 
+ 	/*
+ 	 * Support for updatable views: append the check option if
+ 	 * required. If any pretty print flags is enabled, we need
+ 	 * to do a linebreak before.
+ 	 */
+ 	if (ev_kind != NO_OPTION_EXPLICIT || ev_kind != NO_OPTION_IMPLICIT)
+ 	{
+ 		if (prettyFlags & PRETTYFLAG_INDENT)
+ 			appendStringInfo(buf, "\n");
+ 
+ 		appendStringInfoSpaces(buf, 1);
+ 
+ 		if (ev_kind == LOCAL_OPTION_IMPLICIT)
+ 			appendStringInfo(buf, " WITH LOCAL CHECK OPTION");
+ 		else if (ev_kind == CASCADED_OPTION_IMPLICIT)
+ 			appendStringInfo(buf, " WITH CASCADED CHECK OPTION");
+ 	}
+ 
  	appendStringInfo(buf, ";");
  
  	heap_close(ev_relation, AccessShareLock);
Index: src/backend/utils/cache/relcache.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/backend/utils/cache/relcache.c,v
retrieving revision 1.247
diff -c -r1.247 relcache.c
*** src/backend/utils/cache/relcache.c	31 Jul 2006 20:09:05 -0000	1.247
--- src/backend/utils/cache/relcache.c	30 Aug 2006 07:47:48 -0000
***************
*** 646,651 ****
--- 646,652 ----
  		rule->event = rewrite_form->ev_type - '0';
  		rule->attrno = rewrite_form->ev_attr;
  		rule->isInstead = rewrite_form->is_instead;
+ 		rule->ev_kind = rewrite_form->ev_kind;
  
  		/*
  		 * Must use heap_getattr to fetch ev_action and ev_qual.  Also,
***************
*** 748,753 ****
--- 749,756 ----
  				return false;
  			if (!equal(rule1->actions, rule2->actions))
  				return false;
+ 			if(rule1->ev_kind != rule2->ev_kind)
+ 				return false;
  		}
  	}
  	else if (rlock2 != NULL)
Index: src/bin/pg_dump/pg_dump.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/bin/pg_dump/pg_dump.c,v
retrieving revision 1.447
diff -c -r1.447 pg_dump.c
*** src/bin/pg_dump/pg_dump.c	21 Aug 2006 00:57:25 -0000	1.447
--- src/bin/pg_dump/pg_dump.c	30 Aug 2006 07:47:52 -0000
***************
*** 51,56 ****
--- 51,57 ----
  #include "catalog/pg_proc.h"
  #include "catalog/pg_trigger.h"
  #include "catalog/pg_type.h"
+ #include "catalog/pg_rewrite.h"
  #include "commands/sequence.h"
  #include "libpq/libpq-fs.h"
  #include "mb/pg_wchar.h"
***************
*** 3658,3663 ****
--- 3659,3665 ----
  	int			i_ruletable;
  	int			i_ev_type;
  	int			i_is_instead;
+ 	int			i_ev_kind;
  
  	/* Make sure we are in proper schema */
  	selectSourceSchema("pg_catalog");
***************
*** 3666,3672 ****
  	{
  		appendPQExpBuffer(query, "SELECT "
  						  "tableoid, oid, rulename, "
! 						  "ev_class as ruletable, ev_type, is_instead "
  						  "FROM pg_rewrite "
  						  "ORDER BY oid");
  	}
--- 3668,3675 ----
  	{
  		appendPQExpBuffer(query, "SELECT "
  						  "tableoid, oid, rulename, "
! 						  "ev_class as ruletable, ev_type, is_instead, "
! 						  "ev_kind "
  						  "FROM pg_rewrite "
  						  "ORDER BY oid");
  	}
***************
*** 3675,3681 ****
  		appendPQExpBuffer(query, "SELECT "
  						  "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
  						  "oid, rulename, "
! 						  "ev_class as ruletable, ev_type, is_instead "
  						  "FROM pg_rewrite "
  						  "ORDER BY oid");
  	}
--- 3678,3685 ----
  		appendPQExpBuffer(query, "SELECT "
  						  "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
  						  "oid, rulename, "
! 						  "ev_class as ruletable, ev_type, is_instead, "
! 						  "ev_kind "
  						  "FROM pg_rewrite "
  						  "ORDER BY oid");
  	}
***************
*** 3695,3700 ****
--- 3699,3705 ----
  	i_ruletable = PQfnumber(res, "ruletable");
  	i_ev_type = PQfnumber(res, "ev_type");
  	i_is_instead = PQfnumber(res, "is_instead");
+ 	i_ev_kind = PQfnumber(res, "ev_kind");
  
  	for (i = 0; i < ntups; i++)
  	{
***************
*** 3718,3739 ****
  		ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
  		ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
  		ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
  		if (ruleinfo[i].ruletable)
  		{
  			/*
! 			 * If the table is a view, force its ON SELECT rule to be sorted
! 			 * before the view itself --- this ensures that any dependencies
! 			 * for the rule affect the table's positioning. Other rules are
! 			 * forced to appear after their table.
  			 */
! 			if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
! 				ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
! 			{
! 				addObjectDependency(&ruleinfo[i].ruletable->dobj,
! 									ruleinfo[i].dobj.dumpId);
! 				/* We'll merge the rule into CREATE VIEW, if possible */
! 				ruleinfo[i].separate = false;
! 			}
  			else
  			{
  				addObjectDependency(&ruleinfo[i].dobj,
--- 3723,3757 ----
  		ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
  		ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
  		ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
+ 		ruleinfo[i].ev_kind = *(PQgetvalue(res, i, i_ev_kind));
  		if (ruleinfo[i].ruletable)
  		{
  			/*
! 			 * If the table is a view, force its ON SELECT rule to be
! 			 * sorted before the view itself --- this ensures that any
! 			 * dependencies for the rule affect the table's positioning.
! 			 * Other rules are forced to appear after their table.
! 			 *
! 			 * Do the same for implicit rules (for updateable views support).
  			 */
! 			if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW) 
! 				if (ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
! 				{
! 					addObjectDependency(&ruleinfo[i].ruletable->dobj,
! 										ruleinfo[i].dobj.dumpId);
! 					/* We'll merge the rule into CREATE VIEW, if possible */
! 					ruleinfo[i].separate = false;
! 				}
! 				else
! 					if (ruleinfo[i].ev_kind != NO_OPTION_EXPLICIT)
! 					{
! 						addObjectDependency(&ruleinfo[i].ruletable->dobj,
! 											ruleinfo[i].dobj.dumpId);
! 						/* We'll merge the rule into CREATE VIEW, if possible */
! 						ruleinfo[i].separate = false;
! 					}
! 					else
! 						ruleinfo[i].separate = true;
  			else
  			{
  				addObjectDependency(&ruleinfo[i].dobj,
Index: src/bin/pg_dump/pg_dump.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/bin/pg_dump/pg_dump.h,v
retrieving revision 1.129
diff -c -r1.129 pg_dump.h
*** src/bin/pg_dump/pg_dump.h	21 Aug 2006 00:57:25 -0000	1.129
--- src/bin/pg_dump/pg_dump.h	30 Aug 2006 07:47:53 -0000
***************
*** 260,267 ****
  	TableInfo  *ruletable;		/* link to table the rule is for */
  	char		ev_type;
  	bool		is_instead;
  	bool		separate;		/* TRUE if must dump as separate item */
! 	/* separate is always true for non-ON SELECT rules */
  } RuleInfo;
  
  typedef struct _triggerInfo
--- 260,271 ----
  	TableInfo  *ruletable;		/* link to table the rule is for */
  	char		ev_type;
  	bool		is_instead;
+ 	char		ev_kind;
  	bool		separate;		/* TRUE if must dump as separate item */
! 	/* 
! 	 * separate is true for non-ON SELECT rules and 
! 	 * for implicit rules (for updateable views support) 
! 	 */
  } RuleInfo;
  
  typedef struct _triggerInfo
Index: src/bin/pg_dump/pg_dump_sort.c
===================================================================
RCS file: /projects/cvsroot/pgsql/src/bin/pg_dump/pg_dump_sort.c,v
retrieving revision 1.15
diff -c -r1.15 pg_dump_sort.c
*** src/bin/pg_dump/pg_dump_sort.c	14 Jul 2006 14:52:26 -0000	1.15
--- src/bin/pg_dump/pg_dump_sort.c	30 Aug 2006 07:47:55 -0000
***************
*** 816,821 ****
--- 816,862 ----
  		}
  	}
  
+ 	/* View and its implicit rule */
+ 	if (nLoop == 2 &&
+ 		loop[0]->objType == DO_TABLE &&
+ 		loop[1]->objType == DO_RULE &&
+ 		((RuleInfo *) loop[1])->ev_kind != 'e' &&
+ 		((RuleInfo *) loop[1])->ruletable == (TableInfo *) loop[0])
+ 	{
+ 		repairViewRuleLoop(loop[0], loop[1]);
+ 		return;
+ 	}
+ 	if (nLoop == 2 &&
+ 		loop[1]->objType == DO_TABLE &&
+ 		loop[0]->objType == DO_RULE &&
+ 		((RuleInfo *) loop[0])->ev_kind != 'e' &&
+ 		((RuleInfo *) loop[0])->ruletable == (TableInfo *) loop[1])
+ 	{
+ 		repairViewRuleLoop(loop[1], loop[0]);
+ 		return;
+ 	}
+ 
+ 	/* Indirect loop involving view and implicit rule */
+ 	if (nLoop > 2)
+ 	{
+ 		for (i = 0; i < nLoop; i++)
+ 		{
+ 			if (loop[i]->objType == DO_TABLE)
+ 			{
+ 				for (j = 0; j < nLoop; j++)
+ 				{
+ 					if (loop[j]->objType == DO_RULE &&
+ 						((RuleInfo *) loop[j])->ev_kind != 'e' &&
+ 						((RuleInfo *) loop[j])->ruletable == (TableInfo *) loop[i])
+ 					{
+ 						repairViewRuleMultiLoop(loop[i], loop[j]);
+ 						return;
+ 					}
+ 				}
+ 			}
+ 		}
+ 	}
+ 
  	/* Table and CHECK constraint */
  	if (nLoop == 2 &&
  		loop[0]->objType == DO_TABLE &&
Index: src/include/catalog/pg_proc.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/catalog/pg_proc.h,v
retrieving revision 1.422
diff -c -r1.422 pg_proc.h
*** src/include/catalog/pg_proc.h	19 Aug 2006 01:36:33 -0000	1.422
--- src/include/catalog/pg_proc.h	30 Aug 2006 07:47:58 -0000
***************
*** 3845,3850 ****
--- 3845,3851 ----
  DESCR("convert int4 to boolean");
  DATA(insert OID = 2558 ( int4				   PGNSP PGUID 12 f f t f i 1  23 "16" _null_ _null_ _null_ bool_int4 - _null_ ));
  DESCR("convert boolean to int4");
+ /* internal function required for view update rules */
  DATA(insert OID = 2559 ( lastval			   PGNSP PGUID 12 f f t f v 0 20 "" _null_ _null_ _null_	lastval - _null_ ));
  DESCR("current value from last used sequence");
  
***************
*** 3898,3903 ****
--- 3899,3908 ----
  DATA(insert OID = 2592 (  gist_circle_compress	PGNSP PGUID 12 f f t f i 1 2281 "2281" _null_ _null_ _null_ gist_circle_compress - _null_ ));
  DESCR("GiST support");
  
+ /* functions for view update facility */
+ DATA(insert OID = 2570 ( pg_view_update_error       PGNSP PGUID 12 f f f f i 1 16 "16" _null_ _null_ _null_ pg_view_update_error - _null_));
+ DESCR("evaluates boolean input for view update check option");
+ 
  /* GIN */
  DATA(insert OID = 2730 (  gingettuple	   PGNSP PGUID 12 f f t f v 2 16 "2281 2281" _null_ _null_ _null_  gingettuple - _null_ ));
  DESCR("gin(internal)");
Index: src/include/catalog/pg_rewrite.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/catalog/pg_rewrite.h,v
retrieving revision 1.26
diff -c -r1.26 pg_rewrite.h
*** src/include/catalog/pg_rewrite.h	5 Mar 2006 15:58:55 -0000	1.26
--- src/include/catalog/pg_rewrite.h	30 Aug 2006 07:47:58 -0000
***************
*** 43,48 ****
--- 43,49 ----
  	int2		ev_attr;
  	char		ev_type;
  	bool		is_instead;
+ 	char		ev_kind;
  
  	/* NB: remaining fields must be accessed via heap_getattr */
  	text		ev_qual;
***************
*** 60,72 ****
   *		compiler constants for pg_rewrite
   * ----------------
   */
! #define Natts_pg_rewrite				7
  #define Anum_pg_rewrite_rulename		1
  #define Anum_pg_rewrite_ev_class		2
  #define Anum_pg_rewrite_ev_attr			3
  #define Anum_pg_rewrite_ev_type			4
  #define Anum_pg_rewrite_is_instead		5
! #define Anum_pg_rewrite_ev_qual			6
! #define Anum_pg_rewrite_ev_action		7
  
  #endif   /* PG_REWRITE_H */
--- 61,84 ----
   *		compiler constants for pg_rewrite
   * ----------------
   */
! #define Natts_pg_rewrite				8
  #define Anum_pg_rewrite_rulename		1
  #define Anum_pg_rewrite_ev_class		2
  #define Anum_pg_rewrite_ev_attr			3
  #define Anum_pg_rewrite_ev_type			4
  #define Anum_pg_rewrite_is_instead		5
! #define Anum_pg_rewrite_ev_kind			6
! #define Anum_pg_rewrite_ev_qual			7
! #define Anum_pg_rewrite_ev_action		8
! 
! /*
!  * Possible values for ev_kind 
!  */
! #define LOCAL_OPTION_IMPLICIT    'l' /* WITH LOCAL CHECK OPTION */
! #define CASCADED_OPTION_IMPLICIT 'c' /* WITH CASCADED CHECK OPTION */
! #define NO_OPTION_IMPLICIT       'n' /* no check option specified */
! #define NO_OPTION_NOTHING_RULE   'r' /* identifier for implicit
! 										INSTEAD NOTHING	RULE */
! #define NO_OPTION_EXPLICIT       'e' /* rule was created by user */
  
  #endif   /* PG_REWRITE_H */
Index: src/include/commands/view.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/commands/view.h,v
retrieving revision 1.23
diff -c -r1.23 view.h
*** src/include/commands/view.h	5 Mar 2006 15:58:55 -0000	1.23
--- src/include/commands/view.h	30 Aug 2006 07:47:58 -0000
***************
*** 16,22 ****
  
  #include "nodes/parsenodes.h"
  
! extern void DefineView(RangeVar *view, Query *view_parse, bool replace);
  extern void RemoveView(const RangeVar *view, DropBehavior behavior);
  
  #endif   /* VIEW_H */
--- 16,24 ----
  
  #include "nodes/parsenodes.h"
  
! extern void DefineView(RangeVar *view, Query *view_parse, bool replace, 
! 					   bool checkOption, bool cascade);
! 
  extern void RemoveView(const RangeVar *view, DropBehavior behavior);
  
  #endif   /* VIEW_H */
Index: src/include/nodes/parsenodes.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/nodes/parsenodes.h,v
retrieving revision 1.325
diff -c -r1.325 parsenodes.h
*** src/include/nodes/parsenodes.h	25 Aug 2006 04:06:56 -0000	1.325
--- src/include/nodes/parsenodes.h	30 Aug 2006 07:47:59 -0000
***************
*** 1673,1678 ****
--- 1673,1679 ----
  	List	   *aliases;		/* target column names */
  	Query	   *query;			/* the SQL statement */
  	bool		replace;		/* replace an existing view? */
+ 	List	   *options;        /* view check options, NIL means no check */
  } ViewStmt;
  
  /* ----------------------
Index: src/include/nodes/relation.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/nodes/relation.h,v
retrieving revision 1.126
diff -c -r1.126 relation.h
*** src/include/nodes/relation.h	1 Jul 2006 18:38:33 -0000	1.126
--- src/include/nodes/relation.h	30 Aug 2006 07:48:00 -0000
***************
*** 260,266 ****
  
  	/* information about a base rel (not set for join rels!) */
  	Index		relid;
! 	RTEKind		rtekind;		/* RELATION, SUBQUERY, or FUNCTION */
  	AttrNumber	min_attr;		/* smallest attrno of rel (often <0) */
  	AttrNumber	max_attr;		/* largest attrno of rel */
  	Relids	   *attr_needed;	/* array indexed [min_attr .. max_attr] */
--- 260,266 ----
  
  	/* information about a base rel (not set for join rels!) */
  	Index		relid;
! 	RTEKind		rtekind;		/* see parsenodes.h */
  	AttrNumber	min_attr;		/* smallest attrno of rel (often <0) */
  	AttrNumber	max_attr;		/* largest attrno of rel */
  	Relids	   *attr_needed;	/* array indexed [min_attr .. max_attr] */
Index: src/include/rewrite/prs2lock.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/rewrite/prs2lock.h,v
retrieving revision 1.21
diff -c -r1.21 prs2lock.h
*** src/include/rewrite/prs2lock.h	5 Mar 2006 15:58:58 -0000	1.21
--- src/include/rewrite/prs2lock.h	30 Aug 2006 07:48:01 -0000
***************
*** 29,34 ****
--- 29,35 ----
  	Node	   *qual;
  	List	   *actions;
  	bool		isInstead;
+ 	char        ev_kind;
  } RewriteRule;
  
  /*
Index: src/include/rewrite/rewriteDefine.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/rewrite/rewriteDefine.h,v
retrieving revision 1.21
diff -c -r1.21 rewriteDefine.h
*** src/include/rewrite/rewriteDefine.h	5 Mar 2006 15:58:58 -0000	1.21
--- src/include/rewrite/rewriteDefine.h	30 Aug 2006 07:48:01 -0000
***************
*** 16,22 ****
  
  #include "nodes/parsenodes.h"
  
! extern void DefineQueryRewrite(RuleStmt *args);
  
  extern void RenameRewriteRule(Oid owningRel, const char *oldName,
  				  const char *newName);
--- 16,23 ----
  
  #include "nodes/parsenodes.h"
  
! extern void DefineQueryRewrite(RuleStmt *args,
! 							   char     ev_kind);
  
  extern void RenameRewriteRule(Oid owningRel, const char *oldName,
  				  const char *newName);
Index: src/include/rewrite/rewriteRemove.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/rewrite/rewriteRemove.h,v
retrieving revision 1.22
diff -c -r1.22 rewriteRemove.h
*** src/include/rewrite/rewriteRemove.h	16 Jun 2006 20:23:45 -0000	1.22
--- src/include/rewrite/rewriteRemove.h	30 Aug 2006 07:48:01 -0000
***************
*** 20,24 ****
--- 20,26 ----
  extern void RemoveRewriteRule(Oid owningRel, const char *ruleName,
  				  DropBehavior behavior, bool missing_ok);
  extern void RemoveRewriteRuleById(Oid ruleOid);
+ extern void deleteImplicitRulesOnEvent(Relation rel, CmdType event_type, 
+                                        Oid exceptOid);
  
  #endif   /* REWRITEREMOVE_H */
Index: src/include/rewrite/rewriteSupport.h
===================================================================
RCS file: /projects/cvsroot/pgsql/src/include/rewrite/rewriteSupport.h,v
retrieving revision 1.28
diff -c -r1.28 rewriteSupport.h
*** src/include/rewrite/rewriteSupport.h	5 Mar 2006 15:58:58 -0000	1.28
--- src/include/rewrite/rewriteSupport.h	30 Aug 2006 07:48:01 -0000
***************
*** 17,22 ****
--- 17,33 ----
  /* The ON SELECT rule of a view is always named this: */
  #define ViewSelectRuleName	"_RETURN"
  
+ /*------------------------------------------------------------------------------
+  * some names to be used for implicit view update rules
+  *------------------------------------------------------------------------------
+  */
+ #define INSERTRULENAME "_INSERT"
+ #define DELETERULENAME "_DELETE"
+ #define UPDATERULENAME "_UPDATE"
+ #define NOTHING_INSERTRULENAME "_NOTHING_INSERT"
+ #define NOTHING_UPDATERULENAME "_NOTHING_UPDATE"
+ #define NOTHING_DELETERULENAME "_NOTHING_DELETE"
+ 
  extern bool IsDefinedRewriteRule(Oid owningRel, const char *ruleName);
  
  extern void SetRelationRuleStatus(Oid relationId, bool relHasRules,
upd-views.txttext/plain; charset=iso-8859-1; name=upd-views.txtDownload
#14Tom Lane
tgl@sss.pgh.pa.us
In reply to: Bernd Helmle (#13)
Re: Updatable views

Bernd Helmle <mailings@oopsware.de> writes:

[ latest views patch ]

This is the first time I've actually looked at this patch, and I am
dismayed. viewUpdate.c looks like nothing so much as a large program
with a small program struggling to get out. What is all the stuff about
handling multiple base rels? SQL92, at least, does not say that a join
is updatable, and AFAICT this patch is rejecting that too ... though
it's hard to tell with the conditions for allowing the join to be
updatable scattered through a lot of different functions. And some of
the code seems to be expecting multiple implicit rules and other parts
not. I get the impression that a lot of this code is left over from a
more ambitious first draft and ought to be removed in the name of
readability/maintainability.

I'm unclear as to why you've got DO INSTEAD NOTHING rules in there ---
the spec says that a WITH CHECK OPTION violation results in an error,
not in nothing happening, so it doesn't seem to me that we should need
any NOTHING rules to implement the spec. It would probably help if
there were some header documentation that explained exactly how the
module intends to transform a SELECT to create the various action rules.

The pg_dump changes seem pretty odd too. Why wouldn't you just
ignore implicit rules during a dump, expecting the system to
regenerate them when the view is reloaded?

regards, tom lane

#15Jim C. Nasby
jnasby@pervasive.com
In reply to: Tom Lane (#14)
Re: [HACKERS] Updatable views

On Wed, Aug 30, 2006 at 12:01:25PM -0400, Tom Lane wrote:

Bernd Helmle <mailings@oopsware.de> writes:

[ latest views patch ]

This is the first time I've actually looked at this patch, and I am
dismayed. viewUpdate.c looks like nothing so much as a large program
with a small program struggling to get out. What is all the stuff about
handling multiple base rels? SQL92, at least, does not say that a join
is updatable, and AFAICT this patch is rejecting that too ... though
it's hard to tell with the conditions for allowing the join to be
updatable scattered through a lot of different functions. And some of
the code seems to be expecting multiple implicit rules and other parts
not. I get the impression that a lot of this code is left over from a
more ambitious first draft and ought to be removed in the name of
readability/maintainability.

If that code is on the right path to allowing things like updates to the
many side of a join then it would be worth adding comments to that
effect. Or maybe a comment referencing whatever version of the file the
code was yanked out of.
--
Jim C. Nasby, Sr. Engineering Consultant jnasby@pervasive.com
Pervasive Software http://pervasive.com work: 512-231-6117
vcard: http://jim.nasby.net/pervasive.vcf cell: 512-569-9461

#16Peter Eisentraut
peter_e@gmx.net
In reply to: Tom Lane (#14)
Re: [HACKERS] Updatable views

Am Mittwoch, 30. August 2006 18:01 schrieb Tom Lane:

This is the first time I've actually looked at this patch, and I am
dismayed. viewUpdate.c looks like nothing so much as a large program
with a small program struggling to get out. What is all the stuff about
handling multiple base rels? SQL92, at least, does not say that a join
is updatable, and AFAICT this patch is rejecting that too ...

But later SQL versions allow some of that, so at least it shouldn't hurt to
have some parts of the code to be more general in preparation of that.

I'm unclear as to why you've got DO INSTEAD NOTHING rules in there ---

You need to have one unconditional rule if you have a bunch of conditional
ones. The system does not see through the fact that the conditional ones
cover all cases.

The pg_dump changes seem pretty odd too. Why wouldn't you just
ignore implicit rules during a dump, expecting the system to
regenerate them when the view is reloaded?

Right.

--
Peter Eisentraut
http://developer.postgresql.org/~petere/

#17Bernd Helmle
mailings@oopsware.de
In reply to: Tom Lane (#14)
Re: Updatable views

--On Mittwoch, August 30, 2006 12:01:25 -0400 Tom Lane <tgl@sss.pgh.pa.us>
wrote:

Bernd Helmle <mailings@oopsware.de> writes:

[ latest views patch ]

This is the first time I've actually looked at this patch, and I am
dismayed. viewUpdate.c looks like nothing so much as a large program
with a small program struggling to get out. What is all the stuff about
handling multiple base rels? SQL92, at least, does not say that a join
is updatable, and AFAICT this patch is rejecting that too ... though
it's hard to tell with the conditions for allowing the join to be
updatable scattered through a lot of different functions. And some of
the code seems to be expecting multiple implicit rules and other parts
not. I get the impression that a lot of this code is left over from a
more ambitious first draft and ought to be removed in the name of
readability/maintainability.

I not sure what parts of the code you are refering to exactly, but I admit
that
there are code parts that could deal with multiple base relations and
rules.
get_base_base_relation() is an example, it is used to create lookup tables
for reversed columns so we could break them down to the correct position in
their base tables. Restricting that to only one base relation wouldn't make
any
difference. Furthermore, SQL99 allows at least updatable views with joined
relations which preserve their keys in the view definition. So i don't
think it's that
bad to leave parts of the code that way for future improvements.

I'm unclear as to why you've got DO INSTEAD NOTHING rules in there ---
the spec says that a WITH CHECK OPTION violation results in an error,
not in nothing happening, so it doesn't seem to me that we should need
any NOTHING rules to implement the spec. It would probably help if

Well, instead of something like

"ERROR: cannot insert into a view
HINT: You need an unconditional ON INSERT DO INSTEAD rule."

you will get

"ERROR: view update commands violates rule condition"

with the correct error code set, because the view update check function is
fired before.
The first one isn't very useful for someone who simply wants to insert data
into the
view which isn't allowed to get in. You never get the view update check
function fired
without the DO INSTEAD rule applied to a view created with a check option.

there were some header documentation that explained exactly how the
module intends to transform a SELECT to create the various action rules.

I agree with you, maybe it's a good to add a README to src/backend/rewrite?

The pg_dump changes seem pretty odd too. Why wouldn't you just
ignore implicit rules during a dump, expecting the system to
regenerate them when the view is reloaded?

Uhm, you're right. It's easier to exclude them in the SELECT query directly
instead
of selecting them, iterating over and filter them out. I'll fix that.
(Looks like this is a
"cannot see the wood for the trees"-mistake....)

--
Thanks

Bernd

#18Tom Lane
tgl@sss.pgh.pa.us
In reply to: Peter Eisentraut (#16)
Re: [HACKERS] Updatable views

Peter Eisentraut <peter_e@gmx.net> writes:

Am Mittwoch, 30. August 2006 18:01 schrieb Tom Lane:

This is the first time I've actually looked at this patch, and I am
dismayed. viewUpdate.c looks like nothing so much as a large program
with a small program struggling to get out.

But later SQL versions allow some of that, so at least it shouldn't hurt to
have some parts of the code to be more general in preparation of that.

If it bloats the code to unreadability, it's bad.

I'm unclear as to why you've got DO INSTEAD NOTHING rules in there ---

You need to have one unconditional rule if you have a bunch of conditional
ones. The system does not see through the fact that the conditional ones
cover all cases.

AFAICS, for the cases we are able to implement within the existing rule
mechanism, there should be exactly one unconditional rule. If you
propose more, then you are going to have insurmountable problems with
the usual sorts of multiple-evaluation risks.

The proposed WITH CHECK OPTION implementation is unworkable for exactly
this reason --- it will give the wrong answers in the presence of
volatile functions such as nextval(). I believe that we cannot
implement WITH CHECK OPTION as a rule. It's a constraint, instead,
and will have to be checked the way the executor presently checks
constraints, ie after forming the finished new tuple(s).

(Someday we're going to have to look into redesigning the rule system
so that it can cope better with the kinds of situations that give rise
to multiple-evaluation problems. But today is not that day.)

It's possible that if we strip the patch down to SQL92-equivalent
functionality (no multiple base rels) without WITH CHECK OPTION,
we would have something that would work reliably atop the existing
rule mechanism. It's getting mighty late in the 8.2 cycle to be
doing major rework though.

regards, tom lane

#19Peter Eisentraut
peter_e@gmx.net
In reply to: Tom Lane (#18)
Re: [HACKERS] Updatable views

Am Donnerstag, 31. August 2006 15:55 schrieb Tom Lane:

I'm unclear as to why you've got DO INSTEAD NOTHING rules in there ---

You need to have one unconditional rule if you have a bunch of
conditional ones. The system does not see through the fact that the
conditional ones cover all cases.

AFAICS, for the cases we are able to implement within the existing rule
mechanism, there should be exactly one unconditional rule. If you
propose more, then you are going to have insurmountable problems with
the usual sorts of multiple-evaluation risks.

I'm not sure what you are saying here ...

The implementation creates, for each of the three actions INSERT, UPDATE,
DELETE, one conditional rule that redirects the action from the view into the
unterlying table, conditional on the view condition being fulfilled. The
unconditional DO INSTEAD NOTHING rule then catches the cases where the view
condition is not fulfilled. So there is, for each action, exactly one
conditional and one unconditional rule. Which is consistent with what you
said above, so I don't see the problem.

The proposed WITH CHECK OPTION implementation is unworkable for exactly
this reason --- it will give the wrong answers in the presence of
volatile functions such as nextval().

I'm not sure why anyone would want to define a view condition containing a
volatile function. At least it wouldn't put a major dent into this feature
if such views were decreed not updatable.

--
Peter Eisentraut
http://developer.postgresql.org/~petere/

#20Tom Lane
tgl@sss.pgh.pa.us
In reply to: Peter Eisentraut (#19)
Re: [HACKERS] Updatable views

Peter Eisentraut <peter_e@gmx.net> writes:

Am Donnerstag, 31. August 2006 15:55 schrieb Tom Lane:

The proposed WITH CHECK OPTION implementation is unworkable for exactly
this reason --- it will give the wrong answers in the presence of
volatile functions such as nextval().

I'm not sure why anyone would want to define a view condition containing a
volatile function. At least it wouldn't put a major dent into this feature
if such views were decreed not updatable.

The problem is not with the view condition. Consider

CREATE TABLE data (id serial primary key, ...);

CREATE VIEW only_new_data AS SELECT * FROM data WHERE id > 12345
WITH CHECK OPTION;

INSERT INTO only_new_data VALUES(nextval('data_id_seq'), ...);

The proposed implementation will execute nextval twice (bad), and will
apply the WITH CHECK OPTION test to the value that isn't the one stored
(much worse). It doesn't help if the id is defaulted.

regards, tom lane

#21Bernd Helmle
bernd.helmle@oopsware.de
In reply to: Tom Lane (#20)
Re: [PATCHES] Updatable views

--On Donnerstag, August 31, 2006 11:10:47 -0400 Tom Lane
<tgl@sss.pgh.pa.us> wrote:

The problem is not with the view condition. Consider

CREATE TABLE data (id serial primary key, ...);

CREATE VIEW only_new_data AS SELECT * FROM data WHERE id > 12345
WITH CHECK OPTION;

INSERT INTO only_new_data VALUES(nextval('data_id_seq'), ...);

The proposed implementation will execute nextval twice (bad), and will
apply the WITH CHECK OPTION test to the value that isn't the one stored
(much worse). It doesn't help if the id is defaulted.

*scratches head*....i don't see a shortcoming solution for this in my
current implementation,
indeed. I admit that this is a serious containment of updatable views in
its current
incarnation (at least for the check option).

*thinking*
I would like to try to grab your idea to push down the CHECK OPTION logic
down to the executor as a (table/view?) constraint. Would that be an idea
worth to consider and,
most important, is this doable? I don't have that much experience in the
executor, so i fear
this isn't something that will be done within a week or so.....:(

--
Thanks

Bernd

#22Tom Lane
tgl@sss.pgh.pa.us
In reply to: Bernd Helmle (#21)
Re: [PATCHES] Updatable views

Bernd Helmle <bernd.helmle@oopsware.de> writes:

I would like to try to grab your idea to push down the CHECK OPTION logic
down to the executor as a (table/view?) constraint. Would that be an idea
worth to consider and,
most important, is this doable? I don't have that much experience in the
executor, so i fear
this isn't something that will be done within a week or so.....:(

You're certainly welcome to work on it --- I don't have time at the
moment. But I agree there's little chance of getting it done in time
for 8.2.

I have not read the spec's definition of WITH CHECK OPTION lately, so
there may be something fundamentally wrong in what I'm about to say,
but the way I'm envisioning this working is that W.C.O. is embodied as
a check constraint (or something pretty similar --- a pg_constraint
entry certainly) attached to the view. The rewriter would then be
responsible for collecting all the check options that need to be
enforced for a given rewritten query. This'd require some rework of
the rewriter/planner/executor API: right now the executor is solely
responsible for collecting check constraints to apply in an updating
query, and we'd want to change that. My thought is we might as well
move the collection responsibility over to the rewriter 100%: the
rewriter decorates a Query with the list of constraint expressions
to apply, and the executor just checks what it's told to. The planner
probably need not do much with the constraint expressions beyond what
it normally does with, say, targetlist expressions.

Some thoughts:

* It's too early in the morning for me to be clear about the difference
between CASCADED and LOCAL CHECK OPTION --- I think that this would
merely alter the set of check constraints collected for a particular
query, but if there's something more fundamental there, this scheme
might not work at all. So look into that first.

* The reason we currently collect constraints at executor start is that
ALTER TABLE ADD CONSTRAINT has no way to invalidate cached plans, so
it's unsafe to store lists of constraints in plans. So this scheme
*requires* that we have a plan invalidation mechanism in place (at least
before we release, maybe not before the patch can go in). This doesn't
bother me because I intend anyway to see to it that there's plan inval
in 8.3.

* With check constraints now passing through the planner, it'd become
trivial to allow subqueries in check constraints. Just sayin'.

* We'd probably eliminate the idea of storing constraints in TupleDescs,
which would be a good simplification anyway (eg, eliminate the bogus
distinction between CreateTupleDescCopy and CreateTupleDescCopyConstr).
OTOH that might make it harder to allow rowtypes to have associated
constraints? Needs thought.

regards, tom lane

#23Bernd Helmle
mailings@oopsware.de
In reply to: Tom Lane (#22)
Re: [PATCHES] Updatable views

[Quick note: sorry if you received this mail multiple times,
i've moved to a new workstation and my MUA gots hosed up
with its identities (all of them has the same adress, suddenly)
and I recognized that too late.....i'm sorry]

--On Freitag, September 01, 2006 10:03:42 -0400 Tom Lane
<tgl@sss.pgh.pa.us> wrote:

Bernd Helmle <bernd.helmle@oopsware.de> writes:

You're certainly welcome to work on it --- I don't have time at the
moment. But I agree there's little chance of getting it done in time
for 8.2.

What we can do is to restrict view updates that involves a volatile function
completely. As soon as the rewriter wants to apply an implicit system rule
to a current query which holds volatile functions, we could treat this as
an error.
However, i haven't looked into that right now how doable that would be, but
it seems correct in terms of data reliability (treat it as "volatile in
view update is
evil" ;)

Maybe it's worth to look how other database systems solve this problem.

I have not read the spec's definition of WITH CHECK OPTION lately, so
there may be something fundamentally wrong in what I'm about to say,
but the way I'm envisioning this working is that W.C.O. is embodied as
a check constraint (or something pretty similar --- a pg_constraint
entry certainly) attached to the view. The rewriter would then be
responsible for collecting all the check options that need to be
enforced for a given rewritten query. This'd require some rework of
the rewriter/planner/executor API: right now the executor is solely
responsible for collecting check constraints to apply in an updating
query, and we'd want to change that. My thought is we might as well
move the collection responsibility over to the rewriter 100%: the
rewriter decorates a Query with the list of constraint expressions
to apply, and the executor just checks what it's told to. The planner
probably need not do much with the constraint expressions beyond what
it normally does with, say, targetlist expressions.

In order you want to do a CASCADED CHECK OPTION,
you need to collect all expressions out of underlying relations and rewrite
them to match
the table you are selecting...that looks like a very expensive operation.

Some thoughts:

* It's too early in the morning for me to be clear about the difference
between CASCADED and LOCAL CHECK OPTION --- I think that this would
merely alter the set of check constraints collected for a particular
query, but if there's something more fundamental there, this scheme
might not work at all. So look into that first.

LOCAL checks the data to be updated against its own view WHERE condition
only, where
CASCADED involves all WHERE conditions of all underlying views. That said,
it's
necessary to grep out all WHERE conditions of all relations involved in an
update operation and apply them to the current query as a constraint
expression. The
current implementation passes this recursively via a conditional rule
through the
rewriter. It looked to me as an attractive implementation, but it has this
annoying
multiple evaluation side effects....:(

* The reason we currently collect constraints at executor start is that
ALTER TABLE ADD CONSTRAINT has no way to invalidate cached plans, so
it's unsafe to store lists of constraints in plans. So this scheme
*requires* that we have a plan invalidation mechanism in place (at least
before we release, maybe not before the patch can go in). This doesn't
bother me because I intend anyway to see to it that there's plan inval
in 8.3.

So we need to stall this idea unless we have something workable in this
area. So
what's the plan for 8.2? Should we reject updatable views completely or
is there some interest to apply this without CHECK OPTION? Some basic
functionality
could be simulated with table constraints, however, it's not what users out
there
would expect....

* With check constraints now passing through the planner, it'd become
trivial to allow subqueries in check constraints. Just sayin'.

That would be a nice feature, indeed ;)

* We'd probably eliminate the idea of storing constraints in TupleDescs,
which would be a good simplification anyway (eg, eliminate the bogus
distinction between CreateTupleDescCopy and CreateTupleDescCopyConstr).
OTOH that might make it harder to allow rowtypes to have associated
constraints? Needs thought.

regards, tom lane

--
Thanks

Bernd

#24Alvaro Herrera
alvherre@commandprompt.com
In reply to: Bernd Helmle (#23)
Re: [PATCHES] Updatable views

Bernd Helmle wrote:

<tgl@sss.pgh.pa.us> wrote:

* It's too early in the morning for me to be clear about the difference
between CASCADED and LOCAL CHECK OPTION --- I think that this would
merely alter the set of check constraints collected for a particular
query, but if there's something more fundamental there, this scheme
might not work at all. So look into that first.

LOCAL checks the data to be updated against its own view WHERE
condition only, where CASCADED involves all WHERE conditions of all
underlying views.

I don't understand this part very well. Say if you have a view WITH
CHECK OPTION whose condition is "foo > 5", and then define a view WITH
LOCAL CHECK OPTION on top of that, whose condition is "bar > 5". Does
the local check option on the second view that I can insert a row with
foo=4, bar=6? That doesn't violate the condition of bar > 5, so it
seems fine to me. But it also seems quite idiotic because it violated
the original foo>5 condition.

--
Alvaro Herrera http://www.CommandPrompt.com/
The PostgreSQL Company - Command Prompt, Inc.

#25Tom Lane
tgl@sss.pgh.pa.us
In reply to: Bernd Helmle (#23)
Re: [PATCHES] Updatable views

Bernd Helmle <mailings@oopsware.de> writes:

What we can do is to restrict view updates that involves a volatile function
completely. As soon as the rewriter wants to apply an implicit system rule
to a current query which holds volatile functions, we could treat this as
an error.

So in other words, views on serial columns don't work? I don't think
that's going to be acceptable.

In order you want to do a CASCADED CHECK OPTION,
you need to collect all expressions out of underlying relations and rewrite
them to match
the table you are selecting...that looks like a very expensive operation.

Not really worse than what the rewriter is doing already --- in fact,
I think it's isomorphic to what would happen to the rule qual
expressions in your existing patch.

So we need to stall this idea unless we have something workable in
this area. So what's the plan for 8.2? Should we reject updatable
views completely or is there some interest to apply this without CHECK
OPTION?

I'm about to propose that we should try to go beta next week (see
forthcoming message). If you can strip down your patch to avoid the
multi-eval problems in the next couple of days, I'm still willing to
consider it, but at the moment I'm assuming that it needs to be held
for 8.3.

regards, tom lane

#26Jaime Casanova
systemguards@gmail.com
In reply to: Alvaro Herrera (#24)
Re: [PATCHES] Updatable views

On 9/1/06, Alvaro Herrera <alvherre@commandprompt.com> wrote:

Bernd Helmle wrote:

<tgl@sss.pgh.pa.us> wrote:

* It's too early in the morning for me to be clear about the difference
between CASCADED and LOCAL CHECK OPTION --- I think that this would
merely alter the set of check constraints collected for a particular
query, but if there's something more fundamental there, this scheme
might not work at all. So look into that first.

LOCAL checks the data to be updated against its own view WHERE
condition only, where CASCADED involves all WHERE conditions of all
underlying views.

I don't understand this part very well. Say if you have a view WITH
CHECK OPTION whose condition is "foo > 5", and then define a view WITH
LOCAL CHECK OPTION on top of that, whose condition is "bar > 5". Does
the local check option on the second view that I can insert a row with
foo=4, bar=6? That doesn't violate the condition of bar > 5, so it

yes. or at least that's the way i read that...

seems fine to me. But it also seems quite idiotic because it violated
the original foo>5 condition.

and that means that without the CHECK OPTION constraint you can insert
anything into the base table no matter what the WHERE condition in the
view is...
again, this is the way informix implements it...

ahhh, the great members of the SQL COMITTEE...

--
regards,
Jaime Casanova

"Programming today is a race between software engineers striving to
build bigger and better idiot-proof programs and the universe trying
to produce bigger and better idiots.
So far, the universe is winning."
Richard Cook

#27Bernd Helmle
mailings@oopsware.de
In reply to: Alvaro Herrera (#24)
Re: [PATCHES] Updatable views

--On Freitag, September 01, 2006 11:34:49 -0400 Alvaro Herrera
<alvherre@commandprompt.com> wrote:

I don't understand this part very well. Say if you have a view WITH
CHECK OPTION whose condition is "foo > 5", and then define a view WITH
LOCAL CHECK OPTION on top of that, whose condition is "bar > 5". Does
the local check option on the second view that I can insert a row with
foo=4, bar=6? That doesn't violate the condition of bar > 5, so it
seems fine to me. But it also seems quite idiotic because it violated
the original foo>5 condition.

That's exactly what i'm reading out there, too. If such a view definition
is useful or not
depends on its use case. Correct me if i'm wrong....

--
Thanks

Bernd

#28Bernd Helmle
mailings@oopsware.de
In reply to: Tom Lane (#25)
Re: [PATCHES] Updatable views

--On Freitag, September 01, 2006 11:41:16 -0400 Tom Lane
<tgl@sss.pgh.pa.us> wrote:

So in other words, views on serial columns don't work? I don't think
that's going to be acceptable.

They work in such a case that someone isn't allowed to put a volatile
function in an update query....

Not really worse than what the rewriter is doing already --- in fact,
I think it's isomorphic to what would happen to the rule qual
expressions in your existing patch.

Currently you don't have to rewrite the rule conditions itself every
time you apply them to the query tree since they are stored in pg_rewrite
matching all various (reversed) varattno's, resno's and whatever.
If i understand correctly you need to do that with constraints every time
you fire an update query on a view for each underlying relation....

I'm about to propose that we should try to go beta next week (see
forthcoming message). If you can strip down your patch to avoid the
multi-eval problems in the next couple of days, I'm still willing to

Depends on how many days "couple of days" are.....if you mean the next
three days
then definitely not, since i'm afk for the whole upcoming weekend. Bad
timing, but
it's not deferrable.... :(

consider it, but at the moment I'm assuming that it needs to be held
for 8.3.

Well, i'll see what i can do next week....it's a little bit disappointing
that these problems
raises so late, but that's no one's fault since there are many side effects
of the rewriting
system involved....

Many thanks for your comments.

Bernd

#29Bruce Momjian
bruce@momjian.us
In reply to: Bernd Helmle (#28)
Re: [PATCHES] Updatable views

This has been saved for the 8.3 release:

http://momjian.postgresql.org/cgi-bin/pgpatches_hold

---------------------------------------------------------------------------

Bernd Helmle wrote:

--On Freitag, September 01, 2006 11:41:16 -0400 Tom Lane
<tgl@sss.pgh.pa.us> wrote:

So in other words, views on serial columns don't work? I don't think
that's going to be acceptable.

They work in such a case that someone isn't allowed to put a volatile
function in an update query....

Not really worse than what the rewriter is doing already --- in fact,
I think it's isomorphic to what would happen to the rule qual
expressions in your existing patch.

Currently you don't have to rewrite the rule conditions itself every
time you apply them to the query tree since they are stored in pg_rewrite
matching all various (reversed) varattno's, resno's and whatever.
If i understand correctly you need to do that with constraints every time
you fire an update query on a view for each underlying relation....

I'm about to propose that we should try to go beta next week (see
forthcoming message). If you can strip down your patch to avoid the
multi-eval problems in the next couple of days, I'm still willing to

Depends on how many days "couple of days" are.....if you mean the next
three days
then definitely not, since i'm afk for the whole upcoming weekend. Bad
timing, but
it's not deferrable.... :(

consider it, but at the moment I'm assuming that it needs to be held
for 8.3.

Well, i'll see what i can do next week....it's a little bit disappointing
that these problems
raises so late, but that's no one's fault since there are many side effects
of the rewriting
system involved....

Many thanks for your comments.

Bernd

---------------------------(end of broadcast)---------------------------
TIP 1: if posting/reading through Usenet, please send an appropriate
subscribe-nomail command to majordomo@postgresql.org so that your
message can get through to the mailing list cleanly

--
Bruce Momjian bruce@momjian.us
EnterpriseDB http://www.enterprisedb.com

+ If your life is a hard drive, Christ can be your backup. +

#30Bruce Momjian
bruce@momjian.us
In reply to: Bernd Helmle (#17)
Re: Updatable views

Where are we on this feature?

---------------------------------------------------------------------------

Bernd Helmle wrote:

--On Mittwoch, August 30, 2006 12:01:25 -0400 Tom Lane <tgl@sss.pgh.pa.us>
wrote:

Bernd Helmle <mailings@oopsware.de> writes:

[ latest views patch ]

This is the first time I've actually looked at this patch, and I am
dismayed. viewUpdate.c looks like nothing so much as a large program
with a small program struggling to get out. What is all the stuff about
handling multiple base rels? SQL92, at least, does not say that a join
is updatable, and AFAICT this patch is rejecting that too ... though
it's hard to tell with the conditions for allowing the join to be
updatable scattered through a lot of different functions. And some of
the code seems to be expecting multiple implicit rules and other parts
not. I get the impression that a lot of this code is left over from a
more ambitious first draft and ought to be removed in the name of
readability/maintainability.

I not sure what parts of the code you are refering to exactly, but I admit
that
there are code parts that could deal with multiple base relations and
rules.
get_base_base_relation() is an example, it is used to create lookup tables
for reversed columns so we could break them down to the correct position in
their base tables. Restricting that to only one base relation wouldn't make
any
difference. Furthermore, SQL99 allows at least updatable views with joined
relations which preserve their keys in the view definition. So i don't
think it's that
bad to leave parts of the code that way for future improvements.

I'm unclear as to why you've got DO INSTEAD NOTHING rules in there ---
the spec says that a WITH CHECK OPTION violation results in an error,
not in nothing happening, so it doesn't seem to me that we should need
any NOTHING rules to implement the spec. It would probably help if

Well, instead of something like

"ERROR: cannot insert into a view
HINT: You need an unconditional ON INSERT DO INSTEAD rule."

you will get

"ERROR: view update commands violates rule condition"

with the correct error code set, because the view update check function is
fired before.
The first one isn't very useful for someone who simply wants to insert data
into the
view which isn't allowed to get in. You never get the view update check
function fired
without the DO INSTEAD rule applied to a view created with a check option.

there were some header documentation that explained exactly how the
module intends to transform a SELECT to create the various action rules.

I agree with you, maybe it's a good to add a README to src/backend/rewrite?

The pg_dump changes seem pretty odd too. Why wouldn't you just
ignore implicit rules during a dump, expecting the system to
regenerate them when the view is reloaded?

Uhm, you're right. It's easier to exclude them in the SELECT query directly
instead
of selecting them, iterating over and filter them out. I'll fix that.
(Looks like this is a
"cannot see the wood for the trees"-mistake....)

--
Thanks

Bernd

---------------------------(end of broadcast)---------------------------
TIP 1: if posting/reading through Usenet, please send an appropriate
subscribe-nomail command to majordomo@postgresql.org so that your
message can get through to the mailing list cleanly

--
Bruce Momjian <bruce@momjian.us> http://momjian.us
EnterpriseDB http://www.enterprisedb.com

+ If your life is a hard drive, Christ can be your backup. +

#31Bruce Momjian
bruce@momjian.us
In reply to: Bernd Helmle (#28)
Re: [PATCHES] Updatable views

Here is the more recent email I have on this feature work.

---------------------------------------------------------------------------

Bernd Helmle wrote:

--On Freitag, September 01, 2006 11:41:16 -0400 Tom Lane
<tgl@sss.pgh.pa.us> wrote:

So in other words, views on serial columns don't work? I don't think
that's going to be acceptable.

They work in such a case that someone isn't allowed to put a volatile
function in an update query....

Not really worse than what the rewriter is doing already --- in fact,
I think it's isomorphic to what would happen to the rule qual
expressions in your existing patch.

Currently you don't have to rewrite the rule conditions itself every
time you apply them to the query tree since they are stored in pg_rewrite
matching all various (reversed) varattno's, resno's and whatever.
If i understand correctly you need to do that with constraints every time
you fire an update query on a view for each underlying relation....

I'm about to propose that we should try to go beta next week (see
forthcoming message). If you can strip down your patch to avoid the
multi-eval problems in the next couple of days, I'm still willing to

Depends on how many days "couple of days" are.....if you mean the next
three days
then definitely not, since i'm afk for the whole upcoming weekend. Bad
timing, but
it's not deferrable.... :(

consider it, but at the moment I'm assuming that it needs to be held
for 8.3.

Well, i'll see what i can do next week....it's a little bit disappointing
that these problems
raises so late, but that's no one's fault since there are many side effects
of the rewriting
system involved....

Many thanks for your comments.

Bernd

---------------------------(end of broadcast)---------------------------
TIP 1: if posting/reading through Usenet, please send an appropriate
subscribe-nomail command to majordomo@postgresql.org so that your
message can get through to the mailing list cleanly

--
Bruce Momjian <bruce@momjian.us> http://momjian.us
EnterpriseDB http://www.enterprisedb.com

+ If your life is a hard drive, Christ can be your backup. +

#32Bruce Momjian
bruce@momjian.us
In reply to: Bernd Helmle (#28)
Re: [PATCHES] Updatable views

Where are on updatable views?

---------------------------------------------------------------------------

Bernd Helmle wrote:

--On Freitag, September 01, 2006 11:41:16 -0400 Tom Lane
<tgl@sss.pgh.pa.us> wrote:

So in other words, views on serial columns don't work? I don't think
that's going to be acceptable.

They work in such a case that someone isn't allowed to put a volatile
function in an update query....

Not really worse than what the rewriter is doing already --- in fact,
I think it's isomorphic to what would happen to the rule qual
expressions in your existing patch.

Currently you don't have to rewrite the rule conditions itself every
time you apply them to the query tree since they are stored in pg_rewrite
matching all various (reversed) varattno's, resno's and whatever.
If i understand correctly you need to do that with constraints every time
you fire an update query on a view for each underlying relation....

I'm about to propose that we should try to go beta next week (see
forthcoming message). If you can strip down your patch to avoid the
multi-eval problems in the next couple of days, I'm still willing to

Depends on how many days "couple of days" are.....if you mean the next
three days
then definitely not, since i'm afk for the whole upcoming weekend. Bad
timing, but
it's not deferrable.... :(

consider it, but at the moment I'm assuming that it needs to be held
for 8.3.

Well, i'll see what i can do next week....it's a little bit disappointing
that these problems
raises so late, but that's no one's fault since there are many side effects
of the rewriting
system involved....

Many thanks for your comments.

Bernd

---------------------------(end of broadcast)---------------------------
TIP 1: if posting/reading through Usenet, please send an appropriate
subscribe-nomail command to majordomo@postgresql.org so that your
message can get through to the mailing list cleanly

--
Bruce Momjian <bruce@momjian.us> http://momjian.us
EnterpriseDB http://postgres.enterprisedb.com

+ If your life is a hard drive, Christ can be your backup. +

#33Bernd Helmle
mailings@oopsware.de
In reply to: Bruce Momjian (#32)
Re: [PATCHES] Updatable views

--On Donnerstag, März 06, 2008 17:03:10 -0500 Bruce Momjian
<bruce@momjian.us> wrote:

Where are on updatable views?

I really want to have this one ready for 8.4, but i have nothing appliable
at the moment. Considering the amount of rework that needs to be done, i
hope i can provide an updated patch version during next commit fest.

--
Thanks

Bernd

#34Jaime Casanova
systemguards@gmail.com
In reply to: Bernd Helmle (#33)
Re: [PATCHES] Updatable views

On Thu, Mar 6, 2008 at 6:35 PM, Bernd Helmle <mailings@oopsware.de> wrote:

--On Donnerstag, März 06, 2008 17:03:10 -0500 Bruce Momjian
<bruce@momjian.us> wrote:

Where are on updatable views?

I really want to have this one ready for 8.4, but i have nothing appliable
at the moment. Considering the amount of rework that needs to be done, i
hope i can provide an updated patch version during next commit fest.

i will be waiting for it!
maybe you can update the wiki with actual state or with the latest
patch you have even if it doesn't apply... just to see what needs to
be done...

--
regards,
Jaime Casanova

#35Simon Riggs
simon@2ndquadrant.com
In reply to: Bruce Momjian (#30)
Re: Updatable views

On Thu, 2007-02-08 at 18:21 -0500, Bruce Momjian wrote:

Where are we on this feature?

Any update, Bernd?

--
Simon Riggs
2ndQuadrant http://www.2ndQuadrant.com

#36Bernd Helmle
mailings@oopsware.de
In reply to: Simon Riggs (#35)
Re: Updatable views

--On Mittwoch, Mai 07, 2008 20:38:59 +0100 Simon Riggs
<simon@2ndquadrant.com> wrote:

Where are we on this feature?

Any update, Bernd?

I've merged the patch into current -HEAD and updated some parts. My current
*working* state can be reviewed at

<http://git.postgresql.org/?p=~psoo/postgresql.git;a=shortlog;h=updatable_views&gt;

I'm still not sure how to implement a reliable CHECK OPTION, but short on
time i haven't done a very deep investigation yet. Next idea was to look at
the updatable cursor stuff, maybe something there can be reused.

--
Thanks

Bernd

#37Simon Riggs
simon@2ndquadrant.com
In reply to: Bernd Helmle (#36)
Re: Updatable views

On Thu, 2008-05-08 at 13:48 +0200, Bernd Helmle wrote:

--On Mittwoch, Mai 07, 2008 20:38:59 +0100 Simon Riggs
<simon@2ndquadrant.com> wrote:

Where are we on this feature?

Any update, Bernd?

I've merged the patch into current -HEAD and updated some parts. My current
*working* state can be reviewed at

<http://git.postgresql.org/?p=~psoo/postgresql.git;a=shortlog;h=updatable_views&gt;

I'm still not sure how to implement a reliable CHECK OPTION, but short on
time i haven't done a very deep investigation yet. Next idea was to look at
the updatable cursor stuff, maybe something there can be reused.

Your earlier patch seemed to add two rules if the view had a with check
option? One with a pass through and another one with a do-nothing and a
where clause.

As I understand it

CREATE VIEW x AS SELECT * FROM foo WHERE where-clause WITH CHECK OPTION

should generate an INSERT rule like this

CREATE RULE somename AS ON INSERT TO x WHERE where-clause DO INSERT ...

which seems straightforward, no?

The SQLStandard default is CASCADED and it seems easier not to worry too
much about the LOCAL option until we have the basics working. I'm not
even sure that we *want* the LOCAL option anyway having read what it
means, plus it isn't supported by many other DBMS.

Do you store anything in the catalog to mark the view as updatable or
not? I couldn't see that but it seemed easier than trying to resolve all
of the updatability characteristics at run-time.

I may be able to help some with the patch, if you'd like?

--
Simon Riggs
2ndQuadrant http://www.2ndQuadrant.com

#38Peter Eisentraut
peter_e@gmx.net
In reply to: Simon Riggs (#37)
Re: Updatable views

Am Donnerstag, 8. Mai 2008 schrieb Simon Riggs:

�CREATE RULE somename AS ON INSERT TO x WHERE where-clause DO INSERT ...

which seems straightforward, no?

Double evaluation is the key word. The conclusion was more or less that you
can't implement check constraints using the rules system. You need to check
them in the executor.

#39Bernd Helmle
mailings@oopsware.de
In reply to: Simon Riggs (#37)
Re: Updatable views

--On Donnerstag, Mai 08, 2008 13:28:14 +0100 Simon Riggs
<simon@2ndquadrant.com> wrote:

On Thu, 2008-05-08 at 13:48 +0200, Bernd Helmle wrote:

--On Mittwoch, Mai 07, 2008 20:38:59 +0100 Simon Riggs
<simon@2ndquadrant.com> wrote:

Where are we on this feature?

Any update, Bernd?

I've merged the patch into current -HEAD and updated some parts. My
current *working* state can be reviewed at

<http://git.postgresql.org/?p=~psoo/postgresql.git;a=shortlog;h=updatabl
e_views>

I'm still not sure how to implement a reliable CHECK OPTION, but short
on time i haven't done a very deep investigation yet. Next idea was to
look at the updatable cursor stuff, maybe something there can be reused.

Your earlier patch seemed to add two rules if the view had a with check
option? One with a pass through and another one with a do-nothing and a
where clause.

As I understand it

CREATE VIEW x AS SELECT * FROM foo WHERE where-clause WITH CHECK OPTION

should generate an INSERT rule like this

CREATE RULE somename AS ON INSERT TO x WHERE where-clause DO INSERT ...

This was indeed the implementation i've proposed. We have rejected this
idea then because it doesn't work with volatile functions reliable due to
double evaluation:

<http://archives.postgresql.org/pgsql-patches/2006-08/msg00483.php&gt;

Tom's example even demonstrates a serious constraint in rule based updates,
since you get side effects in such conditions you won't expect, even
without a CHECK OPTION.

which seems straightforward, no?

The SQLStandard default is CASCADED and it seems easier not to worry too
much about the LOCAL option until we have the basics working. I'm not
even sure that we *want* the LOCAL option anyway having read what it
means, plus it isn't supported by many other DBMS.

Do you store anything in the catalog to mark the view as updatable or
not? I couldn't see that but it seemed easier than trying to resolve all
of the updatability characteristics at run-time.

I'm not sure want you mean, but pg_rewrite.ev_kind stores the nature of the
rule. Updatability is determined by the checkTree() function internally.
It's easy to query pg_rewrite to examine wether a view is updatable or not.

I may be able to help some with the patch, if you'd like?

You're welcome ;)

--
Simon Riggs
2ndQuadrant http://www.2ndQuadrant.com

--
Thanks

Bernd

#40Simon Riggs
simon@2ndquadrant.com
In reply to: Peter Eisentraut (#38)
Re: Updatable views

On Thu, 2008-05-08 at 14:56 +0200, Peter Eisentraut wrote:

Am Donnerstag, 8. Mai 2008 schrieb Simon Riggs:

CREATE RULE somename AS ON INSERT TO x WHERE where-clause DO INSERT ...

which seems straightforward, no?

Double evaluation is the key word. The conclusion was more or less that you
can't implement check constraints using the rules system. You need to check
them in the executor.

That makes sense. I can't see how we would make LOCAL CHECK CONSTRAINTs
work with rules anyhow.

So that means WITH CHECK CONSTRAINT is going to end up executed in a
similar place to constraint evaluation on underlying tables.

That leaves me in a difficult position with MERGE though. MERGE does
something similar with conditional-WHEN clause evaluation, plus
transformation of the sub-statements is only sensible when we have
updatable views. :-(

--
Simon Riggs
2ndQuadrant http://www.2ndQuadrant.com

#41Bernd Helmle
mailings@oopsware.de
In reply to: Simon Riggs (#40)
Re: Updatable views

--On Donnerstag, Mai 08, 2008 14:42:50 +0100 Simon Riggs
<simon@2ndquadrant.com> wrote:

That makes sense. I can't see how we would make LOCAL CHECK CONSTRAINTs
work with rules anyhow.

One of the idea's that came up through the discussion was to make the
rewriter responsible for collecting check constraints such as the local
check condition. They would be pushed down to the executor then where the
correct constraints would be applied. However, i'm currently not in the
position to say if this is doable right now.

The original updatable views patch tracked the state of required and
applied rule conditions during rewrite. This way it applied only the rule
conditions of the specified view in cascading updates.

--
Thanks

Bernd

#42Simon Riggs
simon@2ndquadrant.com
In reply to: Bernd Helmle (#41)
Re: Updatable views

On Thu, 2008-05-08 at 17:20 +0200, Bernd Helmle wrote:

--On Donnerstag, Mai 08, 2008 14:42:50 +0100 Simon Riggs
<simon@2ndquadrant.com> wrote:

That makes sense. I can't see how we would make LOCAL CHECK CONSTRAINTs
work with rules anyhow.

One of the idea's that came up through the discussion was to make the
rewriter responsible for collecting check constraints such as the local
check condition. They would be pushed down to the executor then where the
correct constraints would be applied. However, i'm currently not in the
position to say if this is doable right now.

That's what I was thinking too.

The original updatable views patch tracked the state of required and
applied rule conditions during rewrite. This way it applied only the rule
conditions of the specified view in cascading updates.

Yes, seems like the only way we'll get LOCAL CHECK CONSTRAINTS to work.

Are you planning to work on this?

--
Simon Riggs
2ndQuadrant http://www.2ndQuadrant.com

#43Bernd Helmle
mailings@oopsware.de
In reply to: Simon Riggs (#42)
Re: Updatable views

--On Donnerstag, Mai 08, 2008 16:34:39 +0100 Simon Riggs
<simon@2ndquadrant.com> wrote:

Are you planning to work on this?

Yes, i do. But i have to finish other things first until i can get back
full attention to it, hopefully very soon.

#44Simon Riggs
simon@2ndquadrant.com
In reply to: Bernd Helmle (#43)
Re: Updatable views

On Thu, 2008-05-08 at 21:37 +0200, Bernd Helmle wrote:

--On Donnerstag, Mai 08, 2008 16:34:39 +0100 Simon Riggs
<simon@2ndquadrant.com> wrote:

Are you planning to work on this?

Yes, i do. But i have to finish other things first until i can get back
full attention to it, hopefully very soon.

OK, cool.

It looks to me that the way MERGE processes WHEN clauses is almost
identical to the way updatable views process WITH CHECK OPTION. I'll
assist you with at least that part of it, if I can.

In the meantime, I'll assume its there and get on with the rest of
MERGE.

--
Simon Riggs
2ndQuadrant http://www.2ndQuadrant.com