バージョンごとのドキュメント一覧

41.2. ビューとルールシステム #

<title>Views and the Rule System</title>

Views in <productname>PostgreSQL</productname> are implemented using the rule system. A view is basically an empty table (having no actual storage) with an <literal>ON SELECT DO INSTEAD</literal> rule. Conventionally, that rule is named <literal>_RETURN</literal>. So a view like PostgreSQLにおけるビューはルールシステムを使って実装されています。 ビューは基本的に、ON SELECT DO INSTEADルールのある空のテーブルです(実際の記憶域はありません)。 慣例的に、そのルールは_RETURNという名前です。 ですので、以下のようなビューは

CREATE VIEW myview AS SELECT * FROM mytab;

is very nearly the same thing as 以下と同じものに非常に近いです。

CREATE TABLE myview (same column list as mytab);
CREATE RULE "_RETURN" AS ON SELECT TO myview DO INSTEAD
    SELECT * FROM mytab;

although you can't actually write that, because tables are not allowed to have <literal>ON SELECT</literal> rules. ですが、テーブルはON SELECTルールを持つことができませんので、これを実際には書くことはできません。

A view can also have other kinds of <literal>DO INSTEAD</literal> rules, allowing <command>INSERT</command>, <command>UPDATE</command>, or <command>DELETE</command> commands to be performed on the view despite its lack of underlying storage. This is discussed further below, in <xref linkend="rules-views-update"/>. ビューには他の種類のDO INSTEADルールもあり、基礎となる記憶域がないにもかかわらず、ビューに対してINSERTUPDATE、またはDELETEコマンドを実行できるようにします。 これについては、以下の41.2.4でさらに説明します。

41.2.1. SELECTルールの動き #

<title>How <command>SELECT</command> Rules Work</title>

Rules <literal>ON SELECT</literal> are applied to all queries as the last step, even if the command given is an <command>INSERT</command>, <command>UPDATE</command> or <command>DELETE</command>. 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 <command>SELECT</command> rules are described first. たとえコマンドがINSERTUPDATEDELETEなどであっても、ON SELECTルールは全ての問い合わせに対し最後に適用されます。 そして、このルールは他のコマンド種類のルールと異なるセマンティクスを持っていて、問い合わせツリーを新規に生成せずに、そこにあるものを修正します。 したがってSELECTルールを一番初めに記述します。

Currently, there can be only one action in an <literal>ON SELECT</literal> rule, and it must be an unconditional <command>SELECT</command> action that is <literal>INSTEAD</literal>. This restriction was required to make rules safe enough to open them for ordinary users, and it restricts <literal>ON SELECT</literal> rules to act like views. 現在のところ、ON SELECTルールでは1つのアクションしか許されず、それはINSTEADである無条件のSELECTアクションでなければいけません。 この制約は、一般のユーザが何をしても、ルールシステムが堅牢であるために必要であり、ON SELECTのルールはビュー同様の動作に限定されます。

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 <command>INSERT</command>, <command>UPDATE</command>, and <command>DELETE</command> operations so that the final result will be a view that behaves like a real table with some magic functionality. This is not such a simple example to start from and 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. 本章の例として挙げているのは、ちょっとした演算をする2つの結合のビューと、次にこれらの機能を利用するいくつかのビューです。 初めの2つのビューのうちの1つは、INSERTUPDATEDELETE操作に対するルールを後で追加することでカスタマイズされ、最終結果は何らかの魔法の機能によりあたかも実テーブルのように振舞うビューになります。 初めて学ぶための例としては決して簡単ではなく先に進むことを躊躇させるかもしれませんが、多くの別々の例を持ち出して頭の混乱を招くよりも、全ての論点をステップごとに追う1つの例を挙げる方が良いでしょう。

The real tables we need in the first two rule system descriptions are these: 最初の2つのルールシステムの説明で必要とする実テーブルを以下に示します。


