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

5.10. 継承 #

<title>Inheritance</title>

<productname>PostgreSQL</productname> implements table inheritance, which can be a useful tool for database designers. (SQL:1999 and later define a type inheritance feature, which differs in many respects from the features described here.) PostgreSQLは、データベース設計者にとって便利なテーブルの継承を実装しています。 (SQL:1999以降は型の継承を定義していますが、ここで述べられている継承とは多くの点で異なっています。)

Let's start with an example: suppose we are trying to build a data model for cities. Each state has many cities, but only one capital. We want to be able to quickly retrieve the capital city for any particular state. This can be done by creating two tables, one for state capitals and one for cities that are not capitals. However, what happens when we want to ask for data about a city, regardless of whether it is a capital or not? The inheritance feature can help to resolve this problem. We define the <structname>capitals</structname> table so that it inherits from <structname>cities</structname>: まず例から始めましょう。 市(cities)のデータモデルを作成しようとしていると仮定してください。 それぞれの州にはたくさんの市がありますが、州都(capitals)は1つのみです。 どの州についても州都を素早く検索したいとします。 これは、2つのテーブルを作成することにより実現できます。 1つは州都のテーブルで、もう1つは州都ではない市のテーブルです。 しかし、州都であるか否かに関わらず、市に対するデータを問い合わせたいときには何が起こるのでしょうか? 継承はこの問題を解決できます。 citiesから継承されるcapitalsテーブルを定義するのです。

CREATE TABLE cities (
    name            text,
    population      float,
    elevation       int     -- in feet
);

CREATE TABLE capitals (
    state           char(2)
) INHERITS (cities);

In this case, the <structname>capitals</structname> table <firstterm>inherits</firstterm> all the columns of its parent table, <structname>cities</structname>. State capitals also have an extra column, <structfield>state</structfield>, that shows their state. この場合、capitalsテーブルは、その親テーブルであるcitiesテーブルの列をすべて継承します。 州都は1つの追加の列stateを持ち、州を表現します。

In <productname>PostgreSQL</productname>, a table can inherit from zero or more other tables, and a query can reference either all rows of a table or all rows of a table plus all of its descendant tables. The latter behavior is the default. For example, the following query finds the names of all cities, including state capitals, that are located at an elevation over 500 feet: PostgreSQLでは、1つのテーブルは、0以上のテーブルから継承することが可能です。 また、問い合わせはテーブルのすべての行、またはテーブルのすべての行と継承されたテーブルのすべての行のいずれかを参照できます。 後者がデフォルトの動作になります。 例えば次の問い合わせは、500フィートより高い標高に位置しているすべての市の名前を、州都を含めて検索します。

SELECT name, elevation
    FROM cities
    WHERE elevation > 500;

Given the sample data from the <productname>PostgreSQL</productname> tutorial (see <xref linkend="tutorial-sql-intro"/>), this returns: PostgreSQLチュートリアルからのサンプルデータ(2.1を参照してください)に対して、この問い合わせは、以下の結果を出力します。

   name    | elevation
-----------+-----------
 Las Vegas |      2174
 Mariposa  |      1953
 Madison   |       845

On the other hand, the following query finds all the cities that are not state capitals and are situated at an elevation over 500 feet: 一方、次の問い合わせは、州都ではなく500フィートより高い高度に位置しているすべての市を検索します。

SELECT name, elevation
    FROM ONLY cities
    WHERE elevation > 500;

   name    | elevation
-----------+-----------
 Las Vegas |      2174
 Mariposa  |      1953

Here the <literal>ONLY</literal> keyword indicates that the query should apply only to <structname>cities</structname>, and not any tables below <structname>cities</structname> in the inheritance hierarchy. Many of the commands that we have already discussed &mdash; <command>SELECT</command>, <command>UPDATE</command> and <command>DELETE</command> &mdash; support the <literal>ONLY</literal> keyword. ここでONLYキーワードは、問い合わせがcitiesテーブルのみを対象にしcities以下の継承の階層にあるテーブルは対象としないことを意味します。 これまで議論したコマンドの多く—SELECTUPDATEそしてDELETE —がONLYキーワードをサポートしています。

