The format codes to be used for each column.
Each must presently be zero (text) or one (binary).
All must be zero if the overall copy format is textual.
Identifies the message as a data row.
Length of message contents in bytes, including self.
The number of column values that follow (possibly zero).
does not include itself). Can be zero.
As a special case, -1 indicates a NULL column value.
No value bytes follow in the NULL case.
associated format code.
Identifies the message as a Describe command.
Length of message contents in bytes, including self.
or portal).
Identifies the message as a response to an empty query string.
Length of message contents in bytes, including self.
Identifies the message as an error.
Length of message contents in bytes, including self.
the message terminator and no string follows.
type.
The field value.
Identifies the message as an Execute command.
Length of message contents in bytes, including self.
(an empty string selects the unnamed portal).
Identifies the message as a Flush command.
Length of message contents in bytes, including self.
Identifies the message as a function call.
Length of message contents in bytes, including self.
Specifies the object ID of the function to call.
arguments.
zero (text) or one (binary).
function.
does not include itself). Can be zero.
As a special case, -1 indicates a NULL argument value.
No value bytes follow in the NULL case.
associated format code.
zero (text) or one (binary).
Identifies the message as a function call result.
Length of message contents in bytes, including self.
does not include itself). Can be zero.
As a special case, -1 indicates a NULL function result.
No value bytes follow in the NULL case.
the associated format code.
Identifies the message as a no-data indicator.
Length of message contents in bytes, including self.
Identifies the message as a notice.
Length of message contents in bytes, including self.
the message terminator and no string follows.
type.
The field value.
Identifies the message as a notification response.
Length of message contents in bytes, including self.
The process ID of the notifying backend process.
The name of the condition that the notify has been raised on.
Additional information passed from the notifying process.
Identifies the message as a parameter description.
Length of message contents in bytes, including self.
(may be zero).
Specifies the object ID of the parameter data type.
Identifies the message as a run-time parameter status report.
Length of message contents in bytes, including self.
The name of the run-time parameter being reported.
The current value of the parameter.
Identifies the message as a Parse command.
Length of message contents in bytes, including self.
(an empty string selects the unnamed prepared statement).
The query string to be parsed.
prespecify types for.
Specifies the object ID of the parameter data type.
unspecified.
Identifies the message as a Parse-complete indicator.
Length of message contents in bytes, including self.
Identifies the message as a password response.
Length of message contents in bytes, including self.
The password (encrypted, if requested).
Identifies the message as a portal-suspended indicator.
was reached.
Length of message contents in bytes, including self.
Identifies the message as a simple query.
Length of message contents in bytes, including self.
The query string itself.
whenever the backend is ready for a new query cycle.
Length of message contents in bytes, including self.
Current backend transaction status indicator.
block (queries will be rejected until block is ended).
Identifies the message as a row description.
Length of message contents in bytes, including self.
Specifies the number of fields in a row (may be zero).
The field name.
table, the object ID of the table; otherwise zero.
table, the attribute number of the column; otherwise zero.
The object ID of the field's data type.
Note that negative values denote variable-width types.
The meaning of the modifier is type-specific.
format code is not yet known and will always be zero.
Length of message contents in bytes, including self.
Length of message contents in bytes, including self.
the major version number (3 for the protocol described here).
(0 for the protocol described here).
terminator after the last name/value pair.
there is no default.
The database to connect to. Defaults to the user name.
session defaults.
The parameter value.
Identifies the message as a Sync command.
Length of message contents in bytes, including self.
Identifies the message as a termination.
Length of message contents in bytes, including self.
message.
or a localized translation of one of these. Always present.
-
+
-<Chapter Id="rules">
-<Title>The Rule Systemitle>
+<chapter id="rules">
+<title>The Rule Systemitle>
-<Para>
+<para>
This chapter discusses the rule system in
PostgreSQL. Production rule systems
are conceptually simple, but there are many subtle points
involved in actually using them.
-Para>
+para>
-<Para>
+<para>
Some other database systems define active database rules, which
are usually stored procedures and triggers. In
PostgreSQL, these can be implemented
using functions and triggers as well.
-Para>
+para>
-<Para>
+<para>
The rule system (more precisely speaking, the query rewrite rule
system) is totally different from stored procedures and triggers.
It modifies queries to take rules into consideration, and then
linkend="ONG90">.
-<Sect1 id="querytree">
-<Title>The Query Treeitle>
+<sect1 id="querytree">
+<title>The Query Treeitle>
-<Para>
+<para>
To understand how the rule system works it is necessary to know
when it is invoked and what its input and results are.
-Para>
+para>
-<Para>
+<para>
The rule system is located between the parser and the planner.
It takes the output of the parser, one query tree, and the user-defined
rewrite rules, which are also
query trees with some extra information, and creates zero or more
query trees as result. So its input and output are always things
the parser itself could have produced and thus, anything it sees
- is basically representable as an <Acronym>SQLcronym> statement.
-Para>
+ is basically representable as an <acronym>SQLcronym> statement.
+para>
-<Para>
+<para>
Now what is a query tree? It is an internal representation of an
- <Acronym>SQLcronym> statement where the single parts that it is
+ <acronym>SQLcronym> statement where the single parts that it is
built from are stored separately. These query trees can be shown
in the server log if you set the configuration parameters
debug_print_parse,
stored as query trees, in the system catalog
pg_rewrite. They are not formatted like
the log output, but they contain exactly the same information.
-Para>
+para>
-<Para>
+<para>
Reading a raw query tree requires some experience. But since
- <Acronym>SQLcronym> representations of query trees are
+ <acronym>SQLcronym> representations of query trees are
sufficient to understand the rule system, this chapter will not
teach how to read them.
-Para>
+para>
-<Para>
- When reading the <Acronym>SQLcronym> representations of the
+<para>
+ When reading the <acronym>SQLcronym> representations of the
query trees in this chapter it is necessary to be able to identify
the parts the statement is broken into when it is in the query tree
structure. The parts of a query tree are
-<VariableList>
- <VarListEntry>
- <Term>
+<variablelist>
+ <varlistentry>
+ <term>
the command type
- Term>
- <ListItem>
- <Para>
+ term>
+ <listitem>
+ <para>
This is a simple value telling which command
(SELECT, INSERT,
UPDATE, DELETE) produced
the query tree.
- Para>
- ListItem>
- VarListEntry>
+ para>
+ listitem>
+ varlistentry>
- <VarListEntry>
- <Term>
+ <varlistentry>
+ <term>
the range table
- Term>
+ term>
- <ListItem>
- <Para>
+ <listitem>
+ <para>
The range table is a list of relations that are used in the query.
In a SELECT statement these are the relations given after
the FROM key word.
- Para>
+ para>
- <Para>
+ <para>
Every range table entry identifies a table or view and tells
by which name it is called in the other parts of the query.
In the query tree, the range table entries are referenced by
number rather than by name, so here it doesn't matter if there
- are duplicate names as it would in an <Acronym>SQLcronym>
+ are duplicate names as it would in an <acronym>SQLcronym>
statement. This can happen after the range tables of rules
have been merged in. The examples in this chapter will not have
this situation.
- Para>
- ListItem>
- VarListEntry>
+ para>
+ listitem>
+ varlistentry>
- <VarListEntry>
- <Term>
+ <varlistentry>
+ <term>
the result relation
- Term>
- <ListItem>
- <Para>
+ term>
+ <listitem>
+ <para>
This is an index into the range table that identifies the
relation where the results of the query go.
- Para>
+ para>
- <Para>
+ <para>
SELECT queries normally don't have a result
relation. The special case of a SELECT INTO is
mostly identical to a CREATE TABLE followed by a
INSERT ... SELECT and is not discussed
separately here.
- Para>
+ para>
- <Para>
+ <para>
For INSERT, UPDATE, and
DELETE commands, the result relation is the table
(or view!) where the changes are to take effect.
- Para>
- ListItem>
- VarListEntry>
+ para>
+ listitem>
+ varlistentry>
- <VarListEntry>
- <Term>
+ <varlistentry>
+ <term>
the target list
- Term>
+ term>
- <ListItem>
- <Para>
+ <listitem>
+ <para>
The target list is a list of expressions that define the
result of the query. In the case of a
SELECT, these expressions are the ones that
abbreviation for all the column names of a relation. It is
expanded by the parser into the individual columns, so the
rule system never sees it.)
- Para>
+ para>
- <Para>
+ <para>
DELETE commands don't need a target list
because they don't produce any result. In fact, the planner will
add a special
CTID> entry to the empty target list, but
this is after the rule system and will be discussed later; for the
rule system, the target list is empty.
- Para>
+ para>
- <Para>
+ <para>
For INSERT commands, the target list describes
the new rows that should go into the result relation. It consists of the
expressions in the VALUES> clause or the ones from the
the original command but have defaults. Any remaining columns (with
neither a given value nor a default) will be filled in by the
planner with a constant null expression.
- Para>
+ para>
- <Para>
+ <para>
For UPDATE commands, the target list
describes the new rows that should replace the old ones. In the
rule system, it contains just the expressions from the SET
missing columns by inserting expressions that copy the values from
the old row into the new one. And it will add the special
CTID> entry just as for DELETE, too.
- Para>
+ para>
- <Para>
+ <para>
Every entry in the target list contains an expression that can
be a constant value, a variable pointing to a column of one
of the relations in the range table, a parameter, or an expression
tree made of function calls, constants, variables, operators, etc.
- Para>
- ListItem>
- VarListEntry>
+ para>
+ listitem>
+ varlistentry>
- <VarListEntry>
- <Term>
+ <varlistentry>
+ <term>
the qualification
- Term>
- <ListItem>
- <Para>
+ term>
+ <listitem>
+ <para>
The query's qualification is an expression much like one of
those contained in the target list entries. The result value of
this expression is a Boolean that tells whether the operation
(INSERT, UPDATE,
DELETE, or SELECT) for the
final result row should be executed or not. It corresponds to the WHERE> clause
- of an <Acronym>SQLcronym> statement.
- Para>
- ListItem>
- VarListEntry>
+ of an <acronym>SQLcronym> statement.
+ para>
+ listitem>
+ varlistentry>
- <VarListEntry>
- <Term>
+ <varlistentry>
+ <term>
the join tree
- Term>
- <ListItem>
- <Para>
+ term>
+ <listitem>
+ <para>
The query's join tree shows the structure of the FROM> clause.
For a simple query like SELECT ... FROM a, b, c, the join tree is just
a list of the FROM> items, because we are allowed to join them in
the top-level WHERE> expression as a qualification attached to the
top-level join-tree item, too. So really the join tree represents
both the FROM> and WHERE> clauses of a SELECT.
- Para>
- ListItem>
- VarListEntry>
+ para>
+ listitem>
+ varlistentry>
- <VarListEntry>
- <Term>
+ <varlistentry>
+ <term>
the others
- Term>
- <ListItem>
- <Para>
+ term>
+ <listitem>
+ <para>
The other parts of the query tree like the ORDER BY>
clause aren't of interest here. The rule system
substitutes some entries there while applying rules, but that
doesn't have much to do with the fundamentals of the rule
system.
- Para>
- ListItem>
- VarListEntry>
+ para>
+ listitem>
+ varlistentry>
-VariableList>
+variablelist>
-Sect1>
+sect1>
-<Sect1 id="rules-views">
-<Title>Views and the Rule Systemitle>
+<sect1 id="rules-views">
+<title>Views and the Rule Systemitle>
implementation through rules>
-<Para>
- Views in <ProductName>PostgreSQLame> are implemented
+<para>
+ Views in <productname>PostgreSQLame> are implemented
using the rule system. In fact, there is essentially no difference
between
-<ProgramListing>
+<programlisting>
CREATE VIEW myview AS SELECT * FROM mytab;
-ProgramListing>
+programlisting>
compared against the two commands
-<ProgramListing>
-CREATE TABLE myview (<Replaceable>same column list as mytabeplaceable>);
+<programlisting>
+CREATE TABLE myview (<replaceable>same column list as mytabeplaceable>);
CREATE RULE "_RETURN" AS ON SELECT TO myview DO INSTEAD
SELECT * FROM mytab;
-ProgramListing>
+programlisting>
because this is exactly what the CREATE VIEW
command does internally. This has some side effects. One of them
is that the information about a view in the
- <ProductName>PostgreSQLame> system catalogs is exactly
+ <productname>PostgreSQLame> system catalogs is exactly
the same as it is for a table. So for the parser, there is
absolutely no difference between a table and a view. They are the
same thing: relations.
-Para>
+para>
-<Sect2 id="rules-select">
-<Title>How SELECT Rules Workitle>
+<sect2 id="rules-select">
+<title>How SELECT Rules Workitle>
for SELECT
-<Para>
+<para>
Rules ON SELECT> are applied to all queries as the last step, even
if the command given is an INSERT,
UPDATE or DELETE. And they
have different semantics from rules on the other command types in that they modify the
query tree in place instead of creating a new one. So
SELECT rules are described first.
-Para>
+para>
-<Para>
+<para>
Currently, there can be only one action in an ON SELECT> rule, and it must
be an unconditional SELECT> action that is INSTEAD>. This restriction was
required to make rules safe enough to open them for ordinary users, and
it restricts ON SELECT> rules to act like views.
-Para>
+para>
-<Para>
+<para>
The examples for this chapter are two join views that do some
calculations and some more views using them in turn. One of the
two first views is customized later by adding rules for
this makes things harder to get into. But it's better to have one
example that covers all the points discussed step by step rather
than having many different ones that might mix up in mind.
-Para>
+para>
-<Para>
+<para>
For the example, we need a little min function that
returns the lower of 2 integer values. We create that as
-<ProgramListing>
+<programlisting>
CREATE FUNCTION min(integer, integer) RETURNS integer AS $$
SELECT CASE WHEN $1 < $2 THEN $1 ELSE $2 END
$$ LANGUAGE SQL STRICT;
-ProgramListing>
-Para>
+programlisting>
+para>
-<Para>
+<para>
The real tables we need in the first two rule system descriptions
are these:
-<ProgramListing>
+<programlisting>
CREATE TABLE shoe_data (
shoename text, -- primary key
sh_avail integer, -- available number of pairs
un_name text, -- primary key
un_fact real -- factor to transform to cm
);
-ProgramListing>
+programlisting>
As you can see, they represent shoe-store data.
-Para>
+para>
-<Para>
+<para>
The views are created as
-<ProgramListing>
+<programlisting>
CREATE VIEW shoe AS
SELECT sh.shoename,
sh.sh_avail,
WHERE rsl.sl_color = rsh.slcolor
AND rsl.sl_len_cm >= rsh.slminlen_cm
AND rsl.sl_len_cm <= rsh.slmaxlen_cm;
-ProgramListing>
+programlisting>
The CREATE VIEW command for the
shoelace view (which is the simplest one we
The action of our rule has a query qualification.
The action of the rule is one query tree that is a copy of the
SELECT statement in the view creation command.
-Para>
+para>
- <Note>
- <Para>
+ <note>
+ <para>
The two extra range
table entries for NEW> and OLD> (named *NEW*> and *OLD*> for
historical reasons in the printed query tree) you can see in
the pg_rewrite entry aren't of interest
for SELECT rules.
- Para>
- Note>
+ para>
+ note>
-<Para>
+<para>
Now we populate unit, shoe_data
and shoelace_data and run a simple query on a view:
-<ProgramListing>
+<programlisting>
INSERT INTO unit VALUES ('cm', 1.0);
INSERT INTO unit VALUES ('m', 100.0);
INSERT INTO unit VALUES ('inch', 2.54);
sl5 | 4 | brown | 1 | m | 100
sl6 | 0 | brown | 0.9 | m | 90
(8 rows)
-ProgramListing>
+programlisting>
rules. The SELECT * FROM shoelace was
interpreted by the parser and produced the query tree
-<ProgramListing>
+<programlisting>
SELECT shoelace.sl_name, shoelace.sl_avail,
shoelace.sl_color, shoelace.sl_len,
shoelace.sl_unit, shoelace.sl_len_cm
FROM shoelace shoelace;
-ProgramListing>
+programlisting>
and this is given to the rule system. The rule system walks through the
range table and checks if there are rules
shoelace (the only one up to now) it finds the
_RETURN rule with the query tree
-<ProgramListing>
+<programlisting>
SELECT s.sl_name, s.sl_avail,
s.sl_color, s.sl_len, s.sl_unit,
s.sl_len * u.un_fact AS sl_len_cm
FROM shoelace *OLD*, shoelace *NEW*,
shoelace_data s, unit u
WHERE s.sl_unit = u.un_name;
-ProgramListing>
-Para>
+programlisting>
+para>
-<Para>
+<para>
To expand the view, the rewriter simply creates a subquery range-table
entry containing the rule's action query tree, and substitutes this
range table entry for the original one that referenced the view. The
resulting rewritten query tree is almost the same as if you had typed
-<ProgramListing>
+<programlisting>
SELECT shoelace.sl_name, shoelace.sl_avail,
shoelace.sl_color, shoelace.sl_len,
shoelace.sl_unit, shoelace.sl_len_cm
s.sl_len * u.un_fact AS sl_len_cm
FROM shoelace_data s, unit u
WHERE s.sl_unit = u.un_name) shoelace;
-ProgramListing>
+programlisting>
There is one difference however: the subquery's range table has two
extra entries shoelace *OLD*> and shoelace *NEW*>. These entries don't
executor will still check that the user has proper privileges to access
the view, even though there's no direct use of the view in the rewritten
query.
-Para>
+para>
-<Para>
+<para>
That was the first rule applied. The rule system will continue checking
the remaining range-table entries in the top query (in this example there
are no more), and it will recursively check the range-table entries in
In this example, there are no rewrite rules for shoelace_data> or unit>,
so rewriting is complete and the above is the final result given to
the planner.
-Para>
+para>
-<Para>
+<para>
No we want to write a query that finds out for which shoes currently in the store
we have the matching shoelaces (color and length) and where the
total number of exactly matching pairs is greater or equal to two.
-<ProgramListing>
+<programlisting>
SELECT * FROM shoe_ready WHERE total_avail >= 2;
shoename | sh_avail | sl_name | sl_avail | total_avail
sh1 | 2 | sl1 | 5 | 2
sh3 | 4 | sl7 | 7 | 4
(2 rows)
-ProgramListing>
-Para>
+programlisting>
+para>
-<Para>
+<para>
The output of the parser this time is the query tree
-<ProgramListing>
+<programlisting>
SELECT shoe_ready.shoename, shoe_ready.sh_avail,
shoe_ready.sl_name, shoe_ready.sl_avail,
shoe_ready.total_avail
FROM shoe_ready shoe_ready
WHERE shoe_ready.total_avail >= 2;
-ProgramListing>
+programlisting>
The first rule applied will be the one for the
shoe_ready view and it results in the
query tree
-<ProgramListing>
+<programlisting>
SELECT shoe_ready.shoename, shoe_ready.sh_avail,
shoe_ready.sl_name, shoe_ready.sl_avail,
shoe_ready.total_avail
AND rsl.sl_len_cm >= rsh.slminlen_cm
AND rsl.sl_len_cm <= rsh.slmaxlen_cm) shoe_ready
WHERE shoe_ready.total_avail >= 2;
-ProgramListing>
+programlisting>
Similarly, the rules for shoe and
shoelace are substituted into the range table of
the subquery, leading to a three-level final query tree:
-<ProgramListing>
+<programlisting>
SELECT shoe_ready.shoename, shoe_ready.sh_avail,
shoe_ready.sl_name, shoe_ready.sl_avail,
shoe_ready.total_avail
AND rsl.sl_len_cm >= rsh.slminlen_cm
AND rsl.sl_len_cm <= rsh.slmaxlen_cm) shoe_ready
WHERE shoe_ready.total_avail > 2;
-ProgramListing>
+programlisting>
system doesn't have to concern itself with.
- <Note>
- <Para>
+ <note>
+ <para>
There is currently no recursion stopping mechanism for view rules
in the rule system (only for the other kinds of rules). This
doesn't hurt much, because the only way to push this into an
never happen if CREATE VIEW is used because for
the first CREATE VIEW, the second relation does
not exist and thus the first view cannot select from the second.
- Para>
- Note>
-Sect2>
+ para>
+ note>
+sect2>
-<Sect2>
-<Title>View Rules in Non-SELECT Statementsitle>
+<sect2>
+<title>View Rules in Non-SELECT Statementsitle>
-<Para>
+<para>
Two details of the query tree aren't touched in the description of
view rules above. These are the command type and the result relation.
In fact, view rules don't need this information.
-Para>
+para>
-<Para>
+<para>
There are only a few differences between a query tree for a
SELECT and one for any other
command. Obviously, they have a different command type and for a
t1> and t2> with columns a> and
b>, the query trees for the two statements
-<ProgramListing>
+<programlisting>
SELECT t2.b FROM t1, t2 WHERE t1.a = t2.a;
UPDATE t1 SET b = t2.b WHERE t1.a = t2.a;
-ProgramListing>
+programlisting>
are nearly identical. In particular:
- <ItemizedList>
- <ListItem>
- <Para>
+ <itemizedlist>
+ <listitem>
+ <para>
The range tables contain entries for the tables t1> and t2>.
- Para>
- ListItem>
+ para>
+ listitem>
- <ListItem>
- <Para>
+ <listitem>
+ <para>
The target lists contain one variable that points to column
b> of the range table entry for table t2>.
- Para>
- ListItem>
+ para>
+ listitem>
- <ListItem>
- <Para>
+ <listitem>
+ <para>
The qualification expressions compare the columns a> of both
range-table entries for equality.
- Para>
- ListItem>
+ para>
+ listitem>
- <ListItem>
- <Para>
+ <listitem>
+ <para>
The join trees show a simple join between t1> and t2>.
- Para>
- ListItem>
- ItemizedList>
+ para>
+ listitem>
+ itemizedlist>
the target list by the planner and the final query tree will read
as
-<ProgramListing>
+<programlisting>
UPDATE t1 SET a = t1.a, b = t2.b WHERE t1.a = t2.a;
-ProgramListing>
+programlisting>
and thus the executor run over the join will produce exactly the
same result set as a
-<ProgramListing>
+<programlisting>
SELECT t1.a, t2.b FROM t1, t2 WHERE t1.a = t2.a;
-ProgramListing>
+programlisting>
will do. But there is a little problem in
UPDATE: The executor does not care what the
this is an UPDATE, and it knows that this
result should go into table t1>. But which of the rows that are
there has to be replaced by the new row?
-Para>
+para>
-<Para>
+<para>
To resolve this problem, another entry is added to the target list
in UPDATE (and also in
DELETE) statements: the current tuple ID
original row of
t1> to be updated. After adding the CTID>
to the target list, the query actually looks like
-<ProgramListing>
+<programlisting>
SELECT t1.a, t2.b, t1.ctid FROM t1, t2 WHERE t1.a = t2.a;
-ProgramListing>
+programlisting>
- Now another detail of <ProductName>PostgreSQLame> enters
+ Now another detail of <productname>PostgreSQLame> enters
the stage. Old table rows aren't overwritten, and this
is why ROLLBACK is fast. In an UPDATE,
the new result row is inserted into the table (after stripping the
and current transaction ID. Thus the old row is hidden, and after
the transaction committed the vacuum cleaner can really move it
out.
-Para>
+para>
-<Para>
+<para>
Knowing all that, we can simply apply view rules in absolutely
the same way to any command. There is no difference.
-Para>
-Sect2>
+para>
+sect2>
-<Sect2>
-<
Title>The Power of Views in PostgreSQLitle>
+<sect2>
+<
title>The Power of Views in PostgreSQLitle>
-<Para>
+<para>
The above demonstrates how the rule system incorporates view
definitions into the original query tree. In the second example, a
simple SELECT from one view created a final
query tree that is a join of 4 tables (unit> was used twice with
different names).
-Para>
+para>
-<Para>
+<para>
The benefit of implementing views with the rule system is,
that the planner has all
the information about which tables have to be scanned plus the
The planner has to decide which is
the best path to execute the query, and the more information
the planner has, the better this decision can be. And
- the rule system as implemented in <ProductName>PostgreSQLame>
+ the rule system as implemented in <productname>PostgreSQLame>
ensures, that this is all information available about the query
up to that point.
-Para>
-Sect2>
+para>
+sect2>
-<Sect2 id="rules-views-update">
-<Title>Updating a Viewitle>
+<sect2 id="rules-views-update">
+<title>Updating a Viewitle>
-<Para>
+<para>
What happens if a view is named as the target relation for an
INSERT, UPDATE, or
DELETE? After doing the substitutions
relation points at a subquery range-table entry. This will not
work, so the rewriter throws an error if it sees it has produced
such a thing.
-Para>
+para>
-<Para>
+<para>
To change this, we can define rules that modify the behavior of
these kinds of commands. This is the topic of the next section.
-Para>
-Sect2>
+para>
+sect2>
-Sect1>
+sect1>
-<Sect1 id="rules-update">
-<Title>Rules on INSERT>, UPDATE>, and DELETE>itle>
+<sect1 id="rules-update">
+<title>Rules on INSERT>, UPDATE>, and DELETE>itle>
for DELETE
-<Para>
+<para>
Rules that are defined on INSERT>, UPDATE>,
and DELETE> are significantly different from the view rules
described in the previous section. First, their CREATE
RULE command allows more:
- <ItemizedList>
- <ListItem>
- <Para>
+ <itemizedlist>
+ <listitem>
+ <para>
They are allowed to have no action.
- Para>
- ListItem>
+ para>
+ listitem>
- <ListItem>
- <Para>
+ <listitem>
+ <para>
They can have multiple actions.
- Para>
- ListItem>
+ para>
+ listitem>
- <ListItem>
- <Para>
+ <listitem>
+ <para>
They can be INSTEAD> or ALSO> (default).
- Para>
- ListItem>
+ para>
+ listitem>
- <ListItem>
- <Para>
+ <listitem>
+ <para>
The pseudorelations NEW> and OLD> become useful.
- Para>
- ListItem>
+ para>
+ listitem>
- <ListItem>
- <Para>
+ <listitem>
+ <para>
They can have rule qualifications.
- Para>
- ListItem>
- ItemizedList>
+ para>
+ listitem>
+ itemizedlist>
Second, they don't modify the query tree in place. Instead they
create zero or more new query trees and can throw away the
original one.
-Para>
+para>
-<Sect2>
-<Title>How Update Rules Workitle>
+<sect2>
+<title>How Update Rules Workitle>
-<Para>
+<para>
Keep the syntax
-<ProgramListing>
+<programlisting>
CREATE RULE rule_name> AS ON event>
TO object> [WHERE rule_qualification>]
DO [ALSO|INSTEAD] [action> | (actions>) | NOTHING];
-ProgramListing>
+programlisting>
in mind.
In the following, update rules> means rules that are defined
on INSERT>, UPDATE>, or DELETE>.
-Para>
+para>
-<Para>
+<para>
Update rules get applied by the rule system when the result
relation and the command type of a query tree are equal to the
object and event given in the CREATE RULE command.
There can be zero (NOTHING> key word), one, or multiple actions.
To simplify, we will look at a rule with one action. This rule
can have a qualification or not and it can be INSTEAD> or ALSO> (default).
-Para>
+para>
-<Para>
+<para>
What is a rule qualification? It is a restriction that tells
when the actions of the rule should be done and when not. This
qualification can only reference the pseudorelations NEW> and/or OLD>,
which basically represent the relation that was given as object (but with a
special meaning).
-Para>
+para>
So we have four cases that produce the following query trees for
added to the list. Since only qualified INSTEAD> rules already add the
original query tree, we end up with either one or two output query trees
for a rule with one action.
-Para>
+para>
-<Para>
+<para>
For ON INSERT> rules, the original query (if not suppressed by INSTEAD>)
is done before any actions added by rules. This allows the actions to
see the inserted row(s). But for ON UPDATE> and ON
This ensures that the actions can see the to-be-updated or to-be-deleted
rows; otherwise, the actions might do nothing because they find no rows
matching their qualifications.
-Para>
+para>
-<Para>
+<para>
The query trees generated from rule actions are thrown into the
rewrite system again, and maybe more rules get applied resulting
in more or less query trees.
If after 100 iterations there are still update rules to apply, the
rule system assumes a loop over multiple rule definitions and reports
an error.
-Para>
+para>
-<Para>
+<para>
The query trees found in the actions of the
pg_rewrite system catalog are only
templates. Since they can reference the range-table entries for
a null value (for an INSERT). Any reference to OLD> is
replaced by a reference to the range-table entry that is the
result relation.
-Para>
+para>
-<Para>
+<para>
After the system is done applying update rules, it applies view rules to the
produced query tree(s). Views cannot insert new update actions so
there is no need to apply update rules to the output of view rewriting.
-Para>
+para>
-<Sect3>
-<Title>A First Rule Step by Stepitle>
+<sect3>
+<title>A First Rule Step by Stepitle>
-<Para>
+<para>
Say we want to trace changes to the sl_avail> column in the
shoelace_data relation. So we set up a log table
and a rule that conditionally writes a log entry when an
UPDATE is performed on
shoelace_data.
-<ProgramListing>
+<programlisting>
CREATE TABLE shoelace_log (
sl_name text, -- shoelace changed
sl_avail integer, -- new available value
current_user,
current_timestamp
);
-ProgramListing>
-Para>
+programlisting>
+para>
-<Para>
+<para>
Now someone does:
-<ProgramListing>
+<programlisting>
UPDATE shoelace_data SET sl_avail = 6 WHERE sl_name = 'sl7';
-ProgramListing>
+programlisting>
and we look at the log table:
-<ProgramListing>
+<programlisting>
SELECT * FROM shoelace_log;
sl_name | sl_avail | log_who | log_when
---------+----------+---------+----------------------------------
sl7 | 6 | Al | Tue Oct 20 16:14:45 1998 MET DST
(1 row)
-ProgramListing>
+programlisting>
That's what we expected. What happened in the background is the following.
The parser created the query tree
-<ProgramListing>
+<programlisting>
UPDATE shoelace_data SET sl_avail = 6
FROM shoelace_data shoelace_data
WHERE shoelace_data.sl_name = 'sl7';
-ProgramListing>
+programlisting>
There is a rule log_shoelace that is ON UPDATE> with the rule
qualification expression
-<ProgramListing>
+<programlisting>
NEW.sl_avail <> OLD.sl_avail
-ProgramListing>
+programlisting>
and the action
-<ProgramListing>
+<programlisting>
INSERT INTO shoelace_log VALUES (
*NEW*.sl_name, *NEW*.sl_avail,
current_user, current_timestamp )
FROM shoelace_data *NEW*, shoelace_data *OLD*;
-ProgramListing>
+programlisting>
(This looks a little strange since you can't normally write
INSERT ... VALUES ... FROM>. The FROM>
in the query tree for *NEW*> and *OLD*>.
These are needed so that they can be referenced by variables in
the INSERT command's query tree.)
-Para>
+para>
-<Para>
+<para>
The rule is a qualified ALSO> rule, so the rule system
has to return two query trees: the modified rule action and the original
query tree. In step 1, the range table of the original query is
incorporated into the rule's action query tree. This results in:
-<ProgramListing>
+<programlisting>
INSERT INTO shoelace_log VALUES (
*NEW*.sl_name, *NEW*.sl_avail,
current_user, current_timestamp )
FROM shoelace_data *NEW*, shoelace_data *OLD*,
shoelace_data shoelace_data;
-ProgramListing>
+programlisting>
In step 2, the rule qualification is added to it, so the result set
is restricted to rows where sl_avail> changes:
-<ProgramListing>
+<programlisting>
INSERT INTO shoelace_log VALUES (
*NEW*.sl_name, *NEW*.sl_avail,
current_user, current_timestamp )
FROM shoelace_data *NEW*, shoelace_data *OLD*,
shoelace_data shoelace_data
WHERE *NEW*.sl_avail <> *OLD*.sl_avail;
-ProgramListing>
+programlisting>
(This looks even stranger, since INSERT ... VALUES> doesn't have
a WHERE> clause either, but the planner and executor will have no
restricting the result set further to only the rows that would have been touched
by the original query:
-<ProgramListing>
+<programlisting>
INSERT INTO shoelace_log VALUES (
*NEW*.sl_name, *NEW*.sl_avail,
current_user, current_timestamp )
shoelace_data shoelace_data
WHERE *NEW*.sl_avail <> *OLD*.sl_avail
AND shoelace_data.sl_name = 'sl7';
-ProgramListing>
+programlisting>
original query tree or by the matching variable references
from the result relation:
-<ProgramListing>
+<programlisting>
INSERT INTO shoelace_log VALUES (
shoelace_data.sl_name, 6,
current_user, current_timestamp )
shoelace_data shoelace_data
WHERE 6 <> *OLD*.sl_avail
AND shoelace_data.sl_name = 'sl7';
-ProgramListing>
+programlisting>
Step 5 changes OLD> references into result relation references:
-<ProgramListing>
+<programlisting>
INSERT INTO shoelace_log VALUES (
shoelace_data.sl_name, 6,
current_user, current_timestamp )
shoelace_data shoelace_data
WHERE 6 <> shoelace_data.sl_avail
AND shoelace_data.sl_name = 'sl7';
-ProgramListing>
+programlisting>
original query tree. In short, the output from the rule system
is a list of two query trees that correspond to these statements:
-<ProgramListing>
+<programlisting>
INSERT INTO shoelace_log VALUES (
shoelace_data.sl_name, 6,
current_user, current_timestamp )
UPDATE shoelace_data SET sl_avail = 6
WHERE sl_name = 'sl7';
-ProgramListing>
+programlisting>
These are executed in this order, and that is exactly what
the rule was meant to do.
The substitutions and the added qualifications
ensure that, if the original query would be, say,
-<ProgramListing>
+<programlisting>
UPDATE shoelace_data SET sl_color = 'green'
WHERE sl_name = 'sl7';
-ProgramListing>
+programlisting>
no log entry would get written. In that case, the original query
tree does not contain a target list entry for
replaced by shoelace_data.sl_avail>. Thus, the extra
command generated by the rule is
-<ProgramListing>
+<programlisting>
INSERT INTO shoelace_log VALUES (
shoelace_data.sl_name, shoelace_data.sl_avail,
current_user, current_timestamp )
FROM shoelace_data
WHERE shoelace_data.sl_avail <> shoelace_data.sl_avail
AND shoelace_data.sl_name = 'sl7';
-ProgramListing>
+programlisting>
and that qualification will never be true.
It will also work if the original query modifies multiple rows. So
if someone issued the command
-<ProgramListing>
+<programlisting>
UPDATE shoelace_data SET sl_avail = 0
WHERE sl_color = 'black';
-ProgramListing>
+programlisting>
four rows in fact get updated (sl1>, sl2>, sl3>, and sl4>).
But sl3> already has sl_avail = 0>. In this case, the original
query trees qualification is different and that results
in the extra query tree
-<ProgramListing>
+<programlisting>
INSERT INTO shoelace_log
SELECT shoelace_data.sl_name, 0,
current_user, current_timestamp
FROM shoelace_data
WHERE 0 <> shoelace_data.sl_avail
AND shoelace_data.sl_color = 'black';
-ProgramListing>
+programlisting>
being generated by the rule. This query tree will surely insert
three new log entries. And that's absolutely correct.
-Para>
+para>
-<Para>
+<para>
Here we can see why it is important that the original query tree
is executed last. If the UPDATE had been
executed first, all the rows would have already been set to zero, so the
logging INSERT would not find any row where
0 <> shoelace_data.sl_avail.
-Para>
-Sect3>
+para>
+sect3>
-Sect2>
+sect2>
-<Sect2 id="rules-update-views">
-<Title>Cooperation with Viewsitle>
+<sect2 id="rules-update-views">
+<title>Cooperation with Viewsitle>
-<Para>
+<para>
A simple way to protect view relations from the mentioned
possibility that someone can try to run INSERT,
UPDATE, or DELETE on them is
to let those query trees get thrown away. So we create the rules
-<ProgramListing>
+<programlisting>
CREATE RULE shoe_ins_protect AS ON INSERT TO shoe
DO INSTEAD NOTHING;
CREATE RULE shoe_upd_protect AS ON UPDATE TO shoe
DO INSTEAD NOTHING;
CREATE RULE shoe_del_protect AS ON DELETE TO shoe
DO INSTEAD NOTHING;
-ProgramListing>
+programlisting>
If someone now tries to do any of these operations on the view
relation shoe, the rule system will
query trees will be empty and the whole query will become
nothing because there is nothing left to be optimized or
executed after the rule system is done with it.
-Para>
+para>
-<Para>
+<para>
A more sophisticated way to use the rule system is to
create rules that rewrite the query tree into one that
does the right operation on the real tables. To do that
on the shoelace view, we create
the following rules:
-<ProgramListing>
+<programlisting>
CREATE RULE shoelace_ins AS ON INSERT TO shoelace
DO INSTEAD
INSERT INTO shoelace_data VALUES (
DO INSTEAD
DELETE FROM shoelace_data
WHERE sl_name = OLD.sl_name;
-ProgramListing>
+programlisting>
insert the items from the part list, and one with a special
trick. The creation commands for these are:
-<ProgramListing>
+<programlisting>
CREATE TABLE shoelace_arrive (
arr_name text,
arr_quant integer
UPDATE shoelace
SET sl_avail = sl_avail + NEW.ok_quant
WHERE sl_name = NEW.ok_name;
-ProgramListing>
+programlisting>
Now you can fill the table shoelace_arrive with
the data from the parts list:
-<ProgramListing>
+<programlisting>
SELECT * FROM shoelace_arrive;
arr_name | arr_quant
sl6 | 20
sl8 | 20
(3 rows)
-ProgramListing>
+programlisting>
Take a quick look at the current data:
-<ProgramListing>
+<programlisting>
SELECT * FROM shoelace;
sl_name | sl_avail | sl_color | sl_len | sl_unit | sl_len_cm
sl5 | 4 | brown | 1 | m | 100
sl6 | 0 | brown | 0.9 | m | 90
(8 rows)
-ProgramListing>
+programlisting>
Now move the arrived shoelaces in:
-<ProgramListing>
+<programlisting>
INSERT INTO shoelace_ok SELECT * FROM shoelace_arrive;
-ProgramListing>
+programlisting>
and check the results:
-<ProgramListing>
+<programlisting>
SELECT * FROM shoelace ORDER BY sl_name;
sl_name | sl_avail | sl_color | sl_len | sl_unit | sl_len_cm
sl6 | 20 | Al | Tue Oct 20 19:25:16 1998 MET DST
sl8 | 21 | Al | Tue Oct 20 19:25:16 1998 MET DST
(4 rows)
-ProgramListing>
+programlisting>
transformation will be the last in this chapter. First, there is
the parser's output
-<ProgramListing>
+<programlisting>
INSERT INTO shoelace_ok
SELECT shoelace_arrive.arr_name, shoelace_arrive.arr_quant
FROM shoelace_arrive shoelace_arrive, shoelace_ok shoelace_ok;
-ProgramListing>
+programlisting>
Now the first rule shoelace_ok_ins is applied and turns this
into
-<ProgramListing>
+<programlisting>
UPDATE shoelace
SET sl_avail = shoelace.sl_avail + shoelace_arrive.arr_quant
FROM shoelace_arrive shoelace_arrive, shoelace_ok shoelace_ok,
shoelace_ok *OLD*, shoelace_ok *NEW*,
shoelace shoelace
WHERE shoelace.sl_name = shoelace_arrive.arr_name;
-ProgramListing>
+programlisting>
and throws away the original INSERT on
shoelace_ok. This rewritten query is passed to
the rule system again, and the second applied rule
shoelace_upd produces
-<ProgramListing>
+<programlisting>
UPDATE shoelace_data
SET sl_name = shoelace.sl_name,
sl_avail = shoelace.sl_avail + shoelace_arrive.arr_quant,
shoelace *NEW*, shoelace_data shoelace_data
WHERE shoelace.sl_name = shoelace_arrive.arr_name
AND shoelace_data.sl_name = shoelace.sl_name;
-ProgramListing>
+programlisting>
Again it's an INSTEAD> rule and the previous query tree is trashed.
Note that this query still uses the view shoelace.
But the rule system isn't finished with this step, so it continues
and applies the _RETURN rule on it, and we get
-<ProgramListing>
+<programlisting>
UPDATE shoelace_data
SET sl_name = s.sl_name,
sl_avail = s.sl_avail + shoelace_arrive.arr_quant,
shoelace_data s, unit u
WHERE s.sl_name = shoelace_arrive.arr_name
AND shoelace_data.sl_name = s.sl_name;
-ProgramListing>
+programlisting>
Finally, the rule log_shoelace gets applied,
producing the extra query tree
-<ProgramListing>
+<programlisting>
INSERT INTO shoelace_log
SELECT s.sl_name,
s.sl_avail + shoelace_arrive.arr_quant,
WHERE s.sl_name = shoelace_arrive.arr_name
AND shoelace_data.sl_name = s.sl_name
AND (s.sl_avail + shoelace_arrive.arr_quant) <> s.sl_avail;
-ProgramListing>
+programlisting>
After that the rule system runs out of rules and returns the
generated query trees.
So we end up with two final query trees that are equivalent to the
- <Acronym>SQLcronym> statements
+ <acronym>SQLcronym> statements
-<ProgramListing>
+<programlisting>
INSERT INTO shoelace_log
SELECT s.sl_name,
s.sl_avail + shoelace_arrive.arr_quant,
shoelace_data s
WHERE s.sl_name = shoelace_arrive.sl_name
AND shoelace_data.sl_name = s.sl_name;
-ProgramListing>
+programlisting>
The result is that data coming from one relation inserted into another,
changed into updates on a third, changed into updating
a fourth plus logging that final update in a fifth
gets reduced into two queries.
-Para>
+para>
-<Para>
+<para>
There is a little detail that's a bit ugly. Looking at the two
queries, it turns out that the shoelace_data
relation appears twice in the range table where it could
necessary. And the same redundant scan is done once more in the
UPDATE. But it was a really hard job to make
that all possible at all.
-Para>
+para>
-<Para>
+<para>
Now we make a final demonstration of the
- <ProductName>PostgreSQLame> rule system and its power.
+ <productname>PostgreSQLame> rule system and its power.
Say you add some shoelaces with extraordinary colors to your
database:
-<ProgramListing>
+<programlisting>
INSERT INTO shoelace VALUES ('sl9', 0, 'pink', 35.0, 'inch', 0.0);
INSERT INTO shoelace VALUES ('sl10', 1000, 'magenta', 40.0, 'inch', 0.0);
-ProgramListing>
+programlisting>
We would like to make a view to check which
shoelace entries do not fit any shoe in color.
The view for this is
-<ProgramListing>
+<programlisting>
CREATE VIEW shoelace_mismatch AS
SELECT * FROM shoelace WHERE NOT EXISTS
(SELECT shoename FROM shoe WHERE slcolor = sl_color);
-ProgramListing>
+programlisting>
Its output is
-<ProgramListing>
+<programlisting>
SELECT * FROM shoelace_mismatch;
sl_name | sl_avail | sl_color | sl_len | sl_unit | sl_len_cm
---------+----------+----------+--------+---------+-----------
sl9 | 0 | pink | 35 | inch | 88.9
sl10 | 1000 | magenta | 40 | inch | 101.6
-ProgramListing>
+programlisting>
Now we want to set it up so that mismatching shoelaces that are
not in stock are deleted from the database.
- To make it a little harder for <ProductName>PostgreSQLame>,
+ To make it a little harder for <productname>PostgreSQLame>,
we don't delete it directly. Instead we create one more view
-<ProgramListing>
+<programlisting>
CREATE VIEW shoelace_can_delete AS
SELECT * FROM shoelace_mismatch WHERE sl_avail = 0;
-ProgramListing>
+programlisting>
and do it this way:
-<ProgramListing>
+<programlisting>
DELETE FROM shoelace WHERE EXISTS
(SELECT * FROM shoelace_can_delete
WHERE sl_name = shoelace.sl_name);
-ProgramListing>
+programlisting>
Voilà:
-<ProgramListing>
+<programlisting>
SELECT * FROM shoelace;
sl_name | sl_avail | sl_color | sl_len | sl_unit | sl_len_cm
sl5 | 4 | brown | 1 | m | 100
sl6 | 20 | brown | 0.9 | m | 90
(9 rows)
-ProgramListing>
+programlisting>
gets rewritten into
one single query tree that deletes the requested data
from a real table.
-Para>
+para>
-<Para>
+<para>
There are probably only a few situations out in the real world
where such a construct is necessary. But it makes you feel
comfortable that it works.
-Para>
-Sect2>
+para>
+sect2>
-Sect1>
+sect1>
-<Sect1 id="rules-privileges">
-<Title>Rules and Privilegesitle>
+<sect1 id="rules-privileges">
+<title>Rules and Privilegesitle>
with views
-<Para>
- Due to rewriting of queries by the <ProductName>PostgreSQLame>
+<para>
+ Due to rewriting of queries by the <productname>PostgreSQLame>
rule system, other tables/views than those used in the original
query get accessed. When update rules are used, this can include write access
to tables.
-Para>
+para>
-<Para>
+<para>
Rewrite rules don't have a separate owner. The owner of
a relation (table or view) is automatically the owner of the
rewrite rules that are defined for it.
- The <ProductName>PostgreSQLame> rule system changes the
+ The <productname>PostgreSQLame> rule system changes the
behavior of the default access control system. Relations that
are used due to rules get checked against the
privileges of the rule owner, not the user invoking the rule.
This means that a user only needs the required privileges
for the tables/views that he names explicitly in his queries.
-Para>
+para>
-<Para>
+<para>
For example: A user has a list of phone numbers where some of
them are private, the others are of interest for the secretary of the office.
He can construct the following:
-<ProgramListing>
+<programlisting>
CREATE TABLE phone_data (person text, phone text, private boolean);
CREATE VIEW phone_number AS
SELECT person, phone FROM phone_data WHERE NOT private;
GRANT SELECT ON phone_number TO secretary;
-ProgramListing>
+programlisting>
Nobody except him (and the database superusers) can access the
phone_data> table. But because of the GRANT>,
phone_number> is also performed, but this is done
against the invoking user, so nobody but the user and the
secretary can use it.
-Para>
+para>
-<Para>
+<para>
The privileges are checked rule by rule. So the secretary is for now the
only one who can see the public phone numbers. But the secretary can setup
another view and grant access to that to the public. Then, anyone
And as soon as the user will notice, that the secretary opened
his phone_number> view, he can revoke his access. Immediately, any
access to the secretary's view would fail.
-Para>
+para>
-<Para>
+<para>
One might think that this rule-by-rule checking is a security
hole, but in fact it isn't. But if it did not work this way, the secretary
could set up a table with the same columns as phone_number> and
GRANT command means, I trust you
.
If someone you trust does the thing above, it's time to
think it over and then use REVOKE.
-Para>
+para>
-<Para>
+<para>
This mechanism also works for update rules. In the examples of
the previous section, the owner of the tables in the example
database could grant the privileges SELECT>,
write log entries will still be executed successfully, and that
other user could see the log entries. But he cannot create fake
entries, nor could he manipulate or remove existing ones.
-Para>
-Sect1>
+para>
+sect1>
-<Sect1 id="rules-status">
-<Title>Rules and Command Statusitle>
+<sect1 id="rules-status">
+<title>Rules and Command Statusitle>
-<Para>
- The <ProductName>PostgreSQLame> server returns a command
+<para>
+ The <productname>PostgreSQLame> server returns a command
status string, such as INSERT 149592 1>, for each
command it receives. This is simple enough when there are no rules
involved, but what happens when the query is rewritten by rules?
-Para>
+para>
-<Para>
+<para>
Rules affect the command status as follows:
(This system was established in
PostgreSQL> 7.3.
In versions before that, the command status might show different
results when rules exist.)
-Para>
+para>
-<Para>
+<para>
The programmer can ensure that any desired INSTEAD> rule is the one
that sets the command status in the second case, by giving it the
alphabetically last rule name among the active rules, so that it
gets applied last.
-Para>
-Sect1>
+para>
+sect1>
-<Sect1 id="rules-triggers">
-<Title>Rules versus Triggersitle>
+<sect1 id="rules-triggers">
+<title>Rules versus Triggersitle>
compared with rules
-<Para>
+<para>
Many things that can be done using triggers can also be
- implemented using the <ProductName>PostgreSQLame>
+ implemented using the <productname>PostgreSQLame>
rule system. One of the things that cannot be implemented by
rules are some kinds of constraints, especially foreign keys. It is possible
to place a qualified rule that rewrites a command to NOTHING>
not a good idea. If checks for valid values are required,
and in the case of an invalid value an error message should
be generated, it must be done by a trigger.
-Para>
+para>
-<Para>
+<para>
On the other hand, a trigger that is fired on
INSERT on a view can do the same as a rule: put
the data somewhere else and suppress the insert in the view. But
DELETE, because there is no real data in the
view relation that could be scanned, and thus the trigger would
never get called. Only a rule will help.
-Para>
+para>
-<Para>
+<para>
For the things that can be implemented by both, which is best
depends on the usage of the database.
A trigger is fired for any affected row once. A rule manipulates
called for every single row and must execute its operations
many times. However, the trigger approach is conceptually far
simpler than the rule approach, and is easier for novices to get right.
-Para>
+para>
-<Para>
+<para>
Here we show an example of how the choice of rules versus triggers
plays out in one situation. There are two tables:
-<ProgramListing>
+<programlisting>
CREATE TABLE computer (
hostname text, -- indexed
manufacturer text -- indexed
software text, -- indexed
hostname text -- indexed
);
-ProgramListing>
+programlisting>
Both tables have many thousands of rows and the indexes on
hostname> are unique. The rule or trigger should
implement a constraint that deletes rows from software>
that reference a deleted computer. The trigger would use this command:
-<ProgramListing>
+<programlisting>
DELETE FROM software WHERE hostname = $1;
-ProgramListing>
+programlisting>
Since the trigger is called for each individual row deleted from
computer>, it can prepare and save the plan for this
command and pass the hostname> value in the
parameter. The rule would be written as
-<ProgramListing>
+<programlisting>
CREATE RULE computer_del AS ON DELETE TO computer
DO DELETE FROM software WHERE hostname = OLD.hostname;
-ProgramListing>
+programlisting>
Now we look at different types of deletes. In the case of a
-<ProgramListing>
+<programlisting>
DELETE FROM computer WHERE hostname = 'mypc.local.net';
-ProgramListing>
+programlisting>
the table computer> is scanned by index (fast), and the
command issued by the trigger would also use an index scan (also fast).
The extra command from the rule would be
-<ProgramListing>
+<programlisting>
DELETE FROM software WHERE computer.hostname = 'mypc.local.net'
AND software.hostname = computer.hostname;
-ProgramListing>
+programlisting>
Since there are appropriate indexes setup, the planner
will create a plan of
old>. There are two possible commands to do that. One
is
-<ProgramListing>
+<programlisting>
DELETE FROM computer WHERE hostname >= 'old'
AND hostname < 'ole'
-ProgramListing>
+programlisting>
The command added by the rule will be
-<ProgramListing>
+<programlisting>
DELETE FROM software WHERE computer.hostname >= 'old' AND computer.hostname < 'ole'
AND software.hostname = computer.hostname;
-ProgramListing>
+programlisting>
with the plan
The other possible command is
-<ProgramListing>
+<programlisting>
DELETE FROM computer WHERE hostname ~ '^old';
-ProgramListing>
+programlisting>
which results in the following executing plan for the command
added by the rule:
the table software> whether the rule will still be faster in the
sequential scan situation. 2000 command executions from the trigger over the SPI
manager take some time, even if all the index blocks will soon be in the cache.
-Para>
+para>
-<Para>
+<para>
The last command we look at is
-<ProgramListing>
+<programlisting>
DELETE FROM computer WHERE manufacurer = 'bim';
-ProgramListing>
+programlisting>
Again this could result in many rows to be deleted from
computer>. So the trigger will again run many commands
through the executor. The command generated by the rule will be
-<ProgramListing>
+<programlisting>
DELETE FROM software WHERE computer.manufacurer = 'bim'
AND software.hostname = computer.hostname;
-ProgramListing>
+programlisting>
The plan for that command will again be the nested loop over two
index scans, only using a different index on computer>:
-<ProgramListing>
+<programlisting>
Nestloop
-> Index Scan using comp_manufidx on computer
-> Index Scan using soft_hostidx on software
-ProgramListing>
+programlisting>
In any of these cases, the extra commands from the rule system
will be more or less independent from the number of affected rows
in a command.
-Para>
+para>
-<Para>
+<para>
Another situation is cases on UPDATE where it depends on the
change of an attribute if an action should be performed or
- not. In <ProductName>PostgreSQLame> version 6.4, the
+ not. In <productname>PostgreSQLame> version 6.4, the
attribute specification for rule events is disabled (it will have
its comeback latest in 6.5, maybe earlier
- stay tuned). So for now the only way to
target list and will suppress the additional query completely
if the attribute isn't touched. So the rule, qualified or not,
will only do its scans if there ever could be something to do.
-Para>
+para>
]]>
-<Para>
+<para>
The summary is, rules will only be significantly slower than
triggers if their actions result in large and badly qualified
joins, a situation where the planner fails.
-Para>
-Sect1>
+para>
+sect1>
-Chapter>
+chapter>
-<Chapter Id="runtime">
- <Title>Server Run-time Environmentitle>
+<chapter Id="runtime">
+ <title>Server Run-time Environmentitle>
- <Para>
+ <para>
This chapter discusses how to set up and run the database server
and its interactions with the operating system.
- <Title>Run-time Configurationitle>
+ <title>Run-time Configurationitle>
-Chapter>
+chapter>
- In <ProductName>PostgreSQLame> versions before 7.4,
+ In <productname>PostgreSQLame> versions before 7.4,
sorting and grouping operations would implicitly use operators named
=>, <>, and >>. The new
behavior of relying on default operator classes avoids having to make
user-defined
- <Para>
+ <para>
Every operator is syntactic sugar
for a call to an
underlying function that does the real work; so you must
first create the underlying function before you can create
that helps the query planner optimize queries that use the
operator. The next section will be devoted to explaining
that additional information.
- Para>
+ para>
- <Para>
+ <para>
PostgreSQL supports left unary, right
unary, and binary operators. Operators can be
overloaded;
overloadingoperators
that have different numbers and types of operands. When a query is
executed, the system determines the operator to call from the
number and types of the provided operands.
- Para>
+ para>
- <Para>
+ <para>
Here is an example of creating an operator for adding two complex
numbers. We assume we've already created the definition of type
complex (see ). First we need a
function that does the work, then we can define the operator:
-<ProgramListing>
+<programlisting>
CREATE FUNCTION complex_add(complex, complex)
RETURNS complex
AS 'filename', 'complex_add'
procedure = complex_add,
commutator = +
);
-ProgramListing>
- Para>
+programlisting>
+ para>
- <Para>
+ <para>
Now we could execute a query like this:
(5.2,6.05)
(133.42,144.95)
- Para>
+ para>
- <Para>
+ <para>
We've shown how to create a binary operator here. To create unary
operators, just omit one of leftarg> (for left unary) or
rightarg> (for right unary). The procedure>
clause shown in the example is an optional hint to the query
optimizer. Further details about commutator> and other
optimizer hints appear in the next section.
- Para>
+ para>
Operator Optimization Information
- A <ProductName>PostgreSQLame> operator definition can include
+ A <productname>PostgreSQLame> operator definition can include
several optional clauses that tell the system useful things about how
the operator behaves. These clauses should be provided whenever
appropriate, because they can make for considerable speedups in execution
Additional optimization clauses might be added in future versions of
- <ProductName>PostgreSQLame>. The ones described here are all
+ <productname>PostgreSQLame>. The ones described here are all
the ones that release &version; understands.
The left operand type of a commutable operator is the same as the
right operand type of its commutator, and vice versa. So the name of
- the commutator operator is all that <ProductName>PostgreSQLame>
+ the commutator operator is all that <productname>PostgreSQLame>
needs to be given to look up the commutator, and that's all that needs to
be provided in the COMMUTATOR> clause.
index scan unless it can determine how to flip the clause around to
tab2.y = tab1.x>, because the index-scan machinery expects
to see the indexed column on the left of the operator it is given.
- <ProductName>PostgreSQLame> will not> simply
+ <productname>PostgreSQLame> will not> simply
assume that this is a valid transformation — the creator of the
=> operator must specify that it is valid, by marking the
operator with commutator information.
One way is to omit the COMMUTATOR> clause in the first operator that
you define, and then provide one in the second operator's definition.
- Since <ProductName>PostgreSQLame> knows that commutative
+ Since <productname>PostgreSQLame> knows that commutative
operators come in pairs, when it sees the second definition it will
automatically go back and fill in the missing COMMUTATOR> clause in
the first definition.
The other, more straightforward way is just to include COMMUTATOR> clauses
- in both definitions. When <ProductName>PostgreSQLame> processes
+ in both definitions. When <productname>PostgreSQLame> processes
the first definition and realizes that COMMUTATOR> refers to a nonexistent
operator, the system will make a dummy entry for that operator in the
system catalog. This dummy entry will have valid data only
for the operator name, left and right operand types, and result type,
- since that's all that <ProductName>PostgreSQLame> can deduce
+ since that's all that <productname>PostgreSQLame> can deduce
at this point. The first operator's catalog entry will link to this
dummy entry. Later, when you define the second operator, the system
updates the dummy entry with the additional information from the second
binary operators that return boolean>. The idea behind a restriction
selectivity estimator is to guess what fraction of the rows in a
table will satisfy a WHERE-clause condition of the form
-<ProgramListing>
+<programlisting>
column OP constant
-ProgramListing>
+programlisting>
for the current operator and a particular constant value.
This assists the optimizer by
giving it some idea of how many rows will be eliminated by WHERE>
binary operators that return boolean. The idea behind a join
selectivity estimator is to guess what fraction of the rows in a
pair of tables will satisfy a WHERE>-clause condition of the form
-<ProgramListing>
+<programlisting>
table1.column1 OP table2.column2
-ProgramListing>
+programlisting>
for the current operator. As with the RESTRICT clause, this helps
the optimizer very substantially by letting it figure out which
of several possible join sequences is likely to take the least work.
- In <ProductName>PostgreSQLame> versions before 7.3,
+ In <productname>PostgreSQLame> versions before 7.3,
the MERGES> shorthand was not available: to make a
merge-joinable operator one had to write both SORT1> and
SORT2> explicitly. Also, the LTCMP> and
document all new features
update help output from inside the programs
doc/src/sgml/ref manual pages
- convert any literal "<" and ">" characters
+ convert any literal "<" and ">" characters, use tools/find_gt_lt
* Ports
update config.guess and config.sub at the start of beta
--- /dev/null
+grep '[^]a-z0-9"/!-]>' *.sgml ref/*.sgml
+grep '<[^]a-z0-9"/!-]' *.sgml ref/*.sgml