CREATE TABLE shoe_data (
    shoename   text,          &#45;- primary key
    sh_avail   integer,       &#45;- available number of pairs
    slcolor    text,          &#45;- preferred shoelace color
    slminlen   real,          &#45;- minimum shoelace length
    slmaxlen   real,          &#45;- maximum shoelace length
    slunit     text           &#45;- length unit
);

CREATE TABLE shoe_data (
    shoename   text,          -- 主キー
    sh_avail   integer,       -- 在庫
    slcolor    text,          -- 望ましい靴紐の色
    slminlen   real,          -- 靴紐の最短サイズ
    slmaxlen   real,          -- 靴紐の最長サイズ
    slunit     text           -- 長さの単位
);


CREATE TABLE shoelace_data (
    sl_name    text,          &#45;- primary key
    sl_avail   integer,       &#45;- available number of pairs
    sl_color   text,          &#45;- shoelace color
    sl_len     real,          &#45;- shoelace length
    sl_unit    text           &#45;- length unit
);

CREATE TABLE shoelace_data (
    sl_name    text,          -- 主キー
    sl_avail   integer,       -- 在庫
    sl_color   text,          -- 靴紐の色
    sl_len     real,          -- 靴紐の長さ
    sl_unit    text           -- 長さの単位
);


CREATE TABLE unit (
    un_name    text,          &#45;- primary key
    un_fact    real           &#45;- factor to transform to cm
);

CREATE TABLE unit (
    un_name    text,          -- 主キー
    un_fact    real           -- cmに変換するファクタ
);

As you can see, they represent shoe-store data. これでわかるかもしれませんが、これらは靴屋のデータを表しています。

The views are created as: ビューを以下のように作成します。

CREATE VIEW shoe AS
    SELECT sh.shoename,
           sh.sh_avail,
           sh.slcolor,
           sh.slminlen,
           sh.slminlen * un.un_fact AS slminlen_cm,
           sh.slmaxlen,
           sh.slmaxlen * un.un_fact AS slmaxlen_cm,
           sh.slunit
      FROM shoe_data sh, unit un
     WHERE sh.slunit = un.un_name;

CREATE VIEW shoelace AS
    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_data s, unit u
     WHERE s.sl_unit = u.un_name;

CREATE VIEW shoe_ready AS
    SELECT rsh.shoename,
           rsh.sh_avail,
           rsl.sl_name,
           rsl.sl_avail,
           least(rsh.sh_avail, rsl.sl_avail) AS total_avail
      FROM shoe rsh, shoelace rsl
     WHERE rsl.sl_color = rsh.slcolor
       AND rsl.sl_len_cm >= rsh.slminlen_cm
       AND rsl.sl_len_cm <= rsh.slmaxlen_cm;

The <command>CREATE VIEW</command> command for the <literal>shoelace</literal> view (which is the simplest one we have) will create a relation <literal>shoelace</literal> and an entry in <structname>pg_rewrite</structname> that tells that there is a rewrite rule that must be applied whenever the relation <literal>shoelace</literal> is referenced in a query's range table. The rule has no rule qualification (discussed later, with the non-<command>SELECT</command> rules, since <command>SELECT</command> rules currently cannot have them) and it is <literal>INSTEAD</literal>. Note that rule qualifications are not the same as query qualifications. The action of our rule has a query qualification. The action of the rule is one query tree that is a copy of the <command>SELECT</command> statement in the view creation command. shoelaceビュー(今ある一番簡単なビュー)用のCREATE VIEWコマンドは、shoelaceリレーションと、問い合わせ範囲テーブルの中でshoelaceリレーションが参照される時はいつでも、適用されるべき書き換えルールの存在を示す項目をpg_rewriteに作ります。 ルールはルール条件(SELECTルールは現在持つことができませんので、非SELECTルールのところで取り上げます)を持たないINSTEADです。 ルール条件は問い合わせ条件とは異なることに注意してください! ルールアクションは問い合わせ条件を持っています。 このルールアクションは、ビュー作成コマンド内のSELECTのコピーである、1つの問い合わせツリーです。

注記