You can also write the table name with a trailing <literal>*</literal> to explicitly specify that descendant tables are included: また、明示的に子孫テーブルが含まれていることを示すために、テーブル名の後ろに*を書くこともできます:

SELECT name, elevation
    FROM cities*
    WHERE elevation > 500;

Writing <literal>*</literal> is not necessary, since this behavior is always the default. However, this syntax is still supported for compatibility with older releases where the default could be changed. *の指定は、その動作が常にデフォルトであるため、必要ありません。 しかし、この構文はデフォルトが変更可能であった古いリリースとの互換性のためにまだサポートされています。

In some cases you might wish to know which table a particular row originated from. There is a system column called <structfield>tableoid</structfield> in each table which can tell you the originating table: ある特定の行がどのテーブルからきたものか知りたいという場合もあるでしょう。 それぞれのテーブルにはtableoidという、元になったテーブルを示すシステム列があります。

SELECT c.tableoid, c.name, c.elevation
FROM cities c
WHERE c.elevation > 500;

which returns: 出力は以下のとおりです。

 tableoid |   name    | elevation
----------+-----------+-----------
   139793 | Las Vegas |      2174
   139793 | Mariposa  |      1953
   139798 | Madison   |       845

(If you try to reproduce this example, you will probably get different numeric OIDs.) By doing a join with <structname>pg_class</structname> you can see the actual table names: (この例をそのまま実行しても、おそらく異なる数値OIDが得られるでしょう。) pg_classと結合することで、テーブルの実際の名前が分かります。

SELECT p.relname, c.name, c.elevation
FROM cities c, pg_class p
WHERE c.elevation > 500 AND c.tableoid = p.oid;

which returns: 出力は以下の通りです。

 relname  |   name    | elevation
----------+-----------+-----------
 cities   | Las Vegas |      2174
 cities   | Mariposa  |      1953
 capitals | Madison   |       845

Another way to get the same effect is to use the <type>regclass</type> alias type, which will print the table OID symbolically: 同じ効果を得る別の方法は、別名型regclassを使うことで、これによりテーブルのOIDを記号的に表示します。

SELECT c.tableoid::regclass, c.name, c.elevation
FROM cities c
WHERE c.elevation > 500;

Inheritance does not automatically propagate data from <command>INSERT</command> or <command>COPY</command> commands to other tables in the inheritance hierarchy. In our example, the following <command>INSERT</command> statement will fail: 継承はINSERTまたはCOPYによるデータを、継承の階層にある他のテーブルに自動的に伝播しません。 この例では、次のINSERT文は失敗します。

INSERT INTO cities (name, population, elevation, state)
VALUES ('Albany', NULL, NULL, 'NY');

We might hope that the data would somehow be routed to the <structname>capitals</structname> table, but this does not happen: <command>INSERT</command> always inserts into exactly the table specified. In some cases it is possible to redirect the insertion using a rule (see <xref linkend="rules"/>). However that does not help for the above case because the <structname>cities</structname> table does not contain the column <structfield>state</structfield>, and so the command will be rejected before the rule can be applied. データが、どうにかしてcapitalsテーブルに入ることを期待するかもしれませんが、そのようにはなりません。 INSERTは、いつも指定されたテーブルそれ自体に対してデータを挿入します。 ルール(詳細は第41章を参照してください)を使用して挿入を中継できる場合もあります。 しかし、ルールを使用しても上記のような場合は解決できません。 なぜなら、citiesテーブルにstate列が含まれていないため、ルールが適用される前にコマンドを拒否されてしまうからです。