The two extra range table entries for <literal>NEW</literal> and <literal>OLD</literal> that you can see in the <structname>pg_rewrite</structname> entry aren't of interest for <command>SELECT</command> rules. pg_rewrite項目のNEWOLDに対する2つの特別な範囲テーブル項目はSELECTルールには関係ありません。

Now we populate <literal>unit</literal>, <literal>shoe_data</literal> and <literal>shoelace_data</literal> and run a simple query on a view: ではここでunitshoe_datashoelace_dataにデータを入れ、ビューに簡単な問い合わせを行います。

INSERT INTO unit VALUES ('cm', 1.0);
INSERT INTO unit VALUES ('m', 100.0);
INSERT INTO unit VALUES ('inch', 2.54);

INSERT INTO shoe_data VALUES ('sh1', 2, 'black', 70.0, 90.0, 'cm');
INSERT INTO shoe_data VALUES ('sh2', 0, 'black', 30.0, 40.0, 'inch');
INSERT INTO shoe_data VALUES ('sh3', 4, 'brown', 50.0, 65.0, 'cm');
INSERT INTO shoe_data VALUES ('sh4', 3, 'brown', 40.0, 50.0, 'inch');

INSERT INTO shoelace_data VALUES ('sl1', 5, 'black', 80.0, 'cm');
INSERT INTO shoelace_data VALUES ('sl2', 6, 'black', 100.0, 'cm');
INSERT INTO shoelace_data VALUES ('sl3', 0, 'black', 35.0 , 'inch');
INSERT INTO shoelace_data VALUES ('sl4', 8, 'black', 40.0 , 'inch');
INSERT INTO shoelace_data VALUES ('sl5', 4, 'brown', 1.0 , 'm');
INSERT INTO shoelace_data VALUES ('sl6', 0, 'brown', 0.9 , 'm');
INSERT INTO shoelace_data VALUES ('sl7', 7, 'brown', 60 , 'cm');
INSERT INTO shoelace_data VALUES ('sl8', 1, 'brown', 40 , 'inch');

SELECT * FROM shoelace;

 sl_name   | sl_avail | sl_color | sl_len | sl_unit | sl_len_cm
-----------+----------+----------+--------+---------+-----------
 sl1       |        5 | black    |     80 | cm      |        80
 sl2       |        6 | black    |    100 | cm      |       100
 sl7       |        7 | brown    |     60 | cm      |        60
 sl3       |        0 | black    |     35 | inch    |      88.9
 sl4       |        8 | black    |     40 | inch    |     101.6
 sl8       |        1 | brown    |     40 | inch    |     101.6
 sl5       |        4 | brown    |      1 | m       |       100
 sl6       |        0 | brown    |    0.9 | m       |        90
(8 rows)

This is the simplest <command>SELECT</command> you can do on our views, so we take this opportunity to explain the basics of view rules. The <literal>SELECT * FROM shoelace</literal> was interpreted by the parser and produced the query tree: これは、ビューに対する最も簡単なSELECTですので、この機会にビュールールの基本を説明します。 SELECT * FROM shoelaceはパーサによって処理され、次の問い合わせツリーが生成されます。

SELECT shoelace.sl_name, shoelace.sl_avail,
       shoelace.sl_color, shoelace.sl_len,
       shoelace.sl_unit, shoelace.sl_len_cm
  FROM shoelace shoelace;

and this is given to the rule system. The rule system walks through the range table and checks if there are rules for any relation. When processing the range table entry for <literal>shoelace</literal> (the only one up to now) it finds the <literal>_RETURN</literal> rule with the query tree: このツリーがルールシステムに伝えられます。 ルールシステムは範囲テーブルを参照し、何らかのリレーションに対してルールが存在するか調べます。 shoelace(現時点では唯一のビュー)についての範囲テーブル項目を処理する際、問い合わせツリーで_RETURNルールを検出します。

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;

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: ビューを展開するために、リライタは単純にルールのアクション問い合わせツリーを持つ副問い合わせ範囲テーブルの項目を作り、ビューを参照していた元の範囲テーブルを置き換えます。 書き換えられた結果の問い合わせツリーは、以下のように入力した場合とほぼ同じです。

SELECT shoelace.sl_name, shoelace.sl_avail,
       shoelace.sl_color, shoelace.sl_len,
       shoelace.sl_unit, shoelace.sl_len_cm
  FROM (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_data s, unit u
         WHERE s.sl_unit = u.un_name) shoelace;

There is one difference however: the subquery's range table has two extra entries <literal>shoelace old</literal> and <literal>shoelace new</literal>. These entries don't participate directly in the query, since they aren't referenced by the subquery's join tree or target list. The rewriter uses them to store the access privilege check information that was originally present in the range-table entry that referenced the view. In this way, the 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. しかし1つだけ違いがあります。 副問い合わせの範囲テーブルが2つの余分な項目shoelace oldshoelace newを持っていることです。 これらの項目は副問い合わせの結合ツリーや目的リストで参照されませんので、直接問い合わせでは使われません。 リライタはそれらを使用して、ビューを参照した範囲テーブルの項目に元々存在したアクセス権限確認情報を格納します。 この方法で、書き換えられた問い合わせで直接ビューを使用していなくても、エグゼキュータはユーザがそのビューにアクセスするための正しい権限を持っているか確認します。

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 the added subquery to see if any of them reference views. (But it won't expand <literal>old</literal> or <literal>new</literal> &mdash; otherwise we'd have infinite recursion!) In this example, there are no rewrite rules for <literal>shoelace_data</literal> or <literal>unit</literal>, so rewriting is complete and the above is the final result given to the planner. これが最初に適用されるルールです。 ルールシステムは最上位の問い合わせの残り(この例ではこれ以上ありません)の範囲テーブルの項目をチェックし続けます。 そしてルールシステムは、追加された副問い合わせの範囲テーブルの項目がビューを参照するかを再帰的に確認します (しかしoldnewは展開しません。 そうでなければ無限再帰になってしまいます!)。 この例ではshoelace_dataunit用の書き換えルールはありません。 ですから書き換えは完結し、上記がプランナに渡される最終的な結果となります。

Now 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 than or equal to two. さて、店に置いてある靴紐(の色とサイズ)に一致する靴が店にあるか、完全に一致する靴の在庫数が2以上あるかどうかを把握する問い合わせを書いてみましょう。

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)

The output of the parser this time is the query tree: 今回のパーサの出力は以下の問い合わせツリーです。

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;

The first rule applied will be the one for the <literal>shoe_ready</literal> view and it results in the query tree: 最初に適用されるルールはshoe_readyビュー用のもので、問い合わせツリーにおける結果は以下のようになります。

SELECT shoe_ready.shoename, shoe_ready.sh_avail,
       shoe_ready.sl_name, shoe_ready.sl_avail,
       shoe_ready.total_avail
  FROM (SELECT rsh.shoename,
               rsh.sh_avail,
               rsl.sl_name,
               rsl.sl_avail,
               least(rsh.sh_avail, rsl.sl_avail) AS total_avail
          FROM shoe rsh, shoelace rsl
         WHERE rsl.sl_color = rsh.slcolor
           AND rsl.sl_len_cm >= rsh.slminlen_cm
           AND rsl.sl_len_cm <= rsh.slmaxlen_cm) shoe_ready
 WHERE shoe_ready.total_avail >= 2;

Similarly, the rules for <literal>shoe</literal> and <literal>shoelace</literal> are substituted into the range table of the subquery, leading to a three-level final query tree: 同じように、shoeshoelace用のルールは副問い合わせの範囲テーブルとして代用され、3レベルの最終問い合わせツリーへと導きます。