All check constraints and not-null constraints on a parent table are automatically inherited by its children, unless explicitly specified otherwise with <literal>NO INHERIT</literal> clauses. Other types of constraints (unique, primary key, and foreign key constraints) are not inherited. 親テーブル上の検査制約と非NULL制約は、NO INHERIT句によって明示的に指定されない限り、その子テーブルに自動的に継承されます。 他の種類の制約(一意性制約、主キー、外部キー制約)は継承されません。

A table can inherit from more than one parent table, in which case it has the union of the columns defined by the parent tables. Any columns declared in the child table's definition are added to these. If the same column name appears in multiple parent tables, or in both a parent table and the child's definition, then these columns are <quote>merged</quote> so that there is only one such column in the child table. To be merged, columns must have the same data types, else an error is raised. Inheritable check constraints and not-null constraints are merged in a similar fashion. Thus, for example, a merged column will be marked not-null if any one of the column definitions it came from is marked not-null. Check constraints are merged if they have the same name, and the merge will fail if their conditions are different. テーブルは1つ以上の親テーブルから継承可能です。 この場合、テーブルは親テーブルで定義された列の和になります。 子テーブルで宣言された列は、これらの列に追加されることになります。 もし親テーブルに同じ名前の列がある場合、もしくは、親テーブルと子テーブルに同じ名前の列がある場合は、列が統合されて子テーブルではただ1つの列となります。 統合されるには列は同じデータ型を持っている必要があります。 異なるデータ型の場合にはエラーとなります。 継承可能な検査制約と非NULL制約は、同じようなやり方で統合されます。 つまり、例えば、列定義のいずれかが非NULL制約の印が付いているならば、統合された列に非NULLという印が付きます。 検査制約は、同じ名前を持っている場合に統合され、それらの条件が異なる場合は統合に失敗します。

Table inheritance is typically established when the child table is created, using the <literal>INHERITS</literal> clause of the <link linkend="sql-createtable"><command>CREATE TABLE</command></link> statement. Alternatively, a table which is already defined in a compatible way can have a new parent relationship added, using the <literal>INHERIT</literal> variant of <link linkend="sql-altertable"><command>ALTER TABLE</command></link>. To do this the new child table must already include columns with the same names and types as the columns of the parent. It must also include check constraints with the same names and check expressions as those of the parent. Similarly an inheritance link can be removed from a child using the <literal>NO INHERIT</literal> variant of <command>ALTER TABLE</command>. Dynamically adding and removing inheritance links like this can be useful when the inheritance relationship is being used for table partitioning (see <xref linkend="ddl-partitioning"/>). テーブル継承は、通常、CREATE TABLE文のINHERITS句を使用して、子テーブルを作成する時に確立します。 他にも、互換性を持つ方法で定義済みのテーブルに新しく親子関係を付けることも可能です。 これにはALTER TABLEINHERIT形式を使用します。 このためには、新しい子テーブルは親テーブルと同じ名前の列を持ち、その列の型は同じデータ型でなければなりません。 また、親テーブルと同じ名前、同じ式の検査制約を持っていなければなりません。 ALTER TABLENO INHERIT形式を使用して、同様に継承関係を子テーブルから取り除くことも可能です。 このような継承関係の動的追加、動的削除は、継承関係をテーブルパーティショニング(5.11を参照)に使用している場合に有用です。

One convenient way to create a compatible table that will later be made a new child is to use the <literal>LIKE</literal> clause in <command>CREATE TABLE</command>. This creates a new table with the same columns as the source table. If there are any <literal>CHECK</literal> constraints defined on the source table, the <literal>INCLUDING CONSTRAINTS</literal> option to <literal>LIKE</literal> should be specified, as the new child must have constraints matching the parent to be considered compatible. 後で子テーブルとする予定の、互換性を持つテーブルを簡単に作成する方法の1つは、CREATE TABLELIKE句を使用することです。 これは、元としたテーブルと同じ列を持つテーブルを新しく作成します。 新しい子テーブルが必ず親テーブルと一致する制約を持ち、互換性があるものとみなされるように、元となるテーブルでCHECK制約が存在する場合は、LIKEINCLUDING CONSTRAINTSオプションを指定すべきです。