SELECT shoe_ready.shoename, shoe_ready.sh_avail,
       shoe_ready.sl_name, shoe_ready.sl_avail,
       shoe_ready.total_avail
  FROM (SELECT rsh.shoename,
               rsh.sh_avail,
               rsl.sl_name,
               rsl.sl_avail,
               least(rsh.sh_avail, rsl.sl_avail) AS total_avail
          FROM (SELECT sh.shoename,
                       sh.sh_avail,
                       sh.slcolor,
                       sh.slminlen,
                       sh.slminlen * un.un_fact AS slminlen_cm,
                       sh.slmaxlen,
                       sh.slmaxlen * un.un_fact AS slmaxlen_cm,
                       sh.slunit
                  FROM shoe_data sh, unit un
                 WHERE sh.slunit = un.un_name) rsh,
               (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_data s, unit u
                 WHERE s.sl_unit = u.un_name) rsl
         WHERE rsl.sl_color = rsh.slcolor
           AND rsl.sl_len_cm >= rsh.slminlen_cm
           AND rsl.sl_len_cm <= rsh.slmaxlen_cm) shoe_ready
 WHERE shoe_ready.total_avail > 2;

This might look inefficient, but the planner will collapse this into a single-level query tree by <quote>pulling up</quote> the subqueries, and then it will plan the joins just as if we'd written them out manually. So collapsing the query tree is an optimization that the rewrite system doesn't have to concern itself with. これは非効率的に見えるかもしれませんが、プランナは副問い合わせを引っ張り上げることで、これを単一レベルの問い合わせツリーに縮めてから、手で書き出したかのように結合を計画します。 そのため、問い合わせツリーを縮めるという最適化を、書き換えシステム自身で意識する必要はありません。

41.2.2. 非SELECT文のビュールール #

<title>View Rules in Non-<command>SELECT</command> Statements</title>

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, the command type is not needed by view rules, but the result relation may affect the way in which the query rewriter works, because special care needs to be taken if the result relation is a view. これまでのビュールールの説明では問い合わせツリーの2つの詳細について触れませんでした。 それらは、コマンドタイプと結果リレーションです。 実際、コマンドタイプはビュールールでは必要とされませんが、結果リレーションがビューの場合には特別な考慮が必要ですので、結果リレーションは問い合わせリライタの動作に影響するかもしれません。

There are only a few differences between a query tree for a <command>SELECT</command> and one for any other command. Obviously, they have a different command type and for a command other than a <command>SELECT</command>, the result relation points to the range-table entry where the result should go. Everything else is absolutely the same. So having two tables <literal>t1</literal> and <literal>t2</literal> with columns <literal>a</literal> and <literal>b</literal>, the query trees for the two statements: SELECTと他のコマンドに対する問い合わせツリーの間には大きな違いはありません。 明らかに、それらは違うコマンドタイプを持っていて、SELECT以外のコマンドでは、結果リレーションは結果の格納先となる範囲テーブルの項目を指し示します。 それ以外ではまったく同じです。 ですから、abの列を持つテーブルt1t2に対する以下の2つの文の問い合わせツリーは、ほとんど同じです。

SELECT t2.b FROM t1, t2 WHERE t1.a = t2.a;

UPDATE t1 SET b = t2.b FROM t2 WHERE t1.a = t2.a;

are nearly identical. In particular: 以下に、具体的に示します。

  • The range tables contain entries for the tables <literal>t1</literal> and <literal>t2</literal>. 範囲テーブルには、テーブルt1t2に対する項目があります。

  • The target lists contain one variable that points to column <literal>b</literal> of the range table entry for table <literal>t2</literal>. 目的リストにはテーブルt2に対する範囲テーブル項目のb列を指し示す1つの変数があります。

  • The qualification expressions compare the columns <literal>a</literal> of both range-table entries for equality. 条件式は、範囲テーブルの両項目のa列の等価性を比較します。

  • The join trees show a simple join between <literal>t1</literal> and <literal>t2</literal>. 結合ツリーはt1t2の単純な結合を表しています。

The consequence is, that both query trees result in similar execution plans: They are both joins over the two tables. For the <command>UPDATE</command> the missing columns from <literal>t1</literal> are added to the target list by the planner and the final query tree will read as: 結果として、両方の問い合わせツリーは似たような実行計画になります。 それらはともに2つのテーブルの結合です。 UPDATEではt1から抜けている列はプランナによって目的リストに追加され、最終の問い合わせツリーは、以下のようになります。