A parent table cannot be dropped while any of its children remain. Neither can columns or check constraints of child tables be dropped or altered if they are inherited from any parent tables. If you wish to remove a table and all of its descendants, one easy way is to drop the parent table with the <literal>CASCADE</literal> option (see <xref linkend="ddl-depend"/>). 子テーブルが存在する場合親テーブルを削除することはできません。 また、子テーブルでは、親テーブルから継承した列、または検査制約を削除することも変更することもできません。 テーブルとそのすべての子テーブルを削除したければ、CASCADEオプションを付けて親テーブルを削除することが簡単な方法です(5.14を参照)。

<command>ALTER TABLE</command> will propagate any changes in column data definitions and check constraints down the inheritance hierarchy. Again, dropping columns that are depended on by other tables is only possible when using the <literal>CASCADE</literal> option. <command>ALTER TABLE</command> follows the same rules for duplicate column merging and rejection that apply during <command>CREATE TABLE</command>. ALTER TABLEは、列データ定義と検査制約の変更を継承の階層にあるテーブルに伝えます。 ここでも、他のテーブルに依存する列の削除はCASCADEオプションを使用したときのみ可能となります。 ALTER TABLEは、重複列の統合と拒否について、CREATE TABLE時に適用される規則に従います。

Inherited queries perform access permission checks on the parent table only. Thus, for example, granting <literal>UPDATE</literal> permission on the <structname>cities</structname> table implies permission to update rows in the <structname>capitals</structname> table as well, when they are accessed through <structname>cities</structname>. This preserves the appearance that the data is (also) in the parent table. But the <structname>capitals</structname> table could not be updated directly without an additional grant. In a similar way, the parent table's row security policies (see <xref linkend="ddl-rowsecurity"/>) are applied to rows coming from child tables during an inherited query. A child table's policies, if any, are applied only when it is the table explicitly named in the query; and in that case, any policies attached to its parent(s) are ignored. 継承された問い合わせは、親テーブルのみアクセス権限を検査します。 つまり、例えば、UPDATE権限をcitiesテーブルに付与することは、citiesテーブルを通じてアクセスする場合に、capitalsテーブルにも行の更新権限を付与することを意味します。 これによりデータが親テーブルに(も)あるように見えることが保たれます。 しかし、capitalsテーブルは、追加権限なしに直接更新することはできません。 同様に、親テーブルの行セキュリティポリシー(5.8を参照してください)が、継承された問い合わせの時に子テーブルの行に適用されます。 子テーブルのポリシー(あれば)は、問い合わせにて明示的に指定されたテーブルである時にのみ適用されます。 そしてこの場合、親テーブルに紐付けられたあらゆるポリシーは無視されます。

Foreign tables (see <xref linkend="ddl-foreign-data"/>) can also be part of inheritance hierarchies, either as parent or child tables, just as regular tables can be. If a foreign table is part of an inheritance hierarchy then any operations not supported by the foreign table are not supported on the whole hierarchy either. 外部テーブル(5.12参照)も通常のテーブルと同様、親テーブルあるいは子テーブルとして継承の階層の一部となりえます。 外部テーブルが継承の階層の一部となっている場合、外部テーブルがサポートしない操作は、その継承全体でもサポートされません。

5.10.1. 警告 #

<title>Caveats</title>

Note that not all SQL commands are able to work on inheritance hierarchies. Commands that are used for data querying, data modification, or schema modification (e.g., <literal>SELECT</literal>, <literal>UPDATE</literal>, <literal>DELETE</literal>, most variants of <literal>ALTER TABLE</literal>, but not <literal>INSERT</literal> or <literal>ALTER TABLE ... RENAME</literal>) typically default to including child tables and support the <literal>ONLY</literal> notation to exclude them. Commands that do database maintenance and tuning (e.g., <literal>REINDEX</literal>, <literal>VACUUM</literal>) typically only work on individual, physical tables and do not support recursing over inheritance hierarchies. The respective behavior of each individual command is documented in its reference page (<xref linkend="sql-commands"/>). すべてのSQLコマンドが継承階層に対して動作できるとは限らないことに注意してください。 データの検索、データの変更、スキーマの変更のために使用されるコマンド(例えばSELECTUPDATEDELETEALTER TABLEのほとんどの構文が該当しますが、INSERTALTER TABLE ... RENAMEは含まれません)は通常、デフォルトで子テーブルを含み、また、それを除外するためのONLY記法をサポートします。 データベース保守およびチューニング(例えばREINDEXVACUUM)を行うコマンドは通常、個々の物理テーブルに対してのみ動作し、継承階層に対する再帰をサポートしません。 個々のコマンドのそれぞれの動作はそのマニュアルページ(SQLコマンド)に記載されています。

A serious limitation of the inheritance feature is that indexes (including unique constraints) and foreign key constraints only apply to single tables, not to their inheritance children. This is true on both the referencing and referenced sides of a foreign key constraint. Thus, in the terms of the above example: 継承機能の重大な制限として、インデックス(一意性制約を含む)、および外部キーは、そのテーブルのみに適用され、それを継承した子テーブルには適用されないことがあります。 これは外部キーの参照側、被参照側の両方について当てはまります。 したがって、上の例では

  • If we declared <structname>cities</structname>.<structfield>name</structfield> to be <literal>UNIQUE</literal> or a <literal>PRIMARY KEY</literal>, this would not stop the <structname>capitals</structname> table from having rows with names duplicating rows in <structname>cities</structname>. And those duplicate rows would by default show up in queries from <structname>cities</structname>. In fact, by default <structname>capitals</structname> would have no unique constraint at all, and so could contain multiple rows with the same name. You could add a unique constraint to <structname>capitals</structname>, but this would not prevent duplication compared to <structname>cities</structname>. もし、cities.nameUNIQUEまたはPRIMARY KEYと宣言しても、citiesテーブルの行と重複した行をcapitalsテーブル内に持つことを禁止することにはなりません。 さらに、これらの重複した行はデフォルトでcitiesテーブルへの問い合わせで現れるでしょう。 事実として、capitalsテーブルはデフォルトで一意性制約を持っていませんし、同一の名前の複数の行を持つことがあり得ます。 capitalsテーブルに一意性制約を追加できますが、これはcitiesテーブルと比較して重複を禁止することにはなりません。

  • Similarly, if we were to specify that <structname>cities</structname>.<structfield>name</structfield> <literal>REFERENCES</literal> some other table, this constraint would not automatically propagate to <structname>capitals</structname>. In this case you could work around it by manually adding the same <literal>REFERENCES</literal> constraint to <structname>capitals</structname>. 同じように、cities.name REFERENCESで他のテーブルを参照するようにしても、この制約は自動的にcapitalsに引き継がれるわけではありません。 この場合はcapitalsテーブルに同一のREFERENCES制約を手動で追加すれば問題を回避できます。

  • Specifying that another table's column <literal>REFERENCES cities(name)</literal> would allow the other table to contain city names, but not capital names. There is no good workaround for this case. 他のテーブルの列にREFERENCES cities(name)を指定すると、他のテーブルが市の名前を持つことはできますが、州都の名前を持つことはできません。 この場合は良い回避策がありません。

Some functionality not implemented for inheritance hierarchies is implemented for declarative partitioning. Considerable care is needed in deciding whether partitioning with legacy inheritance is useful for your application. 継承の階層に対して実装されていないいくつかの機能は、宣言的パーティショニングでは実装されています。 従来の継承によるパーティショニングがアプリケーションにとって有用であるかどうかを判断する際に十分注意してください。