UPDATE t1 SET a = t1.a, b = t2.b FROM t2 WHERE t1.a = t2.a;

and thus the executor run over the join will produce exactly the same result set as: そして、結合を実行したエグゼキュータは、

SELECT t1.a, t2.b FROM t1, t2 WHERE t1.a = t2.a;

But there is a little problem in <command>UPDATE</command>: the part of the executor plan that does the join does not care what the results from the join are meant for. It just produces a result set of rows. The fact that one is a <command>SELECT</command> command and the other is an <command>UPDATE</command> is handled higher up in the executor, where it knows that this is an <command>UPDATE</command>, and it knows that this result should go into table <literal>t1</literal>. But which of the rows that are there has to be replaced by the new row? の結果集合とまったく同じ結果集合を作成します。 とは言ってもUPDATEにはちょっとした問題があります。 結合を行うエグゼキュータの計画の部分は、結合の結果が何に向けられているかに関与しません。 エグゼキュータは単に結果となる行の集合を作成するだけです。 1つはSELECTコマンドでもう1つはUPDATEコマンドであるという事実は、エグゼキュータの中のより上位で扱われます。 そこでは、これがUPDATEであるとわかっていて、この結果がテーブルt1に入らなければいけないことを知っています。 しかし、そこにあるどの行が新しい行によって置換されなければならないのでしょうか。

To resolve this problem, another entry is added to the target list in <command>UPDATE</command> (and also in <command>DELETE</command>) statements: the current tuple ID (<acronym>CTID</acronym>).<indexterm><primary>CTID</primary></indexterm> This is a system column containing the file block number and position in the block for the row. Knowing the table, the <acronym>CTID</acronym> can be used to retrieve the original row of <literal>t1</literal> to be updated. After adding the <acronym>CTID</acronym> to the target list, the query actually looks like: この問題を解決するため、UPDATE文(DELETE文の場合も同様)の目的リストに別の項目が付け加えられます。 それは、現在のタプルID(CTID)です。 これはその行のファイルブロック番号とブロック中の位置を持つシステム列です。 テーブルがわかっている場合、CTIDを使用して、元のt1行を抽出して更新することができます。 CTIDを目的リストに追加すると、問い合わせは以下のようになります。

SELECT t1.a, t2.b, t1.ctid FROM t1, t2 WHERE t1.a = t2.a;

Now another detail of <productname>PostgreSQL</productname> enters the stage. Old table rows aren't overwritten, and this is why <command>ROLLBACK</command> is fast. In an <command>UPDATE</command>, the new result row is inserted into the table (after stripping the <acronym>CTID</acronym>) and in the row header of the old row, which the <acronym>CTID</acronym> pointed to, the <literal>cmax</literal> and <literal>xmax</literal> entries are set to the current command counter and current transaction ID. Thus the old row is hidden, and after the transaction commits the vacuum cleaner can eventually remove the dead row. では、PostgreSQLの別の詳細説明に入りましょう。 テーブルの行は上書きされませんので、ROLLBACK処理は速いのです。 UPDATEでは、(CTIDを取り除いた後)テーブルに新しい結果行が挿入され、CTIDが指し示す古い行の行ヘッダ内のcmaxxmax項目は現在のコマンドカウンタと現在のトランザクションIDに設定されます。 このようにして、古い行は隠され、トランザクションがコミットされた後、vacuum掃除機が不必要になった行をそのうちに削除できます。

Knowing all that, we can simply apply view rules in absolutely the same way to any command. There is no difference. これらの詳細が全部理解できれば、どんなコマンドに対してもまったく同じようにしてビューのルールを簡単に適用することができます。 そこには差異がありません。

41.2.3. PostgreSQLにおけるビューの能力 #

<title>The Power of Views in <productname>PostgreSQL</productname></title>

The above demonstrates how the rule system incorporates view definitions into the original query tree. In the second example, a simple <command>SELECT</command> from one view created a final query tree that is a join of 4 tables (<literal>unit</literal> was used twice with different names). ここまでで、ルールシステムがどのようにビューの諸定義を元の問い合わせツリーに組み入れるかを解説しました。 第2の例では、1つのビューからの単純なSELECTによって、最終的に4つのテーブルを結合する問い合わせツリーが生成されました(unitは違った名前で2回使われました)。

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 relationships between these tables plus the restrictive qualifications from the views plus the qualifications from the original query in one single query tree. And this is still the situation when the original query is already a join over views. 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>PostgreSQL</productname> ensures that this is all information available about the query up to that point. ビューをルールシステムで実装する利点は、どのテーブルをスキャンすべきか、それらのテーブル間の関連性、ビューからの制約条件、元の問い合わせ条件に関する情報を全て、プランナが1つの問い合わせツリーの中に持っていることです。 元の問い合わせが既にビューに対する結合である時も同様です。 プランナはここでどれが問い合わせ処理の最適経路かを決定しなければなりません。 プランナは保持する情報が多ければ多いほど、より良い決定を下すことができます。 そしてPostgreSQLに実装されているルールシステムはこれが現時点で、提供されている全ての情報であることを保証します。

41.2.4. ビューの更新について #

<title>Updating a View</title>

What happens if a view is named as the target relation for an <command>INSERT</command>, <command>UPDATE</command>, or <command>DELETE</command>? Doing the substitutions described above would give a query tree in which the result relation points at a subquery range-table entry, which will not work. There are several ways in which <productname>PostgreSQL</productname> can support the appearance of updating a view, however. In order of user-experienced complexity those are: automatically substitute in the underlying table for the view, execute a user-defined trigger, or rewrite the query per a user-defined rule. These options are discussed below. ビューがINSERTUPDATEDELETEなどの目的リレーションとして名付けられた場合はどうなるのでしょうか? 上で説明したような置換をすると、結果リレーションが副問い合わせの範囲テーブル項目を指す問い合わせツリーができてしまい、それは上手く機能しません。しかし、いくつかのケースではPostgreSQLはビューの更新をサポートする事ができます。 ユーザーエクスペリエンスの複雑さの順に、ビューから参照されているテーブルでの自動的な置換、ユーザ定義トリガの実行、ユーザ定義ルールごとの問い合わせの書き換えがあります。 これらのオプションについては、以下で説明します。

If the subquery selects from a single base relation and is simple enough, the rewriter can automatically replace the subquery with the underlying base relation so that the <command>INSERT</command>, <command>UPDATE</command>, or <command>DELETE</command> is applied to the base relation in the appropriate way. Views that are <quote>simple enough</quote> for this are called <firstterm>automatically updatable</firstterm>. For detailed information on the kinds of view that can be automatically updated, see <xref linkend="sql-createview"/>. 副問い合わせが単一の基底リレーションを参照しかつ十分に単純である時、リライタは副問い合わせを基となる基底リレーションに自動的に置き換え、したがって、INSERTUPDATEあるいはDELETEを適切な方法で基底リレーションに適用する事ができます。 この場合の十分に単純なビューは自動的に更新可能であると呼ばれます。自動的に更新可能なビューに関するより詳細な情報については、CREATE VIEWを参照してください。

Alternatively, the operation may be handled by a user-provided <literal>INSTEAD OF</literal> trigger on the view (see <xref linkend="sql-createtrigger"/>). Rewriting works slightly differently in this case. For <command>INSERT</command>, the rewriter does nothing at all with the view, leaving it as the result relation for the query. For <command>UPDATE</command> and <command>DELETE</command>, it's still necessary to expand the view query to produce the <quote>old</quote> rows that the command will attempt to update or delete. So the view is expanded as normal, but another unexpanded range-table entry is added to the query to represent the view in its capacity as the result relation. もう一つの方法として、ビューに対するユーザ定義のINSTEAD OFトリガによってこれらのコマンドを処理する事ができます。この場合、書き換えは少々違う形で行われます (CREATE TRIGGERを参照してください)。 INSERTに対しては、リライタはビューに全く何もせず、問い合わせの結果リレーションをそのままにします。 UPDATEDELETEに対しては、コマンドが更新もしくは削除しようとする古い行を生成するためにビュー問い合わせを展開する必要がまだあります。 そのため、ビューは通常通り展開されますが、もう一つの展開されない範囲テーブル項目が結果リレーションとしてビューを表す問い合わせに追加されます。

The problem that now arises is how to identify the rows to be updated in the view. Recall that when the result relation is a table, a special <acronym>CTID</acronym> entry is added to the target list to identify the physical locations of the rows to be updated. This does not work if the result relation is a view, because a view does not have any <acronym>CTID</acronym>, since its rows do not have actual physical locations. Instead, for an <command>UPDATE</command> or <command>DELETE</command> operation, a special <literal>wholerow</literal> entry is added to the target list, which expands to include all columns from the view. The executor uses this value to supply the <quote>old</quote> row to the <literal>INSTEAD OF</literal> trigger. It is up to the trigger to work out what to update based on the old and new row values. ここで起こる問題はビューで更新される行をどのように特定するかということです。 結果リレーションがテーブルの場合、更新する行の物理的な位置を特定するために特別なCTID項目が目的リストに追加されることを思い出して下さい。 ビューの行には実際の物理的な位置がないため、ビューにはCTIDがありませんので、これは結果リレーションがビューの場合には上手くいきません。 その代わり、UPDATEDELETE操作では、特別な行全体の項目が目的リストに追加されていて、それはビューからすべての列を含むように展開されています。 エグゼキュータはこの値を使って古い行をINSTEAD OFトリガに提供します。 新旧の行の値に基づいて更新するものを計算するのはトリガの責任です。

Another possibility is for the user to define <literal>INSTEAD</literal> rules that specify substitute actions for <command>INSERT</command>, <command>UPDATE</command>, and <command>DELETE</command> commands on a view. These rules will rewrite the command, typically into a command that updates one or more tables, rather than views. That is the topic of <xref linkend="rules-update"/>. 別の方法としては、ビューに対するINSERTUPDATEDELETEコマンドに代替の動作を指定するINSTEADルールを定義する事です。 これらのルールは、ビューではなくコマンドを、通常は1つもしくは複数のテーブルを更新するコマンドに書き換えます。 それが41.4の論題になります。

Note that rules are evaluated first, rewriting the original query before it is planned and executed. Therefore, if a view has <literal>INSTEAD OF</literal> triggers as well as rules on <command>INSERT</command>, <command>UPDATE</command>, or <command>DELETE</command>, then the rules will be evaluated first, and depending on the result, the triggers may not be used at all. ルールが最初に評価され、元の問い合わせが計画され実行される前にそれを書き換えることに注意して下さい。 そのためビューにINSTEAD OFトリガとINSERTUPDATEDELETEに関するルールがあった場合、ルールが最初に評価され、その結果よってはトリガが全く使われないかもしれません。

Automatic rewriting of an <command>INSERT</command>, <command>UPDATE</command>, or <command>DELETE</command> query on a simple view is always tried last. Therefore, if a view has rules or triggers, they will override the default behavior of automatically updatable views. 単純なビューに対するINSERTUPDATEあるいはDELETEコマンドの自動書き換えは常に最後に試みられます。したがって、ビューがルールもしくはトリガを持っていた場合、これらは更新可能ビューのデフォルト動作を上書きします。

If there are no <literal>INSTEAD</literal> rules or <literal>INSTEAD OF</literal> triggers for the view, and the rewriter cannot automatically rewrite the query as an update on the underlying base relation, an error will be thrown because the executor cannot update a view as such. ビューにINSTEADルールもINSTEAD OFトリガも定義されておらず、かつ、リライタが問い合わせを自動的に基となる基底リレーションへの更新に書き換える事ができなかった場合、エグゼキュータはビューを更新できませんのでエラーが発生します。